Last updated: 2022-01-06

Checks: 7 0

Knit directory: cacoaAnalysis/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). 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(20211123) 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 2ff50cc. 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:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    analysis/.Rhistory
    Ignored:    analysis/figure_cluster_based_de_bio.nb.html
    Ignored:    analysis/figure_cluster_free_expression.nb.html
    Ignored:    analysis/figure_compositional.nb.html
    Ignored:    analysis/figure_compositional_cf.nb.html
    Ignored:    analysis/figure_expression_shifts.nb.html
    Ignored:    analysis/figure_heterogeneity.nb.html
    Ignored:    analysis/figure_interpretation.nb.html
    Ignored:    analysis/prepare_cacoa_results.nb.html
    Ignored:    analysis/preprocess.nb.html
    Ignored:    analysis/report_asd.nb.html
    Ignored:    analysis/report_az.nb.html
    Ignored:    analysis/report_ep.nb.html
    Ignored:    analysis/report_ms.nb.html
    Ignored:    analysis/report_pf.nb.html
    Ignored:    analysis/report_scc.nb.html
    Ignored:    analysis/simulation_distances.nb.html
    Ignored:    analysis/simulation_variance.nb.html
    Ignored:    cache/
    Ignored:    data/ASD/
    Ignored:    data/AZ/
    Ignored:    data/EP/
    Ignored:    data/MS/
    Ignored:    data/PF/
    Ignored:    data/SCC/
    Ignored:    man/
    Ignored:    output/figures/

