Last updated: 2024-08-26

Checks: 6 1

Knit directory: multigroup_ctwas_analysis/

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 is untracked by Git. 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(20231112) 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 b0ae84b. 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:    results/

Untracked files:
    Untracked:  analysis/LDL_single_multi_compare.Rmd

Unstaged changes:
    Modified:   analysis/multi_group_compare_predictdb_munro_updated.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.


There are no past versions. Publish this analysis with wflow_publish() to start tracking its development.


library(ctwas)
Warning: replacing previous import 'utils::download.file' by
'restfulr::download.file' when loading 'rtracklayer'
library(EnsDb.Hsapiens.v86)
Loading required package: ensembldb
Loading required package: BiocGenerics

Attaching package: 'BiocGenerics'
The following objects are masked from 'package:stats':

    IQR, mad, sd, var, xtabs
The following objects are masked from 'package:base':

    Filter, Find, Map, Position, Reduce, anyDuplicated, append,
    as.data.frame, basename, cbind, colnames, dirname, do.call,
    duplicated, eval, evalq, get, grep, grepl, intersect, is.unsorted,
    lapply, mapply, match, mget, order, paste, pmax, pmax.int, pmin,
    pmin.int, rank, rbind, rownames, sapply, setdiff, sort, table,
    tapply, union, unique, unsplit, which.max, which.min
Loading required package: GenomicRanges
Loading required package: stats4
Loading required package: S4Vectors

Attaching package: 'S4Vectors'
The following objects are masked from 'package:base':

    I, expand.grid, unname
Loading required package: IRanges
Loading required package: GenomeInfoDb
Loading required package: GenomicFeatures
Loading required package: AnnotationDbi
Loading required package: Biobase
Welcome to Bioconductor

    Vignettes contain introductory material; view with
    'browseVignettes()'. To cite Bioconductor, see
    'citation("Biobase")', and for packages 'citation("pkgname")'.
Loading required package: AnnotationFilter

Attaching package: 'ensembldb'
The following object is masked from 'package:stats':

    filter
library(ggplot2)
library(RColorBrewer)

load("/project2/xinhe/shared_data/multigroup_ctwas/weights/E_S_A_mapping_updated.RData")
ens_db <- EnsDb.Hsapiens.v86

trait <- "LDL-ukb-d-30780_irnt"
gwas_n <- 343621

sum_pve_across_types <- function(ctwas_parameters) {
  # Round the group_pve values
  pve <- round(ctwas_parameters$group_pve, 4)
  pve <- as.data.frame(pve)

  # Extract SNP PVE for later use
  SNP_pve <- pve["SNP", ]

  # Add type and context columns
  pve$type <- sapply(rownames(pve), function(x) { unlist(strsplit(x, "[|]"))[1] })
  pve$context <- sapply(rownames(pve), function(x) { unlist(strsplit(x, "[|]"))[2] })

  # Remove rows with NA values and sort
  pve <- na.omit(pve)
  pve <- pve[order(rownames(pve)), ]

  # Aggregate PVE by type
  df_pve <- aggregate(pve$pve, by = list(pve$type), FUN = sum)
  colnames(df_pve) <- c("type", "total_pve")
  df_pve$total_pve <- round(df_pve$total_pve, 4)

  # Add context-specific columns
  for (context in unique(pve$context)) {
    context_pve <- aggregate(pve$pve, by = list(pve$type, pve$context), FUN = sum)
    context_pve <- context_pve[context_pve$Group.2 == context, ]
    colnames(context_pve)[3] <- context
    df_pve <- merge(df_pve, context_pve[, c("Group.1", context)], by.x = "type", by.y = "Group.1", all.x = TRUE)
  }

  # Insert SNP PVE
  SNP_row <- c("SNP", SNP_pve, rep(0, ncol(df_pve) - 2))
  df_pve <- rbind(df_pve, SNP_row)

  # Convert to numeric except for the type column
  df_pve[, -1] <- lapply(df_pve[, -1], as.numeric)

  # Sum all rows and add a sum_pve row
  sum_row <- colSums(df_pve[, -1], na.rm = TRUE)
  sum_row <- c("total_pve", sum_row)
  df_pve <- rbind(df_pve, sum_row)

  # Clean up row names and return
  row.names(df_pve) <- NULL
  return(df_pve)
}

