BatchQC 2.8.3
Samples are often collected or processed in multiple batches or at different times. This often produces technical biases that can lead to incorrect results in the downstream analysis. BatchQC is a software tool that streamlines batch preprocessing and evaluation by providing shiny app interactive diagnostics, visualizations, and statistical analyses to explore the extent to which batch variation impacts the data. This is contained in a full R package which allows reproducibility of all shiny evaluations and analyses. BatchQC diagnostics help determine whether batch adjustment needs to be done, and how correction should be applied before proceeding with a downstream analysis. Moreover, BatchQC interactively applies multiple common batch effect approaches to the data, and the user can quickly see the benefits of each method. BatchQC is developed as a Shiny App, but is reproducible at the command line through the functions contained in the R package. The output of the shiny app is organized into multiple tabs, and each tab features an important part of the batch effect analysis and visualization of the data. The BatchQC interface has the following features:
BatchQC() is the function that launches the Shiny App in interactive mode.
BatchQC was originally created with sequencing and micro-array samples in mind, however it has been designed in a way that any feature data (including, but not limited to, RNA-seq bulk or single cell, imaging data features, proteomics, methylation, microbiome, and genome sequencing coverage) can be uploaded and stored in a Summarized Experiment table. Please note that each batch correction method and analysis method has specific assumptions that must be met for a data set in order to be statistically valid. Please confirm that your data set meets these assumptions when choosing to use specific methods contained in BatchQC. Details about each can be found in the function descriptions.
We would like to remind users that batch correction analysis may lead to contradictory results. When this occurs, users should use their best judgement when determining the best batch correction method while considering the required assumptions for a method, the degree to which analysis indicate batch correction has been successful, the degree to which biological structure of the data has been maintained, and which methods have traditionally been best practice for your data type. This vignette, as well as the function descriptions, provides guidance on how to interpret results of each individual analysis which may be useful when making judgement calls. You may want to consider which metric disagrees, the degree to which this metric disagrees, and how widely adopted and tested that metric is among other considerations.
To begin, install Bioconductor and then install BatchQC:
if (!requireNamespace("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("BatchQC")
To install the most up-to-date version of BatchQC, please install directly from GitHub. You will need the devtools package. You can install both of these with the following commands:
if (!require("devtools", quietly = TRUE)) {
install.packages("devtools")
}
library(devtools)
install_github("wejlab/BatchQC")
You should now be able to load BatchQC and launch the shiny app.
library(BatchQC)
BatchQC()
Below is an example of how you may use the shiny app to analyze your data:
Upon launching the shiny app, you will be on the “Upload Data” screen. From here, you may upload the following data:
A preview of the selected data will show up under the “Input Summary” and “Full Metadata” tab. Input summary shows the counts file/assay on the Input summary tab and the metadata on the “Full Metadata” tab. If a preview does not load as expected, please ensure your dataset is structured properly and a valid file type.
You MUST hit “Upload” for your data to be available to interact with the shiny app.
All shiny app functions can also be run from the command line; all command line execution require that your data is in a Summarized Experiment object. You can create a summarized experiment object from a features and metadata matrix. This would be done as follows:
# Load package data examples
data(signature_data)
data(batch_indicator)
# Create SE Object
features <- signature_data
metadata <- batch_indicator
se_object <- BatchQC::summarized_experiment(features, metadata)
# Name your assay
SummarizedExperiment::assayNames(se_object) <- "log_intensity"
# Ensure all relevat metadata varaibles are factors
se_object$batch <- as.factor(se_object$batch)
se_object$condition <- as.factor(se_object$condition)
Likewise, you can upload your own data into a summarized experiment object for use with command line functions by providing a data matrix and sample info matrix to the summarized_experiment function.
The remainder of this documentation will utilize the TB example data set included in the package. This can be loaded from the command line as a summarized experiment object with the following:
se_object <- tb_data_upload()
## Loading required namespace: curatedTBData
## Downloading: GSE152218
##
|
| | 0%
|
|============== | 20%
|
|============================ | 40%
|
|========================================== | 60%
|
|======================================================== | 80%
|
|======================================================================| 100%
## Downloading: GSE101705
##
|
| | 0%
|
|========== | 14%
|
|==================== | 29%
|
|============================== | 43%
|
|======================================== | 57%
|
|================================================== | 71%
|
|============================================================ | 86%
|
|======================================================================| 100%
## Finished!
For ease of reference, we will also create variables to store the assay we are interested in, the batch variable, and the covariable we are interested in.
assay_of_interest <- "features"
batch <- "Experiment"
covar <- "TBStatus"
You may choose to use these tools in a different order, although we recommend checking the distribution of your data before deciding the best batch correction method. you may also choose to explore your raw data with the various tools within BatchQC to confirm the presence of a batch effect prior to applying a batch correction method. In this example, we have applied a batch correction method based on the results of the distribution check, but you may choose to do further analysis before selecting (a) (or even comparing) batch correction method(s).
compute_aic' can provide a negative binomial distribution value only for positive discrete data. Positive non-discrete data will result incompute_aic`
reporting only the voom and log-normal distribution analysis.
The negative binomial goodness-of-fit will provide an estimate for discrete or non-discrete data.
These tools are found on the Batch Correction/Normalization tab as we recommend utilizing these tools to inform your choice of batch correction method.
TB_AIC <- compute_aic(se = se_object,
assay_of_interest = assay_of_interest,
batchind = batch,
groupind = covar,
maxit = 1000,
zero_filt_percent = 15
)
## Warning in sqrt(1/i): NaNs produced
## Warning in sqrt(1/i): NaNs produced
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: algorithm did not converge
TB_AIC["AIC_table"]
## $AIC_table
## nb_AIC lognormal_AIC voom_AIC
## Total AIC 18608300.213 4683915.6234 3174420.1261
## Frequency of Minimum AIC 1.000 14109.0000 3247.0000
## AIC Score 18608300.213 331.9807 977.6471
## Median AIC 1099.963 128.2294 177.1217
TB_AIC["AIC_boxplot"]
## $AIC_boxplot
## Warning: Removed 2 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_point()`).
The lowest AIC represented by “AIC Score” indicates the model that is likely the best fit. In this dataset, the lowest “AIC Score” is lognormal. Therefore, we should consider using ComBat as our correction method.
We can further confirm that a negative binomial distribution is not a good fit by running the DESeq2 negative binomial check.
# Set a seed if you would like reproducible results
set.seed(1)
TB_fit <- goodness_of_fit_nb(se = se_object,
count_matrix = assay_of_interest,
condition = covar,
other_variables = batch,
num_genes = 3000,
method = "edgeR")
## calcNormFactors has been renamed to normLibSizes
## Warning: `aes_string()` was deprecated in ggplot2 3.0.0.
## ℹ Please use tidy evaluation idioms with `aes()`.
## ℹ See also `vignette("ggplot2-in-packages")` for more information.
## ℹ The deprecated feature was likely used in the BatchQC package.
## Please report the issue at <https://github.com/wejlab/BatchQC/issues>.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
TB_fit$res_histogram
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.
TB_fit$recommendation
## [1] "These methods have not been tested on data sets with between 21-149 samples. Thus, caution should be had when interpretting the results. With an FDR adjusted p-value cut off of 0.05, 1072 of your condition variable features are below the cutoff. If edgeR's assumptions are met, we would expect a uniform distribution of significant features. Since 36% of features have a significant adjusted pvalue (<0.05), you should be cautious about using edgeR for your analysis. You have significant features, and thus you are at risk of receiving false results."
The recommendation states that the edgeR negative binomial distribution is likely being violated. Therefore we probably should not consider down stream methods that assume a negative binomial distribution.
After you have successfully uploaded your data set of interest, you can apply one of the following Normalization methods if appropriate:
To use one of these two methods, select it from the normalization method drop down, select an assay to perform the normalization on from the drop down, and name the new assay (the prepopulated name can be changed to your preference). You may also choose to log-transform the results of either of these normalization methods or your raw data by selecting the “Log transform” box. Hit “Normalize” to complete the analysis. Your new assay will now be available for further analysis.
Alternatively, this can be called directly from the command line on an SE object and will return the same SE object with an additional assay with the name that you provide as the output_assay_name.
Our TB data set is raw count data and to utilize ComBat we will need normalized data. We will utilize log_CPM normalized data for ComBat. However, examples are provided below on how you would complete many different normalization methods if needed via the command line:
# CPM Normalization
se_object <- BatchQC::normalize_SE(se = se_object, method = "CPM",
log_bool = FALSE, assay_to_normalize = assay_of_interest,
output_assay_name = "CPM_normalized_counts")
# CPM Normalization w/log
se_object <- BatchQC::normalize_SE(se = se_object, method = "CPM",
log_bool = TRUE, assay_to_normalize = assay_of_interest,
output_assay_name = "CPM_log_normalized_counts")
# DESeq Normalization
se_object <- BatchQC::normalize_SE(se = se_object, method = "DESeq",
log_bool = FALSE, assay_to_normalize = assay_of_interest,
output_assay_name = "DESeq_normalized_counts")
# DESeq Normalization w/log
se_object <- BatchQC::normalize_SE(se = se_object, method = "DESeq",
log_bool = TRUE, assay_to_normalize = assay_of_interest,
output_assay_name = "DESeq_log_normalized_counts")
# log adjust
se_object <- BatchQC::normalize_SE(se = se_object, method = "none",
log_bool = TRUE, assay_to_normalize = assay_of_interest,
output_assay_name = "log_normalized_counts")
Select the appropriate Batch Effect correction model to create a batch-corrected assay for your data. You may select one of the following:
To apply your desired batch effect correction model, select the method from the drop down menu, then select the appropriate assay in the second drop down menu, select your batch variable (typically labeled batch in built-in examples), and the covariates that you would like to preserve (not including the batch variable). If desired, revise the name for the corrected assay and then hit “Correct.”
A progress bar will pop up in the bottom right hand corner and a message will state “Correction Complete” in the bottom right hand corner when complete.
You are now ready to analyze your raw and batch effect corrected data sets!
The distribution analysis indicated that our TB data follows a log normal distribution, so ComBat is likely an appropriate batch correction tool. We will use the log-CPM assay since ComBat requires normalized data. Therefore, to run from the command line use the following:
# ComBat correction
se_object <- BatchQC::batch_correct(se = se_object, method = "ComBat",
assay_to_normalize = "CPM_log_normalized_counts", batch = batch,
covar = c(covar), output_assay_name = "ComBat_corrected")
## Found 4182 genes with uniform expression within a single batch (all zeros); these will not be adjusted for batch.
## Found2batches
## Adjusting for1covariate(s) or covariate level(s)
## Standardizing Data across genes
## Fitting L/S model and finding priors
## Finding parametric adjustments
## Adjusting the Data
ComBat-Seq (or limma or sva or svaseq) can be applied to a data set by providing “ComBat-Seq” (or “limma” or “sva” or “svaseq”) to the method parameter in the function call.
This tab allows you to view the batch status of each condition. Select the variable that represents your batch variable and then select the variable that represents the condition. A table will then appear listing each condition in the row and how many samples in each condition are in each batch (displayed in the columns).
To recreate this table, run the following code, which will produce a tibble as output:
batch_design_tibble <- BatchQC::batch_design(se = se_object, batch = batch,
covariate = covar)
batch_design_tibble
## # A tibble: 2 × 3
## # Groups: TBStatus [2]
## TBStatus GSE101705 GSE152218
## <fct> <int> <int>
## 1 LTBI 15 32
## 2 PTB 28 16
This tab displays the Pearson correlation coefficient and Cramer’s V estimation based on the selected batch and condition.
This table can be recreated with the following code:
confound_table <- BatchQC::confound_metrics(se = se_object, batch = batch)
confound_table
## Pearson Correlation Coefficient Cramer's V
## TBStatus 0.4279870 0.3175219
## HIVStatus NaN NaN
## BMI 1.0000000 1.0000000
## BMIcat 0.5898655 0.4589234
Pearson correlation coefficient indicates the strength of the linear relationship between your batch and condition variables. Note that this is the correlation between two categorical variables, so rather than measuring the correlation between the two variables (as with two continuous variables), it directly measures the dependence/independence of the batch and condition in the experimental design—i.e., the potential for confounding, but not confounding itself.
Values for this metric can range from -1 to 1, with a value close to 0 indicating batch/condition independence or a “balanced design”, which should be associated with a lower risk of observing a batch effect. A value closer to -1 or 1 indicates greater imbalance in the design and a higher likelihood of a batch effect.
To calculate only the pearson correlation coefficient, run the following:
pearson_cor_result <- BatchQC::std_pearson_corr_coef(batch_design_tibble)
pearson_cor_result
## [1] 0.427987
The Cramer’s V is an additional metric, similar to the Pearson Correlation, for batch effect and will be between 0 and 1. Values closer to 0 indicate a more balanced design and a lower likelihood of a batch effect, and values closer to 1 are associated with an imbalanced design and a greater likelihood of a batch effect.
To calculate only Cramer’s V, run the following:
cramers_v_result <- BatchQC::cramers_v(batch_design_tibble)
cramers_v_result
## [1] 0.3175219
If both the Pearson Correlation Coefficient and the Cramer’s V test indicate low batch effect, you likely do not need to adjust your results for batch. However, if one or both metrics indicate some or high batch effect, you should use additional analysis tools (listed below) to explore the need for a batch correction for your results.
First, select your unadjusted assay, your batch variable and any covariates of interest. Click “Here we go!” to see the lambda statistic and variation analysis results. The “Individual Variable” tab shows the individual, or raw variation, explained by each variable. The “Residual” tab displays the type 2, or residual, variation for each variable. A box plot is displayed along with a table with the variation specific to each gene listed. This table is searchable and can be displayed in ascending or descending order. Notice the amount of variation attributed to batch. In our signature data set, most of the variation is attributed to batch rather than the condition. This indicates a need for a batch correction.
The “Individual Variation Variable/Batch Ratio” tab displays the individual, or raw variation, divided by the batch. A ratio greater that 1 indicates that batch has a stronger affect than the variable of interest. And the “Residual Variation Variable/Batch Ratio” displays the residual, or type 2 variation, divided by the batch. A ratio greater that 1 indicates that batch has a stronger affect than the variable of interest.
Next, select the batch corrected assay, with the same batch and condition variable and observe the changes in variation. When batch effect is being properly corrected, you should notice that the variation explained by the batch variable has decreased in the batch corrected assay, indicating that the variation in the data is now more likely to be associated with your condition of interest rather than the batch. The ratio statistics should also be less than 1. This is visible in our example data set and confirms the need for batch adjustment.
To recreate the lambda statistic for the TB counts assay, use the following code:
lambda_calculation <- run_lambda(se = se_object,
assay = assay_of_interest,
batch = batch,
condition = covar)
lambda_calculation$correction_recommendation
## [1] "The experimental design is unbalanced. Therefore, you should consider applying a batch correction method to your data. The calculated lambda statistic is 3.47."
lambda_calculation$lambda_stat
## [1] 3.470125
To recreate the variation analysis plot for the TB counts assay, use the following code for individual variation:
ex_variation <- batchqc_explained_variation(se = se_object,
batch = batch, condition = covar, assay_name = assay_of_interest)
EV_boxplot <- BatchQC::EV_plotter(batchqc_ev = ex_variation[[1]])
EV_boxplot
BatchQC::summary_stats_EV_table(ex_variation[[1]])
## Explained Experiment TBStatus Unexplained
## Min. 0.000 0.00000 0.000000 6.370
## 1st Qu. 1.730 1.00000 0.600000 65.010
## Median 8.580 3.10000 1.190000 91.420
## Mean 19.871 14.29845 4.043791 80.129
## 3rd Qu. 34.990 22.19000 4.440000 98.270
## Max. 93.630 93.58000 53.000000 100.000
To recreate the residual variation analysis table for the TB counts assay, use the following code:
EV_boxplot_type_2 <- BatchQC::EV_plotter(batchqc_ev = ex_variation[[2]])
EV_boxplot_type_2
BatchQC::summary_stats_EV_table(ex_variation[[2]])
## Explained Experiment TBStatus Unexplained
## Min. 0.000 0.00000 0.000000 6.370
## 1st Qu. 1.730 0.54000 0.530000 65.010
## Median 8.580 3.73500 1.620000 91.420
## Mean 19.871 15.82695 5.572554 80.129
## 3rd Qu. 34.990 25.96000 7.130000 98.270
## Max. 93.630 84.65000 54.450000 100.000
We can then compare our batch corrected assay, using the following code:
ex_variation <- batchqc_explained_variation(se = se_object,
batch = batch, condition = covar, assay_name = "ComBat_corrected")
EV_boxplot <- BatchQC::EV_plotter(batchqc_ev = ex_variation[[1]])
EV_boxplot
BatchQC::summary_stats_EV_table(ex_variation[[1]])
## Explained Experiment TBStatus Unexplained
## Min. 0.000000 0.000000 0.000000 1.62000
## 1st Qu. 0.730000 0.190000 0.500000 87.15000
## Median 3.040000 0.570000 2.270000 96.96000
## Mean 8.379356 1.071386 8.004516 91.62064
## 3rd Qu. 12.850000 1.340000 12.520000 99.27000
## Max. 98.380000 98.350000 60.260000 100.00000
EV_boxplot_type_2 <- BatchQC::EV_plotter(batchqc_ev = ex_variation[[2]])
EV_boxplot_type_2
BatchQC::summary_stats_EV_table(ex_variation[[2]])
## Explained Experiment TBStatus Unexplained
## Min. 0.000000 0.0000000 0.000000 1.62000
## 1st Qu. 0.730000 0.0200000 0.380000 87.15000
## Median 3.040000 0.0700000 2.100000 96.96000
## Mean 8.379356 0.3745516 7.308033 91.62064
## 3rd Qu. 12.850000 0.2600000 11.540000 99.27000
## Max. 98.380000 89.3800000 54.730000 100.00000
EV_table <- BatchQC::EV_table(batchqc_ev = ex_variation[[1]])
EV_table
## Gene Name Explained Experiment TBStatus Unexplained
## <char> <num> <num> <num> <num>
## 1: A1BG 10.74 1.14 10.74 89.26
## 2: A1BG-AS1 11.89 1.47 11.87 88.11
## 3: A1CF 0.86 0.37 0.73 99.14
## 4: A2M 1.13 0.13 1.13 98.87
## 5: A2M-AS1 15.47 0.95 15.39 84.53
## ---
## 33582: ZYG11A 1.88 0.62 1.73 98.12
## 33583: ZYG11AP1 3.14 2.11 2.02 96.86
## 33584: ZYG11B 9.90 0.03 9.21 90.10
## 33585: ZYX 2.36 0.07 2.31 97.64
## 33586: ZZEF1 27.60 2.27 27.57 72.40
EV_table_type_2 <- BatchQC::EV_table(batchqc_ev = ex_variation[[2]])
EV_table_type_2
## Gene Name Explained Experiment TBStatus Unexplained
## <char> <num> <num> <num> <num>
## 1: A1BG 10.74 0.00 9.60 89.26
## 2: A1BG-AS1 11.89 0.02 10.42 88.11
## 3: A1CF 0.86 0.13 0.49 99.14
## 4: A2M 1.13 0.00 1.00 98.87
## 5: A2M-AS1 15.47 0.08 14.52 84.53
## ---
## 33582: ZYG11A 1.88 0.15 1.26 98.12
## 33583: ZYG11AP1 3.14 1.12 1.02 96.86
## 33584: ZYG11B 9.90 0.69 9.87 90.10
## 33585: ZYX 2.36 0.06 2.30 97.64
## 33586: ZZEF1 27.60 0.03 25.33 72.40
To confirm the presence of batch effects in the simulated dataset, we use kBET, a method that quantifies batch effects through a chi-square test. kBET works by comparing the batch label distribution in each sample’s local neighborhood to the global batch label distribution across the entire dataset. If these distributions differ significantly, it indicates the presence of batch effects. A lower rejection rate indicates well-mixed replicates, which in turn indicate a lower likelihood of a batch effect being present.
Below is how we would run the kBET analysis on the TB data set.
TB_kBET <- BatchQC::run_kBET(se = se_object,
assay_to_normalize = assay_of_interest,
batch = batch)
BatchQC::plot_kBET(TB_kBET)
The boxplot shows that the observed rejection rate is significantly higher than the expected rejection rate, indicating a strong batch effect in the TB dataset.
BatchQC contains a number of visualization methods that may help you identify a batch effect (or to confirm that a batch effect has been removed).
The heatmap tab contains options for a sample correlation heatmap or for a more traditional heatmap comparing samples and genes. Select your assay of interest and the batch and condition(s) of interest. We recommend viewing no more than 500 elements at a time (or the max number in your data set).
This heatmap shows how similar each sample is to each other sample in your data (samples are plotted on both the x and y axis, so are identical to their self). The samples are clustered together based on similarity. Ideally, you would expect your samples to cluster and be more similar to samples from the same condition rather than from the sample batch. If there is clear visual clustering of the batch in your raw data, you should apply a batch correction method. Your batch corrected assay should have stronger clustering by condition.
Using the TB dataset, we initially see clustering based on batch, but after apply ComBat, our adjusted data set clusters more based on condition.
Use the following code to recreate the sample correlation heatmap:
heatmaps <- BatchQC::heatmap_plotter(se = se_object, assay = assay_of_interest,
nfeature = 38, annotation_column = c(batch, covar),
log_option = "FALSE")
correlation_heatmap <- heatmaps$correlation_heatmap
correlation_heatmap