Unstaged changes:
    Modified:   analysis/figure_interpretation.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/figure_compositional.Rmd) and HTML (docs/figure_compositional.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 2ff50cc viktor_petukhov 2022-01-06 Updated the compositional figure
Rmd d864029 viktor_petukhov 2021-12-10 Compositional figure notebooks

getPValueDf <- function(cao, cell.group.order) {
  freqs <- cao$test.results$coda$cnts %>% {. / rowSums(.)}
  pval.df <- cao$sample.groups %>% {split(names(.), .)} %>% 
    {matrixTests::col_wilcoxon_twosample(freqs[.[[1]],], freqs[.[[2]],])} %$% 
    setNames(pvalue, rownames(.)) %>% 
    p.adjust("BH") %>% cacoa:::pvalueToCode(ns.symbol="") %>% 
    {tibble(ind=names(.), freq=., coda=cao$test.results$coda$padj[names(.)])} %>% 
    mutate(ind=factor(ind, levels=cell.group.order), coda=cacoa:::pvalueToCode(coda, ns.symbol="")) %>% 
    rename(Freqs=freq, CoDA=coda)
  
  return(pval.df)
}

addPvalueToCoda <- function(gg, cao, x.vals, show.legend=FALSE, size=4, legend.title="Significance") {
  pval.df <- getPValueDf(cao, cell.group.order=levels(gg$data$ind))
  gg <- gg + 
    geom_text(aes(x=x.vals[1], label=CoDA, color="CoDA"), data=pval.df, vjust=0.75, size=size) +
    geom_text(aes(x=x.vals[2], label=Freqs, color="Wilcox"), data=pval.df, vjust=0.75, size=size) +
    scale_color_manual(values=c("black", "darkred"))
  
  if (show.legend) {
    gg <- gg + 
      cacoa:::theme_legend_position(c(1, 0.04)) +
      guides(fill=guide_none(), color=guide_legend(title=legend.title))
  }
  return(gg)
}

Toy example

Simulate data:

n.cell.types <- 7
cell.types <- paste('type', 1:n.cell.types, sep='')

n.samples <- 20  # number of samples in one group
groups.name <- c('case', 'control')
groups.type <- c(rep(groups.name[1], n.samples), rep(groups.name[2], n.samples))
sample.names <- paste(groups.type, 1:(2*n.samples), sep = '')
groups <- setNames(groups.type %in% groups.name[1], sample.names)

palette <- RColorBrewer::brewer.pal(n.cell.types, "Set1") %>% setNames(cell.types)

sample_groups <- c("control", "case")[groups + 1] %>% setNames(names(groups))

sg_pal <- c(case="#BF1363", control="#39A6A3")
cnt.shift <- 100
cnt.shift2 <- -15

set.seed(1124)

cnts <- lapply(1:(2 * n.samples), function(i) round(rnorm(n.cell.types, mean=50, sd=5))) %>% 
  do.call(rbind, .) %>% set_rownames(sample.names) %>% set_colnames(cell.types)

cnts[,1] <- cnts[,1] + groups * cnt.shift
cnts[,2] <- cnts[,2] + groups * cnt.shift2
cnts[,3] <- cnts[,3] + groups * cnt.shift2

freqs <- cnts %>% {. / rowSums(.)}

res <- cacoa:::runCoda(cnts, groups, n.seed=239)
dfs <- cacoa:::estimateCdaSpace(cnts, groups)

Prepare plots:

theme_text_rot <- theme(axis.text.x=element_text(angle=45, hjust=1, vjust=1))
gg_boxes <- list(freqs=freqs, counts=cnts) %>% lapply(function(mat) {
  df <- melt(t(mat)) %>% set_colnames(c('type', 'sample.name', 'value'))
  df[['group']] <- groups.name[2 - (df$sample.name %in% sample.names[1:n.samples])]
  
  ggplot(df, aes(x=type, y=value, fill=group)) +
    geom_boxplot(outlier.shape = NA) + 
    # geom_jitter(position=position_jitterdodge(jitter.width=0.2), alpha=1, size = 0.1) + 
    scale_fill_manual(values=sg_pal) + 
    stat_compare_means(aes(label=cacoa:::pvalueToCode(..p.adj.., ns.symbol="")), 
                       label.x=1.5, label.y=max(df$value), size=2.5) +
    theme(legend.title=element_blank(), axis.title.x=element_blank()) + 
    theme_text_rot +
    cacoa:::theme_legend_position(c(1, 1))
})

gg_boxes$counts %<>% {. + ylab("Counts")}
gg_boxes$freqs %<>% {. + ylab("Proportions")}

gg_surface <- ggplot(dfs$red, aes(x=S1, y=S2)) +
  geom_abline(slope=-5, intercept=0.1) +
  geom_point(aes(colour=sample_groups)) +
  geom_hline(yintercept=0, linetype="dashed", size=0.2) +
  geom_vline(xintercept=0, linetype="dashed", size=0.2) +
  labs(colour="Condition", x="CDA-1", y="CDA-2") + 
  scale_color_manual(values=sg_pal) +
  theme(panel.grid=element_blank(), legend.position="none")

gg_coda <- res %$% cacoa:::plotCellLoadings(
  loadings, padj, palette=palette, jitter.alpha=0.0,
  ref.level=groups.name[2], target.level=groups.name[1], 
  ref.load.level=res$ref.load.level, annotation.x=1.0
) + theme(
  panel.border=element_rect(size=0.1, fill="transparent"),
  panel.grid.minor.x=element_blank()
)
plot_grid(
  gg_boxes$counts + ylab("Counts"),
  gg_boxes$freqs + ylab("Proportions"),
  gg_surface + theme(plot.margin=margin(t=10)),
  gg_coda,
  nrow=1
)

tree_theme <- theme(
  legend.key.height=unit(10, "pt"), legend.key.width=unit(14, "pt"), 
  legend.position="bottom", plot.margin=margin(),
  axis.text.y=element_text(hjust=1, vjust=0.5, margin=margin()), axis.text.x=element_blank(), 
  axis.ticks=element_blank()
)
gg_toy_tree <- cacoa:::plotContrastTree(
  cnts, groups, ref.level=groups.name[2], target.level=groups.name[1], plot.theme=NULL,
  adjust.pvalues=TRUE, loadings.mean=rowMeans(res$loadings), palette=sg_pal
) + coord_flip() + tree_theme + theme(legend.margin=margin(l=10, t=-30)) +
  guides(color=guide_legend(direction="vertical", title="Condition"))

gg_toy_tree

PF

cao_pf <- DataPath("PF/cao.rds") %>% readr::read_rds() %>% Cacoa$new()
cao_pf$plot.theme %<>% {. + p_theme}
cao_pf$plotCellGroupSizes(show.significance=TRUE, legend.position=c(1, 1))

gg_pf_coda <- cao_pf$plotCellLoadings(show.pvals=FALSE, alpha=0.0, annotation.x=0.61) +
  scale_x_continuous(limits=c(-0.61, 0.7), expand=c(0, 0.0, 0.0, 0.1))

gg_pf_coda %<>% addPvalueToCoda(cao_pf, c(0.53, 0.7), show.legend=FALSE, size=4)

gg_pf_coda

cd45_types <- cao_pf$cache$joint.count.matrix[,"PTPRC"] %>% 
  split(cao_pf$cell.groups[names(.)]) %>% 
  sapply(function(x) mean(x > 0)) %>% sort() %>% {names(.)[. > 0.1]}

cao_pf$estimateCellLoadings(cells.to.remain=cd45_types, name="imm.coda")
gg_pf_coda_imm <- cao_pf$plotCellLoadings(show.pvals=FALSE, alpha=0.0, name="imm.coda", annotation.x=1) +
  scale_x_continuous(limits=c(-1, 1), expand=c(0.01, 0.0))

gg_pf_coda_imm

MS

cao_ms <- DataPath("MS/cao.rds") %>% readr::read_rds() %>% Cacoa$new()
cao_ms$plot.theme %<>% {. + p_theme}
gg_ms_coda <- cao_ms$plotCellLoadings(show.pvals=FALSE, alpha=0.0, jitter.size=0.25, annotation.x=1) +
  scale_x_continuous(limits=c(-1, 1), expand=c(0, 0, 0.05, 0.0))
gg_ms_coda %<>% addPvalueToCoda(cao_ms, c(0.85, 1), size=4)
gg_ms_coda

gg_ms_tree <- cao_ms$plotContrastTree() + coord_flip() + tree_theme + 
  guides(color=guide_legend(direction="vertical", title="Condition", order=1),
         fill=guide_colorbar(title.position="top", order=2, title.hjust=0.5))

gg_ms_tree

Compile figure

p_theme <- theme(
  axis.text=element_text(size=8), axis.title=element_text(size=10),
  legend.title=element_text(size=10), legend.text=element_text(size=8), legend.key.width=unit(12, "pt"),
  plot.margin=margin(b=5, t=5, l=1)
)

theme_margin <- theme(plot.margin=margin(r=10, b=10, t=2))

gg <- plot_grid(
  plot_grid(
    gg_boxes$counts + p_theme + theme(legend.title=element_blank()) + theme_margin,
    gg_boxes$freqs + p_theme + theme(legend.title=element_blank()) + theme_margin,
    gg_surface + p_theme + theme_margin + theme(axis.title.x=element_text(margin=margin(t=-10))), 
    gg_coda + p_theme + theme(axis.title.x=element_text(margin=margin(t=-10)), plot.margin=margin(), 
                              axis.title.y=element_blank()),
    nrow=1, align="h"
  ),
  plot_grid(
    gg_pf_coda + p_theme,
    plot_grid(
      gg_pf_coda_imm + p_theme + theme(plot.margin=margin(r=10, b=5), axis.title.x=element_text(margin=margin())), 
      gg_ms_coda + p_theme,
      ncol=1, rel_heights=c(0.7, 1), align="v"
    ),
    plot_grid(
      gg_toy_tree + p_theme + 
        theme(legend.margin=margin(), legend.box.margin=margin(l=-30, t=-25), plot.margin=margin(l=-50)), 
      gg_ms_tree + 
        scale_y_continuous(expand=c(0, 0, 0.1, 0)) + p_theme + 
        theme(legend.margin=margin(), legend.box.margin=margin(l=-30, t=-35), plot.margin=margin(l=-50, t=7)), 
      ncol=1, rel_heights=c(0.65, 1), align="v"
    ),
    nrow=1, rel_widths=c(1, 1, 0.6)
  ),
  ncol=1, rel_heights=c(1, 2.9)
)

grDevices::cairo_pdf(figurePath("1_composition.pdf"), width=8.5, height=8)
gg
td <- dev.off();

gg


sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.6 LTS

Matrix products: default
BLAS:   /usr/local/R/R-4.0.3/lib/R/lib/libRblas.so
LAPACK: /usr/local/R/R-4.0.3/lib/R/lib/libRlapack.so

locale:
[1] C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] cacoaAnalysis_0.1.0 dataorganizer_0.1.0 cowplot_1.1.1      
 [4] reshape2_1.4.4      ggpubr_0.4.0        cacoa_0.2.0        
 [7] Matrix_1.2-18       magrittr_2.0.1      forcats_0.5.1      