palette <- c(brewer.pal(12, "Paired"), brewer.pal(12, "Set3"), brewer.pal(6, "Dark2"))

pve_pie_chart <- function(pve_vector, palette=NULL, title) {
  # Create data frame for plotting
  data <- data.frame(
    Group = names(pve_vector),
    Value = pve_vector
  )
  
  # Calculate percentages
  data$Percentage <- round(100 * data$Value / sum(data$Value), 1)
  
  # Set palette if not specified
  if (is.null(palette)) {
    palette <- brewer.pal(min(8, length(data$Group)), "Set3")
  }
  
  # Create pie chart
  ggplot(data, aes(x = "", y = Value, fill = Group)) +
    geom_bar(stat = "identity", width = 1, color = "white") +
    coord_polar(theta = "y") +  # This transforms the bar chart into a pie chart
    scale_fill_manual(values = palette, name = "Group") +
    labs(title = title, x = NULL, y = NULL) +
    theme_void() +
    theme(plot.title = element_text(hjust = 0.5), 
          legend.position = "right", 
          legend.title = element_text(face = "bold"), 
          legend.text = element_text(size = 12)) +
    geom_text(aes(label = paste(Percentage, "%", sep="")), position = position_stack(vjust = 0.5))
}

Settings

Weights:

single group: Liver, eQTL

multi group: Liver, Spleen, Adipose_Subcutaneous, Adrenal_Gland, Esophagus_Mucosa; eQTL + sQTL

  • drop_strand_ambig = TRUE,
  • scale_by_ld_variance = TRUE,
  • load_predictdb_LD = F,

Main function

  • niter_prefit = default,
  • niter = default,
  • pre-estimate L

Results

Single group

Parameters

results_dir_single <- paste0("/project/xinhe/xsun/multi_group_ctwas/xxxintalk/results_predictdb_main_single/",trait,"/")


finemap.res.single <- readRDS(paste0(results_dir_single,trait,".ctwas.res.RDS"))
snp_map.single <- readRDS(paste0(results_dir_single,trait,".snp_map.RDS"))
res.single <- finemap.res.single$finemap_res


param.single <- finemap.res.single$param
make_convergence_plots(param.single, gwas_n)

ctwas_parameters.single <- summarize_param(param.single, gwas_n)


group_size.single <- data.frame(group = names(ctwas_parameters.single$group_size),
                         group_size = as.vector(ctwas_parameters.single$group_size))
group_size.single <- t(group_size.single)
DT::datatable(group_size.single,caption = htmltools::tags$caption( style = 'caption-side: topleft; text-align = left; color:black;','Group size'),options = list(pageLength = 5) )

ctwas results

annotated_finemap_res.single <- anno_finemap_res(finemap_res = res.single,
                                          snp_map = snp_map.single,
                                          gene_annot = E_S_A_mapping,
                                          use_gene_pos = "mid",
                                          filter_protein_coding_genes = T,
                                          drop_unannotated_genes = T,
                                          filter_cs = T)
2024-08-26 03:07:04 INFO::Annotating ctwas finemapping result ...
2024-08-26 03:07:30 INFO::keep only protein coding genes
2024-08-26 03:07:30 INFO::keep only results in credible sets
2024-08-26 03:07:30 INFO::add gene_name and gene_type
2024-08-26 03:07:30 INFO::use gene mid positions
2024-08-26 03:07:30 INFO::add SNP positions
res_gene.single <- annotated_finemap_res.single[annotated_finemap_res.single$type != "SNP",]

combined_pip_by_context.single <- combine_gene_pips(finemap_res = annotated_finemap_res.single,
                                             by = "type", digits = 4)
highpip.single <- combined_pip_by_context.single[combined_pip_by_context.single$combined_pip > 0.8,]

DT::datatable(highpip.single,caption = htmltools::tags$caption( style = 'caption-side: topleft; text-align = left; color:black;','Genes with PIP > 0.8'),options = list(pageLength = 5) )

Multi group

Parameters

results_dir_multi <- paste0("/project/xinhe/xsun/multi_group_ctwas/xxxintalk/results_predictdb_main_multi/",trait,"/")


finemap.res.multi <- readRDS(paste0(results_dir_multi,trait,".ctwas.res.RDS"))
snp_map.multi <- readRDS(paste0(results_dir_multi,trait,".snp_map.RDS"))
res.multi <- finemap.res.multi$finemap_res


