diff --git a/DESCRIPTION b/DESCRIPTION index 2568a14c7..58d304e4f 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -114,12 +114,14 @@ Suggests: SummarizedExperiment, tidygraph, trendsceek, - testthat (>= 3.0.0) + testthat (>= 3.0.0), + rmarkdown Remotes: drieslab/GiottoUtils, drieslab/GiottoClass, drieslab/GiottoVisuals Collate: + 'ONTraC_wrapper.R' 'auxiliary_giotto.R' 'cell_segmentation.R' 'clustering.R' diff --git a/NAMESPACE b/NAMESPACE index b9e278ca0..55de5eabd 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -238,6 +238,7 @@ export(getGEFtxCoords) export(getGiottoImage) export(getMultiomics) export(getNearestNetwork) +export(getONTraCv1Input) export(getPolygonInfo) export(getRainbowColors) export(getSpatialEnrichment) @@ -274,6 +275,7 @@ export(jackstrawPlot) export(joinGiottoObjects) export(loadGiotto) export(loadHMRF) +export(loadOntraCResults) export(makePseudoVisium) export(makeSignMatrixDWLS) export(makeSignMatrixDWLSfromMatrix) @@ -293,8 +295,10 @@ export(pieCellTypesFromEnrichment) export(plotCCcomDotplot) export(plotCCcomHeatmap) export(plotCPF) +export(plotCTCompositionInNicheCluster) export(plotCellProximityFeatSpot) export(plotCellProximityFeats) +export(plotCellTypeNTScore) export(plotCellTypesFromEnrichment) export(plotCombineCCcom) export(plotCombineCellCellCommunication) @@ -309,6 +313,7 @@ export(plotInteractive3D) export(plotInteractivePolygons) export(plotMetaDataCellsHeatmap) export(plotMetaDataHeatmap) +export(plotNicheClusterConnectivity) export(plotPCA) export(plotPCA_2D) export(plotPCA_3D) diff --git a/R/ONTraC_wrapper.R b/R/ONTraC_wrapper.R new file mode 100644 index 000000000..0cdc02ff4 --- /dev/null +++ b/R/ONTraC_wrapper.R @@ -0,0 +1,524 @@ +#' @title getONTraCv1Input +#' @name getONTraCv1Input +#' @description generate the input data for ONTraC v1 +#' @inheritParams data_access_params +#' @inheritParams read_data_params +#' @param output_path the path to save the output file +#' @param cell_type the cell type column name in the metadata +#' @returns data.table with columns: Cell_ID, Sample, x, y, Cell_Type +#' @details This function generate the input data for ONTraC v1 +#' @examples +#' g <- GiottoData::loadGiottoMini("visium") +#' +#' getONTraCv1Input( +#' gobject = g, +#' cell_type = "custom_leiden" +#' ) +#' @export +getONTraCv1Input <- function(gobject, # nolint: object_name_linter. + cell_type, + output_path = getwd(), + spat_unit = NULL, + feat_type = NULL, + verbose = TRUE) { + # Set feat_type and spat_unit + spat_unit <- set_default_spat_unit( + gobject = gobject, + spat_unit = spat_unit + ) + feat_type <- set_default_feat_type( + gobject = gobject, + spat_unit = spat_unit, + feat_type = feat_type + ) + + pos_df <- getSpatialLocations( + gobject = gobject, + spat_unit = spat_unit, + output = "data.table" + ) + meta_df <- pDataDT( + gobject = gobject, + spat_unit = spat_unit, + feat_type = feat_type + ) + output_df <- merge(x = pos_df, y = meta_df, by = "cell_ID") + + # check if the cell_type column exits + if (!cell_type %in% colnames(output_df)) { + vmsg(.v = verbose, paste( + "Given", + cell_type, + "do not exist in giotto object's metadata!" + )) + return(NULL) + } + + # add default sample name for one sample obj + if (!"list_ID" %in% colnames(output_df)) { + output_df$list_ID <- "ONTraC" + } + + output_df <- output_df[, .SD, .SDcols = c( + "cell_ID", + "list_ID", + "sdimx", + "sdimy", + cell_type + )] + colnames(output_df) <- c("Cell_ID", "Sample", "x", "y", "Cell_Type") + file_path <- file.path(output_path, "ONTraC_dataset_input.csv") + write.csv(output_df, file = file_path, quote = FALSE, row.names = FALSE) + vmsg(.v = verbose, paste("ONTraC input file was saved as", file_path)) + + return(output_df) +} + + +#' @title load_cell_bin_niche_cluster +#' @name load_cell_bin_niche_cluster +#' @description load cell-level binarized niche cluster +#' @inheritParams data_access_params +#' @inheritParams read_data_params +#' @param ontrac_results_dir the directory where the ONTraC results are saved +#' @returns gobject with cell-level binarized niche cluster +#' @details This function loads the ONTraC outputed cell-level binarized niche +#' cluster into the giotto object. +load_cell_bin_niche_cluster <- function(gobject, + ontrac_results_dir = getwd()) { + bin_niche_cluster_df <- read.csv(file = file.path( + ontrac_results_dir, + "GNN_dir", "cell_level_max_niche_cluster.csv.gz" + )) + colnames(bin_niche_cluster_df) <- c("cell_ID", "NicheCluster") + gobject <- GiottoClass::addCellMetadata(gobject, + new_metadata = bin_niche_cluster_df, + by_column = TRUE, + column_cell_ID = "cell_ID" + ) + return(gobject) +} + + +#' @title load_cell_NT_score +#' @name load_cell_NT_score +#' @description load cell-level NT score +#' @inheritParams data_access_params +#' @inheritParams read_data_params +#' @param ontrac_results_dir the directory where the ONTraC results are saved +#' @returns gobject with cell-level NT score +#' @details This function loads the ONTraC outputed cell-level NT score +load_cell_NT_score <- function(gobject, # nolint: object_name_linter. + ontrac_results_dir = getwd()) { + NT_score_df <- read.csv(file = file.path( # nolint: object_name_linter. + ontrac_results_dir, + "NTScore_dir", "NTScore.csv.gz" + ))[c("Cell_ID", "Cell_NTScore")] + colnames(NT_score_df) <- c("cell_ID", "NTScore") # nolint: object_name_linter. + gobject <- addCellMetadata(gobject, + new_metadata = NT_score_df, # nolint: object_name_linter. + by_column = TRUE, + column_cell_ID = "cell_ID" + ) + + return(gobject) +} + + +#' @title load_cell_niche_cluster_prob +#' @name load_cell_niche_cluster_prob +#' @description load cell-niche cluster probability +#' @inheritParams data_access_params +#' @inheritParams read_data_params +#' @param ontrac_results_dir the directory where the ONTraC results are saved +#' @param name name for the probability matrix +#' @returns gobject with cell-niche cluster probability matrix +#' @details This function loads the ONTraC outputed cell-niche cluster +#' probability as an exprObj into the giotto object. +load_cell_niche_cluster_prob <- function(gobject, + ontrac_results_dir = getwd(), + spat_unit = "cell", + feat_type = "niche cluster", + name = "prob") { + niche_cluster_prob_df <- read.csv(file = file.path( + ontrac_results_dir, + "GNN_dir", "cell_level_niche_cluster.csv.gz" + )) + rownames(niche_cluster_prob_df) <- niche_cluster_prob_df$Cell_ID + niche_cluster_prob_df$Cell_ID <- NULL + expobj <- createExprObj(t(niche_cluster_prob_df), + spat_unit = spat_unit, + feat_type = feat_type + ) + gobject <- GiottoClass::setExpression( + gobject = gobject, + x = expobj, + spat_unit = spat_unit, + feat_type = feat_type, + name = name + ) + + return(gobject) +} + + +#' @title load_nc_connectivity +#' @name load_nc_connectivity +#' @description load niche cluster connectivity +#' @inheritParams data_access_params +#' @inheritParams read_data_params +#' @param ontrac_results_dir the directory where the ONTraC results are saved +#' @param name name for the connectivity matrix +#' @returns gobject with niche cluster connectivity matrix +#' @details This function loads the ONTraC outputed niche cluster connectivity +#' matrix as an exprObj into the giotto object. +load_nc_connectivity <- function(gobject, + ontrac_results_dir = getwd(), + spat_unit = "niche cluster", + feat_type = "connectivity", + name = "normalized") { + connectivity_df <- read.csv(file = file.path( + ontrac_results_dir, + "GNN_dir", "consolidate_out_adj.csv.gz" + ), header = FALSE) + rownames(connectivity_df) <- paste0( + "NicheCluster_", + seq_len(dim(connectivity_df)[1]) - 1 + ) + colnames(connectivity_df) <- paste0( + "NicheCluster_", + seq_len(dim(connectivity_df)[2]) - 1 + ) + expobj <- createExprObj(t(connectivity_df), + spat_unit = spat_unit, + feat_type = feat_type + ) + gobject <- GiottoClass::setExpression( + gobject = gobject, + x = expobj, + spat_unit = spat_unit, + feat_type = feat_type, + name = name + ) + + return(gobject) +} + + +#' @title loadOntraCResults +#' @name loadOntraCResults +#' @description load ONTraC results +#' @inheritParams data_access_params +#' @inheritParams read_data_params +#' @param ontrac_results_dir the directory where the ONTraC results are saved +#' @returns gobject with ONTraC results +#' @details This function loads the ONTraC results into the giotto object. +#' @export +loadOntraCResults <- function(gobject, # nolint: object_name_linter. + ontrac_results_dir = getwd()) { + gobject <- load_cell_bin_niche_cluster(gobject, ontrac_results_dir) + gobject <- load_cell_NT_score(gobject, ontrac_results_dir) + gobject <- load_cell_niche_cluster_prob(gobject, ontrac_results_dir) + gobject <- GiottoClass::addCellMetadata( + gobject = gobject, + spat_unit = "cell", + feat_type = "niche cluster", + new_metadata = pDataDT(gobject), + by_column = TRUE, + column_cell_ID = "cell_ID" + ) + + gobject <- load_nc_connectivity(gobject, ontrac_results_dir) + + return(gobject) +} + +#' @title plotNicheClusterConnectivity +#' @name plotNicheClusterConnectivity +#' @description plot niche cluster connectivity +#' @inheritParams data_access_params +#' @inheritParams plot_output_params +#' @param spat_unit name of spatial unit niche stored cluster features +#' @param feat_type name of the feature type stored niche cluster connectivities +#' @param values name of the expression matrix stored connectivity values +#' @details This function plots the niche cluster connectivity matrix +#' @export +plotNicheClusterConnectivity <- function( # nolint: object_name_linter. + gobject, + spat_unit = "niche cluster", + feat_type = "connectivity", + values = "normalized", + show_plot = NULL, + return_plot = NULL, + save_plot = NULL, + save_param = list(), + theme_param = list(), + default_save_name = "NicheClusterConnectivity") { + # load `guide_edge_colourbar` function in ggraph, + # otherwise it will raise an error when using `scale_edge_colour_gradientn` + library(ggraph) + + # get the niche cluster connectivity matrix + niche_cluster_connectivites <- getExpression( + gobject = gobject, + values = "normalized", + spat_unit = "niche cluster", + feat_type = "connectivity", + output = "matrix" + ) + + # transform the matrix to data.frame for constructing igraph object + niche_cluster_connectivites <- cbind( + expand.grid(dimnames(niche_cluster_connectivites)), + value = as.vector(as.matrix( + niche_cluster_connectivites + )) + ) + colnames(niche_cluster_connectivites) <- c("from", "to", "connectivites") + + # construct igraph object + igd <- igraph::graph_from_data_frame( + d = niche_cluster_connectivites[, c("from", "to", "connectivites")], + directed = FALSE + ) + igd <- igraph::simplify( + graph = igd, + remove.loops = TRUE, + remove.multiple = FALSE + ) + edges_sizes <- igraph::edge_attr(igd, "connectivites") + edges_colors <- edges_sizes + igd <- igraph::set.edge.attribute( + graph = igd, + index = igraph::E(igd), + name = "color", + value = edges_colors + ) + igd <- igraph::set.edge.attribute( + graph = igd, + index = igraph::E(igd), + name = "size", + value = edges_sizes + ) + + # plot + ## layout + coords <- igraph::layout_with_drl( + graph = igd, + weights = edges_sizes, + use.seed = TRUE + ) + gpl <- ggraph::ggraph(graph = igd, layout = coords) + + ## edges + gpl <- gpl + ggraph::geom_edge_link( + ggplot2::aes( + colour = edges_sizes, + edge_width = 5, + edge_alpha = size # nolint: object_usage_linter. + ), + show.legend = FALSE + ) + gpl <- gpl + ggraph::scale_edge_alpha(range = c(0.1, 1)) + gpl <- gpl + ggraph::scale_edge_colour_gradientn( + colours = RColorBrewer::brewer.pal(9, "Reds"), + name = "Value" + ) + + ## node + gpl <- gpl + ggraph::geom_node_point( + ggplot2::aes(colour = name), # nolint: object_usage_linter. + size = 10 + ) + gpl <- gpl + ggplot2::scale_fill_gradientn(colours = viridis::turbo(100)) + gpl <- gpl + ggraph::geom_node_text( + ggplot2::aes(label = name), # nolint: object_usage_linter. + repel = TRUE + ) + + ## theme + gpl <- gpl + ggplot2::theme_bw() + ggplot2::theme( + panel.grid = ggplot2::element_blank(), + panel.border = ggplot2::element_blank(), + axis.title = ggplot2::element_blank(), + axis.text = ggplot2::element_blank(), + axis.ticks = ggplot2::element_blank() + ) + gpl + + # return or save + return(GiottoVisuals::plot_output_handler( + gobject = gobject, + plot_object = gpl, + save_plot = save_plot, + return_plot = return_plot, + show_plot = show_plot, + default_save_name = default_save_name, + save_param = save_param, + else_return = NULL + )) +} + +#' @title plotCTCompositionInNicheCluster +#' @name plotCTCompositionInNicheCluster +#' @description plot cell type composition within each niche cluster +#' @param cell_type the cell type column name in the metadata +#' @inheritParams data_access_params +#' @inheritParams plot_output_params +#' @param spat_unit name of spatial unit niche stored cluster features +#' @param feat_type name of the feature type stored niche cluster connectivities +#' @param values name of the expression matrix stored connectivity values +#' @details This function plots the niche cluster connectivity matrix +#' @export +plotCTCompositionInNicheCluster <- function( # nolint: object_name_linter. + gobject, + cell_type, + values = "prob", + spat_unit = "cell", + feat_type = "niche cluster", + show_plot = NULL, + return_plot = NULL, + save_plot = NULL, + save_param = list(), + theme_param = list(), + default_save_name = "CellTypeCompositionInNicheCluster") { + # Get the cell type composition within each niche cluster + ## extract the cell-level niche cluster probability matrix + exp <- getExpression( + gobject = gobject, + values = values, + spat_unit = spat_unit, + feat_type = feat_type, + output = "exprObj" + ) + prob_df <- as.data.frame(t(as.matrix(exp@exprMat))) + prob_df$cell_ID <- rownames(prob_df) + ## combine the cell type and niche cluster probability matrix + combined_df <- merge( + as.data.frame(pDataDT(gobject, feat_type = feat_type))[, c( + "cell_ID", + cell_type + )], + prob_df, + by = "cell_ID" + ) + + # Calculate the normalized cell type composition within each niche cluster + cell_type_counts_df <- combined_df %>% + tidyr::pivot_longer( + cols = dplyr::starts_with("NicheCluster_"), + names_to = "Cluster", + values_to = "Probability" + ) %>% + dplyr::group_by( + !!rlang::sym(cell_type), + Cluster # nolint: object_usage_linter. + ) %>% + dplyr::summarise(Sum = sum(Probability, # nolint: object_usage_linter. + na.rm = TRUE + )) %>% + tidyr::spread(key = "Cluster", value = "Sum", fill = 0) + cell_type_counts_df <- as.data.frame(cell_type_counts_df) + rownames(cell_type_counts_df) <- cell_type_counts_df[[cell_type]] + cell_type_counts_df[[cell_type]] <- NULL + normalized_df <- as.data.frame(t( + t(cell_type_counts_df) / colSums(cell_type_counts_df) + )) + + + # Reshape the data frame into long format + normalized_df[[cell_type]] <- rownames(normalized_df) + df_long <- normalized_df %>% + tidyr::pivot_longer( + cols = -!!rlang::sym(cell_type), # nolint: object_usage_linter. + names_to = "Cluster", + values_to = "Composition" + ) + + # Create the heatmap using ggplot2 + pl <- ggplot(df_long, aes( + x = !!rlang::sym(cell_type), # nolint: object_usage_linter. + y = Cluster, # nolint: object_usage_linter. + fill = Composition # nolint: object_usage_linter. + )) + + geom_tile() + + viridis::scale_fill_viridis(option = "inferno", limits = c(0, 1)) + + theme_minimal() + + labs( + title = "Normalized cell type compositions within each niche cluster", + x = "Cell_Type", + y = "Cluster" + ) + + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + + # return or save + return(GiottoVisuals::plot_output_handler( + gobject = gobject, + plot_object = pl, + save_plot = save_plot, + return_plot = return_plot, + show_plot = show_plot, + default_save_name = default_save_name, + save_param = save_param, + else_return = NULL + )) +} + + +#' @title plotCellTypeNTScore +#' @name plotCellTypeNTScore +#' @description plot NTScore by cell type +#' @param cell_type the cell type column name in the metadata +#' @inheritParams data_access_params +#' @inheritParams plot_output_params +#' @export +plotCellTypeNTScore <- function(gobject, # nolint: object_name_linter. + cell_type, + values = "NTScore", + spat_unit = "cell", + feat_type = "niche cluster", + show_plot = NULL, + return_plot = NULL, + save_plot = NULL, + save_param = list(), + theme_param = list(), + default_save_name = "CellTypeNTScore") { + # Get the cell type composition within each niche cluster + data_df <- pDataDT( + gobject = gobject, + spat_unit = spat_unit, + feat_type = feat_type + ) + avg_scores <- data_df %>% + dplyr::group_by(!!rlang::sym(cell_type)) %>% # nolint: object_usage_linter. + dplyr::summarise(Avg_NTScore = mean(NTScore)) # nolint: object_usage_linter. + data_df[[cell_type]] <- factor(data_df[[cell_type]], + levels = avg_scores[[cell_type]][order(avg_scores$Avg_NTScore)] + ) + + pl <- ggplot(data_df, aes( + x = NTScore, # nolint: object_usage_linter. + y = !!rlang::sym(cell_type), + fill = !!rlang::sym(cell_type) + )) + + geom_violin() + + theme_minimal() + + labs( + title = "Violin Plot of NTScore by Cell Type", + x = "NTScore", + y = "Cell Type" + ) + + ggplot2::theme(axis.text.x = element_text(angle = 45, hjust = 1)) + + # return or save + return(GiottoVisuals::plot_output_handler( + gobject = gobject, + plot_object = pl, + save_plot = save_plot, + return_plot = return_plot, + show_plot = show_plot, + default_save_name = default_save_name, + save_param = save_param, + else_return = NULL + )) +} diff --git a/R/auxiliary_giotto.R b/R/auxiliary_giotto.R index 82a65fd15..de16b2c08 100644 --- a/R/auxiliary_giotto.R +++ b/R/auxiliary_giotto.R @@ -47,10 +47,13 @@ # mymatrix = log(mymatrix + offset)/log(base) } else if (methods::is(mymatrix, "dgCMatrix")) { mymatrix@x <- log(mymatrix@x + offset) / log(base) - # replace with sparseMatrixStats + # replace with sparseMatrixStats } else if (methods::is(mymatrix, "Matrix")) { mymatrix@x <- log(mymatrix@x + offset) / log(base) - } else { + } else if(methods::is(mymatrix, 'dbMatrix')) { + mymatrix[] <- dplyr::mutate(mymatrix[], x = x + offset) # workaround for lack of @x slot + mymatrix <- log(mymatrix)/log(base) + } else { mymatrix <- log(as.matrix(mymatrix) + offset) / log(base) } @@ -732,7 +735,9 @@ filterGiotto <- function( description = "_filter" ) - return(newGiottoObject) + return(newGiottoObject) + + } @@ -740,6 +745,46 @@ filterGiotto <- function( ### normalization #### +#' @title compute_dbMatrix +#' @description saves dbMatrix to db if global option is set +#' @details +#' Set \code{options(giotto.dbmatrix_compute = FALSE)} if saving dbMatrix +#' after each step of normalization workflow is not desired. +#' @keywords internal +.compute_dbMatrix <- function(dbMatrix, name, verbose = TRUE) { + # input validation + if(!inherits(dbMatrix, 'dbMatrix')) { + stop('dbMatrix must be of class dbMatrix') + } + + if(!is.character(name)) { + stop('name must be a character') + } + + # TODO: update with dbData generic + con = dbMatrix:::get_con(dbMatrix) + + # overwrite table by default + if(name %in% DBI::dbListTables(con)) { + DBI::dbRemoveTable(con, name) + } + + if(verbose){ + msg <- glue::glue('Computing {name} expression matrix on disk...') + cat(msg) + } + + dbMatrix[] |> + dplyr::compute(temporary=F, name = name) + + # TODO: update below with proper setters from dbMatrix + dbMatrix[] <- dplyr::tbl(con, name) # reassign to computed mat + dbMatrix@name <- name + + if(verbose) cat('done \n') + + return(dbMatrix) +} #' @title RNA standard normalization #' @name .rna_standard_normalization @@ -776,9 +821,6 @@ filterGiotto <- function( feat_names <- rownames(raw_expr[]) col_names <- colnames(raw_expr[]) - - - ## 1. library size normalize if (library_size_norm == TRUE) { norm_expr <- .lib_norm_giotto( @@ -853,6 +895,16 @@ filterGiotto <- function( } ## 5. create and set exprObj + # Save dbMatrix to db + compute_mat <- getOption("giotto.dbmatrix_compute", default = FALSE) + if(compute_mat && !is.null(norm_expr)){ + norm_expr <- .compute_dbMatrix( + dbMatrix = norm_expr, + name = 'normalized', + verbose = verbose + ) + } + norm_expr <- create_expr_obj( name = "normalized", exprMat = norm_expr, @@ -861,6 +913,15 @@ filterGiotto <- function( provenance = provenance, misc = NULL ) + + # Save dbMatrix to db + if(compute_mat && !is.null(norm_scaled_expr)){ + norm_scaled_expr = .compute_dbMatrix( + dbMatrix = norm_scaled_expr, + name = 'scaled', + verbose = verbose + ) + } norm_scaled_expr <- create_expr_obj( name = "scaled", diff --git a/R/python_hmrf.R b/R/python_hmrf.R index 76bb4a503..6b0b597d0 100644 --- a/R/python_hmrf.R +++ b/R/python_hmrf.R @@ -135,8 +135,8 @@ doHMRF <- function(gobject, } if (!"matrix" %in% class(expr_values)) { - warning("this matrix will be converted to a dense and memory intensive - base matrix ...") + warning("\n this matrix will be converted to a dense and memory intensive + base matrix ...\n") expr_values <- as.matrix(expr_values) } @@ -145,7 +145,7 @@ doHMRF <- function(gobject, # overwrite if exists if (file.exists(expression_file) & overwrite_output == TRUE) { - message("expression_matrix.txt already exists at this location, will be + message("\n expression_matrix.txt already exists at this location, will be overwritten") data.table::fwrite( data.table::as.data.table(expr_values, keep.rownames = "gene"), @@ -153,7 +153,7 @@ doHMRF <- function(gobject, row.names = FALSE, sep = " " ) } else if (file.exists(expression_file) & overwrite_output == FALSE) { - message("expression_matrix.txt already exists at this location, will be + message("\n expression_matrix.txt already exists at this location, will be used again") } else { data.table::fwrite( @@ -177,7 +177,7 @@ doHMRF <- function(gobject, ] } else { if (is.null(spatial_genes)) { - stop("you need to provide a vector of spatial genes (~500)") + stop("\n you need to provide a vector of spatial genes (~500)") } spatial_genes_detected <- spatial_genes[ spatial_genes %in% rownames(expr_values) @@ -187,14 +187,14 @@ doHMRF <- function(gobject, # overwrite if exists if (file.exists(spatial_genes_file) & overwrite_output == TRUE) { - message("spatial_genes.txt already exists at this location, will be + message("\n spatial_genes.txt already exists at this location, will be overwritten") write.table(spatial_genes_detected, file = spatial_genes_file, quote = FALSE, col.names = FALSE, row.names = FALSE ) } else if (file.exists(spatial_genes_file) & overwrite_output == FALSE) { - message("spatial_genes.txt already exists at this location, will be + message("\n spatial_genes.txt already exists at this location, will be used again") } else { write.table(spatial_genes_detected, @@ -217,14 +217,14 @@ doHMRF <- function(gobject, spatial_network_file <- paste0(output_folder, "/", "spatial_network.txt") if (file.exists(spatial_network_file) & overwrite_output == TRUE) { - message("spatial_network.txt already exists at this location, will be + message("\n spatial_network.txt already exists at this location, will be overwritten") write.table(spatial_network, file = spatial_network_file, row.names = FALSE, col.names = FALSE, quote = FALSE, sep = "\t" ) } else if (file.exists(spatial_network_file) & overwrite_output == FALSE) { - message("spatial_network.txt already exists at this location, will be + message("\n spatial_network.txt already exists at this location, will be used again") } else { write.table(spatial_network, @@ -258,14 +258,14 @@ doHMRF <- function(gobject, ) if (file.exists(spatial_location_file) & overwrite_output == TRUE) { - message("spatial_cell_locations.txt already exists at this location, + message("\n spatial_cell_locations.txt already exists at this location, will be overwritten") write.table(spatial_location, file = spatial_location_file, row.names = FALSE, col.names = FALSE, quote = FALSE, sep = "\t" ) } else if (file.exists(spatial_location_file)) { - message("spatial_cell_locations.txt already exists at this location, + message("\n spatial_cell_locations.txt already exists at this location, will be used again") } else { write.table(spatial_location, @@ -370,7 +370,7 @@ loadHMRF <- function( python_path_used) { output_data <- paste0(output_folder_used, "/", "result.spatial.zscore") if (!file.exists(output_data)) { - stop("doHMRF was not run in this output directory") + stop("\n doHMRF was not run in this output directory") } # check if it indeed exists @@ -411,7 +411,7 @@ viewHMRFresults <- function( third_dim = FALSE, ...) { if (!"HMRFoutput" %in% class(HMRFoutput)) { - stop("HMRFoutput needs to be output from doHMRFextend") + stop("\n HMRFoutput needs to be output from doHMRFextend") } ## reader.py and get_result.py paths @@ -497,7 +497,7 @@ writeHMRFresults <- function( betas_to_view = NULL, print_command = FALSE) { if (!"HMRFoutput" %in% class(HMRFoutput)) { - stop("HMRFoutput needs to be output from doHMRFextend") + stop("\n HMRFoutput needs to be output from doHMRFextend") } ## reader.py and get_result.py paths @@ -514,7 +514,7 @@ writeHMRFresults <- function( # k-values if (is.null(k)) { - stop("you need to select a k that was used with doHMRFextend") + stop("\n you need to select a k that was used with doHMRFextend") } k <- HMRFoutput$k @@ -609,7 +609,7 @@ addHMRF <- function( betas_to_add = NULL, hmrf_name = NULL) { if (!"HMRFoutput" %in% class(HMRFoutput)) { - stop("HMRFoutput needs to be output from doHMRFextend") + stop("\n HMRFoutput needs to be output from doHMRFextend") } # Set feat_type and spat_unit @@ -640,7 +640,7 @@ addHMRF <- function( # k-values if (is.null(k)) { - stop("you need to select a k that was used with doHMRFextend") + stop("\n you need to select a k that was used with doHMRFextend") } k <- HMRFoutput$k @@ -743,7 +743,7 @@ viewHMRFresults2D <- function( ) if (!"HMRFoutput" %in% class(HMRFoutput)) { - stop("HMRFoutput needs to be output from doHMRFextend") + stop("\n HMRFoutput needs to be output from doHMRFextend") } ## reader.py and get_result.py paths @@ -760,7 +760,7 @@ viewHMRFresults2D <- function( # k-values if (is.null(k)) { - stop("you need to select a k that was used with doHMRFextend") + stop("\n please select a valid k used with doHMRFextend") } k <- HMRFoutput$k @@ -853,7 +853,7 @@ viewHMRFresults3D <- function( betas_to_view = NULL, ...) { if (!"HMRFoutput" %in% class(HMRFoutput)) { - stop("HMRFoutput needs to be output from doHMRFextend") + stop("\n HMRFoutput needs to be output from doHMRFextend") } spat_unit <- set_default_spat_unit( @@ -877,7 +877,7 @@ viewHMRFresults3D <- function( # k-values if (is.null(k)) { - stop("you need to select a k that was used with doHMRFextend") + stop("\n please select a valid k used with doHMRFextend") } k <- HMRFoutput$k @@ -1118,9 +1118,9 @@ filterSpatialGenes <- function(gobject, spat_unit = NULL, feat_type = NULL, spat xPt <- length(y0s) - xPt y_cutoff <- y0[xPt] # The y-value at this x point. This is our y_cutoff. gx_sorted <- head(gx_sorted, n = xPt) - message("Elbow method chosen to determine number of spatial genes.") + message("\n Elbow method chosen to determine number of spatial genes.") cat(paste0( - "Elbow point determined to be at x=", xPt, " genes", + "\n Elbow point determined to be at x=", xPt, " genes", " y=", y_cutoff )) } @@ -1164,7 +1164,7 @@ chooseAvailableSpatialGenes <- function(gobject, spat_unit = NULL, feat_type = N } else if (eval3 == TRUE) { return("silhouetteRank") } else { - stop(paste0("No available spatial genes. Please run binSpect or + stop(paste0("\n No available spatial genes. Please run binSpect or silhouetteRank\n"), call. = FALSE) } } @@ -1223,14 +1223,14 @@ checkAndFixSpatialGenes <- function( } else if (use_spatial_genes == "binSpect") { eval1 <- "binSpect.pval" %in% names(gx) if (eval1 == FALSE) { - stop(paste0("use_spatial_genes is set to binSpect, but it has + stop(paste0("\n use_spatial_genes is set to binSpect, but it has not been run yet. Run binSpect first."), call. = FALSE ) } return(use_spatial_genes) } else { - stop(paste0("use_spatial_genes is set to one that is not supported."), + stop(paste0("\n use_spatial_genes is set to one that is not supported."), call. = FALSE ) } @@ -1358,7 +1358,7 @@ initHMRF_V2 <- factor_step = 1.05, python_path = NULL) { wrap_msg( - "If used in published research, please cite: + "\n If used in published research, please cite: Q Zhu, S Shah, R Dries, L Cai, GC Yuan. 'Identification of spatially associated subpopulations by combining scRNAseq and sequential fluorescence in situ hybridization data' @@ -1406,24 +1406,24 @@ initHMRF_V2 <- if (use_neighborhood_composition) { if (is.null(spatial_network_name_for_neighborhood)) { - stop("spatial network is required to define neighborhood, + stop("\n spatial network is required to define neighborhood, set with \'spatial_network_name_for_neighborhood\' \n", call. = FALSE ) } else if (is.null(metadata_to_use)) { - stop("please specify the cluster in meta data, set with + stop("\n please specify the cluster in meta data, set with \'metadata_to_use\' \n", call. = FALSE ) } else if (is.null(cx[[metadata_to_use]])) { - stop("please provide a valid index in meta data, set with + stop("\n please provide a valid index in meta data, set with \'metadata_to_use\'", call. = FALSE ) } cat(paste0( - "use spatial network composition of \'", + "\n use spatial network composition of \'", metadata_to_use, "\' for domain clustering" )) @@ -1471,12 +1471,12 @@ initHMRF_V2 <- rownames(y0) <- cell_ID_enrich cat(paste0( - "Spatial enrichment result: \'", + "\n Spatial enrichment result: \'", existing_spatial_enrichm_to_use, "\' is used." )) if (sum(!rownames(y0) %in% cx$cell_ID) > 0) { - stop("Rownames of selected spatial enrichment result do not + stop("\n Rownames of selected spatial enrichment result do not match to (a subset of) Cell IDs, please fix them.", call. = FALSE ) @@ -1526,7 +1526,7 @@ initHMRF_V2 <- if (!"binSpect.pval" %in% names(gx) && !"silhouetteRank.score" %in% names(gx) && !"silhouetteRankTest.pval" %in% names(gx)) { - stop(paste0("Giotto spatial gene detection has not been run. + stop(paste0("\n Giotto spatial gene detection has not been run. Please run spatial gene detection first: binSpect, silhouetteRank."), call. = FALSE @@ -1534,8 +1534,8 @@ initHMRF_V2 <- } if (!is.null(user_gene_list)) { - message("User supplied gene list detected.") - message("Checking user gene list is spatial...") + message("\n User supplied gene list detected.") + message("\n Checking user gene list is spatial...") use_spatial_genes <- chooseAvailableSpatialGenes(gobject) filtered <- filterSpatialGenes( @@ -1549,26 +1549,26 @@ initHMRF_V2 <- ) if (filtered$num_genes_removed > 0) { cat(paste0( - "Removed ", filtered$num_genes_removed, + "\n Removed ", filtered$num_genes_removed, " from user's input gene list due to being absent or non-spatial genes." )) cat(paste0( - "Kept ", length(filtered$genes), + "\n Kept ", length(filtered$genes), " spatial genes for next step" )) } spatial_genes <- filtered$genes if (length(spatial_genes) == 0) { - stop("No genes are remaining to do HMRF. Please give a + stop("\n No genes are remaining to do HMRF. Please give a larger gene list.", call. = FALSE ) } } else { cat(paste0( - "Choosing spatial genes from the results of ", + "\n Choosing spatial genes from the results of ", use_spatial_genes )) use_spatial_genes <- checkAndFixSpatialGenes( @@ -1589,7 +1589,7 @@ initHMRF_V2 <- method = filter_method ) cat(paste0( - "Kept ", length(filtered$genes), + "\n Kept ", length(filtered$genes), " top spatial genes for next step" )) spatial_genes <- filtered$genes @@ -1603,7 +1603,7 @@ initHMRF_V2 <- ] y0 <- (pc.expr[, use_pca_dim]) } else { - message("Computing spatial coexpression modules...") + message("\n Computing spatial coexpression modules...") spat_cor_netw_DT <- detectSpatialCorFeats( gobject = gobject, feat_type = feat_type, @@ -1623,7 +1623,7 @@ initHMRF_V2 <- name = "spat_netw_clus", k = 20 ) - message("Sampling spatial genes from coexpression + message("\n Sampling spatial genes from coexpression modules...") sample_genes <- sampling_sp_genes( spat_cor_netw_DT$cor_clusters$spat_netw_clus, @@ -1633,15 +1633,15 @@ initHMRF_V2 <- ) spatial_genes_selected <- sample_genes$union_genes cat(paste0( - "Sampled ", length(spatial_genes_selected), + "\n Sampled ", length(spatial_genes_selected), " genes." )) } else { spatial_genes_selected <- spatial_genes } cat(paste0( - "Will use ", length(spatial_genes_selected), - "spatial genes for initialization of HMRF." + "\n Will use ", length(spatial_genes_selected), + " spatial genes for initialization of HMRF." )) expr_values <- expr_values[spatial_genes_selected, ] } else { @@ -1650,7 +1650,7 @@ initHMRF_V2 <- ) if (k.sp < cluster_metagene) { cat(paste0( - "construct ", k.sp, + "\n construct ", k.sp, " coexpression modules due to limited gene size..." )) } @@ -1663,7 +1663,7 @@ initHMRF_V2 <- show_top_feats = 1 ) - cat(paste0("Collecting top spatial genes and calculating + cat(paste0("\n Collecting top spatial genes and calculating metagenes from ", k.sp, " coexpression modules...")) top_per_module <- cluster_genes_DT[ @@ -1742,7 +1742,7 @@ initHMRF_V2 <- edge_ind <- edge_ind + 1 } } - message("Parsing neighborhood graph...") + message("\n Parsing neighborhood graph...") pp <- tidygraph::tbl_graph( edges = as.data.frame(edgelist), directed = FALSE ) @@ -1758,11 +1758,11 @@ initHMRF_V2 <- cl.method <- tolower(cl.method) if (!cl.method %in% c("km", "leiden", "louvain")) { cl.method <- "km" - message("clustering method not specified, use kmeans as default...") + message("\n clustering method not specified, use kmeans as default...") } if (cl.method == "km") { - message("Kmeans initialization...") + message("\n Kmeans initialization...") kk <- smfishHmrf::smfishHmrf.generate.centroid( y = y, par_k = k, par_seed = hmrf_seed, nstart = nstart @@ -1778,7 +1778,7 @@ initHMRF_V2 <- gobject@dimension_reduction$cells$spatial$spatial_feat$coordinates <- y gobject <- createNearestNetwork( - gobject = gobject, + gobject = gobject, spat_unit = spat_unit, feat_type = feat_type, dim_reduction_to_use = "spatial", dim_reduction_name = "spatial_feat", dimensions_to_use = seq_len(ncol(y)), @@ -1786,9 +1786,9 @@ initHMRF_V2 <- ) if (cl.method == "leiden") { - message("Leiden clustering initialization...") + message("\n Leiden clustering initialization...") leiden.cl <- doLeidenCluster( - gobject = gobject, + gobject = gobject, spat_unit = spat_unit, feat_type = feat_type, nn_network_to_use = "sNN", network_name = "sNN.initHMRF", set_seed = hmrf_seed, @@ -1801,9 +1801,9 @@ initHMRF_V2 <- ] mu <- aggregate(y, by = list(cl.match), FUN = mean) } else if (cl.method == "louvain") { - message("Louvain clustering initialization...") + message("\n Louvain clustering initialization...") louvain.cl <- doLouvainCluster( - gobject = gobject, + gobject = gobject, spat_unit = spat_unit, feat_type = feat_type, nn_network_to_use = "sNN", network_name = "sNN.initHMRF", set_seed = hmrf_seed, @@ -1836,7 +1836,7 @@ initHMRF_V2 <- ) damp[i] <- ifelse(is.null(di), 0, di) } - message("Done") + message("\n Done") list( y = y, nei = nei, numnei = numnei, blocks = blocks, damp = damp, mu = mu, sigma = sigma, k = k, genes = colnames(y), @@ -1885,39 +1885,39 @@ initHMRF_V2 <- #' @export doHMRF_V2 <- function(HMRF_init_obj, betas = NULL) { message( - "If used in published research, please cite: + "\n If used in published research, please cite: Q Zhu, S Shah, R Dries, L Cai, GC Yuan. 'Identification of spatially associated subpopulations by combining scRNAseq and sequential fluorescence in situ hybridization data' Nature biotechnology 36 (12), 1183-1190. 2018" ) - message("Please find more explanation and instruction of the HMRF function + message("\n Please find more explanation and instruction of the HMRF function on \n https://bitbucket.org/qzhudfci/smfishhmrf-r/src/master/TRANSITION.md") if (!"y" %in% names(HMRF_init_obj)) { - stop("expression matrix 'y' not in the intialization object") + stop("\n expression matrix 'y' not in the intialization object") } if (!"nei" %in% names(HMRF_init_obj)) { - stop("neighbor matrix 'nei' not in the intialization object") + stop("\n neighbor matrix 'nei' not in the intialization object") } if (!"numnei" %in% names(HMRF_init_obj)) { - stop("number of neighbors 'numnei' not in the intialization object") + stop("\n number of neighbors 'numnei' not in the intialization object") } if (!"blocks" %in% names(HMRF_init_obj)) { - stop("iteration groups 'blocks' not in the intialization object") + stop("\n iteration groups 'blocks' not in the intialization object") } if (!"damp" %in% names(HMRF_init_obj)) { - stop("dampen factors 'damp' not in the intialization object") + stop("\n dampen factors 'damp' not in the intialization object") } if (!"mu" %in% names(HMRF_init_obj)) { - stop("initial mean vector 'mu' not in the intialization object") + stop("\n initial mean vector 'mu' not in the intialization object") } if (!"sigma" %in% names(HMRF_init_obj)) { - stop("initial covariance matrix 'sigma' not in the intialization + stop("\n initial covariance matrix 'sigma' not in the intialization object") } if (!"k" %in% names(HMRF_init_obj)) { - stop("cluster number 'k' not in the intialization object") + stop("\n cluster number 'k' not in the intialization object") } if (!"spat_unit" %in% names(HMRF_init_obj)) { HMRF_init_obj[["spat_unit"]] <- NULL @@ -1939,10 +1939,10 @@ doHMRF_V2 <- function(HMRF_init_obj, betas = NULL) { if (is.null(betas)) { beta_seq <- max(ceiling(ncol(y) / 10), 2) - cat(paste0("Default value beta = ", beta_seq, " is used...")) + cat(paste0("\n Default value beta = ", beta_seq, " is used...")) } else if (length(betas) != 3 || (sum(betas[seq_len(3)] < 0) > 0)) { stop(wrap_txt( - "please provide betas as a vector of 3 non-negative numbers + "\n please provide betas as a vector of 3 non-negative numbers (initial value, increment, total iteration number)", errWidth = TRUE )) @@ -2008,7 +2008,7 @@ doHMRF_V2 <- function(HMRF_init_obj, betas = NULL) { #' @export addHMRF_V2 <- function(gobject, HMRFoutput, name = "hmrf") { if (!"HMRFoutput" %in% class(HMRFoutput)) { - stop("HMRFoutput needs to be output from doHMRF_V2()") + stop("\n HMRFoutput needs to be output from doHMRF_V2()") } if (!"spat_unit" %in% names(HMRFoutput)) { HMRFoutput[["spat_unit"]] <- NULL @@ -2033,19 +2033,19 @@ addHMRF_V2 <- function(gobject, HMRFoutput, name = "hmrf") { gobject = gobject, spat_unit = spat_unit, feat_type = feat_type, - column_cell_ID = "cell_ID", - # new_metadata = HMRFoutput[[i]]$class[match( - # ordered_cell_IDs, names(HMRFoutput[[i]]$class))], - new_metadata = HMRFoutput[[i]]$prob[ordered_cell_IDs, ], + new_metadata = HMRFoutput[[i]]$class[match( + ordered_cell_IDs, + rownames(HMRFoutput[[i]]$prob))], vector_name = paste(name, names(HMRFoutput)[i]) + # ,column_cell_ID = 'cell_ID', # by_column = TRUE ) } return(gobject) } - - + + #' @title viewHMRFresults_V2 #' @name viewHMRFresults_V2 #' @description function to view HMRF results with multiple betas diff --git a/man/getONTraCv1Input.Rd b/man/getONTraCv1Input.Rd new file mode 100644 index 000000000..784a77678 --- /dev/null +++ b/man/getONTraCv1Input.Rd @@ -0,0 +1,45 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{getONTraCv1Input} +\alias{getONTraCv1Input} +\title{getONTraCv1Input} +\usage{ +getONTraCv1Input( + gobject, + cell_type, + output_path = getwd(), + spat_unit = NULL, + feat_type = NULL, + verbose = TRUE +) +} +\arguments{ +\item{gobject}{giotto object} + +\item{cell_type}{the cell type column name in the metadata} + +\item{output_path}{the path to save the output file} + +\item{spat_unit}{spatial unit (e.g. "cell")} + +\item{feat_type}{feature type (e.g. "rna", "dna", "protein")} + +\item{verbose}{be verbose} +} +\value{ +data.table with columns: Cell_ID, Sample, x, y, Cell_Type +} +\description{ +generate the input data for ONTraC v1 +} +\details{ +This function generate the input data for ONTraC v1 +} +\examples{ +g <- GiottoData::loadGiottoMini("visium") + +getONTraCv1Input( + gobject = g, + cell_type = "custom_leiden" +) +} diff --git a/man/loadOntraCResults.Rd b/man/loadOntraCResults.Rd new file mode 100644 index 000000000..2eda6902f --- /dev/null +++ b/man/loadOntraCResults.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{loadOntraCResults} +\alias{loadOntraCResults} +\title{loadOntraCResults} +\usage{ +loadOntraCResults(gobject, ontrac_results_dir = getwd()) +} +\arguments{ +\item{gobject}{giotto object} + +\item{ontrac_results_dir}{the directory where the ONTraC results are saved} +} +\value{ +gobject with ONTraC results +} +\description{ +load ONTraC results +} +\details{ +This function loads the ONTraC results into the giotto object. +} diff --git a/man/load_cell_NT_score.Rd b/man/load_cell_NT_score.Rd new file mode 100644 index 000000000..4a8b5d87b --- /dev/null +++ b/man/load_cell_NT_score.Rd @@ -0,0 +1,22 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{load_cell_NT_score} +\alias{load_cell_NT_score} +\title{load_cell_NT_score} +\usage{ +load_cell_NT_score(gobject, ontrac_results_dir = getwd()) +} +\arguments{ +\item{gobject}{giotto object} + +\item{ontrac_results_dir}{the directory where the ONTraC results are saved} +} +\value{ +gobject with cell-level NT score +} +\description{ +load cell-level NT score +} +\details{ +This function loads the ONTraC outputed cell-level NT score +} diff --git a/man/load_cell_bin_niche_cluster.Rd b/man/load_cell_bin_niche_cluster.Rd new file mode 100644 index 000000000..4aafb4cb5 --- /dev/null +++ b/man/load_cell_bin_niche_cluster.Rd @@ -0,0 +1,23 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{load_cell_bin_niche_cluster} +\alias{load_cell_bin_niche_cluster} +\title{load_cell_bin_niche_cluster} +\usage{ +load_cell_bin_niche_cluster(gobject, ontrac_results_dir = getwd()) +} +\arguments{ +\item{gobject}{giotto object} + +\item{ontrac_results_dir}{the directory where the ONTraC results are saved} +} +\value{ +gobject with cell-level binarized niche cluster +} +\description{ +load cell-level binarized niche cluster +} +\details{ +This function loads the ONTraC outputed cell-level binarized niche +cluster into the giotto object. +} diff --git a/man/load_cell_niche_cluster_prob.Rd b/man/load_cell_niche_cluster_prob.Rd new file mode 100644 index 000000000..2bcb59346 --- /dev/null +++ b/man/load_cell_niche_cluster_prob.Rd @@ -0,0 +1,35 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{load_cell_niche_cluster_prob} +\alias{load_cell_niche_cluster_prob} +\title{load_cell_niche_cluster_prob} +\usage{ +load_cell_niche_cluster_prob( + gobject, + ontrac_results_dir = getwd(), + spat_unit = "cell", + feat_type = "niche cluster", + name = "prob" +) +} +\arguments{ +\item{gobject}{giotto object} + +\item{ontrac_results_dir}{the directory where the ONTraC results are saved} + +\item{spat_unit}{spatial unit (e.g. "cell")} + +\item{feat_type}{feature type (e.g. "rna", "dna", "protein")} + +\item{name}{name for the probability matrix} +} +\value{ +gobject with cell-niche cluster probability matrix +} +\description{ +load cell-niche cluster probability +} +\details{ +This function loads the ONTraC outputed cell-niche cluster +probability as an exprObj into the giotto object. +} diff --git a/man/load_nc_connectivity.Rd b/man/load_nc_connectivity.Rd new file mode 100644 index 000000000..ae96d3677 --- /dev/null +++ b/man/load_nc_connectivity.Rd @@ -0,0 +1,35 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{load_nc_connectivity} +\alias{load_nc_connectivity} +\title{load_nc_connectivity} +\usage{ +load_nc_connectivity( + gobject, + ontrac_results_dir = getwd(), + spat_unit = "niche cluster", + feat_type = "connectivity", + name = "normalized" +) +} +\arguments{ +\item{gobject}{giotto object} + +\item{ontrac_results_dir}{the directory where the ONTraC results are saved} + +\item{spat_unit}{spatial unit (e.g. "cell")} + +\item{feat_type}{feature type (e.g. "rna", "dna", "protein")} + +\item{name}{name for the connectivity matrix} +} +\value{ +gobject with niche cluster connectivity matrix +} +\description{ +load niche cluster connectivity +} +\details{ +This function loads the ONTraC outputed niche cluster connectivity +matrix as an exprObj into the giotto object. +} diff --git a/man/plotCTCompositionInNicheCluster.Rd b/man/plotCTCompositionInNicheCluster.Rd new file mode 100644 index 000000000..24c9a7109 --- /dev/null +++ b/man/plotCTCompositionInNicheCluster.Rd @@ -0,0 +1,47 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{plotCTCompositionInNicheCluster} +\alias{plotCTCompositionInNicheCluster} +\title{plotCTCompositionInNicheCluster} +\usage{ +plotCTCompositionInNicheCluster( + gobject, + cell_type, + values = "prob", + spat_unit = "cell", + feat_type = "niche cluster", + show_plot = NULL, + return_plot = NULL, + save_plot = NULL, + save_param = list(), + theme_param = list(), + default_save_name = "CellTypeCompositionInNicheCluster" +) +} +\arguments{ +\item{gobject}{giotto object} + +\item{cell_type}{the cell type column name in the metadata} + +\item{values}{name of the expression matrix stored connectivity values} + +\item{spat_unit}{name of spatial unit niche stored cluster features} + +\item{feat_type}{name of the feature type stored niche cluster connectivities} + +\item{show_plot}{logical. show plot} + +\item{return_plot}{logical. return ggplot object} + +\item{save_plot}{logical. save the plot} + +\item{save_param}{list of saving parameters, see \code{\link{showSaveParameters}}} + +\item{default_save_name}{default save name for saving, don't change, change save_name in save_param} +} +\description{ +plot cell type composition within each niche cluster +} +\details{ +This function plots the niche cluster connectivity matrix +} diff --git a/man/plotCellTypeNTScore.Rd b/man/plotCellTypeNTScore.Rd new file mode 100644 index 000000000..c24a73bd9 --- /dev/null +++ b/man/plotCellTypeNTScore.Rd @@ -0,0 +1,42 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{plotCellTypeNTScore} +\alias{plotCellTypeNTScore} +\title{plotCellTypeNTScore} +\usage{ +plotCellTypeNTScore( + gobject, + cell_type, + values = "NTScore", + spat_unit = "cell", + feat_type = "rna", + show_plot = NULL, + return_plot = NULL, + save_plot = NULL, + save_param = list(), + theme_param = list(), + default_save_name = "CellTypeNTScore" +) +} +\arguments{ +\item{gobject}{giotto object} + +\item{cell_type}{the cell type column name in the metadata} + +\item{spat_unit}{spatial unit (e.g. "cell")} + +\item{feat_type}{feature type (e.g. "rna", "dna", "protein")} + +\item{show_plot}{logical. show plot} + +\item{return_plot}{logical. return ggplot object} + +\item{save_plot}{logical. save the plot} + +\item{save_param}{list of saving parameters, see \code{\link{showSaveParameters}}} + +\item{default_save_name}{default save name for saving, don't change, change save_name in save_param} +} +\description{ +plot NTScore by cell type +} diff --git a/man/plotNicheClusterConnectivity.Rd b/man/plotNicheClusterConnectivity.Rd new file mode 100644 index 000000000..b6f236496 --- /dev/null +++ b/man/plotNicheClusterConnectivity.Rd @@ -0,0 +1,44 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ONTraC_wrapper.R +\name{plotNicheClusterConnectivity} +\alias{plotNicheClusterConnectivity} +\title{plotNicheClusterConnectivity} +\usage{ +plotNicheClusterConnectivity( + gobject, + spat_unit = "niche cluster", + feat_type = "connectivity", + values = "normalized", + show_plot = NULL, + return_plot = NULL, + save_plot = NULL, + save_param = list(), + theme_param = list(), + default_save_name = "NicheClusterConnectivity" +) +} +\arguments{ +\item{gobject}{giotto object} + +\item{spat_unit}{name of spatial unit niche stored cluster features} + +\item{feat_type}{name of the feature type stored niche cluster connectivities} + +\item{values}{name of the expression matrix stored connectivity values} + +\item{show_plot}{logical. show plot} + +\item{return_plot}{logical. return ggplot object} + +\item{save_plot}{logical. save the plot} + +\item{save_param}{list of saving parameters, see \code{\link{showSaveParameters}}} + +\item{default_save_name}{default save name for saving, don't change, change save_name in save_param} +} +\description{ +plot niche cluster connectivity +} +\details{ +This function plots the niche cluster connectivity matrix +} diff --git a/man/reexports.Rd b/man/reexports.Rd index f5533929f..c4a2e34b5 100644 --- a/man/reexports.Rd +++ b/man/reexports.Rd @@ -298,7 +298,7 @@ These objects are imported from other packages. Follow the links below to see their documentation. \describe{ - \item{GiottoClass}{\code{\link[GiottoClass:activeFeatType-generic]{activeFeatType}}, \code{\link[GiottoClass:activeFeatType-generic]{activeFeatType<-}}, \code{\link[GiottoClass:activeSpatUnit-generic]{activeSpatUnit}}, \code{\link[GiottoClass:activeSpatUnit-generic]{activeSpatUnit<-}}, \code{\link[GiottoClass]{addCellMetadata}}, \code{\link[GiottoClass]{addFeatMetadata}}, \code{\link[GiottoClass]{addGiottoImage}}, \code{\link[GiottoClass]{addGiottoImageMG}}, \code{\link[GiottoClass]{addGiottoLargeImage}}, \code{\link[GiottoClass]{addGiottoPoints}}, \code{\link[GiottoClass:addGiottoPoints]{addGiottoPoints3D}}, \code{\link[GiottoClass]{addGiottoPolygons}}, \code{\link[GiottoClass]{addNetworkLayout}}, \code{\link[GiottoClass]{addSpatialCentroidLocations}}, \code{\link[GiottoClass]{addSpatialCentroidLocationsLayer}}, \code{\link[GiottoClass]{aggregateStacks}}, \code{\link[GiottoClass]{aggregateStacksExpression}}, \code{\link[GiottoClass]{aggregateStacksLocations}}, \code{\link[GiottoClass]{aggregateStacksPolygonOverlaps}}, \code{\link[GiottoClass]{aggregateStacksPolygons}}, \code{\link[GiottoClass]{anndataToGiotto}}, \code{\link[GiottoClass]{annotateGiotto}}, \code{\link[GiottoClass]{annotateSpatialGrid}}, \code{\link[GiottoClass]{annotateSpatialNetwork}}, \code{\link[GiottoClass]{as.points}}, \code{\link[GiottoClass]{as.polygons}}, \code{\link[GiottoClass:r_spatial_conversions]{as.sf}}, \code{\link[GiottoClass:r_spatial_conversions]{as.sp}}, \code{\link[GiottoClass:r_spatial_conversions]{as.stars}}, \code{\link[GiottoClass:r_spatial_conversions]{as.terra}}, \code{\link[GiottoClass]{calculateMetaTable}}, \code{\link[GiottoClass]{calculateMetaTableCells}}, \code{\link[GiottoClass]{calculateOverlap}}, \code{\link[GiottoClass]{calculateOverlapParallel}}, \code{\link[GiottoClass]{calculateOverlapPolygonImages}}, \code{\link[GiottoClass]{calculateOverlapRaster}}, \code{\link[GiottoClass]{calculateOverlapSerial}}, \code{\link[GiottoClass]{calculateSpatCellMetadataProportions}}, \code{\link[GiottoClass:centroids-generic]{centroids}}, \code{\link[GiottoClass]{changeGiottoInstructions}}, \code{\link[GiottoClass]{changeImageBg}}, \code{\link[GiottoClass]{checkGiottoEnvironment}}, \code{\link[GiottoClass]{circleVertices}}, \code{\link[GiottoClass]{combineCellData}}, \code{\link[GiottoClass]{combineFeatureData}}, \code{\link[GiottoClass]{combineFeatureOverlapData}}, \code{\link[GiottoClass]{combineMetadata}}, \code{\link[GiottoClass]{combineSpatialCellFeatureInfo}}, \code{\link[GiottoClass]{combineSpatialCellMetadataInfo}}, \code{\link[GiottoClass]{combineToMultiPolygon}}, \code{\link[GiottoClass]{convertGiottoLargeImageToMG}}, \code{\link[GiottoClass]{copy}}, \code{\link[GiottoClass]{createBentoAdata}}, \code{\link[GiottoClass]{createCellMetaObj}}, \code{\link[GiottoClass]{createDimObj}}, \code{\link[GiottoClass]{createExprObj}}, \code{\link[GiottoClass]{createFeatMetaObj}}, \code{\link[GiottoClass]{createGiottoImage}}, \code{\link[GiottoClass]{createGiottoInstructions}}, \code{\link[GiottoClass]{createGiottoLargeImage}}, \code{\link[GiottoClass]{createGiottoLargeImageList}}, \code{\link[GiottoClass]{createGiottoObject}}, \code{\link[GiottoClass]{createGiottoObjectSubcellular}}, \code{\link[GiottoClass]{createGiottoPoints}}, \code{\link[GiottoClass]{createGiottoPolygon}}, \code{\link[GiottoClass:createGiottoPolygon]{createGiottoPolygonsFromDfr}}, \code{\link[GiottoClass:createGiottoPolygon]{createGiottoPolygonsFromGeoJSON}}, \code{\link[GiottoClass:createGiottoPolygon]{createGiottoPolygonsFromMask}}, \code{\link[GiottoClass]{createMetafeats}}, \code{\link[GiottoClass]{createNearestNetObj}}, \code{\link[GiottoClass]{createNearestNetwork}}, \code{\link[GiottoClass]{createSpatEnrObj}}, \code{\link[GiottoClass]{createSpatialDefaultGrid}}, \code{\link[GiottoClass]{createSpatialDelaunayNetwork}}, \code{\link[GiottoClass]{createSpatialFeaturesKNNnetwork}}, \code{\link[GiottoClass]{createSpatialGrid}}, \code{\link[GiottoClass]{createSpatialKNNnetwork}}, \code{\link[GiottoClass]{createSpatialNetwork}}, \code{\link[GiottoClass]{createSpatialWeightMatrix}}, \code{\link[GiottoClass]{createSpatLocsObj}}, \code{\link[GiottoClass]{createSpatNetObj}}, \code{\link[GiottoClass]{crop}}, \code{\link[GiottoClass]{cropGiottoLargeImage}}, \code{\link[GiottoClass]{density}}, \code{\link[GiottoClass]{distGiottoImage}}, \code{\link[GiottoClass]{estimateImageBg}}, \code{\link[GiottoClass]{ext}}, \code{\link[GiottoClass:ext]{ext<-}}, \code{\link[GiottoClass]{fDataDT}}, \code{\link[GiottoClass:spatIDs-generic]{featIDs}}, \code{\link[GiottoClass:featType-generic]{featType}}, \code{\link[GiottoClass:featType-generic]{featType<-}}, \code{\link[GiottoClass:featureNetwork-class]{featureNetwork}}, \code{\link[GiottoClass]{flip}}, \code{\link[GiottoClass]{gefToGiotto}}, \code{\link[GiottoClass]{getCellMetadata}}, \code{\link[GiottoClass]{getDimReduction}}, \code{\link[GiottoClass]{getExpression}}, \code{\link[GiottoClass]{getFeatureInfo}}, \code{\link[GiottoClass]{getFeatureMetadata}}, \code{\link[GiottoClass]{getGiottoImage}}, \code{\link[GiottoClass]{getMultiomics}}, \code{\link[GiottoClass]{getNearestNetwork}}, \code{\link[GiottoClass]{getPolygonInfo}}, \code{\link[GiottoClass]{getSpatialEnrichment}}, \code{\link[GiottoClass]{getSpatialEnrichment}}, \code{\link[GiottoClass]{getSpatialGrid}}, \code{\link[GiottoClass]{getSpatialGrid}}, \code{\link[GiottoClass]{getSpatialLocations}}, \code{\link[GiottoClass]{getSpatialLocations}}, \code{\link[GiottoClass]{getSpatialNetwork}}, \code{\link[GiottoClass]{getSpatialNetwork}}, \code{\link[GiottoClass:giotto-class]{giotto}}, \code{\link[GiottoClass:giottoImage-class]{giottoImage}}, \code{\link[GiottoClass:giottoLargeImage-class]{giottoLargeImage}}, \code{\link[GiottoClass]{giottoMasterToSuite}}, \code{\link[GiottoClass:giottoPoints-class]{giottoPoints}}, \code{\link[GiottoClass:giottoPolygon-class]{giottoPolygon}}, \code{\link[GiottoClass]{giottoToAnnData}}, \code{\link[GiottoClass]{giottoToSeurat}}, \code{\link[GiottoClass]{giottoToSeuratV4}}, \code{\link[GiottoClass]{giottoToSeuratV5}}, \code{\link[GiottoClass]{giottoToSpatialExperiment}}, \code{\link[GiottoClass]{hexVertices}}, \code{\link[GiottoClass]{hist}}, \code{\link[GiottoClass]{installGiottoEnvironment}}, \code{\link[GiottoClass:instructions-generic]{instructions}}, \code{\link[GiottoClass:instructions-generic]{instructions<-}}, \code{\link[GiottoClass]{joinGiottoObjects}}, \code{\link[GiottoClass]{loadGiotto}}, \code{\link[GiottoClass]{makePseudoVisium}}, \code{\link[GiottoClass]{objHistory}}, \code{\link[GiottoClass:objName-generic]{objName}}, \code{\link[GiottoClass:objName-generic]{objName<-}}, \code{\link[GiottoClass:generate_grid]{orthoGrid}}, \code{\link[GiottoClass]{overlapImagesToMatrix}}, \code{\link[GiottoClass:overlaps-generic]{overlaps}}, \code{\link[GiottoClass]{overlapToMatrix}}, \code{\link[GiottoClass]{overlapToMatrixMultiPoly}}, \code{\link[GiottoClass]{pDataDT}}, \code{\link[GiottoClass]{plotGiottoImage}}, \code{\link[GiottoClass]{polyStamp}}, \code{\link[GiottoClass:prov-generic]{prov}}, \code{\link[GiottoClass:prov-generic]{prov<-}}, \code{\link[GiottoClass]{readCellMetadata}}, \code{\link[GiottoClass]{readDimReducData}}, \code{\link[GiottoClass]{readExprData}}, \code{\link[GiottoClass]{readExprMatrix}}, \code{\link[GiottoClass]{readFeatData}}, \code{\link[GiottoClass]{readFeatMetadata}}, \code{\link[GiottoClass]{readGiottoInstructions}}, \code{\link[GiottoClass]{readNearestNetData}}, \code{\link[GiottoClass]{readPolygonData}}, \code{\link[GiottoClass]{readSpatEnrichData}}, \code{\link[GiottoClass]{readSpatLocsData}}, \code{\link[GiottoClass]{readSpatNetData}}, \code{\link[GiottoClass]{reconnectGiottoImage}}, \code{\link[GiottoClass]{rectVertices}}, \code{\link[GiottoClass]{removeCellAnnotation}}, \code{\link[GiottoClass]{removeFeatAnnotation}}, \code{\link[GiottoClass]{removeGiottoEnvironment}}, \code{\link[GiottoClass]{replaceGiottoInstructions}}, \code{\link[GiottoClass]{rescale}}, \code{\link[GiottoClass]{rescalePolygons}}, \code{\link[GiottoClass]{saveGiotto}}, \code{\link[GiottoClass]{setCellMetadata}}, \code{\link[GiottoClass]{setDimReduction}}, \code{\link[GiottoClass]{setExpression}}, \code{\link[GiottoClass]{setFeatureInfo}}, \code{\link[GiottoClass]{setFeatureMetadata}}, \code{\link[GiottoClass]{setGiotto}}, \code{\link[GiottoClass]{setGiottoImage}}, \code{\link[GiottoClass]{setMultiomics}}, \code{\link[GiottoClass]{setNearestNetwork}}, \code{\link[GiottoClass]{setPolygonInfo}}, \code{\link[GiottoClass]{setSpatialEnrichment}}, \code{\link[GiottoClass]{setSpatialGrid}}, \code{\link[GiottoClass]{setSpatialLocations}}, \code{\link[GiottoClass]{setSpatialNetwork}}, \code{\link[GiottoClass]{seuratToGiotto}}, \code{\link[GiottoClass]{seuratToGiottoV4}}, \code{\link[GiottoClass]{seuratToGiottoV5}}, \code{\link[GiottoClass]{showGiottoCellMetadata}}, \code{\link[GiottoClass]{showGiottoDimRed}}, \code{\link[GiottoClass]{showGiottoExpression}}, \code{\link[GiottoClass]{showGiottoFeatInfo}}, \code{\link[GiottoClass]{showGiottoFeatMetadata}}, \code{\link[GiottoClass]{showGiottoImageNames}}, \code{\link[GiottoClass]{showGiottoInstructions}}, \code{\link[GiottoClass]{showGiottoNearestNetworks}}, \code{\link[GiottoClass]{showGiottoSpatEnrichments}}, \code{\link[GiottoClass]{showGiottoSpatGrids}}, \code{\link[GiottoClass]{showGiottoSpatialInfo}}, \code{\link[GiottoClass]{showGiottoSpatLocs}}, \code{\link[GiottoClass]{showGiottoSpatNetworks}}, \code{\link[GiottoClass]{showProcessingSteps}}, \code{\link[GiottoClass]{smoothGiottoPolygons}}, \code{\link[GiottoClass]{spatialExperimentToGiotto}}, \code{\link[GiottoClass:spatIDs-generic]{spatIDs}}, \code{\link[GiottoClass]{spatQueryGiottoPolygons}}, \code{\link[GiottoClass]{spatShift}}, \code{\link[GiottoClass:spatUnit-generic]{spatUnit}}, \code{\link[GiottoClass:spatUnit-generic]{spatUnit<-}}, \code{\link[GiottoClass]{spin}}, \code{\link[GiottoClass]{stitchFieldCoordinates}}, \code{\link[GiottoClass]{stitchFieldCoordinates}}, \code{\link[GiottoClass]{stitchGiottoLargeImage}}, \code{\link[GiottoClass]{subsetGiotto}}, \code{\link[GiottoClass]{subsetGiottoLocs}}, \code{\link[GiottoClass]{subsetGiottoLocsMulti}}, \code{\link[GiottoClass]{subsetGiottoLocsSubcellular}}, \code{\link[GiottoClass]{tessellate}}, \code{\link[GiottoClass:generate_grid]{triGrid}}, \code{\link[GiottoClass]{updateGiottoImage}}, \code{\link[GiottoClass]{updateGiottoImageMG}}, \code{\link[GiottoClass]{updateGiottoLargeImage}}, \code{\link[GiottoClass]{updateGiottoObject}}, \code{\link[GiottoClass]{updateGiottoPointsObject}}, \code{\link[GiottoClass]{updateGiottoPolygonObject}}, \code{\link[GiottoClass:wrap]{vect}}, \code{\link[GiottoClass]{wrap}}, \code{\link[GiottoClass]{writeGiottoLargeImage}}} + \item{GiottoClass}{\code{\link[GiottoClass:activeFeatType-generic]{activeFeatType}}, \code{\link[GiottoClass:activeFeatType-generic]{activeFeatType<-}}, \code{\link[GiottoClass:activeSpatUnit-generic]{activeSpatUnit}}, \code{\link[GiottoClass:activeSpatUnit-generic]{activeSpatUnit<-}}, \code{\link[GiottoClass]{addCellMetadata}}, \code{\link[GiottoClass]{addFeatMetadata}}, \code{\link[GiottoClass]{addGiottoImage}}, \code{\link[GiottoClass]{addGiottoImageMG}}, \code{\link[GiottoClass]{addGiottoLargeImage}}, \code{\link[GiottoClass]{addGiottoPoints}}, \code{\link[GiottoClass:addGiottoPoints]{addGiottoPoints3D}}, \code{\link[GiottoClass]{addGiottoPolygons}}, \code{\link[GiottoClass]{addNetworkLayout}}, \code{\link[GiottoClass]{addSpatialCentroidLocations}}, \code{\link[GiottoClass]{addSpatialCentroidLocationsLayer}}, \code{\link[GiottoClass]{aggregateStacks}}, \code{\link[GiottoClass]{aggregateStacksExpression}}, \code{\link[GiottoClass]{aggregateStacksLocations}}, \code{\link[GiottoClass]{aggregateStacksPolygonOverlaps}}, \code{\link[GiottoClass]{aggregateStacksPolygons}}, \code{\link[GiottoClass]{anndataToGiotto}}, \code{\link[GiottoClass]{annotateGiotto}}, \code{\link[GiottoClass]{annotateSpatialGrid}}, \code{\link[GiottoClass]{annotateSpatialNetwork}}, \code{\link[GiottoClass]{as.points}}, \code{\link[GiottoClass]{as.polygons}}, \code{\link[GiottoClass:r_spatial_conversions]{as.sf}}, \code{\link[GiottoClass:r_spatial_conversions]{as.sp}}, \code{\link[GiottoClass:r_spatial_conversions]{as.stars}}, \code{\link[GiottoClass:r_spatial_conversions]{as.terra}}, \code{\link[GiottoClass]{calculateMetaTable}}, \code{\link[GiottoClass]{calculateMetaTableCells}}, \code{\link[GiottoClass]{calculateOverlap}}, \code{\link[GiottoClass]{calculateOverlapParallel}}, \code{\link[GiottoClass]{calculateOverlapPolygonImages}}, \code{\link[GiottoClass]{calculateOverlapRaster}}, \code{\link[GiottoClass]{calculateOverlapSerial}}, \code{\link[GiottoClass]{calculateSpatCellMetadataProportions}}, \code{\link[GiottoClass:centroids-generic]{centroids}}, \code{\link[GiottoClass]{changeGiottoInstructions}}, \code{\link[GiottoClass]{changeImageBg}}, \code{\link[GiottoClass]{checkGiottoEnvironment}}, \code{\link[GiottoClass]{circleVertices}}, \code{\link[GiottoClass]{combineCellData}}, \code{\link[GiottoClass]{combineFeatureData}}, \code{\link[GiottoClass]{combineFeatureOverlapData}}, \code{\link[GiottoClass]{combineMetadata}}, \code{\link[GiottoClass]{combineSpatialCellFeatureInfo}}, \code{\link[GiottoClass]{combineSpatialCellMetadataInfo}}, \code{\link[GiottoClass]{combineToMultiPolygon}}, \code{\link[GiottoClass]{convertGiottoLargeImageToMG}}, \code{\link[GiottoClass]{copy}}, \code{\link[GiottoClass]{createBentoAdata}}, \code{\link[GiottoClass]{createCellMetaObj}}, \code{\link[GiottoClass]{createDimObj}}, \code{\link[GiottoClass]{createExprObj}}, \code{\link[GiottoClass]{createFeatMetaObj}}, \code{\link[GiottoClass]{createGiottoImage}}, \code{\link[GiottoClass]{createGiottoInstructions}}, \code{\link[GiottoClass]{createGiottoLargeImage}}, \code{\link[GiottoClass]{createGiottoLargeImageList}}, \code{\link[GiottoClass]{createGiottoObject}}, \code{\link[GiottoClass]{createGiottoObjectSubcellular}}, \code{\link[GiottoClass]{createGiottoPoints}}, \code{\link[GiottoClass]{createGiottoPolygon}}, \code{\link[GiottoClass:createGiottoPolygon]{createGiottoPolygonsFromDfr}}, \code{\link[GiottoClass:createGiottoPolygon]{createGiottoPolygonsFromGeoJSON}}, \code{\link[GiottoClass:createGiottoPolygon]{createGiottoPolygonsFromMask}}, \code{\link[GiottoClass]{createMetafeats}}, \code{\link[GiottoClass]{createNearestNetObj}}, \code{\link[GiottoClass]{createNearestNetwork}}, \code{\link[GiottoClass]{createSpatEnrObj}}, \code{\link[GiottoClass]{createSpatLocsObj}}, \code{\link[GiottoClass]{createSpatNetObj}}, \code{\link[GiottoClass]{createSpatialDefaultGrid}}, \code{\link[GiottoClass]{createSpatialDelaunayNetwork}}, \code{\link[GiottoClass]{createSpatialFeaturesKNNnetwork}}, \code{\link[GiottoClass]{createSpatialGrid}}, \code{\link[GiottoClass]{createSpatialKNNnetwork}}, \code{\link[GiottoClass]{createSpatialNetwork}}, \code{\link[GiottoClass]{createSpatialWeightMatrix}}, \code{\link[GiottoClass]{crop}}, \code{\link[GiottoClass]{cropGiottoLargeImage}}, \code{\link[GiottoClass]{density}}, \code{\link[GiottoClass]{distGiottoImage}}, \code{\link[GiottoClass]{estimateImageBg}}, \code{\link[GiottoClass]{ext}}, \code{\link[GiottoClass:ext]{ext<-}}, \code{\link[GiottoClass]{fDataDT}}, \code{\link[GiottoClass:spatIDs-generic]{featIDs}}, \code{\link[GiottoClass:featType-generic]{featType}}, \code{\link[GiottoClass:featType-generic]{featType<-}}, \code{\link[GiottoClass:featureNetwork-class]{featureNetwork}}, \code{\link[GiottoClass]{flip}}, \code{\link[GiottoClass]{gefToGiotto}}, \code{\link[GiottoClass]{getCellMetadata}}, \code{\link[GiottoClass]{getDimReduction}}, \code{\link[GiottoClass]{getExpression}}, \code{\link[GiottoClass]{getFeatureInfo}}, \code{\link[GiottoClass]{getFeatureMetadata}}, \code{\link[GiottoClass]{getGiottoImage}}, \code{\link[GiottoClass]{getMultiomics}}, \code{\link[GiottoClass]{getNearestNetwork}}, \code{\link[GiottoClass]{getPolygonInfo}}, \code{\link[GiottoClass]{getSpatialEnrichment}}, \code{\link[GiottoClass]{getSpatialEnrichment}}, \code{\link[GiottoClass]{getSpatialGrid}}, \code{\link[GiottoClass]{getSpatialGrid}}, \code{\link[GiottoClass]{getSpatialLocations}}, \code{\link[GiottoClass]{getSpatialLocations}}, \code{\link[GiottoClass]{getSpatialNetwork}}, \code{\link[GiottoClass]{getSpatialNetwork}}, \code{\link[GiottoClass:giotto-class]{giotto}}, \code{\link[GiottoClass:giottoImage-class]{giottoImage}}, \code{\link[GiottoClass:giottoLargeImage-class]{giottoLargeImage}}, \code{\link[GiottoClass]{giottoMasterToSuite}}, \code{\link[GiottoClass:giottoPoints-class]{giottoPoints}}, \code{\link[GiottoClass:giottoPolygon-class]{giottoPolygon}}, \code{\link[GiottoClass]{giottoToAnnData}}, \code{\link[GiottoClass]{giottoToSeurat}}, \code{\link[GiottoClass]{giottoToSeuratV4}}, \code{\link[GiottoClass]{giottoToSeuratV5}}, \code{\link[GiottoClass]{giottoToSpatialExperiment}}, \code{\link[GiottoClass]{hexVertices}}, \code{\link[GiottoClass]{hist}}, \code{\link[GiottoClass]{installGiottoEnvironment}}, \code{\link[GiottoClass:instructions-generic]{instructions}}, \code{\link[GiottoClass:instructions-generic]{instructions<-}}, \code{\link[GiottoClass]{joinGiottoObjects}}, \code{\link[GiottoClass]{loadGiotto}}, \code{\link[GiottoClass]{makePseudoVisium}}, \code{\link[GiottoClass]{objHistory}}, \code{\link[GiottoClass:objName-generic]{objName}}, \code{\link[GiottoClass:objName-generic]{objName<-}}, \code{\link[GiottoClass:generate_grid]{orthoGrid}}, \code{\link[GiottoClass]{overlapImagesToMatrix}}, \code{\link[GiottoClass]{overlapToMatrix}}, \code{\link[GiottoClass]{overlapToMatrixMultiPoly}}, \code{\link[GiottoClass:overlaps-generic]{overlaps}}, \code{\link[GiottoClass]{pDataDT}}, \code{\link[GiottoClass]{plotGiottoImage}}, \code{\link[GiottoClass]{polyStamp}}, \code{\link[GiottoClass:prov-generic]{prov}}, \code{\link[GiottoClass:prov-generic]{prov<-}}, \code{\link[GiottoClass]{readCellMetadata}}, \code{\link[GiottoClass]{readDimReducData}}, \code{\link[GiottoClass]{readExprData}}, \code{\link[GiottoClass]{readExprMatrix}}, \code{\link[GiottoClass]{readFeatData}}, \code{\link[GiottoClass]{readFeatMetadata}}, \code{\link[GiottoClass]{readGiottoInstructions}}, \code{\link[GiottoClass]{readNearestNetData}}, \code{\link[GiottoClass]{readPolygonData}}, \code{\link[GiottoClass]{readSpatEnrichData}}, \code{\link[GiottoClass]{readSpatLocsData}}, \code{\link[GiottoClass]{readSpatNetData}}, \code{\link[GiottoClass]{reconnectGiottoImage}}, \code{\link[GiottoClass]{rectVertices}}, \code{\link[GiottoClass]{removeCellAnnotation}}, \code{\link[GiottoClass]{removeFeatAnnotation}}, \code{\link[GiottoClass]{removeGiottoEnvironment}}, \code{\link[GiottoClass]{replaceGiottoInstructions}}, \code{\link[GiottoClass]{rescale}}, \code{\link[GiottoClass]{rescalePolygons}}, \code{\link[GiottoClass]{saveGiotto}}, \code{\link[GiottoClass]{setCellMetadata}}, \code{\link[GiottoClass]{setDimReduction}}, \code{\link[GiottoClass]{setExpression}}, \code{\link[GiottoClass]{setFeatureInfo}}, \code{\link[GiottoClass]{setFeatureMetadata}}, \code{\link[GiottoClass]{setGiotto}}, \code{\link[GiottoClass]{setGiottoImage}}, \code{\link[GiottoClass]{setMultiomics}}, \code{\link[GiottoClass]{setNearestNetwork}}, \code{\link[GiottoClass]{setPolygonInfo}}, \code{\link[GiottoClass]{setSpatialEnrichment}}, \code{\link[GiottoClass]{setSpatialGrid}}, \code{\link[GiottoClass]{setSpatialLocations}}, \code{\link[GiottoClass]{setSpatialNetwork}}, \code{\link[GiottoClass]{seuratToGiotto}}, \code{\link[GiottoClass]{seuratToGiottoV4}}, \code{\link[GiottoClass]{seuratToGiottoV5}}, \code{\link[GiottoClass]{showGiottoCellMetadata}}, \code{\link[GiottoClass]{showGiottoDimRed}}, \code{\link[GiottoClass]{showGiottoExpression}}, \code{\link[GiottoClass]{showGiottoFeatInfo}}, \code{\link[GiottoClass]{showGiottoFeatMetadata}}, \code{\link[GiottoClass]{showGiottoImageNames}}, \code{\link[GiottoClass]{showGiottoInstructions}}, \code{\link[GiottoClass]{showGiottoNearestNetworks}}, \code{\link[GiottoClass]{showGiottoSpatEnrichments}}, \code{\link[GiottoClass]{showGiottoSpatGrids}}, \code{\link[GiottoClass]{showGiottoSpatLocs}}, \code{\link[GiottoClass]{showGiottoSpatNetworks}}, \code{\link[GiottoClass]{showGiottoSpatialInfo}}, \code{\link[GiottoClass]{showProcessingSteps}}, \code{\link[GiottoClass]{smoothGiottoPolygons}}, \code{\link[GiottoClass:spatIDs-generic]{spatIDs}}, \code{\link[GiottoClass]{spatQueryGiottoPolygons}}, \code{\link[GiottoClass]{spatShift}}, \code{\link[GiottoClass:spatUnit-generic]{spatUnit}}, \code{\link[GiottoClass:spatUnit-generic]{spatUnit<-}}, \code{\link[GiottoClass]{spatialExperimentToGiotto}}, \code{\link[GiottoClass]{spin}}, \code{\link[GiottoClass]{stitchFieldCoordinates}}, \code{\link[GiottoClass]{stitchFieldCoordinates}}, \code{\link[GiottoClass]{stitchGiottoLargeImage}}, \code{\link[GiottoClass]{subsetGiotto}}, \code{\link[GiottoClass]{subsetGiottoLocs}}, \code{\link[GiottoClass]{subsetGiottoLocsMulti}}, \code{\link[GiottoClass]{subsetGiottoLocsSubcellular}}, \code{\link[GiottoClass]{tessellate}}, \code{\link[GiottoClass:generate_grid]{triGrid}}, \code{\link[GiottoClass]{updateGiottoImage}}, \code{\link[GiottoClass]{updateGiottoImageMG}}, \code{\link[GiottoClass]{updateGiottoLargeImage}}, \code{\link[GiottoClass]{updateGiottoObject}}, \code{\link[GiottoClass]{updateGiottoPointsObject}}, \code{\link[GiottoClass]{updateGiottoPolygonObject}}, \code{\link[GiottoClass:wrap]{vect}}, \code{\link[GiottoClass]{wrap}}, \code{\link[GiottoClass]{writeGiottoLargeImage}}} \item{GiottoUtils}{\code{\link[GiottoUtils:pipe]{\%>\%}}, \code{\link[GiottoUtils]{getDistinctColors}}, \code{\link[GiottoUtils]{getRainbowColors}}} diff --git a/tests/testthat/test-dbMatrix_filterGiotto.R b/tests/testthat/test-dbMatrix_filterGiotto.R new file mode 100644 index 000000000..29979f555 --- /dev/null +++ b/tests/testthat/test-dbMatrix_filterGiotto.R @@ -0,0 +1,45 @@ +# silence deprecated internal functions +rlang::local_options(lifecycle_verbosity = "quiet") + +# ---------------------------------------------------------------------------- # +# Setup data +visium = GiottoData::loadGiottoMini(dataset = "visium") +dgc = getExpression(visium, output = "matrix") + +con = DBI::dbConnect(duckdb::duckdb(), ":memory:") + +dbsm = dbMatrix::dbMatrix(value = dgc, + con = con, + name = 'dgc', + class = "dbSparseMatrix", + overwrite = TRUE) + +# Create exprObj with dbsm +expObj_db = createExprObj(expression_data = dbsm, + expression_matrix_class = 'dbSparseMatrix', + name = 'raw') + +# Create giotto object +gobject_db = suppressWarnings(createGiottoObject(expression = expObj_db)) + +# ---------------------------------------------------------------------------- # +# Perform filtering +visium_filtered = filterGiotto(visium, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +gobject_db_filtered = filterGiotto(gobject_db, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +# Get filtered matrix +dgc_visium = getExpression(visium_filtered, output = "matrix") +mat_db = getExpression(gobject_db_filtered, output = "matrix") +dgc_db = dbMatrix:::as_matrix(mat_db) + +# ---------------------------------------------------------------------------- # +# Test filterGiotto() equivalence between dbMatrix and dgCMatrix + +test_that("dbMatrix equivalent to dgCMatrix after filterGiotto()", { + expect_equal(dgc_visium, dgc_db) +}) diff --git a/tests/testthat/test-dbMatrix_libNorm.R b/tests/testthat/test-dbMatrix_libNorm.R new file mode 100644 index 000000000..be575f17b --- /dev/null +++ b/tests/testthat/test-dbMatrix_libNorm.R @@ -0,0 +1,64 @@ +# silence deprecated internal functions +rlang::local_options(lifecycle_verbosity = "quiet") + +# ---------------------------------------------------------------------------- # +# Setup data +visium = GiottoData::loadGiottoMini(dataset = "visium") +dgc = getExpression(visium, output = "matrix") + +con = DBI::dbConnect(duckdb::duckdb(), ":memory:") + +dbsm = dbMatrix::dbMatrix(value = dgc, + con = con, + name = 'dgc', + class = "dbSparseMatrix", + overwrite = TRUE) + +# Create exprObj with dbsm +expObj_db = createExprObj(expression_data = dbsm, + expression_matrix_class = 'dbSparseMatrix', + name = 'raw') + +# Create giotto object +gobject_db = suppressWarnings(createGiottoObject(expression = expObj_db)) + +# ---------------------------------------------------------------------------- # +# Perform filtering +visium_filtered = filterGiotto(visium, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +gobject_db_filtered = filterGiotto(gobject_db, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +# ---------------------------------------------------------------------------- # +# Perform library normalization and scaling +visium_filtered = normalizeGiotto(gobject = visium_filtered, + spat_unit = 'cell', + feat_type = 'rna', + expression_values = 'raw', + library_size_norm = TRUE, + log_norm = FALSE, + scale_feats = FALSE, + scale_cells = FALSE) + + +gobject_db_filtered = normalizeGiotto(gobject = gobject_db_filtered, + spat_unit = 'cell', + feat_type = 'rna', + expression_values = 'raw', + library_size_norm = TRUE, + log_norm = FALSE, + scale_feats = FALSE, + scale_cells = FALSE) +# Get normalized matrix +dgc_visium = getExpression(visium_filtered, output = "matrix", values = "normalized") +mat_db = getExpression(gobject_db_filtered, output = "matrix", values = "normalized") +dgc_db = dbMatrix:::as_matrix(mat_db) + +# ---------------------------------------------------------------------------- # +# Test normalizeGiotto() equivalence between dbMatrix and dgCMatrix +test_that("dbMatrix equivalent to dgCMatrix after normalizeGiotto(library_size_norm = TRUE)", { + expect_equal(dgc_visium, dgc_db) +}) \ No newline at end of file diff --git a/tests/testthat/test-dbMatrix_logNorm.R b/tests/testthat/test-dbMatrix_logNorm.R new file mode 100644 index 000000000..1731e634f --- /dev/null +++ b/tests/testthat/test-dbMatrix_logNorm.R @@ -0,0 +1,64 @@ +# silence deprecated internal functions +rlang::local_options(lifecycle_verbosity = "quiet") + +# ---------------------------------------------------------------------------- # +# Setup data +visium = GiottoData::loadGiottoMini(dataset = "visium") +dgc = getExpression(visium, output = "matrix") + +con = DBI::dbConnect(duckdb::duckdb(), ":memory:") + +dbsm = dbMatrix::dbMatrix(value = dgc, + con = con, + name = 'dgc', + class = "dbSparseMatrix", + overwrite = TRUE) + +# Create exprObj with dbsm +expObj_db = createExprObj(expression_data = dbsm, + expression_matrix_class = 'dbSparseMatrix', + name = 'raw') + +# Create giotto object +gobject_db = suppressWarnings(createGiottoObject(expression = expObj_db)) + +# ---------------------------------------------------------------------------- # +# Perform filtering +visium_filtered = filterGiotto(visium, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +gobject_db_filtered = filterGiotto(gobject_db, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +# ---------------------------------------------------------------------------- # +# Perform library normalization and scaling +visium_filtered = normalizeGiotto(gobject = visium_filtered, + spat_unit = 'cell', + feat_type = 'rna', + expression_values = 'raw', + library_size_norm = FALSE, + log_norm = TRUE, + scale_feats = FALSE, + scale_cells = FALSE) + + +gobject_db_filtered = normalizeGiotto(gobject = gobject_db_filtered, + spat_unit = 'cell', + feat_type = 'rna', + expression_values = 'raw', + library_size_norm = FALSE, + log_norm = TRUE, + scale_feats = FALSE, + scale_cells = FALSE) +# Get normalized matrix +dgc_visium = getExpression(visium_filtered, output = "matrix", values = "normalized") +mat_db = getExpression(gobject_db_filtered, output = "matrix", values = "normalized") +dgc_db = dbMatrix:::as_matrix(mat_db) + +# ---------------------------------------------------------------------------- # +# Test normalizeGiotto() equivalence between dbMatrix and dgCMatrix +test_that("dbMatrix equivalent to dgCMatrix after normalizeGiotto(log_norm=TRUE)", { + expect_equal(dgc_visium, dgc_db) +}) \ No newline at end of file diff --git a/tests/testthat/test-dbMatrix_scale.R b/tests/testthat/test-dbMatrix_scale.R new file mode 100644 index 000000000..b28504d35 --- /dev/null +++ b/tests/testthat/test-dbMatrix_scale.R @@ -0,0 +1,64 @@ +# silence deprecated internal functions +rlang::local_options(lifecycle_verbosity = "quiet") + +# ---------------------------------------------------------------------------- # +# Setup data +visium = GiottoData::loadGiottoMini(dataset = "visium") +dgc = getExpression(visium, output = "matrix") + +con = DBI::dbConnect(duckdb::duckdb(), ":memory:") + +dbsm = dbMatrix::dbMatrix(value = dgc, + con = con, + name = 'dgc', + class = "dbSparseMatrix", + overwrite = TRUE) + +# Create exprObj with dbsm +expObj_db = createExprObj(expression_data = dbsm, + expression_matrix_class = 'dbSparseMatrix', + name = 'raw') + +# Create giotto object +gobject_db = suppressWarnings(createGiottoObject(expression = expObj_db)) + +# ---------------------------------------------------------------------------- # +# Perform filtering +visium_filtered = filterGiotto(visium, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +gobject_db_filtered = filterGiotto(gobject_db, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +# ---------------------------------------------------------------------------- # +# Perform library normalization and scaling +visium_filtered = normalizeGiotto(gobject = visium_filtered, + spat_unit = 'cell', + feat_type = 'rna', + expression_values = 'raw', + library_size_norm = FALSE, + log_norm = FALSE, + scale_feats = TRUE, + scale_cells = TRUE) + + +gobject_db_filtered = normalizeGiotto(gobject = gobject_db_filtered, + spat_unit = 'cell', + feat_type = 'rna', + expression_values = 'raw', + library_size_norm = FALSE, + log_norm = FALSE, + scale_feats = TRUE, + scale_cells = TRUE) +# Get normalized matrix +dgc_visium = getExpression(visium_filtered, output = "matrix", values = "scaled") |> as.matrix() +mat_db = getExpression(gobject_db_filtered, output = "matrix", values = "scaled") +dgc_db = dbMatrix:::as_matrix(mat_db) + +# ---------------------------------------------------------------------------- # +# Test normalizeGiotto() equivalence between dbMatrix and dgCMatrix +test_that("dbMatrix equivalent to dgCMatrix after normalizeGiotto(scale_feats=T,scale=cells=T)", { + expect_equal(dgc_visium, dgc_db) +}) \ No newline at end of file diff --git a/vignettes/dbMatrix.Rmd b/vignettes/dbMatrix.Rmd new file mode 100644 index 000000000..588737d97 --- /dev/null +++ b/vignettes/dbMatrix.Rmd @@ -0,0 +1,93 @@ +--- +title: "Using dbMatrix with Giotto" +output: rmarkdown::html_vignette +vignette: > + %\VignetteIndexEntry{Using dbMatrix with Giotto} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + comment = "#>" +) +``` + +# Introduction +This vignette demonstrates how to use a [`dbMatrix`](https://github.com/drieslab/dbMatrix) within a Giotto Object. The `dbMatrix` is a database-backed matrix that can be used to store large matrices in a database. This allows for efficient storage and retrieval of large matrices and enables efficiently working with larger-than-memory cell count matrices. + +# 1. Set up Giotto + +```{r, eval=FALSE} +# Ensure Giotto Suite is installed. +if(!"Giotto" %in% installed.packages()) { + devtools::install_github("drieslab/Giotto@suite") +} + +# Ensure GiottoData, a small, helper module for tutorials, is installed. +if(!"GiottoData" %in% installed.packages()) { + devtools::install_github("drieslab/GiottoData") +} + +library(Giotto) +library(GiottoData) + +# Ensure the Python environment for Giotto has been installed. +genv_exists = checkGiottoEnvironment() +if(!genv_exists){ + # The following command need only be run once to install the Giotto environment. + installGiottoEnvironment() +} +``` + +# 2. Create Giotto object with `dbMatrix` + +```{r} +# Get test dataset from Giotto Data package +visium = GiottoData::loadGiottoMini(dataset = "visium") + +# Extract the cell expression matrix as a test dataset +dgc = getExpression(visium, output = "matrix") + +# Create a DBI connection object +con = DBI::dbConnect(duckb::duckdb(), ":memory:") + +# Create a dbSparseMatrix using the dbMatrix constructor function +dbsm = dbMatrix::dbMatrix(value = dgc, + con = con, + name = 'dgc', + class = "dbSparseMatrix", + overwrite = TRUE) + +# Create Giotto exprObj with the dbMatrix +expObj_db = createExprObj(expression_data = dbsm, + expression_matrix_class = 'dbSparseMatrix', + name = 'raw') + +# Create the Giotto object consisting of only the cell count matrix +gobject_db = createGiottoObject(expression = expObj_db) +``` + +# 3. Preprocess Giotto object with `dbMatrix` +```{r} +# Perform filtering +gobject_db_filtered = filterGiotto(gobject_db, spat_unit = "cell", + feat_type = "rna", + expression_values = "raw") + +# Perform library normalization and scaling +gobject_db_filtered = normalizeGiotto(gobject = gobject_db_filtered, + spat_unit = 'cell', + feat_type = 'rna', + expression_values = 'raw', + library_size_norm = FALSE, + log_norm = FALSE, + scale_feats = TRUE, + scale_cells = TRUE) +``` + + +```{r} +sessionInfo() +``` \ No newline at end of file