--- title: "An Introduction to Harman" author: "Jason Ross and Yalchin Oytam" date: "`r doc_date()`" package: "`r pkg_ver('Harman')`" abstract: > Harman is a PCA and constrained optimisation based technique that maximises the removal of batch effects from datasets, with the constraint that the probability of overcorrection (i.e. removing genuine biological signal along with batch noise) is kept to a fraction which is set by the end-user. output: BiocStyle::html_document vignette: > %\VignetteIndexEntry{IntroductionToHarman} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r style, eval=TRUE, echo = FALSE, results = 'asis'} BiocStyle::markdown() ``` # Introduction The quantification of methylation can be expressed as the log-transformed ratio of methylated over unmethylated signal (M) or the ratio of methylated over total (methylated plus unmethylated) signal (β). *It is important to use M values when batch effect correcting Infinium methylation data as these are unbounded*. By definition, β is constrained between 0 and 1, and after correction there is no guarantee the values will still be within this range. M values can be batch-adjusted and then transformed back into the more readily interpretable β methylation values by a simple inverse logit transformation. With this transformation, very large negative and positive M values become asymptotic to β of 0 and 1, respectively. Before detecting clusters, this conversion from M-values to β must be undertaken. *The Harman package is available from Bioconductor (`r Biocpkg("Harman")`).* ```{r, echo=FALSE, warning=FALSE} library(knitr) library(RColorBrewer) ``` # Transcriptome data examples ## Working with a simple transciptome microarray dataset First off, let's load an example dataset from `r Biocexptpkg("HarmanData")` where the batches and experimental variable are balanced. ```{r} library(Harman) library(HarmanData) data(OLF) ``` The olfactory stem cell study is an experiment to gauge the response of human olfactory neurosphere-derived (hONS) cells established from adult donors to ZnO nanoparticles. A total of 28 Affymetrix HuGene 1.0 ST arrays were normalised together using RMA. The data comprises six treatment groups plus a control group, each consisting of four replicates: ```{r} table(olf.info) ``` The `olf.info` data.frame has the expt and batch variables across `r ncol(olf.info)` columns, with each sample described in one row to give `r nrow(olf.info)` rows. ```{r} olf.info[1:7,] ``` The data is a data.frame of normalised log2 expression values with dimensions: `r nrow(olf.data)` rows (features) x `r ncol(olf.data)` columns (samples). This data can be handed to Harman as is, or first coerced into a matrix. ```{r} head(olf.data) ``` ### Running Harman **Okay, so let's run Harman.** ```{r runharman} olf.harman <- harman(olf.data, expt=olf.info$Treatment, batch=olf.info$Batch, limit=0.95) ``` This creates a `harmanresults` S3 object which has a number of slots. These include the centre and rotation slots of a prcomp object which is returned after calling `prcomp(t(x))`, where x is the datamatrix supplied. These two slots are required for reconstructing the data later. The other slots are the factors supplied for the analysis (specified as expt and batch), the runtime parameters and some summary stats for Harman. Finally, there are the original and corrected PC scores. ```{r} str(olf.harman) ``` ### Inspecting results Harman objects can be inspected with methods such as `pcaPlot` and `arrowPlot`, as well as the generic functions `plot` and `summary`. ```{r, fig.height=4, fig.width=7} plot(olf.harman) ``` ```{r, fig.height=5, fig.width=5} arrowPlot(olf.harman, main='Arrowplot of correction') ``` Using `summary` or inspecting the stats slot we can see Harman corrected the first 7 PCs and left the rest uncorrected. ```{r} summary(olf.harman) ``` ```{r, echo=FALSE} kable(olf.harman$stats) ``` As the confidence (limit) was 0.95, Harman will look for batch effects until this limit is met. It does this by reducing the batch means in an iterative way using a binary search algorithm until the chance that biological variance is being removed (the factor given in expt) is too high. Consider the values specified in the `confidence` column as the likelihood that separation of samples in this PC is due to batch alone and not due to the experimental variable. If this confidence value is less than limit, Harman will not make another iterative correction. For example, on PC8 the confidence is about 0.835 which is below the limit of 0.95, so Harman did not alter data on this PC. Let's check this on a plot. ```{r, fig.height=5, fig.width=5} arrowPlot(olf.harman, 1, 8) ``` The horizontal arrows show us that, on PC1 the scores were shifted, but on PC8 they were not. If both dimensions were not shifted, the `arrowPlot` will default to printing **x** instead of arrows (*can't have 0 length arrows!*) ```{r, fig.height=5, fig.width=5} arrowPlot(olf.harman, 8, 9) ``` We can also easily colour the PCA plot by the experimental variable to compare: ```{r, fig.height=4, fig.width=7} par(mfrow=c(1,2)) pcaPlot(olf.harman, colBy='batch', pchBy='expt', main='Col by Batch') pcaPlot(olf.harman, colBy='expt', pchBy='batch', main='Col by Expt') ``` ### Reconstruct the corrected data So, if corrections have been made and we're happy with the value of limit, then we reconstruct corrected data from the Harman adjusted PC scores. To do this, a harmanresults object is handed to the function `reconstructData()`. This function produces a matrix of the same dimensions as the input matrix filled with corrected data. ```{r} olf.data.corrected <- reconstructData(olf.harman) ``` This new data can be over-written into something like an ExpressionSet object with a command like `exprs(eset) <- data.corrected`. An example of this is below. To convince you that Harman is working as it should in reconstructing the data back from the PCA domain, let's test this principle on the original data. ```{r} olf.data.remade <- reconstructData(olf.harman, this='original') all.equal(as.matrix(olf.data), olf.data.remade) ``` So, the data is indeed the same *(to within the machine epsilon limit for floating point error)!* ### How does the new data differ from the old data? Let's try graphically plotting the differences using `image()`. First, the rows (assays) are ordered by the variation in the difference between the original and corrected data. ```{r, fig.height=9, fig.width=7} olf.data.diff <- abs(as.matrix(olf.data) - olf.data.corrected) diff_rowvar <- apply(olf.data.diff, 1, var) by_rowvar <- order(diff_rowvar) par(mfrow=c(1,1)) image(x=1:ncol(olf.data.diff), y=1:nrow(olf.data.diff), z=t(olf.data.diff[by_rowvar, ]), xlab='Sample', ylab='Probeset', main='Harman probe adjustments (ordered by variance)', cex.main=0.7, col=brewer.pal(9, 'Reds')) ``` We can see that most Harman adjusted probes were from batch 3 (samples 15 to 21), while batch 1 is relatively unchanged. In batches 2 and 3, often the same probes were adjusted to a larger extent in batch 3. This suggests some probes on this array design are prone to a batch effect. ```{r cleanup1, echo=FALSE} rm(list=ls()[grep("olf", ls())]) ``` ## Another simple transciptome dataset The IMR90 Human lung fibroblast cell line data that was published in a paper by Johnson et al [doi: 10.1093/biostatistics/kxj037](doi: 10.1093/biostatistics/kxj037) comes with Harman as an example dataset. ```{r} require(Harman) require(HarmanData) data(IMR90) ``` The data is structured like so: ```{r, echo=FALSE} kable(imr90.info) ``` It can be seen from the below table the experimental structure is completely balanced. ```{r} table(expt=imr90.info$Treatment, batch=imr90.info$Batch) ``` ### Evidence of batch effects While there isn't glaring batch effects in PC1 and PC2, they are more apparent when plotting PC1 and PC3. ```{r, fig.height=4, fig.width=7} par(mfrow=c(1,2), mar=c(4, 4, 4, 2) + 0.1) imr90.pca <- prcomp(t(imr90.data), scale. = TRUE) prcompPlot(imr90.pca, pc_x=1, pc_y=2, colFactor=imr90.info$Batch, pchFactor=imr90.info$Treatment, main='IMR90, PC1 v PC2') prcompPlot(imr90.pca, pc_x=1, pc_y=3, colFactor=imr90.info$Batch, pchFactor=imr90.info$Treatment, main='IMR90, PC1 v PC3') ``` ### Running Harman ```{r} imr90.hm <- harman(as.matrix(imr90.data), expt=imr90.info$Treatment, batch=imr90.info$Batch) ``` We can see the most batch correction was actually on the 3rd principal component and the data was also corrected on the 1st and 4th component. ```{r, echo=FALSE} kable(imr90.hm$stats) ``` Plotting PC1 v. PC2 and PC1 v. PC3... ```{r, fig.height=4, fig.width=7} plot(imr90.hm, pc_x=1, pc_y=2) plot(imr90.hm, pc_x=1, pc_y=3) ``` While no batch effect was found on PC2, there are batch effects on PC1, 3 and 4. An `arrowPlot()` shows the extent of the correction: ```{r, fig.height=5, fig.width=5} arrowPlot(imr90.hm, pc_x=1, pc_y=3) ``` On PC1 the data has been shifted only a little, while on PC3 a large batch-effect signature seems to be present. The corrected data on the PC1 v. PC3 plot is still a little separated by batch. If we wish to aggressively stomp on the batch effect, (with increased risk of removing some experimental variance), we may specify something like limit=0.9. ```{r, fig.height=4, fig.width=7} imr90.hm <- harman(as.matrix(imr90.data), expt=imr90.info$Treatment, batch=imr90.info$Batch, limit=0.9) plot(imr90.hm, pc_x=1, pc_y=3) ``` This time the samples across batches are less separated on the plot and there is also a batch effect found on PC2. ```{r, echo=FALSE} kable(imr90.hm$stats) ``` ### Reconstruct the corrected data Again, as before we reconstuct the data. Let's also use this data to do a comparison: a PCA plot of the original data and shiny new reconstructed data. ```{r, fig.height=4, fig.width=7} imr90.data.corrected <- reconstructData(imr90.hm) par(mfrow=c(1,2)) prcompPlot(imr90.data, 1, 3, colFactor=imr90.hm$factors$batch, cex=1.5, main='PCA, Original') prcompPlot(imr90.data.corrected, 1, 3, colFactor=imr90.hm$factors$batch, cex=1.5, main='PCA, Corrected') ``` ```{r cleanup2, echo=FALSE} rm(list=ls()[grep("imr90", ls())]) ``` ## Working with very small datasets This example is an illustration of how Harman will have reduced power in teasing apart biological and technical variance when presented with a very small dataset (2 replicates and 2 conditions). To illustrate, we use the toy dataset in `r Biocexptpkg("affydata")`. The `Dilution` data within relates to two sources of cRNA, A (human liver tissue) and B (Central Nervous System cell line), which have been hybridized to human array (HGU95A) in a range of proportions and dilutions. This toy example is taken from arrays hybridized to source A at 10 μg and 20 μg. There are two replicate arrays for each generated cRNA, with each array replicate processed in a different scanner. [*For more information see Gautier et al., affy - Analysis of Affymetrix GeneChip data at the probe level*](http://bioinformatics.oxfordjournals.org/content/20/3/307.full.pdf). ```{r affydata, warning=FALSE, message=FALSE, comment=FALSE} library(affydata, quietly = TRUE, warn.conflicts = FALSE) data(Dilution) Dilution.log <- Dilution intensity(Dilution.log) <- log(intensity(Dilution)) cols <- brewer.pal(nrow(pData(Dilution)), 'Paired') ``` This dataset contains technical replicates of liver RNA run on two different scanners. Technical replicates are denoted as A and B samples. There are two technical replicates across two array scanners. The 10 and 20 The second 2 are also replicates. The second arrays are hybridized to twice as much RNA so the intensities should be, in general, bigger. ```{r, echo=FALSE} kable(pData(Dilution)) ``` ```{r, fig.height=4, fig.width=4} boxplot(Dilution, col=cols) ``` Notice that the scanner effect (A vs B) is stronger than the RNA concentration effect (10 vs 20). This certainly hints at a batch effect. Let’s normalize the data by two methods (Loess and Quantile) and see if it removes this technical noise. ```{r normalize, fig.height=7, fig.width=9} Dilution.loess <- normalize(Dilution.log, method="loess") Dilution.qnt <- normalize(Dilution.log, method="quantiles") # define a quick PCA and plot function pca <- function(exprs, pc_x=1, pc_y=2, cols, ...) { pca <- prcomp(t(exprs), retx=TRUE, center=TRUE) if(is.factor(cols)) { factor_names <- levels(cols) num_levels <- length(factor_names) palette <- rainbow(num_levels) mycols <- palette[cols] } else { mycols <- cols } plot(pca$x[, pc_x], pca$x[, pc_y], xlab=paste('PC', pc_x, sep=''), ylab=paste('PC', pc_y, sep=''), col=mycols, ...) if(is.factor(cols)) { legend(x=min(pca$x[, pc_x]), y=max(pca$x[, pc_y]), legend=factor_names, fill=palette, cex=0.5) } } par(mfrow=c(1,2), mar=c(4, 4, 4, 2) + 0.1) boxplot(Dilution.loess, col=cols, main='Loess') boxplot(Dilution.qnt, col=cols, main='Quantile') pca(exprs(Dilution.loess), cols=cols, cex=1.5, pch=16, main='PCA Loess') pca(exprs(Dilution.qnt), cols=cols, cex=1.5, pch=16, main='PCA Quantile') ``` The boxplots give the impression the batch effect has been removed. However, principal component analysis (PCA) shows the batch effect to still be the largest source of variance in the data. PC1 is dominated by batch effect (seperation of bold and pastel colours), while on PC2 the effect of RNA quantity is observed, so green (10 μg) compared with blue (20 μg). ### Running Harman Let’s fire up harman and try to remove this batch effect. ```{r affydata_harman1} library(Harman) loess.hm <- harman(exprs(Dilution.loess), expt=pData(Dilution.loess)$liver, batch=pData(Dilution.loess)$scanner) qnt.hm <- harman(exprs(Dilution.qnt), expt=pData(Dilution.qnt)$liver, batch=pData(Dilution.qnt)$scanner) ``` If we inspect the stats on the Harman runs, Loess-normalised data ```{r, echo=FALSE, fig.align='left'} kable(loess.hm$stats) ``` Quantile-normalised data ```{r, echo=FALSE, fig.align='left'} kable(qnt.hm$stats) ``` **The correction statistic is 1.0 for all dimensions, so Harman didn’t find any batch effect!** ### More aggressive settings While our intuition tells us there is a batch effect, with the default settings (limit=0.95), harman fails to find one. *This is due to the fact there are only two replicates in each batch!* Let’s step up the limit now, to a confidence interval of 0.75. So, we are 75% sure only technical (batch) variation and not biological variation is being removed. ```{r affydata_harman2} loess.hm <- harman(exprs(Dilution.loess), expt=pData(Dilution.loess)$liver, batch=pData(Dilution.loess)$scanner, limit=0.75) qnt.hm <- harman(exprs(Dilution.qnt), expt=pData(Dilution.qnt)$liver, batch=pData(Dilution.qnt)$scanner, limit=0.75) ``` This time a batch effect is found on PC1. Loess-normalised data ```{r, echo=FALSE} kable(loess.hm$stats) ``` Quantile-normalised data ```{r, echo=FALSE} kable(qnt.hm$stats) ``` ### Harman plots So what corrections did Harman make with limit=0.75? Let’s take a look… ```{r, fig.height=4, fig.width=7} par(mfrow=c(2,2), mar=c(4, 4, 4, 2) + 0.1) plot(loess.hm, 1, 2, pch=17, col=cols) plot(qnt.hm, 1, 2, pch=17, col=cols) ``` ### Reconstruct the corrected data ```{r affydata_reconstruct} Dilution.loess.hm <- Dilution.loess Dilution.qnt.hm <- Dilution.qnt exprs(Dilution.loess.hm) <- reconstructData(loess.hm) exprs(Dilution.qnt.hm) <- reconstructData(qnt.hm) ``` ```{r} detach('package:affydata') ``` # Working with unbalanced and confounded data ## Example dataset The dataset (`r Biocexptpkg("bladderbatch")`) for this exercise is that discussed by Jeff Leek and others [here](http://www.nature.com/nrg/journal/v11/n10/pdf/nrg2825.pdf) and arises from this [paper](http://www.ncbi.nlm.nih.gov/pubmed/15173019). This was a bladder cancer study comparing Affymetrix HG-U133A microarray expression profiles across five groups: superficial transitional cell carcinoma (sTCC) with surrounding carcinoma *in situ* (CIS) lesions (sTCC+CIS) or without surrounding CIS lesions (sTCC-CIS), muscle invasive carcinomas (mTCC) with normal bladder mucosa from patients without a bladder cancer history (Normal) and biopsies from cystectomy specimens (Biopsy). The arrays were run on 5 different days (5 batches). First, loading the data: ```{r, message=FALSE, warning=FALSE} library(bladderbatch) library(Harman) # This loads an ExpressionSet object called bladderEset data(bladderdata) bladderEset ``` The phenotype data. ```{r, echo=FALSE} kable(pData(bladderEset)) ``` A table of batch by outcome. ```{r} table(batch=pData(bladderEset)$batch, expt=pData(bladderEset)$outcome) ``` ### Batch structure The experimental design is very poor in controlling for a batch effect. Ideally, the five factors should be distributed across the five run dates (batches). Instead, four out of the five experimental factors are distributed across two batches. The sTCC+CIS samples are all within batch 5. In this instance, batch is completely confounded with the experimental variable, so any variation in the data will be a sum of the biological variance and technical variance. Any inference about the difference of sTCC+CIS to other groups needs to be made very guardedly. It is also worth noting the spread of the mTCC samples across batches is suboptimal. While there are 11 samples in batch 1, there is only a single sample in batch 2. Finally, batches 3 and 4 have only one sample type. Let's explore the multivariate grouping of the data by generating some PCA plots, first with colouring by batch and then by experimental variable. ```{r, fig.height=4, fig.width=7} par(mfrow=c(1,2)) prcompPlot(exprs(bladderEset), colFactor=pData(bladderEset)$batch, pchFactor=pData(bladderEset)$outcome, main='Col by Batch') prcompPlot(exprs(bladderEset), colFactor=pData(bladderEset)$outcome, pchFactor=pData(bladderEset)$batch, main='Col by Expt') ``` The batch structures are highly unbalanced and so a batch effect is not immediately obvious to casual observation. However, a closer examination of samples that are represented well across two batches (Biopsy and Normal), shows a batch effect is certainly present. Certainly, with an older microarray technology like the Affymetrix HG-U133A, batch effects will be present. ### Running Harman Even though the batch structures are highly unbalanced, this dataset is quite large - so, we expect Harman to be well powered to find batch effects. Let's take a look. ```{r, cache=FALSE} expt <- pData(bladderEset)$outcome batch <- pData(bladderEset)$batch bladder_harman <- harman(exprs(bladderEset), expt=expt, batch=batch) sum(bladder_harman$stats$correction < 1) ``` Harman found `r sum(bladder_harman$stats$correction < 1)` of the `r length(bladder_harman$stats$correction)` PCs had a batch effect. ```{r} summary(bladder_harman) ``` The `summary()` shows PC3 to be highly affected by batch. Now plotting the original and corrected data. ```{r, fig.height=4, fig.width=7} par(mfrow=c(1,1)) plot(bladder_harman) ``` This time for PCs 1 and 3. ```{r, fig.height=4, fig.width=7} plot(bladder_harman, 1, 3) ``` Now the PC scores changes displayed on an `arrowPlot`. ```{r, fig.height=5, fig.width=5} arrowPlot(bladder_harman, 1, 3) ``` ### Reconstruct the corrected data First create a new object and then fill the exprs slot of the `r class(bladderEset)[1]` object with Harman corrected data. Alternatively, the existing object can have the exprs slot overwritten. ```{r} CorrectedBladderEset <- bladderEset exprs(CorrectedBladderEset) <- reconstructData(bladder_harman) comment(bladderEset) <- 'Original' comment(CorrectedBladderEset) <- 'Corrected' ``` ## Limma analysis Let's check the effects of Harman with a `r Biocpkg("limma")` analysis. First fitting the original data: ```{r, message=FALSE, warning=FALSE} library(limma, quietly=TRUE) design <- model.matrix(~0 + expt) colnames(design) <- c("Biopsy", "mTCC", "Normal", "sTCC", "sTCCwCIS") contrast_matrix <- makeContrasts(sTCCwCIS - sTCC, sTCCwCIS - Normal, Biopsy - Normal, levels=design) fit <- lmFit(exprs(bladderEset), design) fit2 <- contrasts.fit(fit, contrast_matrix) fit2 <- eBayes(fit2) summary(decideTests(fit2)) ``` Now a linear model on the Harman corrected data: ```{r} fit_hm <- lmFit(exprs(CorrectedBladderEset), design) fit2_hm <- contrasts.fit(fit_hm, contrast_matrix) fit2_hm <- eBayes(fit2_hm) summary(decideTests(fit2_hm)) ``` We can see the dramatic effect Harman has had in reducing the number of significant microarray probes. The huge reduction in the Biopsy - Normal contrast makes biological sense, about half of the biopsies were from cystectomies that were histologically normal. The Harman corrected data on the sTCCwCIS - sTCC contrast suggests that surrounding *in situ* lesions (CIS) does not overly impact the transcriptome of superficial transitional cell carcinoma (sTCC). ```{r cleanup_bladderbatch, echo=FALSE} rm(list=ls()[!grepl("^pca$", ls())]) detach('package:bladderbatch') ``` # Methylation data examples ## Example dataset As an example, let's consider the Illumina Infinium HumanMethylation450 BeadChip data (450k array). First up, an important tip, **put M-values into Harman (M), not Beta-values (β).** Harman is designed for continuous ordinal data, not data which is constrained, such as β; which by definition are between 0 and 1. Input M into Harman and if β are needed downstream, convert the corrected M back into β using something like the `m2beta()` function in the `r Biocpkg("lumi")` package, or the `ilogit2()` function in `r Biocpkg("minfi")`. M-values also have the property of having far more centrality than β. PCA is a parametric technique and so it works best with an underlying Gaussian distribution to the data. While it has been historically shown that PCA works rather well in non-parametric settings, Harman might be expected to be more sensitive if the data is more centred (M), rather than bimodal at the extremes (β). β of exactly 0 or 1 will translate to minus infinity and infinity, respectively, in M space. M is the `logit2()` of a β and β are `ilogit2` of M. These infinite values will make the internal singular value decomposition (SVD) step of Harman throw an exception. Further, infinite M-values are not commutative. If an M of Inf or -Inf is transformed back into a β it will have the value NaN or 0, respectively. For these reasons we do not recommend a normalisation step which creates β of exactly 0 or 1. ```{r, message=FALSE, warning=FALSE} library(minfi, quietly = TRUE) logit2 ilogit2 ilogit2(Inf) ilogit2(-Inf) ``` A normalisation technique such as `preprocessIllumina()` in the `r Biocpkg("minfi")` package will give some β of exactly 0 or 1, while a technique such as `preprocessSWAN()` does not. Instead it incorporates a small offset, alpha, as suggested by [Pan Du et al](http://www.biomedcentral.com/content/pdf/1471-2105-11-587.pdf). If you have a `MethySet` object, the `r Biocpkg("minfi")` package now allows a user to specify an `offset` to the β as well as a `betaThreshold` to constrain betas away from 0 or 1. While we do not recommend use of a normalisation technique that generate β of exactly 0 or 1, sometimes, we realise, only this normalised data is available. For instance, when the data has been downloaded from a public resource, pre-normalised with no raw red and green channel data. For this case, we have supplied the `shiftBetas()` helper function in Harman to resolve this problem. We shift beta values of *exactly* 0 or 1 by a very small amount (typically 1 x 10^-4^) before transformation into M. As an example: ```{r} betas <- seq(0, 1, by=0.05) betas newBetas <- shiftBetas(betas, shiftBy=1e-4) newBetas range(betas) range(newBetas) logit2(betas) logit2(newBetas) ``` ### Loading 450K data So, let's get underway and analyse the toy dataset supplied with minfi. ```{r loadminfidata, message=FALSE, warning=FALSE} library(minfiData, quietly = TRUE) baseDir <- system.file("extdata", package="minfiData") targets <- read.metharray.sheet(baseDir) ``` Read in the files, normalise using `preprocessSWAN()` and `preprocessIllumina()` and filter out poorly called CpG sites. ```{r read450K} rgSet <- read.metharray.exp(targets=targets) mSetSw <- preprocessSWAN(rgSet) mSet <- preprocessIllumina(rgSet, bg.correct=TRUE, normalize="controls", reference=2) detP <- detectionP(rgSet) keep <- rowSums(detP < 0.01) == ncol(rgSet) mSetIl <- mSet[keep,] mSetSw <- mSetSw[keep,] ``` This dataset has quite a few phenotype variables of interest. The samples are paired cancer-normal samples from three people, 1 male and 2 females. ```{r, echo=FALSE} kable(pData(mSetSw)[,c('Sample_Group', 'person', 'sex', 'status', 'Array', 'Slide')]) ``` As mentioned above, it is prudent to look for sources of biological epigenetic variance which is potentially unrelated to the main experimental factor. If the source of variance has high population prevalence, it will often present by chance with unequal representation across each batch. If the biological variance is undeclared, batch effect correction methods will naïvely mistake this as array feature technical variance and moderate batches with unequal representation towards the global mean. In DNA methylation studies, obvious sources of biological variance are gender and cellular composition. Doing some exploratory data analysis using MDS (considering it is methylation data), we can see that status is separated on PC1 and sex on PC2. This makes biological sense as we know cancer and gender both have large effects on DNA methylation. In cancer samples, there is typically global hypomethylation and focal hypermethylation at some CpG islands. While in the case of gender, female and male samples have very different X chromosome methylation (due to X chromosome inactivation in females) and there are also other DNA gender-associated methylation differences on the autosomes. If the plot is recoloured by "Slide"", there is some suggestion a batch effect is intermingled with these two experimental variables. The tricky question is how to use Harman to remove the influence of Slide on the data, without also removing variance due to the experimental variables of interest? ```{r mdsplots, fig.height=5, fig.width=7} par(mfrow=c(1, 1)) cancer_by_gender_factor <- as.factor(paste(pData(mSetSw)$sex, pData(mSetSw)$status) ) mdsPlot(mSetSw, sampGroups=cancer_by_gender_factor, pch=16) mdsPlot(mSetSw, sampGroups=as.factor(pData(mSet)$Slide), pch=16) ``` The experiment is very small, with only `r nrow(pData(mSet))` (paired) samples. The MDS plots suggests there are two main phenotypes of influence, status and sex. The batch variable in this case is "Slide". The sex phenotype variable, which is highly influencing the data, is spread unevenly across the two slides (batches). ```{r} table(gender=pData(mSetSw)$sex, slide=pData(mSetSw)$Slide) ``` From the table, we can see that only slide 5723646052 has samples of male origin. If we specify a simple cancer-based model with `expt=pData(mSetSw)$status` and `batch=pData(mSetSw)$Slide`, Harman will attribute the male-specific methylation signature of the two paired male samples on slide 5723646052 as batch effect and will try and eliminate it. There are two strategies here: 1. Form a compound factor by joining the status and sex factors together. 2. Generate two Harman corrections, one for status and one for sex. As this experiment is so small, the first strategy won't be very effective. Only the factor level "F normal" is shared by both batches and for only one replicate. It's very hard for Harman to get an idea of the batch distributions. ```{r} cancer_by_gender_factor <- as.factor(paste(pData(mSetSw)$sex, pData(mSetSw)$status) ) table(expt=cancer_by_gender_factor, batch=pData(mSetSw)$Slide) ``` In the second strategy, both levels of expt are shared across both levels of batch. This is a far more ideal way to find batch effects. Of course though, *there is confounding between sex and Slide!* So, in these cases, do not consider a batch confounded factor in downstream differential analysis. ```{r} table(expt=pData(mSetSw)$status, batch=pData(mSetSw)$Slide) ``` ### Appropriate normalisation If the β distribution is shifted away from 0 or 1 by a very small amount, (say 1e-7), this will generate extreme M-values. Instead a moderate correction (such as 1e-4) seems the preferred option. ```{r shift, fig.height=7, fig.width=7} par(mfrow=c(2,2)) library(lumi, quietly = TRUE) shifted_betas <- shiftBetas(betas=getBeta(mSetIl), shiftBy=1e-7) shifted_ms <- beta2m(shifted_betas) # same as logit2() from package minfi plot(density(shifted_ms, 0.05), main="Shifted M-values, shiftBy = 1e-7", cex.main=0.7) shifted_betas <- shiftBetas(betas=getBeta(mSetIl), shiftBy=1e-4) shifted_ms <- beta2m(shifted_betas) # same as logit2() from package minfi plot(density(shifted_ms, 0.05), main="Shifted M-values, shiftBy = 1e-4", cex.main=0.7) plot(density(beta2m(getBeta(mSetSw)), 0.05), main="SWAN normalised M-values", cex.main=0.7) ``` It can be seen that M have far more central-tendency (more Gaussian-like) than β. ```{r, fig.height=4, fig.width=7} par(mfrow=c(1,2)) plot(density(shifted_betas, 0.1), main="Beta-values, shiftBy = 1e-4", cex.main=0.7) plot(density(shifted_ms, 0.1), main="M-values, shiftBy = 1e-4", cex.main=0.7) ``` A comparison of M-values produced by the GenomeStudio-like `preprocessIllumina()` function and by `preprocessSWAN()`. ```{r, fig.height=4, fig.width=7} par(mfrow=c(1,2)) plot(density(shifted_ms, 0.1), main="GenomeStudio-like M-values, shiftBy = 1e-4", cex.main=0.7) plot(density(getM(mSetSw), 0.1), main="SWAN M-values", cex.main=0.7) ``` **From here on, we will work with SWAN normalised M.** ### Harman correction of M For this example, status is declared as the experimental variable. When comparing conditions with very large DNA methylation differences, such as cancer and non-neoplastic samples, the batch effect will not be so easy to observe amongst all that biological variation. This scenario changes with a more subtle phenotype of interest. More arrays in each batch will allow Harman to more easily find batch effects. Considering this experiment is so small, an aggressive setting (limit=0.65) is needed to find a batch effect across a number of PCs (PCs 2, 5 and 1 in particular). A plot shows the correction made was relatively minor. ```{r, fig.height=4, fig.width=7} methHarman <- harman(getM(mSetSw), expt=pData(mSetSw)$status, batch=pData(mSetSw)$Slide, limit=0.65) summary(methHarman) plot(methHarman, 2, 5) ``` ### Reconstruct the corrected data It is difficult to tease out the batch effect with such a small experimental group. Rather than further reduce the limit, let's just convert the data back. ```{r} ms_hm <- reconstructData(methHarman) betas_hm <- m2beta(ms_hm) ``` ## Clustering of methylation values ### Introduction **There are caveats with batch-effect correction of methylation data**. The distribution of β at particular CpG sites may be modal in nature, which results in a clustered methylation pattern across samples. Clustered methylation profiles can be due to technical or biological factors, and batch correction should ideally remove the former but preserve the latter. Harman (and other methods such as ComBat) have biological variance to keep declared per sample, rather than per CpG site, so they are prone to erroneously attributing methylation clustering at particular CpG sites to technical factors. When the distribution of biologically relevant clustered methylation is unbalanced across batches, then batch effect removal software will inappropriately seek to converge the means of each batch. It is good practice to retrospectively identify the CpG sites subject to such erroneous correction as it can profoundly destroy biologically meaningful clustering of the data. The first recommendation is to undertake exploratory data analysis (like the MDS plotting example above) to look for obvious sample-wise sources of biological variance in the data, such as gender and cellular composition. These sources of sample-wise biological variance should be declared *a priori* and incorporated as factors into the batch correction. Without this, methods such as Harman and ComBat will seek to eliminate this biological variance when the batches have unequal loading of these factors. The second recommendation is to look for inappropriate feature-wise correction. Often this feature-wise biological variance on methylation arrays is the result of a single nucleotide polymorphism (SNP) at the cytosine within the measured CpG site. C-to-T transversion events at CpG sites are the most frequent SNPs in the genome and post-bisulfite conversion, this inherited genotype is misrepresented as epigenetic state – an inherited ‘T’ allele and a bisulfite-treated unmethylated ‘C’ allele are identical. CpG sites might also have methylation rates influenced by other proximal or distal SNPs. These cis-acting DNA polymorphisms can create allele-specific DNA methylation (ASM). Identifying feature-wise biological variance *a priori* is problematic. Filtering the features by lists of proximal SNPs does not account for unknown relationships between methylation state and distal SNPs, nor metastable epialleles. To optimally apply batch effect correction, we must empirically identify *post-hoc* the features where the algorithm is incorrectly distorting the data. The aim of batch-effect correction is to reduce technical variance in the data. When the methylation data is clustered with unequal epiallele loadings across batches, batch-effect removal algorithms will moderate the batches together, reducing technical variance but destroying the biologically relevant clustering patterns. The more recent versions of Harman (since V1.24) have a solution to identify inappropriate correction via a 'cluster-aware' variance statistic instead of considering variance in totality. This statistic computes the sum of squares relative to each individual cluster centroid and not the centroid of all the data. The 'cluster-aware' variance statistic will separate out instances of appropriate and inappropriate correction. Thereafter, investigators can use batch-effect corrected values for CpG sites that qualify as appropriately corrected and the original uncorrected data for CpG sites highly clustered due to biological factors, where correction is inappropriate. Large EWAS studies can use the functions in Harman to find clustered CpG sites in their study. Smaller studies may wish to use the reference matrices we provide in the `r Biocpkg("HarmanData")` package. ### Implications for EWAS **For the probes erroneously corrected, the original uncorrected data should be used in any downstream linear regressions.** It could also be useful to use the clustering data identified above to determine which probes might benefit from logistic regression analysis, where the probes are regressed not on the M or β value, but their cluster membership. This approach might be particularly useful for identifying and analysing metastable epialleles. ### Loading the reference matrix A reference matrix of data from 5 datasets can be loaded from `r Biocpkg("HarmanData")`. ```{r} library(HarmanData) data(Infinium5) lvr.harman[1:2, ] md.harman[1:2, ] ``` ### Discovering clusters _de novo_ in large EWAS studies To undertake this, there are a set of three functions in Harman designed to be run in series. Firstly, `discoverClusteredMethylation` takes a matrix of methylation beta values and clusters the data across a range of ks specified by the user. Then the data is reclustered again across the the best two candidate values for k (determined by the rate of change in Bayesian information criterion), and minimum cluster size and distance filters are employed. If both clusters meet these filters, then the higher value of k is returned. This function should be run on uncorrected data that ideally has slides removed which are prone to batch effect. This will bias towards finding clusters that are driven by biological factors such as X-chromosome inactivation and allele-specific methylation. The output of the above is input for `kClusterMethylation`. This function extracts cluster membership and statistics on variance for a given β matrix. The full dataset should be specified for this step (not trimmed data where samples prone to batch effect are removed). Finally, `clusterStats` provides a comparison of differences of uncorrected to batch-corrected β. This function generates a data.frame containing log variance ratio and mean beta differences to clusters after correction. Let's use the first 1000 rows on the toy data above to illustrate the workflow. ```{r} betas_sml <- getBeta(mSetSw)[1:1000, ] betas_hm_sml <- betas_hm[1:1000, ] myK <- discoverClusteredMethylation(betas_sml, min_cluster_size = 3, cores=2, printInfo = TRUE) mykClust = kClusterMethylation(betas_sml, row_ks=myK, cores=2) res <- clusterStats(pre_betas=betas_sml, post_betas=betas_hm_sml, kClusters = mykClust) res[1:2, ] ``` Here is a further canned example using 11 CpG sites from the EpiSCOPE cohort 450K data. ```{r} library(HarmanData) data(episcope) bad_batches <- c(1, 5, 9, 17, 25) is_bad_sample <- episcope$pd$array_num %in% bad_batches myK <- discoverClusteredMethylation(episcope$original[, !is_bad_sample]) mykClust <- kClusterMethylation(episcope$original, row_ks=myK) res <- clusterStats(pre_betas=episcope$original, post_betas=episcope$harman, kClusters = mykClust) res[1:2, ] ``` This set of 11 CpG sites illustrates examples of appropriate (cg04294190) and inappropriate (cg25465065) correction. ```{r clust_plot, fig.height=7, fig.width=7} slide_cols <- rep(brewer.pal(9, "Set1"), times=5)[as.factor(episcope$pd$array_num)] myplot <- function(probe) { plot(episcope$original[probe, ], main=paste(probe, ". Pre-var: ", round(res[probe, "pre_withinvar"], 5), sep=""), xlab="", ylab="Beta", cex=0.7, cex.main=0.9, ylim=c(0, 1), col=slide_cols) plot(episcope$harman[probe, ], main=paste(probe, ". Post-var: ", round(res[probe, "post_withinvar"], 5), ", LVR: ", round(res[probe, "log2_var_ratio"], 2), sep=""), xlab="", ylab="Beta", cex=0.7, cex.main=0.9, ylim=c(0, 1), col=slide_cols) } par(mfrow=c(2,2)) myplot("cg04294190") myplot("cg25465065") ``` For each feature, the number of clusters are determined empirically. In the above example, cg04294190 was identified as having 1 cluster as the slides prone to batch effect (1, 5, 9, 17, 25) were removed in the initial cluster identification step. One-dimensional K-means clustering analysis yielded 3 clusters for cg25465065. Next, the within-cluster sum of squares is computed for each cluster and summed as the total within-cluster sum of squares. This is computed before batch correction (pre) and after (post). To determine if the batch effection correction algorithm is appropriately correcting a given feature, `log2_var_ratio` (LVR) is the critical statistic. This is computed as `log2(post_withinvar / pre_withinvar)`. An LVR below 0 suggests the adjustment for that feature was appropriate, whereas an LVR above 0 indicates that cluster-aware variance is being magnified post-correction, so applying batch-effect correction to this probe is likely to be inappropriate. ### Thresholding In practice, when applying the LVR statistic to identify batch-effect susceptible probes, fully methylated or unmethylated CpG sites often have very small corrections made to them by Harman, but given the initial small variance, result in large changes in LVR. To focus on probes with a large change in LVR and an appreciable difference to β after correction we suggest the use of thresholding. To classify as 'erroneously corrected' or 'batch-effect susceptible' we suggest as a rule of thumb to use a cut-off of 50% variance increase (log2(1.5), LVR = 0.584) or decrease (log2(1/1.5), LVR = -0.584) and mean differences after correction of at least β >= |0.01|. These absolute value mean differences are given in the `meandiffs` column in the output of `clusterStats`. #### On *de novo* clustered data This is illustrated is below. ```{r} # Erroneously corrected res$probe_id[res$log2_var_ratio > log2(1.5) & res$meandiffs > 0.01] # Batch-effect susceptible res$probe_id[res$log2_var_ratio < log2(1/1.5) & res$meandiffs > 0.01] ``` #### Using a reference The reference matrix can also be used to threshold. In the below example, we find all the probes in the MethylationEPIC reference datasets (BodyFatness, NOVI, URECA) which consistently seem batch-effect susceptible. Batch effects are fairly idiosyncratic to each project, so in this case we are hunting for probes which often seem troublesome across projects. To find erroneously corrected probes we are thresholding on 1 or more datasets. This accounts for rare SNPs which may only appear in high enough frequency to identify a cluster in a subset of projects. ```{r} is_epic <- grepl("BodyFatness|NOVI|URECA", colnames(lvr.harman)) epic_lvr <- na.omit(lvr.harman[, is_epic]) epic_md <- na.omit(md.harman[, is_epic]) sum_batchy_lvr <- apply(epic_lvr, 1, function(p) sum(p < log2(1/1.5))) sum_geno_lvr <- apply(epic_lvr, 1, function(p) sum(p > log2(1.5))) sum_md <- apply(epic_md, 1, function(p) sum(p > 0.01)) table(sum_batchy_lvr & sum_md) table(sum_geno_lvr & sum_md) ``` Using these thresholds, there were `r sum(sum_batchy_lvr & sum_md)` probes consistently prone to some batch effect over the three MethylationEPIC datasets and `r sum(sum_geno_lvr & sum_md)` probes with a substantial erroneous changes post-correction, likely due to allele-specific methylation or a similar phenomenon. ## Limma analysis In downstream differential methylation analysis using `r Biocpkg("limma")` or otherwise, care must be taken to interpret the results. As Harman was run with the expt variable set to status, any other variation unrelated to status which is unbalanced across the two slides is considered as batch noise. For example, we have already shown that sex is a highly influential factor and it is unbalanced across the slides; only person of id3 is male and both the normal and cancer samples are on slide 5723646052. **Therefore, we expect Harman to attribute this gender effect to a slide effect.** In the specification of a linear model of `model.matrix(~id + group)`, we should then expect to find no differential methylation in person id3, the male. Let's try this: ```{r limma} library(limma) group <- factor(pData(mSetSw)$status, levels=c("normal", "cancer")) id <- factor(pData(mSetSw)$person) design <- model.matrix(~id + group) design ``` Now time to fit this design to both the original M-values and the Harman corrected M-values. ```{r fit} fit_hm <- lmFit(ms_hm, design) fit_hm <- eBayes(fit_hm) fit <- lmFit(getM(mSetSw), design) fit <- eBayes(fit) ``` Our intuition is correct. Harman has indeed squashed the variation in person id3, there are now no differentially methylated probes. ```{r limma_output} summary_fit_hm <- summary(decideTests(fit_hm)) summary_fit <- summary(decideTests(fit)) summary_fit_hm summary_fit ``` We also note, our ability to detect cancer-related differential methylation has been enhanced. There are now `r summary_fit_hm[1, 4] - summary_fit[1, 4]` more hypermethylated CpG probes and `r summary_fit_hm[3, 4] - summary_fit[3, 4]` more hypomethylated CpG probes. ```{r, echo=FALSE, warning=FALSE, message=FALSE} rm(list=ls()[!grepl("^pca$", ls())]) #detach('package:minfiData', force = TRUE) #detach('package:lumi', force = TRUE) #detach('package:minfi', force = TRUE) #detach('package:IlluminaHumanMethylation450kanno.ilmn12.hg19', force = TRUE) ``` # Mass Spectrophotometry data example ## Example dataset We use the data available in the `r Biocexptpkg("msmsEDA")` library which has 14 samples across two treatments and two batches. ### Loading the mass-spec data ```{r msms, message=FALSE, warning=FALSE} # Call dependencies library(msmsEDA) library(Harman) data(msms.dataset) msms.dataset ``` ### Preprocessing The data matrix in an MSnSet object from package `r Biocexptpkg("msmsEDA")` may have all zero rows (if it's a subset of a larger object) and some samples may have NA values, which correspond to proteins not identified in that particular sample. Principle components analysis cannot be undertaken on matrices with such features. So first we can use the wrapper function `pp.msms.data()`, which removes all zero rows and replaces NA with 0. ```{r msms_pp} # Preprocess to remove rows which are all 0 and replace NA values with 0. msms_pp <- pp.msms.data(msms.dataset) ``` ### Batch structure ```{r, echo=FALSE} kable(pData(msms_pp)) ``` ```{r} # Create experimental and batch variables expt <- pData(msms_pp)$treat batch <- pData(msms_pp)$batch table(expt, batch) ``` ### Running Harman ```{r msms_harman} # Log2 transform data, add 1 to avoid infinite values log_ms_exprs <- log(exprs(msms_pp) + 1, 2) # Correct data with Harman hm <- harman(log_ms_exprs, expt=expt, batch=batch) summary(hm) ``` The Harman result is interesting. This MS data seems to have the batch effect contained within the 1st and 14th PCs only. A marked difference compared to transcriptome microarray data and the like. A plot rather convincingly shows that Harman was able to remove the batch effect. ```{r, fig.height=4, fig.width=7} plot(hm) ``` ### Reconstruct the corrected data As usual we now reconstruct corrected data, but we add an extra transformation step on the end. As the data was Log2 transformed we convert it back to the original format (and subtract 1 as this was added before during the transformation into Log2 space). The corrected and transformed back data is placed into a new 'MSnSet' instance. ```{r} # Reconstruct data and convert from Log2, removing 1 as we added it before. log_ms_exprs_hm <- reconstructData(hm) ms_exprs_hm <- 2^log_ms_exprs_hm - 1 # Place corrected data into a new 'MSnSet' instance msms_pp_hm <- msms_pp exprs(msms_pp_hm) <- ms_exprs_hm ``` ```{r, echo=FALSE} rm(list=ls()[!grepl("^pca$", ls())]) detach('package:msmsEDA') ``` # Comparison to ComBat ComBat, available in the `r Biocpkg("sva")` package, adjusts for known batches using an empirical Bayesian framework. This involves mean and variance shrinkage on a feature by feature basis using the Bayesian model to estimate the shrinkage parameters. To allow some robustness in estimates when the number of samples is low, the model pools information across genes. Harman uses a dimensionality reduction approach with a confidence constraint set by the user. In this case, the features by samples matrix is decomposed into principal components. Unlike ComBat, batch adjustments are not on a feature by feature basis but on a principal component by principal component basis. Each orthogonal component is examined for evidence of a batch effect and if one is found, the batch means are moved step-wise towards zero in principal component space until the confidence limit for no evidence of a batch effect is met. Finally the adjusted PC scores are transformed back into raw data space. Fundamentally, Harman shifts feature values in a coordinated way across a batch one prinicipal component at a time, whereas ComBat shifts feature values one feature at a time by an amount informed by the batch structure and overall mean and variance of the data. To compare the techniques, we will apply the methods to a dataset and plot the difference between the original data matrix and after correction. ### IMR90 example data For this comparison we use the IMR90 data from the transcriptomics example earlier. This is the dataset used in the original ComBat paper by Johnson et al [doi: 10.1093/biostatistics/kxj037](doi: 10.1093/biostatistics/kxj037) This data has 4 treatments and 3 batches. ```{r} table(imr90.info) ``` ### Applying Harman and ComBat to adjust for known batches In accordance with the [advice](https://support.bioconductor.org/p/62874/) of Jeff Leek, for ComBat we do not include the variable of interest in specification of the model matrix. ```{r, message=FALSE, warning=FALSE} library(HarmanData) library(sva) modcombat <- model.matrix(~1, data=imr90.info) imr90.data.cb <- ComBat(dat=as.matrix(imr90.data), batch=imr90.info$Batch, mod=modcombat, par.prior=TRUE, prior.plots=FALSE) imr90.hr <- harman(imr90.data, expt = imr90.info$Treatment, batch = imr90.info$Batch) imr90.data.hr <- reconstructData(imr90.hr) prcompPlot(imr90.data, pc_x = 1, pc_y = 3, colFactor = imr90.info$Batch, pchFactor = imr90.info$Treatment, main='PC1 versus PC3') arrowPlot(imr90.hr, pc_x = 1, pc_y = 3, main='PC1 versus PC3') ``` ### Compare Plotting the differences between matrix values as a type of heatmap. The features of the microarray (rows) are ordered by the degree of correction in Harman. ```{r} library(RColorBrewer) diffMap <- function(a, b, feature_order=1:nrow(a), batch, ...) { image(t(abs(a[feature_order, ] - b[feature_order, ])), col = brewer.pal(9, "Greys"), xaxt='n', yaxt='n', xlab='Batch', ylab='Ordered feature', ...) axis(1, at=seq(0, 1, length.out=length(batch)), labels=batch) } ``` ```{r, fig.height=7, fig.width=7} probe_diffs_hr <- order(rowSums(abs(as.matrix(imr90.data - imr90.data.hr)))) probe_diffs_cb <- order(rowSums(abs(as.matrix(imr90.data - imr90.data.cb)))) diffMap(a=imr90.data, b=imr90.data.hr, feature_order=probe_diffs_hr, batch=imr90.info$Batch, main='Original - Harman') ``` ```{r, fig.height=7, fig.width=7} diffMap(a=imr90.data, b=imr90.data.cb, feature_order=probe_diffs_hr, batch=imr90.info$Batch, main='Original - ComBat') ``` ```{r, fig.height=7, fig.width=7} diffMap(a=imr90.data.hr, b=imr90.data.cb, feature_order=probe_diffs_hr, batch=imr90.info$Batch, main='Harman - ComBat') ``` ### Concluding remarks The feature by feature and sample by sample nature of ComBat is evident. In particular, the outlying sample in batch 3 has been subjected to quite extensive feature adjustment. Harman adjusts the values of features within batches in a coordinated way. In is particular example, Harman identifies across batches a highly coordinate set of features which need correction. Despite their differences, the Harman and Combat approaches have large overlaps in the features they identify as needing correction and the amount of feature adjustment required.