param.multi <- finemap.res.multi$param
make_convergence_plots(param.multi, gwas_n,colors = palette)

ctwas_parameters.multi <- summarize_param(param.multi, gwas_n)


group_size.multi <- data.frame(group = names(ctwas_parameters.multi$group_size),
                         group_size = as.vector(ctwas_parameters.multi$group_size))
group_size.multi <- t(group_size.multi)
DT::datatable(group_size.multi,caption = htmltools::tags$caption( style = 'caption-side: topleft; text-align = left; color:black;','Group size'),options = list(pageLength = 5) )
para.multi <- sum_pve_across_types(ctwas_parameters.multi)
DT::datatable(para.multi,caption = htmltools::tags$caption( style = 'caption-side: topleft; text-align = left; color:black;','Heritability contribution by contexts'),options = list(pageLength = 5) )
pve_vector.multi <- as.numeric(para.multi$total_pve[1:3])
names(pve_vector.multi) <- para.multi$type[1:3]
pve_pie_chart(pve_vector.multi, title = "Pie Chart of PVE across Types", palette)

ctwas results

annotated_finemap_res.multi <- anno_finemap_res(finemap_res = res.multi,
                                          snp_map = snp_map.multi,
                                          gene_annot = E_S_A_mapping,
                                          use_gene_pos = "mid",
                                          filter_protein_coding_genes = T,
                                          drop_unannotated_genes = T,
                                          filter_cs = T)
2024-08-26 03:08:01 INFO::Annotating ctwas finemapping result ...
2024-08-26 03:08:13 INFO::keep only protein coding genes
2024-08-26 03:08:13 INFO::keep only results in credible sets
2024-08-26 03:08:13 INFO::add gene_name and gene_type
2024-08-26 03:08:13 INFO::split PIPs for traits mapped to multiple genes
2024-08-26 03:08:13 INFO::use gene mid positions
2024-08-26 03:08:13 INFO::add SNP positions
res_gene.multi <- annotated_finemap_res.multi[annotated_finemap_res.multi$type != "SNP",]

combined_pip_by_context.multi <- combine_gene_pips(finemap_res = annotated_finemap_res.multi,
                                             by = "type", digits = 4)
highpip.multi <- combined_pip_by_context.multi[combined_pip_by_context.multi$combined_pip > 0.8,]

DT::datatable(highpip.multi,caption = htmltools::tags$caption( style = 'caption-side: topleft; text-align = left; color:black;','Genes with PIP > 0.8'),options = list(pageLength = 5) )

Comparing the results

overlap <- highpip.multi[highpip.multi$gene_name %in% highpip.single$gene_name,]

sprintf("the number of genes reported by single group analysis: %s", nrow(highpip.single))
[1] "the number of genes reported by single group analysis: 33"
sprintf("the number of genes reported by multi group analysis: %s", nrow(highpip.multi))
[1] "the number of genes reported by multi group analysis: 37"
sprintf("the number of overlapped gene: %s", nrow(overlap))
[1] "the number of overlapped gene: 16"
DT::datatable(overlap,caption = htmltools::tags$caption( style = 'caption-side: topleft; text-align = left; color:black;','overlapped genes'),options = list(pageLength = 5) )
multi_unique <- combined_pip_by_context.multi[!combined_pip_by_context.multi$gene_name %in% overlap$gene_name,]
multi_unique <- multi_unique[multi_unique$combined_pip > 0.8,]
DT::datatable(multi_unique,caption = htmltools::tags$caption( style = 'caption-side: topleft; text-align = left; color:black;','Unique genes -- multi group'),options = list(pageLength = 5) )
unique_detail <- res_gene.multi[!res_gene.multi$gene_name %in%overlap$gene_name,]
unique_detail <- unique_detail[unique_detail$gene_name %in% highpip.multi$gene_name,]
save(unique_detail, file = "/project/xinhe/xsun/multi_group_ctwas/xxxintalk/unique_detail.rdata")

sessionInfo()
R version 4.2.0 (2022-04-22)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS/LAPACK: /software/openblas-0.3.13-el7-x86_64/lib/libopenblas_haswellp-r0.3.13.so

locale:
[1] C

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

