Last updated: 2022-02-09

Checks: 7 0

Knit directory: snRNA_eqtl/

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(20211124) 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 f9035b6. 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:    .Rproj.user/
    Ignored:    data_sensitive/
    Ignored:    output/.DS_Store

Untracked files:
    Untracked:  analysis/._index.Rmd
    Untracked:  analysis/additional/
    Untracked:  analysis/alternatives/
    Untracked:  analysis/clean_analysis.Rmd
    Untracked:  analysis/log_run_slurm_out
    Untracked:  analysis/log_run_slurm_stderr
    Untracked:  analysis/portfolio/
    Untracked:  analysis/revision.Rmd
    Untracked:  analysis/run_slurm.Rscript
    Untracked:  analysis/run_slurm.sbatch
    Untracked:  data/dice/
    Untracked:  data/epigenome_enrichment/
    Untracked:  data/gencode/
    Untracked:  data/gnomad_loeuf/
    Untracked:  data/gtex/
    Untracked:  data/gwas/
    Untracked:  data/gwas_epigenome_overlap/
    Untracked:  data/locuszoom/
    Untracked:  data/magma_interaction_eqtl/
    Untracked:  data/magma_specific_genes/
    Untracked:  data/metabrain/
    Untracked:  data/umap/
    Untracked:  output/._.DS_Store
    Untracked:  output/coloc/
    Untracked:  output/eqtl/
    Untracked:  output/eqtl_specific/
    Untracked:  output/figures/
    Untracked:  output/figures_rev/
    Untracked:  output/gwas_epigenome_overlap/
    Untracked:  output/shiny/
    Untracked:  output/tables/