[10] stringr_1.4.0       dplyr_1.0.7         purrr_0.3.4        
[13] readr_1.4.0         tidyr_1.1.4         tibble_3.1.5       
[16] ggplot2_3.3.5       tidyverse_1.3.0     workflowr_1.6.2    

loaded via a namespace (and not attached):
  [1] utf8_1.2.2           reticulate_1.22      R.utils_2.10.1      
  [4] tidyselect_1.1.1     grid_4.0.3           Rtsne_0.15          
  [7] devtools_2.3.2       munsell_0.5.0        codetools_0.2-16    
 [10] withr_2.4.2          colorspace_2.0-2     highr_0.9           
 [13] knitr_1.36           rstudioapi_0.13      stats4_4.0.3        
 [16] ggsignif_0.6.1       labeling_0.4.2       git2r_0.27.1        
 [19] urltools_1.7.3       mnormt_2.0.2         farver_2.1.0        
 [22] rprojroot_2.0.2      Matrix.utils_0.9.8   vctrs_0.3.8         
 [25] generics_0.1.0       xfun_0.26            R6_2.5.1            
 [28] doParallel_1.0.16    ggbeeswarm_0.6.0     clue_0.3-59         
 [31] cachem_1.0.6         assertthat_0.2.1     promises_1.1.1      
 [34] scales_1.1.1         beeswarm_0.4.0       gtable_0.3.0        
 [37] processx_3.4.5       drat_0.1.8           rlang_0.4.11        
 [40] GlobalOptions_0.1.2  splines_4.0.3        rstatix_0.7.0       
 [43] lazyeval_0.2.2       broom_0.7.9          brew_1.0-6          
 [46] yaml_2.2.1           abind_1.4-5          modelr_0.1.8        
 [49] backports_1.2.1      httpuv_1.5.4         tools_4.0.3         
 [52] usethis_1.6.3        psych_2.1.6          sccore_1.0.1        
 [55] ellipsis_0.3.2       jquerylib_0.1.4      RColorBrewer_1.1-2  
 [58] ggdendro_0.1.22      coda.base_0.3.1      BiocGenerics_0.36.1 
 [61] sessioninfo_1.1.1    Rcpp_1.0.7           plyr_1.8.6          
 [64] ps_1.4.0             prettyunits_1.1.1    dendsort_0.3.3      
 [67] GetoptLong_1.0.5     S4Vectors_0.28.1     grr_0.9.5           
 [70] haven_2.4.1          ggrepel_0.9.1        cluster_2.1.0       
 [73] fs_1.5.0             data.table_1.14.2    openxlsx_4.2.3      
 [76] circlize_0.4.13      triebeard_0.3.0      reprex_0.3.0        
 [79] tmvnsim_1.0-2        whisker_0.4          matrixStats_0.61.0  
 [82] pkgload_1.2.1        hms_1.1.1            evaluate_0.14       
 [85] rio_0.5.26           RMTstat_0.3          readxl_1.3.1        
 [88] N2R_0.1.1            IRanges_2.24.1       gridExtra_2.3       
 [91] shape_1.4.6          testthat_3.0.0       compiler_4.0.3      
 [94] crayon_1.4.1         R.oo_1.24.0          htmltools_0.5.2     
 [97] mgcv_1.8-33          later_1.1.0.1        conos_1.4.4         