other attached packages:
 [1] RColorBrewer_1.1-3        ggplot2_3.5.1            
 [3] EnsDb.Hsapiens.v86_2.99.0 ensembldb_2.20.2         
 [5] AnnotationFilter_1.20.0   GenomicFeatures_1.48.3   
 [7] AnnotationDbi_1.58.0      Biobase_2.56.0           
 [9] GenomicRanges_1.48.0      GenomeInfoDb_1.39.9      
[11] IRanges_2.30.0            S4Vectors_0.34.0         
[13] BiocGenerics_0.42.0       ctwas_0.4.7              

loaded via a namespace (and not attached):
  [1] colorspace_2.0-3            rjson_0.2.21               
  [3] ellipsis_0.3.2              rprojroot_2.0.3            
  [5] XVector_0.36.0              locuszoomr_0.2.1           
  [7] fs_1.5.2                    rstudioapi_0.13            
  [9] farver_2.1.0                DT_0.22                    
 [11] ggrepel_0.9.1               bit64_4.0.5                
 [13] fansi_1.0.3                 xml2_1.3.3                 
 [15] codetools_0.2-18            logging_0.10-108           
 [17] cachem_1.0.6                knitr_1.39                 
 [19] jsonlite_1.8.0              workflowr_1.7.0            
 [21] Rsamtools_2.12.0            dbplyr_2.1.1               
 [23] png_0.1-7                   readr_2.1.2                
 [25] compiler_4.2.0              httr_1.4.3                 
 [27] assertthat_0.2.1            Matrix_1.5-3               
 [29] fastmap_1.1.0               lazyeval_0.2.2             
 [31] cli_3.6.1                   later_1.3.0                
 [33] htmltools_0.5.2             prettyunits_1.1.1          
 [35] tools_4.2.0                 gtable_0.3.0               
 [37] glue_1.6.2                  GenomeInfoDbData_1.2.8     
 [39] dplyr_1.1.4                 rappdirs_0.3.3             
 [41] Rcpp_1.0.12                 jquerylib_0.1.4            
 [43] vctrs_0.6.5                 Biostrings_2.64.0          
 [45] rtracklayer_1.56.0          crosstalk_1.2.0            
 [47] xfun_0.41                   stringr_1.5.1              
 [49] lifecycle_1.0.4             irlba_2.3.5                
 [51] restfulr_0.0.14             XML_3.99-0.14              
 [53] zlibbioc_1.42.0             zoo_1.8-10                 
 [55] scales_1.3.0                gggrid_0.2-0               
 [57] hms_1.1.1                   promises_1.2.0.1           
 [59] MatrixGenerics_1.8.0        ProtGenerics_1.28.0        
 [61] parallel_4.2.0              SummarizedExperiment_1.26.1
 [63] LDlinkR_1.2.3               yaml_2.3.5                 
 [65] curl_4.3.2                  memoise_2.0.1              
 [67] sass_0.4.1                  biomaRt_2.54.1             
 [69] stringi_1.7.6               RSQLite_2.3.1              
 [71] highr_0.9                   BiocIO_1.6.0               
 [73] filelock_1.0.2              BiocParallel_1.30.3        
 [75] rlang_1.1.2                 pkgconfig_2.0.3            
 [77] matrixStats_0.62.0          bitops_1.0-7               
 [79] evaluate_0.15               lattice_0.20-45            
 [81] purrr_1.0.2                 labeling_0.4.2             
 [83] GenomicAlignments_1.32.0    htmlwidgets_1.5.4          
 [85] cowplot_1.1.1               bit_4.0.4                  
 [87] tidyselect_1.2.0            magrittr_2.0.3             
 [89] R6_2.5.1                    generics_0.1.2             
 [91] DelayedArray_0.22.0         DBI_1.2.2                  
 [93] withr_2.5.0                 pgenlibr_0.3.3             
 [95] pillar_1.9.0                KEGGREST_1.36.3            
 [97] RCurl_1.98-1.7              mixsqp_0.3-43              
 [99] tibble_3.2.1                crayon_1.5.1               
[101] utf8_1.2.2                  BiocFileCache_2.4.0        
[103] plotly_4.10.0               tzdb_0.4.0                 
[105] rmarkdown_2.25              progress_1.2.2             
[107] grid_4.2.0                  data.table_1.14.2          
[109] blob_1.2.3                  git2r_0.30.1               
[111] digest_0.6.29               tidyr_1.3.0                
[113] httpuv_1.6.5                munsell_0.5.0              
[115] viridisLite_0.4.0           bslib_0.3.1