Last updated: 2022-02-22

Checks: 7 0

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.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

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 1affd7b. 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:    Table_S4.csv
    Ignored:    code/.DS_Store
    Ignored:    code/._.DS_Store
    Ignored:    data/.DS_Store
    Ignored:    data/._.DS_Store
    Ignored:    data/data_for_analysis/
    Ignored:    data/full_data/

Unstaged changes:
    Modified:   .gitignore
    Modified:   analysis/Supp-Figure_6.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
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

Introduction

This script generates plots for Supplementary Figure 9.

Preparations

Load libraries

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)

Load Data

# 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 Relation Table

# 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 = "_")

Supp Figure 9A

Expressor in Tcell groups

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.

Supp Figure 9B

Grouping from Figure 1E

# 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.

Supp Figure 9C

CP output

# 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 the analysis

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   9388034  501.4   14603417  780.0  14603417  780.0
Vcells 747115554 5700.1 1086952781 8292.8 905727318 6910.2
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.89348 mins

Visualize

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] unix_1.5.4                  neighbouRhood_0.4          
 [3] magrittr_2.0.2              dtplyr_1.2.1               
 [5] dendextend_1.15.2           rstatix_0.7.0              
 [7] ComplexHeatmap_2.10.0       ggpubr_0.4.0               
 [9] ggpmisc_0.4.5               ggpp_0.4.3                 
[11] data.table_1.14.2           cowplot_1.1.1              
[13] gridExtra_2.3               dittoSeq_1.6.0             
[15] scater_1.22.0               scuttle_1.4.0              
[17] tidyr_1.2.0                 ggbeeswarm_0.6.0           
[19] ggplot2_3.3.5               SingleCellExperiment_1.16.0
[21] SummarizedExperiment_1.24.0 Biobase_2.54.0             
[23] GenomicRanges_1.46.1        GenomeInfoDb_1.30.1        
[25] IRanges_2.28.0              S4Vectors_0.32.3           
[27] BiocGenerics_0.40.0         MatrixGenerics_1.6.0       
[29] matrixStats_0.61.0          dplyr_1.0.7                
[31] workflowr_1.7.0            

loaded via a namespace (and not attached):
  [1] backports_1.4.1           circlize_0.4.13          
  [3] plyr_1.8.6                BiocParallel_1.28.3      
  [5] digest_0.6.29             foreach_1.5.2            
  [7] htmltools_0.5.2           magick_2.7.3             
  [9] viridis_0.6.2             fansi_1.0.2              
 [11] ScaledMatrix_1.2.0        cluster_2.1.2            
 [13] doParallel_1.0.16         colorspace_2.0-2         
 [15] ggrepel_0.9.1             xfun_0.29                
 [17] callr_3.7.0               crayon_1.4.2             
 [19] RCurl_1.98-1.5            jsonlite_1.7.3           
 [21] iterators_1.0.13          glue_1.6.1               
 [23] gtable_0.3.0              zlibbioc_1.40.0          
 [25] XVector_0.34.0            MatrixModels_0.5-0       
 [27] GetoptLong_1.0.5          DelayedArray_0.20.0      
 [29] car_3.0-12                BiocSingular_1.10.0      
 [31] shape_1.4.6               abind_1.4-5              
 [33] SparseM_1.81              scales_1.1.1             
 [35] pheatmap_1.0.12           DBI_1.1.2                
 [37] Rcpp_1.0.8                viridisLite_0.4.0        
 [39] clue_0.3-60               rsvd_1.0.5               
 [41] httr_1.4.2                RColorBrewer_1.1-2       
 [43] ellipsis_0.3.2            pkgconfig_2.0.3          
 [45] farver_2.1.0              sass_0.4.0               
 [47] utf8_1.2.2                tidyselect_1.1.1         
 [49] labeling_0.4.2            rlang_1.0.0              
 [51] reshape2_1.4.4            later_1.3.0              
 [53] munsell_0.5.0             tools_4.1.2              
 [55] cli_3.1.1                 generics_0.1.2           
 [57] broom_0.7.12              ggridges_0.5.3           
 [59] evaluate_0.14             stringr_1.4.0            
 [61] fastmap_1.1.0             yaml_2.2.2               
 [63] processx_3.5.2            knitr_1.37               
 [65] fs_1.5.2                  purrr_0.3.4              
 [67] sparseMatrixStats_1.6.0   whisker_0.4              
 [69] quantreg_5.87             compiler_4.1.2           
 [71] rstudioapi_0.13           beeswarm_0.4.0           
 [73] png_0.1-7                 ggsignif_0.6.3           
 [75] tibble_3.1.6              bslib_0.3.1              
 [77] stringi_1.7.6             highr_0.9                
 [79] ps_1.6.0                  lattice_0.20-45          
 [81] Matrix_1.4-0              vctrs_0.3.8              
 [83] pillar_1.7.0              lifecycle_1.0.1          
 [85] jquerylib_0.1.4           GlobalOptions_0.1.2      
 [87] BiocNeighbors_1.12.0      bitops_1.0-7             
 [89] irlba_2.3.5               httpuv_1.6.5             
 [91] R6_2.5.1                  promises_1.2.0.1         
 [93] vipor_0.4.5               codetools_0.2-18         
 [95] assertthat_0.2.1          rprojroot_2.0.2          
 [97] rjson_0.2.21              withr_2.4.3              
 [99] GenomeInfoDbData_1.2.7    beachmat_2.10.0          
[101] rmarkdown_2.11            DelayedMatrixStats_1.16.0
[103] carData_3.0-5             git2r_0.29.0             
[105] getPass_0.2-2