diff --git a/NAMESPACE b/NAMESPACE index 99b5d9b..2be1414 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -18,6 +18,7 @@ export(get_abundance_info) export(get_avg_pb_exprs) export(get_empirical_pvals) export(get_frac_exprs) +export(get_frac_exprs_sampleAgnostic) export(get_ligand_activities_targets_DEgenes) export(get_ligand_activities_targets_DEgenes_beta) export(get_muscat_exprs_avg) diff --git a/R/expression_processing.R b/R/expression_processing.R index 0a05c69..53313bd 100644 --- a/R/expression_processing.R +++ b/R/expression_processing.R @@ -618,6 +618,94 @@ get_frac_exprs = function(sce, sample_id, celltype_id, group_id, batches = NA, m return(list(frq_df = frq_df, frq_df_group = frq_df_group, expressed_df = expressed_df)) } +#' @title get_frac_exprs_sampleAgnostic +#' +#' @description \code{get_frac_exprs_sampleAgnostic} Calculate the average fraction of expression of each gene per group. All cells from all samples will be pooled per group/condition. +#' @usage get_frac_exprs_sampleAgnostic(sce, sample_id, celltype_id, group_id, batches = NA, min_cells = 10, fraction_cutoff = 0.05, min_sample_prop = 0.5) +#' +#' @inheritParams get_frac_exprs +#' @param min_sample_prop Default, and only recommended value = 1. Hereby, the gene should be expressed in at least one group/condition. +#' +#' @return List containing data frames with the fraction of expression per sample and per group. +#' +#' @import dplyr +#' @import tibble +#' @importFrom tidyr gather +#' @importFrom SummarizedExperiment colData +#' +#' @examples +#' \dontrun{ +#' library(dplyr) +#' sample_id = "tumor" +#' group_id = "pEMT" +#' celltype_id = "celltype" +#' frac_info = get_frac_exprs_sampleAgnostic(sce = sce, sample_id = sample_id, celltype_id = celltype_id, group_id = group_id) +#' } +#' +#' @export +#' +get_frac_exprs_sampleAgnostic = function(sce, sample_id, celltype_id, group_id, batches = NA, + min_cells = 10, fraction_cutoff = 0.05, min_sample_prop = 1){ + + sample_id = group_id + frq_df = get_muscat_exprs_frac(sce, sample_id = sample_id, + celltype_id = celltype_id, group_id = group_id) %>% .$frq_celltype_samples + metadata = SummarizedExperiment::colData(sce) %>% tibble::as_tibble() + metadata_abundance = metadata %>% dplyr::select(group_id, celltype_id) + print(head(metadata_abundance)) + metadata_abundance = cbind(metadata[, group_id], metadata_abundance) + print(head(metadata_abundance)) + colnames(metadata_abundance) = c("sample", "group", "celltype") + print(head(metadata_abundance)) + metadata_abundance = metadata_abundance %>% tibble::as_tibble() + print(head(metadata_abundance)) + + abundance_data = metadata_abundance %>% tibble::as_tibble() %>% + dplyr::group_by(sample, celltype) %>% dplyr::count() %>% + dplyr::inner_join(metadata_abundance %>% tibble::as_tibble() %>% + dplyr::distinct(sample, group), by = "sample") + abundance_data = abundance_data %>% dplyr::mutate(keep_sample = n >= + min_cells) %>% dplyr::mutate(keep_sample = factor(keep_sample, + levels = c(TRUE, FALSE))) + grouping_df = abundance_data[,c("sample","group")] %>% + tibble::as_tibble() %>% dplyr::distinct() + grouping_df_filtered = grouping_df %>% inner_join(abundance_data) %>% + filter(keep_sample == TRUE) + print(paste0("Groups are considered if they have more than ", + min_cells, " cells of the cell type of interest")) + frq_df_group = frq_df %>% dplyr::inner_join(grouping_df_filtered) %>% + dplyr::group_by(group, celltype, gene) %>% dplyr::summarise(fraction_group = mean(fraction_sample)) + n_smallest_group_tbl = grouping_df_filtered %>% dplyr::group_by(group, + celltype) %>% dplyr::count() %>% dplyr::group_by(celltype) %>% + dplyr::summarize(n_smallest_group = min(n)) %>% dplyr::mutate(n_min = min_sample_prop * + n_smallest_group) %>% distinct() + print(paste0("Genes with non-zero counts in at least ", fraction_cutoff * + 100, "% of cells of a cell type of interest in a particular group/condition will be considered as expressed in that group/condition")) + for (i in seq(length(unique(n_smallest_group_tbl$celltype)))) { + celltype_oi = unique(n_smallest_group_tbl$celltype)[i] + n_min = n_smallest_group_tbl %>% filter(celltype == celltype_oi) %>% + pull(n_min) + print(paste0("Genes expressed in at least ", n_min, " group will considered as expressed in the cell type: ", + celltype_oi)) + } + frq_df = frq_df %>% dplyr::inner_join(grouping_df) %>% dplyr::mutate(expressed_sample = fraction_sample >= + fraction_cutoff) + expressed_df = frq_df %>% inner_join(n_smallest_group_tbl) %>% + inner_join(abundance_data) %>% dplyr::group_by(gene, + celltype) %>% dplyr::summarise(n_expressed = sum(expressed_sample)) %>% + dplyr::mutate(expressed = n_expressed >= n_min) %>% distinct(celltype, + gene, expressed) + for (i in seq(length(unique(expressed_df$celltype)))) { + celltype_oi = unique(expressed_df$celltype)[i] + n_genes = expressed_df %>% filter(celltype == celltype_oi) %>% + filter(expressed == TRUE) %>% pull(gene) %>% unique() %>% + length() + print(paste0(n_genes, " genes are considered as expressed in the cell type: ", + celltype_oi)) + } + return(list(frq_df = frq_df, frq_df_group = frq_df_group, + expressed_df = expressed_df)) +} #' @title process_info_to_ic #' #' @description \code{process_info_to_ic} Process cell type expression information into intercellular communication focused information. Only keep information of ligands for the sender cell type setting, and information of receptors for the receiver cell type. diff --git a/R/pipeline.R b/R/pipeline.R index 18c49d1..f3a04f1 100644 --- a/R/pipeline.R +++ b/R/pipeline.R @@ -643,7 +643,7 @@ multi_nichenet_analysis = function(sce, #' covariates = NA #' contrasts_oi = c("'High-Low','Low-High'") #' contrast_tbl = tibble(contrast = c("High-Low","Low-High"), group = c("High","Low")) -#' output = multi_nichenet_analysis( +#' output = multi_nichenet_analysis_sampleAgnostic( #' sce = sce, #' celltype_id = celltype_id, #' sample_id = sample_id, @@ -919,12 +919,15 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, # sce = sce[, SummarizedExperiment::colData(sce)[,group_id] %in% contrast_tbl$group] # keep only considered groups # do not do this -- this could give errors if only interested in one contrast but multiple groups + sce = scuttle::logNormCounts(sce) + + if(verbose == TRUE){ print("Make diagnostic abundance plots + define expressed genes") } ## check abundance info - abundance_info = get_abundance_info(sce = sce, sample_id = sample_id, group_id = group_id, celltype_id = celltype_id, min_cells = min_cells, senders_oi = senders_oi, receivers_oi = receivers_oi, batches = batches) + abundance_info = get_abundance_info(sce = sce, sample_id = group_id, group_id = group_id, celltype_id = celltype_id, min_cells = min_cells, senders_oi = senders_oi, receivers_oi = receivers_oi, batches = batches) ## check for condition-specific cell types sample_group_celltype_df = abundance_info$abundance_data %>% filter(n > min_cells) %>% ungroup() %>% distinct(sample_id, group_id) %>% cross_join(abundance_info$abundance_data %>% ungroup() %>% distinct(celltype_id)) %>% arrange(sample_id) @@ -933,11 +936,11 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, abundance_df$keep[is.na(abundance_df$keep)] = FALSE abundance_df_summarized = abundance_df %>% mutate(keep = as.logical(keep)) %>% group_by(group_id, celltype_id) %>% summarise(samples_present = sum((keep))) celltypes_absent_one_condition = abundance_df_summarized %>% filter(samples_present == 0) %>% pull(celltype_id) %>% unique() # find truly condition-specific cell types by searching for cell types truely absent in at least one condition - celltypes_present_one_condition = abundance_df_summarized %>% filter(samples_present >= 2) %>% pull(celltype_id) %>% unique() # require presence in at least 2 samples of one group so it is really present in at least one condition + celltypes_present_one_condition = abundance_df_summarized %>% filter(samples_present >= 1) %>% pull(celltype_id) %>% unique() # require presence in at least 2 samples of one group so it is really present in at least one condition condition_specific_celltypes = intersect(celltypes_absent_one_condition, celltypes_present_one_condition) total_nr_conditions = SummarizedExperiment::colData(sce)[,group_id] %>% unique() %>% length() - absent_celltypes = abundance_df_summarized %>% dplyr::filter(samples_present < 2) %>% dplyr::group_by(celltype_id) %>% dplyr::count() %>% dplyr::filter(n == total_nr_conditions) %>% dplyr::pull(celltype_id) + absent_celltypes = abundance_df_summarized %>% dplyr::filter(samples_present < 1) %>% dplyr::group_by(celltype_id) %>% dplyr::count() %>% dplyr::filter(n == total_nr_conditions) %>% dplyr::pull(celltype_id) print("condition-specific celltypes:") print(condition_specific_celltypes) @@ -953,7 +956,7 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, sce = sce[, SummarizedExperiment::colData(sce)[,celltype_id] %in% retained_celltypes] ## define expressed genes - frq_list = get_frac_exprs(sce = sce, sample_id = sample_id, celltype_id = celltype_id, group_id = group_id, batches = batches, min_cells = min_cells, fraction_cutoff = fraction_cutoff, min_sample_prop = min_sample_prop) + frq_list = get_frac_exprs_sampleAgnostic(sce = sce, sample_id = sample_id, celltype_id = celltype_id, group_id = group_id, batches = batches, min_cells = min_cells, fraction_cutoff = fraction_cutoff, min_sample_prop = min_sample_prop) ### Perform the DE analysis ---------------------------------------------------------------- @@ -961,41 +964,18 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, print("Calculate differential expression for all cell types") } - if(findMarkers == FALSE){ - DE_info = get_DE_info(sce = sce, sample_id = sample_id, group_id = group_id, celltype_id = celltype_id, batches = batches, covariates = covariates, contrasts_oi = contrasts_oi, min_cells = min_cells, - assay_oi_pb = assay_oi_pb, - fun_oi_pb = fun_oi_pb, - de_method_oi = de_method_oi, - findMarkers = findMarkers, - expressed_df = frq_list$expressed_df) - } else { - DE_info = get_DE_info(sce = sce, sample_id = sample_id, group_id = group_id, celltype_id = celltype_id, batches = batches, covariates = covariates, contrasts_oi = contrasts_oi, min_cells = min_cells, + DE_info = get_DE_info(sce = sce, sample_id = sample_id, group_id = group_id, celltype_id = celltype_id, batches = batches, covariates = covariates, contrasts_oi = contrasts_oi, min_cells = min_cells, assay_oi_pb = assay_oi_pb, fun_oi_pb = fun_oi_pb, de_method_oi = de_method_oi, - findMarkers = findMarkers, + findMarkers = TRUE, contrast_tbl = contrast_tbl, expressed_df = frq_list$expressed_df) - } - - if(empirical_pval == TRUE){ - if(findMarkers == TRUE){ - DE_info_emp = get_empirical_pvals(DE_info$celltype_de_findmarkers) - } else { - DE_info_emp = get_empirical_pvals(DE_info$celltype_de$de_output_tidy) - } - } - if(empirical_pval == FALSE){ - if(findMarkers == TRUE){ - celltype_de = DE_info$celltype_de_findmarkers - } else { - celltype_de = DE_info$celltype_de$de_output_tidy - } - } else { - celltype_de = DE_info_emp$de_output_tidy_emp %>% dplyr::select(-p_val, -p_adj) %>% dplyr::rename(p_val = p_emp, p_adj = p_adj_emp) - } + + celltype_de = DE_info$celltype_de_findmarkers + # print(celltype_de %>% dplyr::group_by(cluster_id, contrast) %>% dplyr::filter(p_adj <= p_val_threshold & abs(logFC) >= logFC_threshold) %>% dplyr::count() %>% dplyr::arrange(-n)) senders_oi = celltype_de$cluster_id %>% unique() @@ -1023,16 +1003,20 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, if(verbose == TRUE){ print("Calculate normalized average and pseudobulk expression") } - abundance_expression_info = process_abundance_expression_info(sce = sce, sample_id = sample_id, group_id = group_id, celltype_id = celltype_id, min_cells = min_cells, senders_oi = union(senders_oi, condition_specific_celltypes), receivers_oi = union(receivers_oi, condition_specific_celltypes), lr_network = lr_network, batches = batches, frq_list = frq_list, abundance_info = abundance_info) + abundance_expression_info = process_abundance_expression_info(sce = sce, sample_id = group_id, group_id = group_id, celltype_id = celltype_id, min_cells = min_cells, senders_oi = union(senders_oi, condition_specific_celltypes), receivers_oi = union(receivers_oi, condition_specific_celltypes), lr_network = lr_network, batches = batches, frq_list = frq_list, abundance_info = abundance_info) metadata_combined = SummarizedExperiment::colData(sce) %>% tibble::as_tibble() if(!is.na(batches)){ - grouping_tbl = metadata_combined[,c(sample_id, group_id, batches)] %>% tibble::as_tibble() %>% dplyr::distinct() - colnames(grouping_tbl) = c("sample","group",batches) + grouping_tbl = metadata_combined[,c(group_id, batches)] %>% tibble::as_tibble() %>% dplyr::distinct() + colnames(grouping_tbl) = c("group",batches) + grouping_tbl = grouping_tbl %>% mutate(sample = group) + grouping_tbl = grouping_tbl %>% tibble::as_tibble() } else { - grouping_tbl = metadata_combined[,c(sample_id, group_id)] %>% tibble::as_tibble() %>% dplyr::distinct() - colnames(grouping_tbl) = c("sample","group") + grouping_tbl = metadata_combined[,c(group_id)] %>% tibble::as_tibble() %>% dplyr::distinct() + colnames(grouping_tbl) = c("group") + grouping_tbl = grouping_tbl %>% mutate(sample = group) %>% select(sample, group) + } rm(sce) @@ -1040,6 +1024,7 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, if(verbose == TRUE){ print("Calculate NicheNet ligand activities and ligand-target links") } + ligand_activities_targets_DEgenes = suppressMessages(suppressWarnings(get_ligand_activities_targets_DEgenes( receiver_de = celltype_de, receivers_oi = receivers_oi, @@ -1072,29 +1057,13 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, )) # Prepare Unsupervised analysis of samples! ------------------------------------------------------------------------------------------------------------ - - if(return_lr_prod_matrix == TRUE){ - - ids_oi = prioritization_tables$group_prioritization_tbl %>% dplyr::filter(fraction_expressing_ligand_receptor > 0) %>% dplyr::pull(id) %>% unique() - - lr_prod_df = abundance_expression_info$sender_receiver_info$pb_df %>% dplyr::inner_join(grouping_tbl, by = "sample") %>% dplyr::mutate(lr_interaction = paste(ligand, receptor, sep = "_")) %>% dplyr::mutate(id = paste(lr_interaction, sender, receiver, sep = "_")) %>% dplyr::select(sample, id, ligand_receptor_pb_prod) %>% dplyr::filter(id %in% ids_oi) %>% dplyr::distinct() %>% tidyr::spread(id, ligand_receptor_pb_prod) - lr_prod_mat = lr_prod_df %>% dplyr::select(-sample) %>% data.frame() %>% as.matrix() - rownames(lr_prod_mat) = lr_prod_df$sample - - col_remove = lr_prod_mat %>% apply(2,function(x)sum(x != 0)) %>% .[. == 0] %>% names() - row_remove = lr_prod_mat %>% apply(1,function(x)sum(x != 0)) %>% .[. == 0] %>% names() - - lr_prod_mat = lr_prod_mat %>% .[rownames(.) %>% generics::setdiff(col_remove),colnames(.) %>% generics::setdiff(col_remove)] - } else { - lr_prod_mat = NULL - } + lr_prod_mat = NULL # Add information on prior knowledge and expression correlation between LR and target expression ------------------------------------------------------------------------------------------------------------ if(verbose == TRUE){ print("Calculate correlation between LR pairs and target genes") } - lr_target_prior_cor = lr_target_prior_cor_inference(prioritization_tables$group_prioritization_tbl$receiver %>% unique(), abundance_expression_info, celltype_de, grouping_tbl, prioritization_tables, ligand_target_matrix, logFC_threshold = logFC_threshold, p_val_threshold = p_val_threshold, p_val_adj = p_val_adj, top_n_LR = top_n_LR) - + lr_target_prior_cor = tibble() ## save output if(length(condition_specific_celltypes) > 0) { @@ -1144,7 +1113,7 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, prioritization_tables_with_condition_specific_celltype_receiver = prioritization_tables_with_condition_specific_celltype_receiver, combined_prioritization_tables = combined_prioritization_tables, grouping_tbl = grouping_tbl, - lr_target_prior_cor = lr_target_prior_cor + lr_target_prior_cor = tibble() ) multinichenet_output = make_lite_output_condition_specific(multinichenet_output, top_n_LR = top_n_LR) @@ -1160,7 +1129,7 @@ multi_nichenet_analysis_sampleAgnostic = function(sce, ligand_activities_targets_DEgenes = ligand_activities_targets_DEgenes, prioritization_tables = prioritization_tables, grouping_tbl = grouping_tbl, - lr_target_prior_cor = lr_target_prior_cor + lr_target_prior_cor = tibble() ) multinichenet_output = make_lite_output(multinichenet_output, top_n_LR = top_n_LR) } diff --git a/R/pipeline_wrappers.R b/R/pipeline_wrappers.R index 56be3bb..6747177 100644 --- a/R/pipeline_wrappers.R +++ b/R/pipeline_wrappers.R @@ -1005,4 +1005,4 @@ make_lite_output_condition_specific = function(multinichenet_output, top_n_LR = } return(multinichenet_output) -} \ No newline at end of file +} diff --git a/man/get_frac_exprs_sampleAgnostic.Rd b/man/get_frac_exprs_sampleAgnostic.Rd new file mode 100644 index 0000000..70edd18 --- /dev/null +++ b/man/get_frac_exprs_sampleAgnostic.Rd @@ -0,0 +1,41 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/expression_processing.R +\name{get_frac_exprs_sampleAgnostic} +\alias{get_frac_exprs_sampleAgnostic} +\title{get_frac_exprs_sampleAgnostic} +\usage{ +get_frac_exprs_sampleAgnostic(sce, sample_id, celltype_id, group_id, batches = NA, min_cells = 10, fraction_cutoff = 0.05, min_sample_prop = 0.5) +} +\arguments{ +\item{sce}{SingleCellExperiment object of the scRNAseq data of interest. Contains both sender and receiver cell types.} + +\item{sample_id}{Name of the meta data column that indicates from which sample/patient a cell comes from} + +\item{celltype_id}{Name of the column in the meta data of sce that indicates the cell type of a cell.} + +\item{group_id}{Name of the meta data column that indicates from which group/condition a cell comes from} + +\item{batches}{NA if no batches should be corrected for. If there should be corrected for batches during DE analysis and pseudobulk expression calculation, this argument should be the name(s) of the columns in the meta data that indicate the batch(s). Should be categorical. Pseudobulk expression values will be corrected for the first element of this vector.} + +\item{min_cells}{Indicates the minimal number of cells that a sample should have to be considered in the DE analysis. Default: 10. See `muscat::pbDS`.} + +\item{fraction_cutoff}{Cutoff indicating the minimum fraction of cells of a cell type in a specific sample that are necessary to consider a gene (e.g. ligand/receptor) as expressed in a sample.} + +\item{min_sample_prop}{Default, and only recommended value = 1. Hereby, the gene should be expressed in at least one group/condition.} +} +\value{ +List containing data frames with the fraction of expression per sample and per group. +} +\description{ +\code{get_frac_exprs_sampleAgnostic} Calculate the average fraction of expression of each gene per group. All cells from all samples will be pooled per group/condition. +} +\examples{ +\dontrun{ +library(dplyr) +sample_id = "tumor" +group_id = "pEMT" +celltype_id = "celltype" +frac_info = get_frac_exprs_sampleAgnostic(sce = sce, sample_id = sample_id, celltype_id = celltype_id, group_id = group_id) +} + +} diff --git a/man/multi_nichenet_analysis_sampleAgnostic.Rd b/man/multi_nichenet_analysis_sampleAgnostic.Rd index 37cecd3..0b3b02d 100644 --- a/man/multi_nichenet_analysis_sampleAgnostic.Rd +++ b/man/multi_nichenet_analysis_sampleAgnostic.Rd @@ -105,7 +105,7 @@ batches = NA covariates = NA contrasts_oi = c("'High-Low','Low-High'") contrast_tbl = tibble(contrast = c("High-Low","Low-High"), group = c("High","Low")) -output = multi_nichenet_analysis( +output = multi_nichenet_analysis_sampleAgnostic( sce = sce, celltype_id = celltype_id, sample_id = sample_id, diff --git a/vignettes/basic_analysis_steps_MISC.Rmd b/vignettes/basic_analysis_steps_MISC.Rmd index b1b2ac9..a58ee21 100644 --- a/vignettes/basic_analysis_steps_MISC.Rmd +++ b/vignettes/basic_analysis_steps_MISC.Rmd @@ -582,7 +582,7 @@ ligand_activities_targets_DEgenes$ligand_activities %>% head(20) In the previous steps, we calculated expression, differential expression and NicheNet ligand activity. In the final step, we will now combine all calculated information to rank all sender-ligand---receiver-receptor pairs according to group/condition specificity. We will use the following criteria to prioritize ligand-receptor interactions: * Upregulation of the ligand in a sender cell type and/or upregulation of the receptor in a receiver cell type - in the condition of interest. -* Cell-type and condition specific expression of the ligand in the sender cell type and receptor in the receiver cell type (to mitigate the influence of upregulated but still relatively weakly expressed ligands/receptors). +* Cell-type specific expression of the ligand in the sender cell type and receptor in the receiver cell type in the condition of interest (to mitigate the influence of upregulated but still relatively weakly expressed ligands/receptors). * Sufficiently high expression levels of ligand and receptor in many samples of the same group. * High NicheNet ligand activity, to further prioritize ligand-receptor pairs based on their predicted effect of the ligand-receptor interaction on the gene expression in the receiver cell type. diff --git a/vignettes/basic_analysis_steps_MISC_SACL.Rmd b/vignettes/basic_analysis_steps_MISC_SACL.Rmd new file mode 100644 index 0000000..ce7bfeb --- /dev/null +++ b/vignettes/basic_analysis_steps_MISC_SACL.Rmd @@ -0,0 +1,794 @@ +--- +title: "MultiNicheNet analysis: MIS-C threewise comparison - sample-agnostic/cell-level alternative" +author: "Robin Browaeys" +package: "`r BiocStyle::pkg_ver('multinichenetr')`" +output: + BiocStyle::html_document +vignette: > + %\VignetteIndexEntry{MultiNicheNet analysis: MIS-C threewise comparison - sample-agnostic/cell-level alternative} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + + + +```{r setup, include = FALSE} +knitr::opts_chunk$set( + collapse = TRUE, + # comment = "#>", + warning = FALSE, + message = FALSE +) +library(BiocStyle) +``` + +In this vignette, you can learn how to perform a sample-agnostic/cell-level MultiNicheNet analysis to compare cell-cell communication between conditions of interest. In this workflow, cells from the same condition will be pooled together similar to regular differential cell-cell communication workflows. **We only recommend running this pipeline if you have less than 3 samples in each of the groups/conditions you want to compare. Do not run this workflow if you have more samples per condition.** + +As input you need a SingleCellExperiment object containing at least the raw count matrix and metadata providing the following information for each cell: the **group**, **sample** and **cell type**. + +As example expression data of interacting cells, we will here use scRNAseq data of immune cells in MIS-C patients and healthy siblings from this paper of Hoste et al.: [TIM3+ TRBV11-2 T cells and IFNγ signature in patrolling monocytes and CD16+ NK cells delineate MIS-C](https://rupress.org/jem/article/219/2/e20211381/212918/TIM3-TRBV11-2-T-cells-and-IFN-signature-in) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.6362434.svg)](https://doi.org/10.5281/zenodo.6362434). +MIS-C (multisystem inflammatory syndrome in children) is a novel rare immunodysregulation syndrome that can arise after SARS-CoV-2 infection in children. We will use MultiNicheNet to explore immune cell crosstalk enriched in MIS-C compared to healthy siblings and adult COVID-19 patients. + +In this vignette, we will first prepare the MultiNicheNet core analysis, then run the several steps in the MultiNicheNet core analysis, and finally interpret the output. + +# Preparation of the MultiNicheNet core analysis + +```{r load-libs, message = FALSE, warning = FALSE} +library(SingleCellExperiment) +library(dplyr) +library(ggplot2) +library(nichenetr) +library(multinichenetr) +``` + +## Load NicheNet's ligand-receptor network and ligand-target matrix + +MultiNicheNet builds upon the NicheNet framework and uses the same prior knowledge networks (ligand-receptor network and ligand-target matrix, currently v2 version). + +The Nichenet v2 networks and matrices for both mouse and human can be downloaded from Zenodo [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.7074291.svg)](https://doi.org/10.5281/zenodo.7074291). + +We will read these object in for human because our expression data is of human patients. +Gene names are here made syntactically valid via `make.names()` to avoid the loss of genes (eg H2-M3) in downstream visualizations. + +```{r} +organism = "human" +``` + +```{r, results='hide'} +options(timeout = 120) + +if(organism == "human"){ + + lr_network_all = + readRDS(url( + "https://zenodo.org/record/10229222/files/lr_network_human_allInfo_30112033.rds" + )) %>% + mutate( + ligand = convert_alias_to_symbols(ligand, organism = organism), + receptor = convert_alias_to_symbols(receptor, organism = organism)) + + lr_network_all = lr_network_all %>% + mutate(ligand = make.names(ligand), receptor = make.names(receptor)) + + lr_network = lr_network_all %>% + distinct(ligand, receptor) + + ligand_target_matrix = readRDS(url( + "https://zenodo.org/record/7074291/files/ligand_target_matrix_nsga2r_final.rds" + )) + + colnames(ligand_target_matrix) = colnames(ligand_target_matrix) %>% + convert_alias_to_symbols(organism = organism) %>% make.names() + rownames(ligand_target_matrix) = rownames(ligand_target_matrix) %>% + convert_alias_to_symbols(organism = organism) %>% make.names() + + lr_network = lr_network %>% filter(ligand %in% colnames(ligand_target_matrix)) + ligand_target_matrix = ligand_target_matrix[, lr_network$ligand %>% unique()] + +} else if(organism == "mouse"){ + + lr_network_all = readRDS(url( + "https://zenodo.org/record/10229222/files/lr_network_mouse_allInfo_30112033.rds" + )) %>% + mutate( + ligand = convert_alias_to_symbols(ligand, organism = organism), + receptor = convert_alias_to_symbols(receptor, organism = organism)) + + lr_network_all = lr_network_all %>% + mutate(ligand = make.names(ligand), receptor = make.names(receptor)) + lr_network = lr_network_all %>% + distinct(ligand, receptor) + + ligand_target_matrix = readRDS(url( + "https://zenodo.org/record/7074291/files/ligand_target_matrix_nsga2r_final_mouse.rds" + )) + + colnames(ligand_target_matrix) = colnames(ligand_target_matrix) %>% + convert_alias_to_symbols(organism = organism) %>% make.names() + rownames(ligand_target_matrix) = rownames(ligand_target_matrix) %>% + convert_alias_to_symbols(organism = organism) %>% make.names() + + lr_network = lr_network %>% filter(ligand %in% colnames(ligand_target_matrix)) + ligand_target_matrix = ligand_target_matrix[, lr_network$ligand %>% unique()] + +} +``` + +## Read in SingleCellExperiment Object + +In this vignette, we will load in a subset of the scRNAseq data of the MIS-C [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.8010790.svg)](https://doi.org/10.5281/zenodo.8010790). For the sake of demonstration, this subset only contains 3 cell types. These celltypes are some of the cell types that were found to be most interesting related to MIS-C according to Hoste et al. + +If you start from a Seurat object, you can convert it easily to a SingleCellExperiment object via `sce = Seurat::as.SingleCellExperiment(seurat_obj, assay = "RNA")`. + +Because the NicheNet 2.0. networks are in the most recent version of the official gene symbols, we will make sure that the gene symbols used in the expression data are also updated (= converted from their "aliases" to official gene symbols). Afterwards, we will make them again syntactically valid. + +```{r, results='hide'} +sce = readRDS(url( + "https://zenodo.org/record/8010790/files/sce_subset_misc.rds" + )) +sce = alias_to_symbol_SCE(sce, "human") %>% makenames_SCE() +``` +This dataset does not yet contain normalized counts: + +```{r} +sce = scuttle::logNormCounts(sce) +``` + +## Prepare the settings of the MultiNicheNet cell-cell communication analysis + +In this step, we will formalize our research question into MultiNicheNet input arguments. + +### Define in which metadata columns we can find the **group**, **sample** and **cell type** IDs + +In this case study, we want to study differences in cell-cell communication patterns between MIS-C patients (M), their healthy siblings (S) and adult patients with severe covid (A). The meta data columns that indicate this disease status(=group/condition of interest) is `MIS.C.AgeTier`. + +Cell type annotations are indicated in the `Annotation_v2.0` column, and the sample is indicated by the `ShortID` column. +If your cells are annotated in multiple hierarchical levels, we recommend using a relatively high level in the hierarchy because MultiNicheNet focuses on differential expression and not differential abundance + +```{r} +group_id = "MIS.C.AgeTier" +sample_id = "ShortID" +celltype_id = "Annotation_v2.0" +``` + +In the sammple-agnostic / cell-level worklow, it is not possible to correct for batch effects or covariates. Therefore, you here have to use the following NA settings: + +```{r} +covariates = NA +batches = NA +``` + +__Important__: The column names of group, sample, and cell type should be syntactically valid (`make.names`) + +__Important__: All group, sample, and cell type names should be syntactically valid as well (`make.names`) (eg through `SummarizedExperiment::colData(sce)$ShortID = SummarizedExperiment::colData(sce)$ShortID %>% make.names()`) + +### Define the contrasts of interest. + +Here, we want to compare each patient group to the other groups, so the MIS-C (M) group vs healthy control siblings (S) and adult COVID19 patients (A) (= M vs S+A) and so on. We want to know which cell-cell communication patterns are specific for the M vs A+S group, the A vs M+S group and the S vs A+M group. + +To perform this comparison, we need to set the following contrasts: + +```{r} +contrasts_oi = c("'M-(S+A)/2','S-(M+A)/2','A-(S+M)/2'") +``` + +__Very Important__ Note the format to indicate the contrasts! This formatting should be adhered to very strictly, and white spaces are not allowed! Check `?get_DE_info` for explanation about how to define this well. The most important points are that: +*each contrast is surrounded by single quotation marks +*contrasts are separated by a comma without any white space +*all contrasts together are surrounded by double quotation marks. + +If you compare against two groups, you should divide by 2 (as demonstrated here), if you compare against three groups, you should divide by 3 and so on. + +For downstream visualizations and linking contrasts to their main condition, we also need to run the following: +This is necessary because we will also calculate cell-type+condition specificity of ligands and receptors. + +```{r} +contrast_tbl = tibble(contrast = + c("M-(S+A)/2","S-(M+A)/2", "A-(S+M)/2"), + group = c("M","S","A")) +``` + +If you want to compare only two groups (eg M vs S), you can use the following: +`contrasts_oi = c("'M-S','S-M'") ` +`contrast_tbl = tibble(contrast = c("M-S","S-M"), group = c("M","S"))` + +### Define the sender and receiver cell types of interest. + +If you want to focus the analysis on specific cell types (e.g. because you know which cell types reside in the same microenvironments based on spatial data), you can define this here. If you have sufficient computational resources and no specific idea of cell-type colocalzations, we recommend to consider all cell types as potential senders and receivers. Later on during analysis of the output it is still possible to zoom in on the cell types that interest you most, but your analysis is not biased to them. + +Here we will consider all cell types in the data: + +```{r} +senders_oi = SummarizedExperiment::colData(sce)[,celltype_id] %>% unique() +receivers_oi = SummarizedExperiment::colData(sce)[,celltype_id] %>% unique() +sce = sce[, SummarizedExperiment::colData(sce)[,celltype_id] %in% + c(senders_oi, receivers_oi) + ] +``` + +In case you would have samples in your data that do not belong to one of the groups/conditions of interest, we recommend removing them and only keeping conditions of interst: + +```{r} +conditions_keep = c("M", "S", "A") +sce = sce[, SummarizedExperiment::colData(sce)[,group_id] %in% + conditions_keep + ] +``` +# Running the MultiNicheNet core analysis + +Now we will run the core of a MultiNicheNet analysis. This analysis consists of the following steps: + +* 1. Cell-type filtering: determine which cell types are sufficiently present +* 2. Gene filtering: determine which genes are sufficiently expressed in each present cell type +* 3. Pseudobulk expression calculation: determine and normalize per-sample pseudobulk expression levels for each expressed gene in each present cell type +* 4. Differential expression (DE) analysis: determine which genes are differentially expressed +* 5. Ligand activity prediction: use the DE analysis output to predict the activity of ligands in receiver cell types and infer their potential target genes +* 6. Prioritization: rank cell-cell communication patterns through multi-criteria prioritization + +Following these steps, one can optionally +* 7. Calculate the across-samples expression correlation between ligand-receptor pairs and target genes +* 8. Prioritize communication patterns involving condition-specific cell types through an alternative prioritization scheme + +After these steps, the output can be further explored as we will demonstrate in the "Downstream analysis of the MultiNicheNet output" section. + +In this vignette, we will demonstrate these steps one-by-one, which offers the most flexibility to the user to assess intermediary results. Other vignettes will demonstrate the use of the `multi_nichenet_analysis` wrapper function. + +## Cell-type filtering: determine which cell types are sufficiently present + +In this step we will calculate and visualize cell type abundances. This will give an indication about which cell types will be retained in the analysis, and which cell types will be filtered out. + +In the following analysis we will a required minimum number of cells per cell type per condition at 10. Conditions that have less than `min_cells` cells will be excluded from the analysis for that specific cell type. + +```{r} +min_cells = 10 +``` + +```{r} +abundance_info = get_abundance_info( + sce = sce, + sample_id = group_id, group_id = group_id, celltype_id = celltype_id, + min_cells = min_cells, + senders_oi = senders_oi, receivers_oi = receivers_oi, + batches = batches + ) +``` + +First, we will check the cell type abundance diagnostic plots. + +### Interpretation of cell type abundance information + +The first plot visualizes the number of cells per celltype-condition combination, and indicates which combinations are removed during the DE analysis because there are less than `min_cells` in the celltype-condition combination. + +```{r} +abundance_info$abund_plot_sample +``` + +The red dotted line indicates the required minimum of cells as defined above in `min_cells`. We can see here that all cell types are present in all conditions. + +### Cell type filtering based on cell type abundance information + +In case this plot would indicate that not all cell types are present in all conditions: +running the following block of code can help you determine which cell types are condition-specific and which cell types are absent. + +```{r} +sample_group_celltype_df = abundance_info$abundance_data %>% + filter(n > min_cells) %>% + ungroup() %>% + distinct(sample_id, group_id) %>% + cross_join( + abundance_info$abundance_data %>% + ungroup() %>% + distinct(celltype_id) + ) %>% + arrange(sample_id) + +abundance_df = sample_group_celltype_df %>% left_join( + abundance_info$abundance_data %>% ungroup() + ) + +abundance_df$n[is.na(abundance_df$n)] = 0 +abundance_df$keep[is.na(abundance_df$keep)] = FALSE +abundance_df_summarized = abundance_df %>% + mutate(keep = as.logical(keep)) %>% + group_by(group_id, celltype_id) %>% + summarise(samples_present = sum((keep))) + +celltypes_absent_one_condition = abundance_df_summarized %>% + filter(samples_present == 0) %>% pull(celltype_id) %>% unique() +# find truly condition-specific cell types by searching for cell types +# truely absent in at least one condition + +celltypes_present_one_condition = abundance_df_summarized %>% + filter(samples_present >= 1) %>% pull(celltype_id) %>% unique() +# require presence in at least 1 samples of one group so +# it is really present in at least one condition + +condition_specific_celltypes = intersect( + celltypes_absent_one_condition, + celltypes_present_one_condition) + +total_nr_conditions = SummarizedExperiment::colData(sce)[,group_id] %>% + unique() %>% length() + +absent_celltypes = abundance_df_summarized %>% + filter(samples_present < 1) %>% + group_by(celltype_id) %>% + count() %>% + filter(n == total_nr_conditions) %>% + pull(celltype_id) + +print("condition-specific celltypes:") +print(condition_specific_celltypes) + +print("absent celltypes:") +print(absent_celltypes) +``` +Absent cell types will be filtered out, condition-specific cell types can be filtered out if you as a user do not want to run the alternative workflow for condition-specific cell types at the end of the core MultiNicheNet analysis. + +```{r} +analyse_condition_specific_celltypes = FALSE +``` + +```{r} +if(analyse_condition_specific_celltypes == TRUE){ + senders_oi = senders_oi %>% setdiff(absent_celltypes) + receivers_oi = receivers_oi %>% setdiff(absent_celltypes) +} else { + senders_oi = senders_oi %>% + setdiff(union(absent_celltypes, condition_specific_celltypes)) + receivers_oi = receivers_oi %>% + setdiff(union(absent_celltypes, condition_specific_celltypes)) +} + +sce = sce[, SummarizedExperiment::colData(sce)[,celltype_id] %in% + c(senders_oi, receivers_oi) + ] +``` + +## Gene filtering: determine which genes are sufficiently expressed in each present cell type + +Before running the DE analysis, we will determine which genes are not sufficiently expressed and should be filtered out. +We will perform gene filtering based on a similar procedure as used in `edgeR::filterByExpr`. However, we adapted this procedure to be more interpretable for single-cell datasets. + +For each cell type, we will consider genes expressed if they are expressed in at least one condition. To do this, we need to set `min_sample_prop = 1`. + +```{r} +min_sample_prop = 1 +``` + +But how do we define which genes are expressed in a condition? For this we will consider genes as expressed if they have non-zero expression values in a `fraction_cutoff` fraction of cells of that cell type in that condition By default, we set `fraction_cutoff = 0.05`, which means that genes should show non-zero expression values in at least 5% of cells in a condition + +```{r} +fraction_cutoff = 0.05 +``` + +We recommend using these default values unless there is specific interest in prioritizing (very) weakly expressed interactions. In that case, you could lower the value of `fraction_cutoff`. We explicitly recommend against using `fraction_cutoff > 0.10`. + +Now we will calculate the information required for gene filtering with the following command: + +```{r} +frq_list = get_frac_exprs_sampleAgnostic( + sce = sce, + sample_id = sample_id, celltype_id = celltype_id, group_id = group_id, + batches = batches, + min_cells = min_cells, + fraction_cutoff = fraction_cutoff, min_sample_prop = min_sample_prop) +``` +Now only keep genes that are expressed by at least one cell type: + +```{r} +genes_oi = frq_list$expressed_df %>% + filter(expressed == TRUE) %>% pull(gene) %>% unique() +sce = sce[genes_oi, ] +``` + +## Pseudobulk expression calculation: determine and normalize per-sample pseudobulk expression levels for each expressed gene in each present cell type + +After filtering out absent cell types and genes, we will continue the analysis by calculating the different prioritization criteria that we will use to prioritize cell-cell communication patterns. + +First, we will determine and normalize per-condition pseudobulk expression levels for each expressed gene in each present cell type. The function `process_abundance_expression_info` will link this expression information for ligands of the sender cell types to the corresponding receptors of the receiver cell types. This will later on allow us to define the cell-type specicificy criteria for ligands and receptors. + +```{r} +abundance_expression_info = process_abundance_expression_info( + sce = sce, + sample_id = group_id, group_id = group_id, celltype_id = celltype_id, + min_cells = min_cells, + senders_oi = senders_oi, receivers_oi = receivers_oi, + lr_network = lr_network, + batches = batches, + frq_list = frq_list, + abundance_info = abundance_info) +``` + +Normalized pseudobulk expression values per gene/celltype/condition can be inspected by: + +```{r} +abundance_expression_info$celltype_info$pb_df %>% head() +``` + +Inspecting these values for ligand-receptor interactions can be done by: + +```{r} +abundance_expression_info$sender_receiver_info$pb_df %>% head() +``` + +## Differential expression (DE) analysis: determine which genes are differentially expressed + +In this step, we will perform genome-wide differential expression analysis of receiver and sender cell types to define DE genes between the conditions of interest (as formalized by the `contrasts_oi`). Based on this analysis, we later can define the levels of differential expression of ligands in senders and receptors in receivers, and define the set of affected target genes in the receiver cell types (which will be used for the ligand activity analysis). + +Because we don't have several samples per condition, we cannot apply pseudobulking followed by EdgeR as done in the regular MultiNicheNet workflow. Instead, we will here perform a classic FindMarkers approach. This has as consequence that you cannot perform DE on multifactorial experimental designs. You can only compare one group vs other group(s). + +```{r} +DE_info = get_DE_info( + sce = sce, + sample_id = sample_id, group_id = group_id, celltype_id = celltype_id, + batches = batches, covariates = covariates, + contrasts_oi = contrasts_oi, + min_cells = min_cells, + expressed_df = frq_list$expressed_df, + findMarkers = TRUE, + contrast_tbl = contrast_tbl) +``` + +### Check DE results + +Check DE output information in table with logFC and p-values for each gene-celltype-contrast: + +```{r} +celltype_de = DE_info$celltype_de_findmarkers +``` + +```{r} +celltype_de %>% arrange(-logFC) %>% head() +``` + +### Combine DE information for ligand-senders and receptors-receivers + +To end this step, we will combine the DE information of senders and receivers by linking their ligands and receptors together based on the prior knowledge ligand-receptor network. + +```{r} +sender_receiver_de = combine_sender_receiver_de( + sender_de = celltype_de, + receiver_de = celltype_de, + senders_oi = senders_oi, + receivers_oi = receivers_oi, + lr_network = lr_network +) +``` + +```{r} +sender_receiver_de %>% head(20) +``` + +## Ligand activity prediction: use the DE analysis output to predict the activity of ligands in receiver cell types and infer their potential target genes + +In this step, we will predict NicheNet ligand activities and NicheNet ligand-target links based on these differential expression results. We do this to prioritize interactions based on their predicted effect on a receiver cell type. We will assume that the most important group-specific interactions are those that lead to group-specific gene expression changes in a receiver cell type. + +Similarly to base NicheNet (https://github.com/saeyslab/nichenetr), we use the DE output to create a "geneset of interest": here we assume that DE genes within a cell type may be DE because of differential cell-cell communication processes. In the ligand activity prediction, we will assess the enrichment of target genes of ligands within this geneset of interest. In case high-probabiliy target genes of a ligand are enriched in this set compared to the background of expressed genes, we predict that this ligand may have a high activity. + +Because the ligand activity analysis is an enrichment procedure, it is important that this geneset of interest should contain a sufficient but not too large number of genes. The ratio geneset_oi/background should ideally be between 1/200 and 1/10 (or close to these ratios). + +To determine the genesets of interest based on DE output, we need to define some logFC and/or p-value thresholds per cell type/contrast combination. In general, we recommend inspecting the nr. of DE genes for all cell types based on the default thresholds and adapting accordingly. + +### Assess geneset_oi-vs-background ratios for different DE output tresholds prior to the NicheNet ligand activity analysis + +We will first inspect the geneset_oi-vs-background ratios for the default tresholds: + +```{r} +logFC_threshold = 0.25 # lower here for FindMarkers than for Pseudobulk-EdgeR +p_val_threshold = 0.05 +``` + +```{r} +p_val_adj = TRUE +``` + +```{r} +geneset_assessment = contrast_tbl$contrast %>% + lapply( + process_geneset_data, + celltype_de, logFC_threshold, p_val_adj, p_val_threshold + ) %>% + bind_rows() +geneset_assessment +``` +We can see here that for most cell type / contrast combinations, all geneset/background ratio's are within the recommended range (`in_range_up` and `in_range_down` columns). When these geneset/background ratio's would not be within the recommended ranges, we should interpret ligand activity results for these cell types with more caution, or use different thresholds (for these or all cell types). Here, a few celltype-contrast combination are not in the recommended range for up- and or-down genes but they are close (recommend ranges between 0.005 and 0.1). + +### Perform the ligand activity analysis and ligand-target inference + +After the ligand activity prediction, we will also infer the predicted target genes of these ligands in each contrast. For this ligand-target inference procedure, we also need to select which top n of the predicted target genes will be considered (here: top 250 targets per ligand). This parameter will not affect the ligand activity predictions. It will only affect ligand-target visualizations and construction of the intercellular regulatory network during the downstream analysis. We recommend users to test other settings in case they would be interested in exploring fewer, but more confident target genes, or vice versa. + +```{r} +top_n_target = 250 +``` + +The NicheNet ligand activity analysis can be run in parallel for each receiver cell type, by changing the number of cores as defined here. Using more cores will speed up the analysis at the cost of needing more memory. This is only recommended if you have many receiver cell types of interest. + +```{r} +verbose = TRUE +cores_system = 8 +n.cores = min(cores_system, celltype_de$cluster_id %>% unique() %>% length()) +``` + +Running the ligand activity prediction will take some time (the more cell types and contrasts, the more time) + +```{r} +ligand_activities_targets_DEgenes = suppressMessages(suppressWarnings( + get_ligand_activities_targets_DEgenes( + receiver_de = celltype_de, + receivers_oi = intersect(receivers_oi, celltype_de$cluster_id %>% unique()), + ligand_target_matrix = ligand_target_matrix, + logFC_threshold = logFC_threshold, + p_val_threshold = p_val_threshold, + p_val_adj = p_val_adj, + top_n_target = top_n_target, + verbose = verbose, + n.cores = n.cores + ) +)) +``` + +You can check the output of the ligand activity and ligand-target inference here: + +```{r} +ligand_activities_targets_DEgenes$ligand_activities %>% head(20) +``` + +## Prioritization: rank cell-cell communication patterns through multi-criteria prioritization + +In the previous steps, we calculated expression, differential expression and NicheNet ligand activity. In the final step, we will now combine all calculated information to rank all sender-ligand---receiver-receptor pairs according to group/condition specificity. We will use the following criteria to prioritize ligand-receptor interactions: + +* Upregulation of the ligand in a sender cell type and/or upregulation of the receptor in a receiver cell type - in the condition of interest. +* Cell-type specific expression of the ligand in the sender cell type and receptor in the receiver cell type in the condition of interest (to mitigate the influence of upregulated but still relatively weakly expressed ligands/receptors). +* Sufficiently high expression levels of ligand and receptor in many samples of the same group. +* High NicheNet ligand activity, to further prioritize ligand-receptor pairs based on their predicted effect of the ligand-receptor interaction on the gene expression in the receiver cell type. + +We will combine these prioritization criteria in a single aggregated prioritization score. In the default setting, we will weigh each of these criteria equally (`scenario = "regular"`). This setting is strongly recommended. However, we also provide some additional setting to accomodate different biological scenarios. The setting `scenario = "lower_DE"` halves the weight for DE criteria and doubles the weight for ligand activity. This is recommended in case your hypothesis is that the differential CCC patterns in your data are less likely to be driven by DE (eg in cases of differential migration into a niche). The setting `scenario = "no_frac_LR_expr"` ignores the criterion "Sufficiently high expression levels of ligand and receptor in many samples of the same group". This may be interesting for users that have data with a limited number of samples and don’t want to penalize interactions if they are not sufficiently expressed in some samples. + +Finally, we still need to make one choice. For NicheNet ligand activity we can choose to prioritize ligands that only induce upregulation of target genes (`ligand_activity_down = FALSE`) or can lead potentially lead to both up- and downregulation (`ligand_activity_down = TRUE`). The benefit of `ligand_activity_down = FALSE` is ease of interpretability: prioritized ligand-receptor pairs will be upregulated in the condition of interest, just like their target genes. `ligand_activity_down = TRUE` can be harder to interpret because target genes of some interactions may be upregulated in the other conditions compared to the condition of interest. This is harder to interpret, but may help to pick up interactions that can also repress gene expression. + +Here we will choose for setting `ligand_activity_down = FALSE` and focus specifically on upregulating ligands. + +```{r} +ligand_activity_down = FALSE +``` + +```{r} +sender_receiver_tbl = sender_receiver_de %>% distinct(sender, receiver) + +metadata_combined = SummarizedExperiment::colData(sce) %>% tibble::as_tibble() + + if(!is.na(batches)){ + grouping_tbl = metadata_combined[,c(group_id, batches)] %>% tibble::as_tibble() %>% dplyr::distinct() + colnames(grouping_tbl) = c("group",batches) + grouping_tbl = grouping_tbl %>% mutate(sample = group) + grouping_tbl = grouping_tbl %>% tibble::as_tibble() + } else { + grouping_tbl = metadata_combined[,c(group_id)] %>% tibble::as_tibble() %>% dplyr::distinct() + colnames(grouping_tbl) = c("group") + grouping_tbl = grouping_tbl %>% mutate(sample = group) %>% select(sample, group) + + } + +prioritization_tables = suppressMessages(generate_prioritization_tables( + sender_receiver_info = abundance_expression_info$sender_receiver_info, + sender_receiver_de = sender_receiver_de, + ligand_activities_targets_DEgenes = ligand_activities_targets_DEgenes, + contrast_tbl = contrast_tbl, + sender_receiver_tbl = sender_receiver_tbl, + grouping_tbl = grouping_tbl, + scenario = "regular", # all prioritization criteria will be weighted equally + fraction_cutoff = fraction_cutoff, + abundance_data_receiver = abundance_expression_info$abundance_data_receiver, + abundance_data_sender = abundance_expression_info$abundance_data_sender, + ligand_activity_down = ligand_activity_down + )) +``` + +Check the output tables + +First: group-based summary table + +```{r} +prioritization_tables$group_prioritization_tbl %>% head(20) +``` +This table gives the final prioritization score of each interaction, and the values of the individual prioritization criteria. + +With this step, all required steps are finished. Now, we can optionally still run the following steps +* Prioritize communication patterns involving condition-specific cell types through an alternative prioritization scheme +However, this is not relevant for this dataset since there are no condition-specific cell types here. + +## Save all the output of MultiNicheNet + +To avoid needing to redo the analysis later, we will here to save an output object that contains all information to perform all downstream analyses. + +```{r} +path = "./" + +multinichenet_output = list( + celltype_info = abundance_expression_info$celltype_info, + celltype_de = celltype_de, + sender_receiver_info = abundance_expression_info$sender_receiver_info, + sender_receiver_de = sender_receiver_de, + ligand_activities_targets_DEgenes = ligand_activities_targets_DEgenes, + prioritization_tables = prioritization_tables, + grouping_tbl = grouping_tbl, + lr_target_prior_cor = tibble() + ) +multinichenet_output = make_lite_output(multinichenet_output) + +save = FALSE +if(save == TRUE){ + saveRDS(multinichenet_output, paste0(path, "multinichenet_output.rds")) + +} +``` + +# Interpreting the MultiNicheNet analysis output + +## Visualization of differential cell-cell interactions + +### Summarizing ChordDiagram circos plots + +In a first instance, we will look at the broad overview of prioritized interactions via condition-specific Chordiagram circos plots. + +We will look here at the top 50 predictions across all contrasts, senders, and receivers of interest. + +```{r} +prioritized_tbl_oi_all = get_top_n_lr_pairs( + multinichenet_output$prioritization_tables, + top_n = 50, + rank_per_group = FALSE + ) +``` + +```{r, fig.width=7, fig.height=7} +prioritized_tbl_oi = + multinichenet_output$prioritization_tables$group_prioritization_tbl %>% + filter(id %in% prioritized_tbl_oi_all$id) %>% + distinct(id, sender, receiver, ligand, receptor, group) %>% + left_join(prioritized_tbl_oi_all) +prioritized_tbl_oi$prioritization_score[is.na(prioritized_tbl_oi$prioritization_score)] = 0 + +senders_receivers = union(prioritized_tbl_oi$sender %>% unique(), prioritized_tbl_oi$receiver %>% unique()) %>% sort() + +colors_sender = RColorBrewer::brewer.pal(n = length(senders_receivers), name = 'Spectral') %>% magrittr::set_names(senders_receivers) +colors_receiver = RColorBrewer::brewer.pal(n = length(senders_receivers), name = 'Spectral') %>% magrittr::set_names(senders_receivers) + +circos_list = make_circos_group_comparison(prioritized_tbl_oi, colors_sender, colors_receiver) +``` + +### Interpretable bubble plots + +Whereas these ChordDiagrams show the most specific interactions per group, they don't give insights into the data behind these predictions. Therefore we will now look at visualizations that indicate the different prioritization criteria used in MultiNicheNet. + +In the next type of plots, we will 1) visualize the per-sample scaled product of normalized ligand and receptor pseudobulk expression, 2) visualize the scaled ligand activities, 3) cell-type specificity. + +We will now check the top 50 interactions specific for the MIS-C group + +```{r} +group_oi = "M" +``` + +```{r} +prioritized_tbl_oi_M_50 = get_top_n_lr_pairs( + multinichenet_output$prioritization_tables, + top_n = 50, + groups_oi = group_oi) +``` + +```{r, fig.height=13, fig.width=16} +plot_oi = make_sample_lr_prod_activity_plots( + multinichenet_output$prioritization_tables, + prioritized_tbl_oi_M_50) +plot_oi +``` +Samples that were left out of the DE analysis are indicated with a smaller dot (this helps to indicate the samples that did not contribute to the calculation of the logFC, and thus not contributed to the final prioritization) + +As a further help for further prioritization, we can assess the level of curation of these LR pairs as defined by the Intercellular Communication part of the Omnipath database + +```{r} +prioritized_tbl_oi_M_50_omnipath = prioritized_tbl_oi_M_50 %>% + inner_join(lr_network_all) +``` + +Now we add this to the bubble plot visualization: +```{r, fig.height=13, fig.width=16} +plot_oi = make_sample_lr_prod_activity_plots_Omnipath( + multinichenet_output$prioritization_tables, + prioritized_tbl_oi_M_50_omnipath) +plot_oi +``` + +As you can see, the HEBP1-FPR2 interaction has no Omnipath DB scores. This is because this LR pair was not documented by the Omnipath LR database. Instead it was documented by the original NicheNet LR network (source: Guide2Pharmacology) as can be seen in the table. + +Further note: Typically, there are way more than 50 differentially expressed and active ligand-receptor pairs per group across all sender-receiver combinations. Therefore it might be useful to zoom in on specific cell types as senders/receivers: + +Eg M_Monocyte_CD16 as receiver: + +```{r} +prioritized_tbl_oi_M_50 = get_top_n_lr_pairs( + multinichenet_output$prioritization_tables, + 50, + groups_oi = group_oi, + receivers_oi = "M_Monocyte_CD16") +``` + +```{r, fig.height=13, fig.width=16} +plot_oi = make_sample_lr_prod_activity_plots_Omnipath( + multinichenet_output$prioritization_tables, + prioritized_tbl_oi_M_50 %>% inner_join(lr_network_all)) +plot_oi +``` + +Eg M_Monocyte_CD16 as sender: + +```{r} +prioritized_tbl_oi_M_50 = get_top_n_lr_pairs( + multinichenet_output$prioritization_tables, + 50, + groups_oi = group_oi, + senders_oi = "M_Monocyte_CD16") +``` + +```{r, fig.height=13, fig.width=16} +plot_oi = make_sample_lr_prod_activity_plots_Omnipath( + multinichenet_output$prioritization_tables, + prioritized_tbl_oi_M_50 %>% inner_join(lr_network_all)) +plot_oi +``` + +You can make these plots also for the other groups, like we will illustrate now for the S group + +```{r} +group_oi = "S" +``` + +```{r, fig.height=13, fig.width=18} +prioritized_tbl_oi_S_50 = get_top_n_lr_pairs( + multinichenet_output$prioritization_tables, + 50, + groups_oi = group_oi) + +plot_oi = make_sample_lr_prod_activity_plots_Omnipath( + multinichenet_output$prioritization_tables, + prioritized_tbl_oi_S_50 %>% inner_join(lr_network_all)) +plot_oi +``` + + +## Visualization of differential ligand-target links + +### Without filtering of target genes based on LR-target expression correlation + +In another type of plot, we can visualize the ligand activities for a group-receiver combination, and show the predicted ligand-target links, and also the expression of the predicted target genes across samples. + +For this, we now need to define a receiver cell type of interest. As example, we will take `L_T_TIM3._CD38._HLADR.` cells as receiver, and look at the top 10 senderLigand-receiverReceptor pairs with these cells as receiver. + +```{r} +group_oi = "M" +receiver_oi = "M_Monocyte_CD16" +prioritized_tbl_oi_M_10 = get_top_n_lr_pairs( + multinichenet_output$prioritization_tables, + 10, + groups_oi = group_oi, + receivers_oi = receiver_oi) +``` + +```{r, fig.width=20, fig.height=7} +combined_plot = make_ligand_activity_target_plot( + group_oi, + receiver_oi, + prioritized_tbl_oi_M_10, + multinichenet_output$prioritization_tables, + multinichenet_output$ligand_activities_targets_DEgenes, contrast_tbl, + multinichenet_output$grouping_tbl, + multinichenet_output$celltype_info, + ligand_target_matrix, + plot_legend = FALSE) +combined_plot +```