[100] lubridate_1.7.9.2    DBI_1.1.1            dbplyr_2.0.0        
[103] pagoda2_1.0.7        ComplexHeatmap_2.9.4 MASS_7.3-53         
[106] car_3.0-10           cli_3.0.1            heplots_1.3-8       
[109] R.methodsS3_1.8.1    parallel_4.0.3       igraph_1.2.6        
[112] pkgconfig_2.0.3      foreign_0.8-80       xml2_1.3.2          
[115] foreach_1.5.1        vipor_0.4.5          leidenAlg_0.1.0     
[118] rvest_0.3.6          callr_3.5.1          digest_0.6.28       
[121] matrixTests_0.1.9    rmarkdown_2.11       cellranger_1.1.0    
[124] tidytree_0.3.4       Rook_1.1-1           curl_4.3.2          
[127] rjson_0.2.20         lifecycle_1.0.1      nlme_3.1-149        
[130] jsonlite_1.7.2       carData_3.0-4        desc_1.3.0          
[133] fansi_0.5.0          pillar_1.6.3         lattice_0.20-41     
[136] ggrastr_1.0.1        fastmap_1.1.0        httr_1.4.2          
[139] pkgbuild_1.1.0       glue_1.4.2           remotes_2.2.0       
[142] zip_2.2.0            png_0.1-7            iterators_1.0.13    
[145] candisc_0.8-5        stringi_1.7.5        memoise_2.0.0       
[148] irlba_2.3.3          ape_5.5