Unstaged changes:
    Modified:   .gitignore
    Modified:   analysis/04_coloc.Rmd
    Modified:   analysis/_site.yml
    Modified:   analysis/get_tables.Rmd
    Modified:   analysis/plot_figures.Rmd
    Deleted:    output/README.md

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/03_cell_type_specific_eQTL.Rmd) and HTML (docs/03_cell_type_specific_eQTL.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 f9035b6 Julien Bryois 2022-02-09 Celltype specific
html f59562d Julien Bryois 2022-02-09 Build site.
Rmd e493b25 Julien Bryois 2022-02-09 Celltype specific
html 93d08c4 Julien Bryois 2022-02-08 Build site.
Rmd bbdda1d Julien Bryois 2022-02-08 Cell type specific NA
html 20dc714 Julien Bryois 2022-02-08 Build site.
Rmd d40e4b5 Julien Bryois 2022-02-08 Cell type specific NA
html a7fc8c0 Julien Bryois 2022-02-02 Build site.
html a46e2d9 Julien Bryois 2022-01-27 Build site.
html 9fd5e02 Julien Bryois 2022-01-25 Build site.
Rmd e2fc864 Julien Bryois 2022-01-25 cell type specific
html a480859 Julien Bryois 2021-12-15 Build site.
Rmd 7976db1 Julien Bryois 2021-12-15 Update without soupy samples
html 55bd5ea Julien Bryois 2021-12-14 Build site.
Rmd 0b0746e Julien Bryois 2021-12-14 Update without soupy samples
html 7c04fdf Julien Bryois 2021-12-10 Build site.
Rmd cd25623 Julien Bryois 2021-12-10 interaction_qtl_original
html 6098430 Julien Bryois 2021-12-09 Build site.
Rmd 138b087 Julien Bryois 2021-12-09 interaction_qtl_soup_filter_NA_replacement
html 9ef68ed Julien Bryois 2021-12-09 Build site.
Rmd 38fa8bb Julien Bryois 2021-12-09 interaction_qtl_soup_filter_NA_replacement
html 9540a29 Julien Bryois 2021-12-08 Build site.
Rmd c72dd96 Julien Bryois 2021-12-08 interaction_qtl_no_soup_filter
html b818df6 Julien Bryois 2021-12-07 Build site.
Rmd 79a827a Julien Bryois 2021-12-07 interaction_qtl_soup_filter

Library

library(tidyverse)
library(parallel)
library(seqminer)
library(glmmTMB)

Prepare data

Load eQTL data

d <- read_tsv('output/eqtl/eqtl.PC70.txt')
d_sig <- filter(d,adj_p<0.05)

Load gene expression

expression_ms <- readRDS('data_sensitive/expression/ms_sum_expression.individual_id.rds') %>% mutate(dataset='ms')
expression_ad <- readRDS('data_sensitive/expression/ad_sum_expression.individual_id.rds') %>% mutate(dataset='ad')
expression <- rbind(expression_ms,expression_ad)

Compute TMM libsize

get_tmm_libsize <- function(cell_type_id){
  
 x <-  expression %>% 
    filter(cell_type==cell_type_id) %>% 
    dplyr::select(ensembl,individual_id,counts) %>% 
    spread(individual_id,counts) %>% 
    column_to_rownames('ensembl') %>% 
    edgeR::DGEList(counts = .) %>% #TMM normalize the data using edgeR
    edgeR::calcNormFactors(.)
 
 out <- tibble(cell_type=cell_type_id,individual_id=rownames(x$samples),libsize_TMM=edgeR::effectiveLibSizes(x))
 
 return(out)
}
cell_types <- unique(expression$cell_type)
tmm_libsizes <- mclapply(cell_types,get_tmm_libsize,mc.cores=8) %>% 
  bind_rows() %>% 
  mutate(individual_id=make.names(individual_id))

Load genotypes

genotype_file <- 'data_sensitive/genotypes/processed/combined_final.vcf.gz'
snp_positions_file <- 'data_sensitive/eqtl/PC70_caveman/sig_eQTL_snps_alleles.txt'
snp_coordinates <- read_tsv(snp_positions_file,col_names = FALSE) %>% setNames(c('chr','start','sid','A1','A2'))
genotypes <- tabix.read.table(genotype_file, paste0(snp_coordinates$chr,':',snp_coordinates$start,'-',snp_coordinates$start)) %>% gather(individual_id,genotype,-CHROM,-POS,-ID,-REF,-ALT,-QUAL,-FILTER,-INFO,-FORMAT) %>% 
  dplyr::select(ID,individual_id,genotype) %>% 
    mutate(genotype_parsed=case_when(
      genotype=='1/1' ~ 2,
      genotype=='0/1' ~ 1,
      genotype=='1/0' ~ 1,
      genotype=='0/0' ~ 0,
    )) %>% as_tibble() %>% 
    dplyr::select(ID,individual_id,genotype_parsed) %>% 
    filter(!is.na(genotype_parsed)) %>% 
  dplyr::rename(sid=ID)

Get covariates

cov_files <- list.files('data_sensitive/eqtl/PC70/',pattern = 'cov.txt.gz',full.names = TRUE)

cov <- tibble(files = cov_files) %>%
  mutate(
    file_content = map(cov_files, read_tsv),
    cell_type = basename(files) %>%
      gsub('.cov.txt.gz', ' ', .) %>%
      gsub('\\.', ' ', .) %>%
      gsub('OPCs   COPs', 'OPCs / COPs', .) %>%
      gsub(' $', '', .)
  ) %>%
  dplyr::select(-files) %>%
  unnest(file_content) %>%
  gather(individual_id, cov_value, -id, -cell_type) %>%
  spread(id, cov_value) %>%
  mutate(individual_id = gsub('-|/', '.', individual_id)) %>%
  mutate_at(vars(contains('PC')), as.numeric)

Function to try different optimizers if model did not converge

#Function to try other optimizers if model did not converge
try_other_optimizers <- function(model_fit){
  
  if (model_fit$fit$convergence != 0 | model_fit$sdr$pdHess == FALSE) {
      tryCatch(
        {
          model_fit <- update(model_fit, control = glmmTMB::glmmTMBControl(
          optimizer = optim, optArgs = list( method = "BFGS" ) ))
        }, error=function(cond){
            message('Error optimizer BFGS')
        })
    }
    if (model_fit$fit$convergence != 0 | model_fit$sdr$pdHess == FALSE) {
       tryCatch(
        {
          model_fit <- update(model_fit, control = glmmTMB::glmmTMBControl(
          optimizer = optim, optArgs = list( method = "SANN" ) ))
        }, error=function(cond){
          message('Error optimizer SANN')
        })
    }
  return(model_fit)
}

Run interaction model

Note:

If a gene is not expressed in a cell type, we can’t estimate the genetic effect on gene expression in that cell type. Hence, an eQTL for a gene that is expressed in a single cell type would not be called cell-type specific.

interaction_model <- function(i){

  gene_id <- d_sig$pid[i]
  ensenmbl_id <- gsub('.+_','',gene_id)
  snp_id <- d_sig$sid[i]
  cell_type_id <- d_sig$cell_type[i]
  
  expression_gene <- filter(expression,ensembl==ensenmbl_id) %>%
    mutate(individual_id=make.names(individual_id))
  
  genotype_snp <- filter(genotypes,sid==snp_id)
  
  df <- inner_join(expression_gene,genotype_snp,by='individual_id')
  
  #Add covariates
  df <- inner_join(df,cov,by=c('cell_type','individual_id'))
  
  #Add TMM libsize
  df <- inner_join(df,tmm_libsizes,by=c('cell_type','individual_id'))
  
  #Aggregate - Set all cell types that are not the cell type in which the eQTL was discovered as 'Others'
  df <- df %>% 
    mutate(cell_type_model=
             factor(ifelse(cell_type==cell_type_id,cell_type,'Others'),levels=c('Others',cell_type_id)))
  
  #Aggregate - Model formula
  full_model <- 
      as.formula(paste0('counts ~ genotype_parsed+cell_type+genotype_parsed:cell_type_model+diagnosis+study+',
                                  paste0('PC',1:3,collapse='+'),'+',
                                  paste0('PC',1:5,'_exp',collapse='+'),
                                  '+(1|individual_id)'))
  
  #Aggregate - Run model 
  full_model_nb_aggregate <- glmmTMB(full_model,offset=log(libsize_TMM),
                                   data=df,
                                   family=nbinom2,
                                   control = glmmTMBControl(parallel = 1))
  
  #if not converged, try different optimizers
  full_model_nb_aggregate <- try_other_optimizers(full_model_nb_aggregate)
  
  #Check if model converged or not
  full_model_nb_aggregate_convergence <- ifelse(full_model_nb_aggregate$fit$convergence,FALSE,TRUE)

  nb_pvalues_aggregate <- summary(full_model_nb_aggregate)$coefficients$cond %>% 
    as.data.frame() %>% 
    rownames_to_column('variable') %>% 
    filter(grepl('genotype_parsed:',variable)) %>% 
    dplyr::select(-variable)
  
 
  # At least one
  # Change levels for the cell_type_model variables
  df <- df %>% mutate(cell_type_model=fct_relevel(cell_type,cell_type_id))
  
  full_model_nb <- glmmTMB(full_model,
                           offset=log(libsize_TMM),
                           data=df,
                           family=nbinom2,
                           control = glmmTMBControl(parallel = 1))

  # if not converged, try different optimizers
  full_model_nb <- try_other_optimizers(full_model_nb)

  #Check if model converged or not
  full_model_nb_convergence <- ifelse(full_model_nb$fit$convergence,FALSE,TRUE)
  
  nb_pvalues <- summary(full_model_nb)$coefficients$cond %>% 
      as.data.frame() %>% 
      rownames_to_column('variable') %>% 
      filter(grepl('genotype_parsed:',variable)) %>% 
      dplyr::select(variable,`Pr(>|z|)`) %>% 
      mutate(variable=gsub('genotype_parsed:cell_type_model','',variable)) %>% 
      mutate(p_bonf=p.adjust(`Pr(>|z|)`,method='bonferroni'))
  
  nb_pvalues_all <- nb_pvalues %>% dplyr::select(-p_bonf) %>% spread(variable,`Pr(>|z|)`)
  nb_pvalues_all[,cell_type_id] <- NA
  colnames(nb_pvalues_all) <- paste0(colnames(nb_pvalues_all),'_p')
  
  nb_pvalues_all <- nb_pvalues_all[,order(names(nb_pvalues_all))]
  
  out <- tibble(cell_type_id=cell_type_id,gene_id=gene_id,snp_id=snp_id,
                nb_pvalue_aggregate=nb_pvalues_aggregate$`Pr(>|z|)`,
                nb_pvalue_at_least_one=min(nb_pvalues$p_bonf,na.rm=TRUE)) %>% 
    cbind(nb_pvalues_all,
          nb_pvalue_aggregate_model_converged=full_model_nb_aggregate_convergence,
          nb_pvalue_at_least_one_model_converged=full_model_nb_convergence)

  return(out)
}

Get results

results <- mclapply(1:nrow(d_sig),interaction_model,mc.cores=36) %>% 
  setNames(1:nrow(d_sig)) %>% 
  bind_rows() %>% 
  arrange(nb_pvalue_aggregate) %>% 
  as_tibble() %>% 
  mutate_if(is.numeric,signif,3)

Write

dir.create('output/eqtl_specific/',showWarnings = FALSE)
write_tsv(results,'output/eqtl_specific/eqtl.PC70.specific.txt')

sessionInfo()
R version 4.0.1 (2020-06-06)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: CentOS Linux 7 (Core)

Matrix products: default
BLAS/LAPACK: /pstore/apps/OpenBLAS/0.3.1-GCC-7.3.0-2.30/lib/libopenblasp-r0.3.1.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  stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
 [1] glmmTMB_1.0.2.1 seqminer_8.0    forcats_0.5.0   stringr_1.4.0  
 [5] dplyr_1.0.0     purrr_0.3.4     readr_1.3.1     tidyr_1.1.0    
 [9] tibble_3.0.1    ggplot2_3.3.3   tidyverse_1.3.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.6        lubridate_1.7.9   lattice_0.20-41   assertthat_0.2.1 
 [5] rprojroot_1.3-2   digest_0.6.25     R6_2.4.1          cellranger_1.1.0 
 [9] backports_1.1.7   reprex_0.3.0      evaluate_0.14     httr_1.4.1       
[13] pillar_1.4.4      rlang_0.4.10      readxl_1.3.1      minqa_1.2.4      
[17] rstudioapi_0.11   nloptr_1.2.2.1    whisker_0.4       blob_1.2.1       
[21] Matrix_1.2-18     rmarkdown_2.2     splines_4.0.1     statmod_1.4.34   
[25] lme4_1.1-26       TMB_1.7.20        munsell_0.5.0     broom_0.5.6      
[29] compiler_4.0.1    httpuv_1.5.4      modelr_0.1.8      xfun_0.14        
[33] pkgconfig_2.0.3   htmltools_0.5.1.1 tidyselect_1.1.0  workflowr_1.6.2  
[37] fansi_0.4.1       crayon_1.3.4      dbplyr_1.4.4      withr_2.2.0      
[41] later_1.1.0.1     MASS_7.3-51.6     grid_4.0.1        nlme_3.1-148     
[45] jsonlite_1.6.1    gtable_0.3.0      lifecycle_0.2.0   DBI_1.1.0        
[49] git2r_0.27.1      magrittr_1.5      scales_1.1.1      cli_2.0.2        
[53] stringi_1.4.6     fs_1.4.1          promises_1.1.1    xml2_1.3.2       
[57] ellipsis_0.3.1    generics_0.0.2    vctrs_0.3.1       boot_1.3-25      
[61] tools_4.0.1       glue_1.4.1        hms_0.5.3         yaml_2.2.1       
[65] colorspace_1.4-1  rvest_0.3.5       knitr_1.28        haven_2.3.1