Last updated: 2022-02-23
Checks: 6 1
Knit directory: MelanomaIMC/
This reproducible R Markdown analysis was created with workflowr (version 1.7.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.
The R Markdown file has unstaged changes. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish
to commit the R Markdown file and build the HTML.
Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.
The command set.seed(20200728)
was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.
Great job! Recording the operating system, R version, and package versions is critical for reproducibility.
Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.
Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.
Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.
The results in this page were generated with repository version cd92c51. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.
Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish
or wflow_git_commit
). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:
Ignored files:
Ignored: .DS_Store
Ignored: .Rproj.user/
Ignored: code/.DS_Store
Ignored: code/._.DS_Store
Ignored: data/.DS_Store
Ignored: data/._.DS_Store
Ignored: data/data_for_analysis/
Ignored: data/data_for_analysis_zenodo/
Ignored: data/full_data.zip
Ignored: data/full_data/
Unstaged changes:
Modified: .gitignore
Modified: analysis/Supp-Figure_9.rmd
Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.
These are the previous versions of the repository in which changes were made to the R Markdown (analysis/Supp-Figure_9.rmd
) and HTML (docs/Supp-Figure_9.html
) files. If you’ve configured a remote Git repository (see ?wflow_git_remote
), click on the hyperlinks in the table below to view the files as they were in that past version.
File | Version | Author | Date | Message |
---|---|---|---|---|
html | fe331cb | toobiwankenobi | 2022-02-22 | re-run whole analysis |
html | d246c15 | toobiwankenobi | 2022-02-22 | update Supp Fig 9 |
Rmd | 64e5fde | toobiwankenobi | 2022-02-16 | change order and naming of supp fig files |
Rmd | b20b6fb | toobiwankenobi | 2022-02-02 | update code for Supp Figures |
Rmd | 3da15db | toobiwankenobi | 2021-11-24 | changes for revision |
This script generates plots for Supplementary Figure 9.
sapply(list.files("code/helper_functions", full.names = TRUE), source)
code/helper_functions/calculateSummary.R
value ?
visible FALSE
code/helper_functions/censor_dat.R
value ?
visible FALSE
code/helper_functions/detect_mRNA_expression.R
value ?
visible FALSE
code/helper_functions/DistanceToClusterCenter.R
value ?
visible FALSE
code/helper_functions/findMilieu.R code/helper_functions/findPatch.R
value ? ?
visible FALSE FALSE
code/helper_functions/getInfoFromString.R
value ?
visible FALSE
code/helper_functions/getSpotnumber.R
value ?
visible FALSE
code/helper_functions/plotCellCounts.R
value ?
visible FALSE
code/helper_functions/plotCellFractions.R
value ?
visible FALSE
code/helper_functions/plotDist.R code/helper_functions/read_Data.R
value ? ?
visible FALSE FALSE
code/helper_functions/scatter_function.R
value ?
visible FALSE
code/helper_functions/sceChecks.R
value ?
visible FALSE
code/helper_functions/validityChecks.R
value ?
visible FALSE
library(SingleCellExperiment)
library(dplyr)
library(ggplot2)
library(ggbeeswarm)
library(tidyr)
library(scater)
library(dittoSeq)
library(gridExtra)
library(cowplot)
library(data.table)
library(ggpmisc)
library(ggpubr)
library(ComplexHeatmap)
library(rstatix)
library(dendextend)
library(parallel)
library(neighbouRhood)
library(unix)
library(cytomapper)
# SCE object
sce_rna = readRDS(file = "data/data_for_analysis/sce_RNA.rds")
sce_prot = readRDS(file = "data/data_for_analysis/sce_protein.rds")
sce_rna <- sce_rna[,sce_rna$Location != "CTRL"]
sce_prot <- sce_prot[,sce_prot$Location != "CTRL"]
# meta data
dat_relation = fread(file = "data/data_for_analysis/protein/Object relationships.csv",stringsAsFactors = FALSE)
dat_relation_rna = fread(file = "data/data_for_analysis/RNA/Object relationships.csv",stringsAsFactors = FALSE)
targets <- metadata(sce_rna)$chemokines_morethan600_withcontrol
# prepare data
dat_relation$cellID_first <- paste("RNA", paste(dat_relation$`First Image Number`, dat_relation$`First Object Number`, sep = "_"), sep = "_")
dat_relation$cellID_second <- paste("RNA", paste(dat_relation$`Second Image Number`, dat_relation$`Second Object Number`, sep = "_"), sep = "_")
all_mask <- loadImages(x = "data/full_data/rna/cpout/",
pattern = "ilastik_s2_Probabilities_equalized_cellmask.tiff")
# we load the metadata for the images.
image_mat_rna <- as.data.frame(read.csv(file = "data/data_for_analysis/rna/Image.csv",stringsAsFactors = FALSE))
# we extract only the FileNames of the masks as they are in the all_masks object
cur_df <- data.frame(cellmask = image_mat_rna$FileName_cellmask,
ImageNumber = image_mat_rna$ImageNumber,
Description = image_mat_rna$Metadata_Description)
# we set the rownames of the extracted data to be equal to the names of all_masks
rownames(cur_df) <- gsub(pattern = ".tiff",replacement = "",image_mat_rna$FileName_cellmask)
# we add the extracted information via mcols in the order of the all_masks object
mcols(all_mask) <- cur_df[names(all_mask),]
all_mask <- scaleImages(all_mask,2^16-1)
# select the images K10 (absent), K3 (low), A11 (med), N3 (high) as representative images for the T cell grouping
# subset masks
mask_sub <- all_mask[mcols(all_mask)$Description %in% c("K10", "N3", "K3", "A11")]
sce_prot_sub <- sce_prot[,sce_prot$Description %in% c("K10", "N3", "K3", "A11")]
# rename all cells that are not CD8+ T cell
sce_prot_sub$celltype <- ifelse(sce_prot_sub$celltype %in% c("CD8+ T cell"), sce_prot_sub$celltype, "Other")
# create color vector
col_list <- list()
col_list$`Cell Type` <- metadata(sce_prot)$colour_vectors$celltype[c("Tumor", "CD8+ T cell")]
names(col_list$`Cell Type`) <- c("Other", "CD8+ T cell")
col_list$`Cell Type`["CD8+ T cell"] <- "green"
sce_prot_sub$`Cell Type` <- sce_prot_sub$celltype
plotCells(mask = mask_sub,
object = sce_prot_sub,
cell_id = "CellNumber", img_id = "Description",
colour_by = "Cell Type",
colour = col_list)
targets <- metadata(sce_rna)$chemokines_morethan600_withcontrol
frac <- data.frame(colData(sce_rna)) %>%
filter(Location != "CTRL") %>%
group_by(Description, Tcell_density_score_image, expressor) %>%
summarise(n=n()) %>%
mutate(fraction = n / sum(n)) %>%
filter(expressor %in% targets) %>%
reshape2::dcast(Description + Tcell_density_score_image ~ expressor, value.var = "fraction", fill = 0) %>%
reshape2::melt(id.vars = c("Description", "Tcell_density_score_image"), variable.name = "expressor", value.name = "fraction")
stat.test <- frac %>%
group_by(expressor) %>%
kruskal_test(data = ., fraction ~ Tcell_density_score_image) %>%
adjust_pvalue(method = "BH") %>%
add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1)) %>%
arrange(p.adj) %>%
mutate(group1 = expressor, group2 = expressor) %>%
add_x_position()
frac$expressor <- factor(frac$expressor, levels = stat.test$expressor)
ggplot(frac, aes(x=expressor, y = fraction)) +
geom_boxplot(alpha=.75, outlier.size = 0.5, aes(fill = Tcell_density_score_image)) +
stat_pvalue_manual(x = "group1", y.position = 0.055, stat.test, size = 4) +
scale_color_discrete(guide = FALSE) +
theme_bw() +
theme(text = element_text(size = 15),
axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) +
guides(fill=guide_legend(title="T cell Score")) +
xlab("") +
ylab("Fractions") +
coord_cartesian(ylim = c(0,0.06))
Warning: It is deprecated to specify `guide = FALSE` to remove a guide. Please
use `guide = "none"` instead.
# Create table with celltype fractions
cur_df <- data.frame(celltype = sce_prot$celltype,
Description = sce_prot$Description,
Location = sce_prot$Location)
# remove control samples
cur_df <- cur_df %>%
filter(Location != "CTRL") %>%
group_by(Description, celltype) %>%
summarise(n=n()) %>%
group_by(Description) %>%
mutate(fraction = n / sum(n)) %>%
reshape2::dcast(Description ~ celltype, value.var = "fraction", fill=0)
matrixrownames <- cur_df$Description
# now we create a matrix from the data and cluster the data based on the cell fractions
hm_dat = as.matrix(cur_df[,-1])
rownames(hm_dat) <- as.character(matrixrownames)
# calculate distance and then cluster images based on cluster fraction
dd <- dist((hm_dat), method = "euclidean")
hc <- hclust(dd, method = "ward.D2")
row_sorted <- hc$labels
dend <- as.dendrogram(hc)
clusters <- data.frame(cutree(dend, k=4)) #### order_clusters_as_data = FALSE??
clusters_1E <- color_branches(dend, k = 4, col = c("gray50", "blue", "green", "red"), groupLabels = TRUE)
# get labels from dend
dend_labels <- clusters_1E %>%
labels()
# change colnames
colnames(clusters) <- "dend_cluster"
clusters$Description <- rownames(clusters)
# same orientation as in 1E
clusters <- clusters[match(dend_labels, clusters$Description),]
# change cluster names
clusters$cluster_name <- ""
clusters[clusters$dend_cluster == 3,]$cluster_name <- "Grey Branch"
clusters[clusters$dend_cluster == 4,]$cluster_name <- "Blue Branch"
clusters[clusters$dend_cluster == 2,]$cluster_name <- "Green Branch"
clusters[clusters$dend_cluster == 1,]$cluster_name <- "Red Branch"
# add cluster to sce_rna object
all_dat <- data.frame(colData(sce_rna))[,c("Description", "ImageNumber")]
all_dat <- left_join(all_dat, clusters)
sce_rna$cluster_name <- as.character(all_dat$cluster_name)
sce_rna$cluster_name <- factor(sce_rna$cluster_name, levels = c("Red Branch", "Green Branch", "Blue Branch", "Grey Branch"))
targets <- metadata(sce_rna)$chemokines_morethan600_withcontrol
frac <- data.frame(colData(sce_rna)) %>%
filter(Location != "CTRL") %>%
group_by(Description, cluster_name, expressor) %>%
summarise(n=n()) %>%
mutate(fraction = n / sum(n)) %>%
filter(expressor %in% targets) %>%
reshape2::dcast(Description + cluster_name ~ expressor, value.var = "fraction", fill = 0) %>%
reshape2::melt(id.vars = c("Description", "cluster_name"), variable.name = "expressor", value.name = "fraction")
stat.test <- frac %>%
group_by(expressor) %>%
kruskal_test(data = ., fraction ~ cluster_name) %>%
adjust_pvalue(method = "BH") %>%
add_significance("p.adj",cutpoints = c(0, 1e-04, 0.001, 0.01, 0.1, 1)) %>%
arrange(p.adj) %>%
mutate(group1 = expressor, group2 = expressor) %>%
add_x_position()
frac$expressor <- factor(frac$expressor, levels = stat.test$expressor)
ggplot(frac, aes(x=expressor, y = fraction)) +
geom_boxplot(alpha=.75, outlier.size = 0.5, aes(fill = cluster_name)) +
stat_pvalue_manual(x = "group1", y.position = 0.055, stat.test, size = 4) +
scale_color_discrete(guide = FALSE) +
theme_bw() +
theme(text = element_text(size = 15),
axis.text.x = element_text(angle = 45, vjust = 1, hjust=1)) +
guides(fill=guide_legend(title="Dendrogram Cluster")) +
xlab("") +
scale_fill_manual(values=c("red", "green", "blue", "grey")) +
ylab("Fractions") +
coord_cartesian(ylim = c(0,0.06))
Warning: It is deprecated to specify `guide = FALSE` to remove a guide. Please
use `guide = "none"` instead.
# Load and prepare
dat_cells = fread(file = "data/data_for_analysis/rna/cell.csv",stringsAsFactors = FALSE)
dat_relation = fread(file = "data/data_for_analysis/rna/Object relationships.csv",stringsAsFactors = FALSE)
# Number of cores used for multicore:
if(detectCores() >= 12){
ncores = round(detectCores()/1.25,0)
}
if(detectCores() > 1 & detectCores() < 12){
ncores = round(detectCores()/2,0)
}
if(detectCores() == 1){
ncores = 1
}
n_perm = 100
start = Sys.time()
cur_sce <- as.data.frame(colData(sce_rna))
# add same cellID to dat_cells as in sce object
dat_cells$cellID <- paste("RNA_", paste(dat_cells$ImageNumber, dat_cells$ObjectNumber, sep = "_"), sep = "")
image_df <- data.frame()
gc()
used (Mb) gc trigger (Mb) max used (Mb)
Ncells 11795507 630 18778532 1002.9 18778532 1002.9
Vcells 907534761 6924 1309232800 9988.7 1090431471 8319.4
rlimit_as(Inf)
$cur
[1] Inf
$max
[1] Inf
for(size in c(2,3,4,5,6)) {
images <- data.frame()
for(i in colnames(cur_sce[,grepl("CCL|CXCL",colnames(cur_sce))])){
# add chemokine info to celltype
sce_info <- cur_sce[,c("cellID", i , "Description")]
# add celltype information
dat_cells_tmp <- left_join(as.data.frame(dat_cells), sce_info, by = "cellID")
#assign labels and groups
dat_cells_tmp$label <- dat_cells_tmp[,i]
dat_cells_tmp$group <- dat_cells_tmp$Description
dat_cells_tmp <- as.data.table(dat_cells_tmp)
# subset dat_relation and dat_cells
dat_cells_sub <- dat_cells_tmp
dat_relation_sub <- dat_relation
# Prepare the data
d = neighbouRhood::prepare_tables(dat_cells_sub, dat_relation_sub)
# Calculate the baseline statistics
dat_baseline = neighbouRhood::apply_labels(d[[1]], d[[2]]) %>%
neighbouRhood::aggregate_classic_patch(., patch_size = size)
# Calculate the permutation statistics
# This will run the test using parallel computing. The name of the idcol does actually not matter.
set.seed(12312)
dat_perm = rbindlist(mclapply(1:n_perm, function(x){
dat_labels = neighbouRhood::shuffle_labels(d[[1]])
neighbouRhood::apply_labels(dat_labels, d[[2]]) %>%
neighbouRhood::aggregate_classic_patch(., patch_size = size)
},mc.cores = ncores
), idcol = 'run')
# calc p values
dat_p <- neighbouRhood::calc_p_vals(dat_baseline, dat_perm, n_perm = n_perm, p_tresh = 0.01)
# select interactions between chemokine+ cells
dat_p$interaction <- paste(dat_p$FirstLabel, dat_p$SecondLabel, sep = "_")
dat_p_wide <- dat_p %>%
reshape2::dcast(group ~ interaction, value.var = "sigval", fill = 0) %>%
select(group, `1_1`)
summary <- as.data.frame(dat_p_wide) %>%
group_by(`1_1`) %>%
summarise(n=n(),.groups = 'drop') %>%
ungroup() %>%
mutate(percentage_sig = (n/sum(n)) * 100)
images <- rbind(images, cbind(summary[1,], i))
gc()
}
# calculate percentage of images with significant patches
images$percentage_sig <- 100 - images$percentage_sig
images$patch_size <- size
images <- select(images, percentage_sig, i, patch_size)
colnames(images) <- c("significant_images", "chemokine", "patch_size")
# add to data.frame
image_df <- rbind(image_df, images)
}
end = Sys.time()
print(end-start)
Time difference of 27.07411 mins
dat <- image_df %>%
reshape2::dcast(chemokine ~ patch_size, value.var = "significant_images", fill = 0)
rownames(dat) <- dat$chemokine
dat$chemokine <- NULL
m <- t(as.matrix(dat))
col_fun = viridis::inferno(100)
Heatmap(m,
cluster_rows = FALSE,
col = col_fun,
column_title = "Self-Interaction",
column_title_side = "bottom",
show_row_names = TRUE,
cell_fun = function(j, i, x, y, width, height, fill) {
grid.text(sprintf("%.1f", m[i, j]), x, y, gp = gpar(fontsize = 15, col = "grey"))
},
heatmap_legend_param = list(
title = "% Significant\nImages", at = c(0, 10, 20, 30, 40, 50),
labels = c("0%", "10%", "20%", "30%","40%", "50%")),
row_title = "Motif Size",
row_names_side = "left",
width = unit(15, "cm"),
height = unit(8, "cm"))
sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 20.04.3 LTS
Matrix products: default
BLAS/LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
[3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
[5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
[7] LC_PAPER=en_US.UTF-8 LC_NAME=C
[9] LC_ADDRESS=C LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
attached base packages:
[1] parallel grid stats4 stats graphics grDevices utils
[8] datasets methods base
other attached packages:
[1] cytomapper_1.6.0 EBImage_4.36.0
[3] unix_1.5.4 neighbouRhood_0.4
[5] magrittr_2.0.2 dtplyr_1.2.1
[7] dendextend_1.15.2 rstatix_0.7.0
[9] ComplexHeatmap_2.10.0 ggpubr_0.4.0
[11] ggpmisc_0.4.5 ggpp_0.4.3
[13] data.table_1.14.2 cowplot_1.1.1
[15] gridExtra_2.3 dittoSeq_1.6.0
[17] scater_1.22.0 scuttle_1.4.0
[19] tidyr_1.2.0 ggbeeswarm_0.6.0
[21] ggplot2_3.3.5 SingleCellExperiment_1.16.0
[23] SummarizedExperiment_1.24.0 Biobase_2.54.0
[25] GenomicRanges_1.46.1 GenomeInfoDb_1.30.1
[27] IRanges_2.28.0 S4Vectors_0.32.3
[29] BiocGenerics_0.40.0 MatrixGenerics_1.6.0
[31] matrixStats_0.61.0 dplyr_1.0.7
[33] workflowr_1.7.0
loaded via a namespace (and not attached):
[1] backports_1.4.1 circlize_0.4.13
[3] systemfonts_1.0.3 plyr_1.8.6
[5] sp_1.4-6 shinydashboard_0.7.2
[7] BiocParallel_1.28.3 digest_0.6.29
[9] foreach_1.5.2 htmltools_0.5.2
[11] magick_2.7.3 viridis_0.6.2
[13] tiff_0.1-11 fansi_1.0.2
[15] ScaledMatrix_1.2.0 cluster_2.1.2
[17] doParallel_1.0.16 svgPanZoom_0.3.4
[19] svglite_2.0.0 jpeg_0.1-9
[21] colorspace_2.0-2 ggrepel_0.9.1
[23] xfun_0.29 callr_3.7.0
[25] crayon_1.4.2 RCurl_1.98-1.5
[27] jsonlite_1.7.3 iterators_1.0.13
[29] glue_1.6.1 gtable_0.3.0
[31] zlibbioc_1.40.0 XVector_0.34.0
[33] MatrixModels_0.5-0 GetoptLong_1.0.5
[35] DelayedArray_0.20.0 car_3.0-12
[37] BiocSingular_1.10.0 Rhdf5lib_1.16.0
[39] shape_1.4.6 HDF5Array_1.22.1
[41] abind_1.4-5 SparseM_1.81
[43] scales_1.1.1 pheatmap_1.0.12
[45] DBI_1.1.2 Rcpp_1.0.8
[47] xtable_1.8-4 viridisLite_0.4.0
[49] clue_0.3-60 rsvd_1.0.5
[51] htmlwidgets_1.5.4 httr_1.4.2
[53] RColorBrewer_1.1-2 ellipsis_0.3.2
[55] farver_2.1.0 pkgconfig_2.0.3
[57] sass_0.4.0 locfit_1.5-9.4
[59] utf8_1.2.2 labeling_0.4.2
[61] reshape2_1.4.4 tidyselect_1.1.1
[63] rlang_1.0.0 later_1.3.0
[65] munsell_0.5.0 tools_4.1.2
[67] cli_3.1.1 generics_0.1.2
[69] broom_0.7.12 ggridges_0.5.3
[71] fftwtools_0.9-11 evaluate_0.14
[73] stringr_1.4.0 fastmap_1.1.0
[75] yaml_2.2.2 processx_3.5.2
[77] knitr_1.37 fs_1.5.2
[79] purrr_0.3.4 sparseMatrixStats_1.6.0
[81] mime_0.12 whisker_0.4
[83] quantreg_5.87 compiler_4.1.2
[85] rstudioapi_0.13 beeswarm_0.4.0
[87] png_0.1-7 ggsignif_0.6.3
[89] tibble_3.1.6 bslib_0.3.1
[91] stringi_1.7.6 highr_0.9
[93] ps_1.6.0 lattice_0.20-45
[95] Matrix_1.4-0 vctrs_0.3.8
[97] rhdf5filters_1.6.0 pillar_1.7.0
[99] lifecycle_1.0.1 jquerylib_0.1.4
[101] GlobalOptions_0.1.2 BiocNeighbors_1.12.0
[103] bitops_1.0-7 irlba_2.3.5
[105] raster_3.5-15 httpuv_1.6.5
[107] R6_2.5.1 promises_1.2.0.1
[109] vipor_0.4.5 codetools_0.2-18
[111] assertthat_0.2.1 rhdf5_2.38.0
[113] rprojroot_2.0.2 rjson_0.2.21
[115] withr_2.4.3 GenomeInfoDbData_1.2.7
[117] terra_1.5-17 beachmat_2.10.0
[119] rmarkdown_2.11 DelayedMatrixStats_1.16.0
[121] carData_3.0-5 git2r_0.29.0
[123] getPass_0.2-2 shiny_1.7.1