<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />


<meta name="author" content="Joyce Hsiao" />


<title>Normalize intensities across batches and positions</title>

<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cosmo.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/textmate.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-4.5.0/css/font-awesome.min.css" rel="stylesheet" />

<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
  pre:not([class]) {
    background-color: white;
  }
</style>
<script type="text/javascript">
if (window.hljs) {
  hljs.configure({languages: []});
  hljs.initHighlightingOnLoad();
  if (document.readyState && document.readyState === "complete") {
    window.setTimeout(function() { hljs.initHighlighting(); }, 0);
  }
}
</script>



<style type="text/css">
h1 {
  font-size: 34px;
}
h1.title {
  font-size: 38px;
}
h2 {
  font-size: 30px;
}
h3 {
  font-size: 24px;
}
h4 {
  font-size: 18px;
}
h5 {
  font-size: 16px;
}
h6 {
  font-size: 12px;
}
.table th:not([align]) {
  text-align: left;
}
</style>


</head>

<body>

<style type = "text/css">
.main-container {
  max-width: 940px;
  margin-left: auto;
  margin-right: auto;
}
code {
  color: inherit;
  background-color: rgba(0, 0, 0, 0.04);
}
img {
  max-width:100%;
  height: auto;
}
.tabbed-pane {
  padding-top: 12px;
}
button.code-folding-btn:focus {
  outline: none;
}
</style>


<style type="text/css">
/* padding for bootstrap navbar */
body {
  padding-top: 51px;
  padding-bottom: 40px;
}
/* offset scroll position for anchor links (for fixed navbar)  */
.section h1 {
  padding-top: 56px;
  margin-top: -56px;
}

.section h2 {
  padding-top: 56px;
  margin-top: -56px;
}
.section h3 {
  padding-top: 56px;
  margin-top: -56px;
}
.section h4 {
  padding-top: 56px;
  margin-top: -56px;
}
.section h5 {
  padding-top: 56px;
  margin-top: -56px;
}
.section h6 {
  padding-top: 56px;
  margin-top: -56px;
}
</style>

<script>
// manage active state of menu based on current page
$(document).ready(function () {
  // active menu anchor
  href = window.location.pathname
  href = href.substr(href.lastIndexOf('/') + 1)
  if (href === "")
    href = "index.html";
  var menuAnchor = $('a[href="' + href + '"]');

  // mark it active
  menuAnchor.parent().addClass('active');

  // if it's got a parent navbar menu mark it active as well
  menuAnchor.closest('li.dropdown').addClass('active');
});
</script>


<div class="container-fluid main-container">

<!-- tabsets -->
<script>
$(document).ready(function () {
  window.buildTabsets("TOC");
});
</script>

<!-- code folding -->




<script>
$(document).ready(function ()  {

    // move toc-ignore selectors from section div to header
    $('div.section.toc-ignore')
        .removeClass('toc-ignore')
        .children('h1,h2,h3,h4,h5').addClass('toc-ignore');

    // establish options
    var options = {
      selectors: "h1,h2,h3",
      theme: "bootstrap3",
      context: '.toc-content',
      hashGenerator: function (text) {
        return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_').toLowerCase();
      },
      ignoreSelector: ".toc-ignore",
      scrollTo: 0
    };
    options.showAndHide = true;
    options.smoothScroll = true;

    // tocify
    var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>

<style type="text/css">

#TOC {
  margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
  position: relative;
  width: 100%;
}
}


.toc-content {
  padding-left: 30px;
  padding-right: 40px;
}

div.main-container {
  max-width: 1200px;
}

div.tocify {
  width: 20%;
  max-width: 260px;
  max-height: 85%;
}

@media (min-width: 768px) and (max-width: 991px) {
  div.tocify {
    width: 25%;
  }
}

@media (max-width: 767px) {
  div.tocify {
    width: 100%;
    max-width: none;
  }
}

.tocify ul, .tocify li {
  line-height: 20px;
}

.tocify-subheader .tocify-item {
  font-size: 0.90em;
  padding-left: 25px;
  text-indent: 0;
}

.tocify .list-group-item {
  border-radius: 0px;
}


</style>

<!-- setup 3col/9col grid for toc_float and main content  -->
<div class="row-fluid">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>

<div class="toc-content col-xs-12 col-sm-8 col-md-9">




<div class="navbar navbar-default  navbar-fixed-top" role="navigation">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="index.html">fucci-seq</a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li>
  <a href="index.html">Home</a>
</li>
<li>
  <a href="about.html">About</a>
</li>
<li>
  <a href="license.html">License</a>
</li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li>
  <a href="https://github.com/jdblischak/fucci-seq">
    <span class="fa fa-github"></span>
     
  </a>
</li>
      </ul>
    </div><!--/.nav-collapse -->
  </div><!--/.container -->
</div><!--/.navbar -->
<!-- Add a small amount of space between sections. -->
<style type="text/css">
div.section {
  padding-top: 12px;
}
</style>

<div class="fluid-row" id="header">



<h1 class="title toc-ignore">Normalize intensities across batches and positions</h1>
<h4 class="author"><em>Joyce Hsiao</em></h4>

</div>


<!-- The file analysis/chunks.R contains chunks that define default settings
shared across the workflowr files. -->
<!-- Update knitr chunk options -->
<!-- Insert the date the file was last updated -->
<p><strong>Last updated:</strong> 2018-02-23</p>
<!-- Insert the code version (Git commit SHA1) if Git repository exists and R
 package git2r is installed -->
<p><strong>Code version:</strong> b299bc0</p>
<hr />
<div id="introductionsummary" class="section level2">
<h2>Introduction/summary</h2>
<p>In notations,</p>
<p><span class="math display">\[
y_{ij} = \mu + \tau_i + \beta_j + \gamma_k + \epsilon_{ij}
\]</span> where <span class="math inline">\(i = 1,2,..., I\)</span> and <span class="math inline">\(j = 1,2,..., J\)</span>. The parameters are estimated under sum-to-zero constraints <span class="math inline">\(\sum \tau_i = 0\)</span> and <span class="math inline">\(\sum \beta_j = 0\)</span>.</p>
<p>Note that in this model 1) not all <span class="math inline">\(y_{ij.}\)</span> exists due to the incompleteness of the design, 2) the effects of individual and block are nonorthogonal, 3) the effects are additive due to the block design.</p>
<p><strong>TO DO: Apply batch correction prior to background correction??</strong></p>
<hr />
</div>
<div id="data-and-packages" class="section level2">
<h2>Data and packages</h2>
<p><span class="math inline">\(~\)</span></p>
<pre class="r"><code>library(data.table)
library(dplyr)
library(ggplot2)
library(cowplot)
library(RColorBrewer)
library(Biobase)
library(scales)
library(car)
library(ashr)
library(lsmeans)</code></pre>
<p>Read in filtered data.</p>
<pre class="r"><code>df &lt;- readRDS(file=&quot;../data/eset-filtered.rds&quot;)
pdata &lt;- pData(df)
fdata &lt;- fData(df)</code></pre>
<hr />
</div>
<div id="source-of-variation" class="section level2">
<h2>Source of variation</h2>
<p>Statistical tests show that for GFP, there’s significant individual effect, plate effect and position effect, and that for RFP and DAPI, there’s no signficant individual effect or position effect but there’s significant plate effect (all at P&lt;.01).</p>
<pre class="r"><code>lm.rfp &lt;- lm(rfp.median.log10sum~factor(chip_id)+factor(experiment) + factor(image_label), 
             data = pdata)
lm.gfp &lt;- lm(gfp.median.log10sum~factor(chip_id)+factor(experiment) + factor(image_label), 
             data = pdata)
lm.dapi &lt;- lm(dapi.median.log10sum~factor(chip_id)+factor(experiment) + factor(image_label), 
             data = pdata)

aov.lm.rfp &lt;- Anova(lm.rfp, type = &quot;III&quot;)
aov.lm.gfp &lt;- Anova(lm.gfp, type = &quot;III&quot;)
aov.lm.dapi &lt;- Anova(lm.dapi, type = &quot;III&quot;)
aov.lm.rfp</code></pre>
<pre><code>Anova Table (Type III tests)

Response: rfp.median.log10sum
                     Sum Sq  Df  F value    Pr(&gt;F)    
(Intercept)          44.799   1 193.7809 &lt; 2.2e-16 ***
factor(chip_id)       2.061   5   1.7830  0.113731    
factor(experiment)    8.836  15   2.5480  0.001004 ** 
factor(image_label)  28.830  95   1.3127  0.029625 *  
Residuals           202.056 874                       
---
Signif. codes:  0 &#39;***&#39; 0.001 &#39;**&#39; 0.01 &#39;*&#39; 0.05 &#39;.&#39; 0.1 &#39; &#39; 1</code></pre>
<pre class="r"><code>aov.lm.gfp</code></pre>
<pre><code>Anova Table (Type III tests)

Response: gfp.median.log10sum
                    Sum Sq  Df  F value    Pr(&gt;F)    
(Intercept)         60.082   1 569.5986 &lt; 2.2e-16 ***
factor(chip_id)      1.608   5   3.0492  0.009779 ** 
factor(experiment)  12.174  15   7.6944 2.293e-16 ***
factor(image_label) 14.688  95   1.4658  0.003756 ** 
Residuals           92.191 874                       
---
Signif. codes:  0 &#39;***&#39; 0.001 &#39;**&#39; 0.01 &#39;*&#39; 0.05 &#39;.&#39; 0.1 &#39; &#39; 1</code></pre>
<pre class="r"><code>aov.lm.dapi</code></pre>
<pre><code>Anova Table (Type III tests)

Response: dapi.median.log10sum
                    Sum Sq  Df   F value  Pr(&gt;F)    
(Intercept)         57.257   1 1474.3536 &lt; 2e-16 ***
factor(chip_id)      0.568   5    2.9233 0.01262 *  
factor(experiment)  12.118  15   20.8019 &lt; 2e-16 ***
factor(image_label)  3.333  95    0.9035 0.73028    
Residuals           33.942 874                      
---
Signif. codes:  0 &#39;***&#39; 0.001 &#39;**&#39; 0.01 &#39;*&#39; 0.05 &#39;.&#39; 0.1 &#39; &#39; 1</code></pre>
<p>Indivdual and plate variation</p>
<p><img src="figure/images-normalize-anova.Rmd/unnamed-chunk-4-1.png" width="1152" style="display: block; margin: auto;" /><img src="figure/images-normalize-anova.Rmd/unnamed-chunk-4-2.png" width="1152" style="display: block; margin: auto;" /><img src="figure/images-normalize-anova.Rmd/unnamed-chunk-4-3.png" width="1152" style="display: block; margin: auto;" /></p>
<p>Position variation</p>
<pre class="r"><code>well.gfp.median &lt;- pdata %&gt;% group_by(image_label) %&gt;% summarize(., median(gfp.median.log10sum))
well.rfp.median &lt;- pdata %&gt;% group_by(image_label) %&gt;% summarize(., median(rfp.median.log10sum))
well.dapi.median &lt;- pdata %&gt;% group_by(image_label) %&gt;% summarize(., median(dapi.median.log10sum))

well.pp &lt;- data.frame(well=pdata$well, image_label=pdata$image_label)
well.pp &lt;- well.pp[!duplicated(well.pp),]
colbrew &lt;- brewer.pal(9, &quot;Set1&quot;)
well.pp$cols &lt;- rep(colbrew[9], 96)
well.pp$cols[which(well.pp$well %in% c(&quot;A03&quot;, &quot;A02&quot;, &quot;A01&quot;, &quot;A09&quot;, &quot;A08&quot;, &quot;A07&quot;))] &lt;- colbrew[1]
well.pp$cols[which(well.pp$well %in% c(&quot;H03&quot;, &quot;H02&quot;, &quot;H01&quot;, &quot;H09&quot;, &quot;H08&quot;, &quot;H07&quot;))] &lt;- colbrew[2]
well.pp$cols[which(well.pp$well %in% c(&quot;A06&quot;, &quot;A05&quot;, &quot;A04&quot;, &quot;A12&quot;, &quot;A11&quot;, &quot;A10&quot;))] &lt;- colbrew[3]
well.pp$cols[which(well.pp$well %in% c(&quot;H06&quot;, &quot;H05&quot;, &quot;H04&quot;, &quot;H12&quot;, &quot;H11&quot;, &quot;H10&quot;))] &lt;- colbrew[4]
well.pp &lt;- well.pp[order(well.pp$image_label),]

ord.gfp &lt;- as.character(well.gfp.median$image_label[order(well.gfp.median$`median(gfp.median.log10sum)`)])
ord.rfp &lt;- as.character(well.rfp.median$image_label[order(well.rfp.median$`median(rfp.median.log10sum)`)])
ord.dapi &lt;- as.character(well.dapi.median$image_label[order(well.dapi.median$`median(dapi.median.log10sum)`)])</code></pre>
<p>These are four corners previously found more likely to have high gene expression values in sequencing data.</p>
<pre class="r"><code>par(mfrow=c(1,1))
plot(1:7, 1:7, pch=&quot;&quot;, axes=F, ann=F)
legend(&quot;center&quot;, legend = c(&quot;A_a&quot;, &quot;H_a&quot;, &quot;A_b&quot;, &quot;H_b&quot;), col=colbrew[c(1,2,3,4)],
       pch=16)</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/unnamed-chunk-6-1.png" width="672" style="display: block; margin: auto;" /></p>
<pre class="r"><code>par(mfrow=c(3,1))
boxplot(rfp.median.log10sum ~ factor(image_label, levels=ord.rfp), 
        data=pdata, ylab = &quot;RFP&quot;,
        col=well.pp$cols[as.numeric(ord.rfp)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
boxplot(gfp.median.log10sum ~ factor(image_label, levels=ord.gfp), 
        data=pdata, ylab = &quot;GFP&quot;,
        col=well.pp$cols[as.numeric(ord.gfp)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
boxplot(dapi.median.log10sum ~ factor(image_label, levels=ord.dapi), 
        data=pdata, ylab = &quot;GFP&quot;,
        col=well.pp$cols[as.numeric(ord.dapi)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
title(&quot;Position variation&quot;, outer=TRUE, line = -1)</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/unnamed-chunk-7-1.png" width="960" style="display: block; margin: auto;" /></p>
<hr />
</div>
<div id="estimate-effects" class="section level2">
<h2>Estimate effects</h2>
<p>Contrast test to estimate effects for for plate and position ID.</p>
<pre class="r"><code># make contrast matrix for plates
# each plate is compared to the average
n_plates &lt;- uniqueN(pdata$experiment)
contrast_plates &lt;- matrix(-1, nrow=n_plates, ncol=n_plates)
diag(contrast_plates) &lt;- n_plates-1

# make contrast matrix for individuals
# each individual is compared to the average
n_pos &lt;- uniqueN(pdata$image_label)
contrast_pos &lt;- matrix(-1, nrow=n_pos, ncol=n_pos)
diag(contrast_pos) &lt;- n_pos-1</code></pre>
<pre class="r"><code>gfp.plates &lt;- summary(lsmeans(lm.gfp, specs=&quot;experiment&quot;, contrast=contrast_plates))
gfp.pos &lt;- summary(lsmeans(lm.gfp, specs=&quot;image_label&quot;, contrast=contrast_pos))

rfp.plates &lt;- summary(lsmeans(lm.rfp, specs=&quot;experiment&quot;, contrast=contrast_plates))
rfp.pos &lt;- summary(lsmeans(lm.rfp, specs=&quot;image_label&quot;, contrast=contrast_pos))

dapi.plates &lt;- summary(lsmeans(lm.dapi, specs=&quot;experiment&quot;, contrast=contrast_plates))
dapi.pos &lt;- summary(lsmeans(lm.dapi, specs=&quot;image_label&quot;, contrast=contrast_pos))</code></pre>
<p>Substract plate effect from the raw estimates.</p>
<pre class="r"><code>## RFP
pdata$rfp.median.log10sum.adjust &lt;- pdata$rfp.median.log10sum
rfp.plates$experiment &lt;- as.character(rfp.plates$experiment)
rfp.pos$experiment &lt;- as.character(rfp.pos$image_label)
pdata$experiment &lt;- as.character(pdata$experiment)

exps &lt;- unique(pdata$experiment)
for (i in 1:uniqueN(exps)) {
  exp &lt;- exps[i]
  ii_exp &lt;- which(pdata$experiment == exp)
  est_exp &lt;- rfp.plates$lsmean[which(rfp.plates$experiment==exp)]
  pdata$rfp.median.log10sum.adjust[ii_exp] &lt;- (pdata$rfp.median.log10sum[ii_exp] - est_exp)
}

pos &lt;- unique(pdata$image_label)
for (i in 1:uniqueN(pos)) {
  p &lt;- pos[i]
  ii_pos &lt;- which(pdata$image_label == p)
  est_pos &lt;- rfp.pos$lsmean[which(rfp.pos$image_label==p)]
  pdata$rfp.median.log10sum.adjust[ii_pos] &lt;- (pdata$rfp.median.log10sum[ii_pos] - est_pos)
}


## GFP
pdata$gfp.median.log10sum.adjust &lt;- pdata$gfp.median.log10sum
gfp.plates$experiment &lt;- as.character(gfp.plates$experiment)
gfp.pos$experiment &lt;- as.character(gfp.pos$image_label)
pdata$experiment &lt;- as.character(pdata$experiment)

exps &lt;- unique(pdata$experiment)
for (i in 1:uniqueN(exps)) {
  exp &lt;- exps[i]
  ii_exp &lt;- which(pdata$experiment == exp)
  est_exp &lt;- gfp.plates$lsmean[which(gfp.plates$experiment==exp)]
  pdata$gfp.median.log10sum.adjust[ii_exp] &lt;- (pdata$gfp.median.log10sum[ii_exp] - est_exp)
}

pos &lt;- unique(pdata$image_label)
for (i in 1:uniqueN(pos)) {
  p &lt;- pos[i]
  ii_pos &lt;- which(pdata$image_label == p)
  est_pos &lt;- gfp.pos$lsmean[which(gfp.pos$image_label==p)]
  pdata$gfp.median.log10sum.adjust[ii_pos] &lt;- (pdata$gfp.median.log10sum[ii_pos] - est_pos)
}



## DAPI
pdata$dapi.median.log10sum.adjust &lt;- pdata$dapi.median.log10sum
dapi.plates$experiment &lt;- as.character(dapi.plates$experiment)
dapi.pos$experiment &lt;- as.character(dapi.pos$image_label)
pdata$experiment &lt;- as.character(pdata$experiment)

exps &lt;- unique(pdata$experiment)
for (i in 1:uniqueN(exps)) {
  exp &lt;- exps[i]
  ii_exp &lt;- which(pdata$experiment == exp)
  est_exp &lt;- dapi.plates$lsmean[which(dapi.plates$experiment==exp)]
  pdata$dapi.median.log10sum.adjust[ii_exp] &lt;- (pdata$dapi.median.log10sum[ii_exp] - est_exp)
}

pos &lt;- unique(pdata$image_label)
for (i in 1:uniqueN(pos)) {
  p &lt;- pos[i]
  ii_pos &lt;- which(pdata$image_label == p)
  est_pos &lt;- dapi.pos$lsmean[which(dapi.pos$image_label==p)]
  pdata$dapi.median.log10sum.adjust[ii_pos] &lt;- (pdata$dapi.median.log10sum[ii_pos] - est_pos)
}</code></pre>
<p>After adjustment</p>
<p><img src="figure/images-normalize-anova.Rmd/boxplot-adjusted-1.png" width="1152" style="display: block; margin: auto;" /><img src="figure/images-normalize-anova.Rmd/boxplot-adjusted-2.png" width="1152" style="display: block; margin: auto;" /><img src="figure/images-normalize-anova.Rmd/boxplot-adjusted-3.png" width="1152" style="display: block; margin: auto;" /></p>
<pre class="r"><code>## These are four corners previously found more likely to have high gene expression values in sequencing data.
par(mfrow=c(1,1))
plot(1:7, 1:7, pch=&quot;&quot;, axes=F, ann=F)
legend(&quot;center&quot;, legend = c(&quot;A_a&quot;, &quot;H_a&quot;, &quot;A_b&quot;, &quot;H_b&quot;), col=colbrew[c(1,2,3,4)],
       pch=16)</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/unnamed-chunk-10-1.png" width="672" style="display: block; margin: auto;" /></p>
<pre class="r"><code>par(mfrow=c(3,1))
boxplot(rfp.median.log10sum.adjust ~ factor(image_label, levels=ord.rfp), 
        data=pdata, ylab = &quot;RFP&quot;,
        col=well.pp$cols[as.numeric(ord.rfp)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
boxplot(gfp.median.log10sum.adjust ~ factor(image_label, levels=ord.gfp), 
        data=pdata, ylab = &quot;GFP&quot;,
        col=well.pp$cols[as.numeric(ord.gfp)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
boxplot(dapi.median.log10sum.adjust ~ factor(image_label, levels=ord.dapi), 
        data=pdata, ylab = &quot;GFP&quot;,
        col=well.pp$cols[as.numeric(ord.dapi)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
title(&quot;Position variation&quot;, outer=TRUE, line = -1)</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/plot-position-adjusted-1.png" width="960" style="display: block; margin: auto;" /></p>
<hr />
</div>
<div id="output-results" class="section level2">
<h2>Output results</h2>
<p>Save corrected data to a temporary output folder.</p>
<pre class="r"><code>saveRDS(pdata, file = &quot;../output/images-normalize-anova.Rmd/pdata.adj.rds&quot;)</code></pre>
<hr />
</div>
<div id="ash" class="section level2">
<h2>ash</h2>
<p>apply shrinkage to position estimates</p>
<pre class="r"><code># # apply limma ebayes to shrink variances
# library(limma)
# gfp.pos.var &lt;- squeezeVar(gfp.pos$SE^2, df = gfp.pos$df)$var.post
# gfp.pos.df &lt;- squeezeVar(gfp.pos$SE^2, df = gfp.pos$df)$df.prior + gfp.pos$df
gfp.pos.ash &lt;- ash(gfp.pos$lsmean, gfp.pos$SE, mixcompdist = &quot;uniform&quot;,
                   lik = lik_t(df=gfp.pos$df[1]), mode = &quot;estimate&quot; )
# gfp.pos.ash.varpost &lt;- ash(gfp.pos$lsmean, gfp.pos.var, mixcompdist = &quot;uniform&quot;,
#                    lik = lik_t(df=gfp.pos.df), mode = &quot;estimate&quot; )


# rfp.pos.var &lt;- squeezeVar(rfp.pos$SE^2, df = rfp.pos$df)$var.post
# rfp.pos.df &lt;- squeezeVar(rfp.pos$SE^2, df = rfp.pos$df)$df.prior + gfp.pos$df
rfp.pos.ash &lt;- ash(rfp.pos$lsmean, rfp.pos$SE, mixcompdist = &quot;uniform&quot;,
                   lik = lik_t(df=rfp.pos$df[1]), mode = &quot;estimate&quot; )
# rfp.pos.ash.varpost &lt;- ash(rfp.pos$lsmean, rfp.pos.var, mixcompdist = &quot;uniform&quot;,
#                    lik = lik_t(df=rfp.pos.df), mode = &quot;estimate&quot; )

# dapi.pos.var &lt;- squeezeVar(dapi.pos$SE^2, df = dapi.pos$df)$var.post
# dapi.pos.df &lt;- squeezeVar(dapi.pos$SE^2, df = dapi.pos$df)$df.prior + gfp.pos$df
dapi.pos.ash &lt;- ash(dapi.pos$lsmean, dapi.pos$SE, mixcompdist = &quot;uniform&quot;,
                   lik = lik_t(df=dapi.pos$df[1]), mode = &quot;estimate&quot; )
# dapi.pos.ash.varpost &lt;- ash(dapi.pos$lsmean, dapi.pos.var, mixcompdist = &quot;uniform&quot;,
#                    lik = lik_t(df=dapi.pos.df), mode = &quot;estimate&quot; )
# 

par(mfrow=c(2,2))
plot(gfp.pos.ash$result$betahat, gfp.pos.ash$result$PosteriorMean,
     xlab = &quot;beta hat&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;GFP&quot;)
abline(0,1, col = &quot;royalblue&quot;)
plot(rfp.pos.ash$result$betahat, rfp.pos.ash$result$PosteriorMean,
     xlab = &quot;beta hat&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;RFP&quot;)
abline(0,1, col = &quot;royalblue&quot;)
plot(dapi.pos.ash$result$betahat, dapi.pos.ash$result$PosteriorMean,
     xlab = &quot;beta hat&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;DAPI&quot;)
abline(0,1, col = &quot;royalblue&quot;)
     
par(mfrow=c(2,2))</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/ash-position-1.png" width="672" style="display: block; margin: auto;" /></p>
<pre class="r"><code>plot(gfp.pos.ash$result$sebetahat, gfp.pos.ash$result$PosteriorSD,
     xlab = &quot;Standard Error&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;GFP&quot;)
abline(0,1, col = &quot;royalblue&quot;)
plot(rfp.pos.ash$result$sebetahat, rfp.pos.ash$result$PosteriorSD,
     xlab = &quot;Standard Error&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;RFP&quot;)
abline(0,1, col = &quot;royalblue&quot;)
plot(dapi.pos.ash$result$sebetahat, dapi.pos.ash$result$PosteriorSD,
     xlab = &quot;Standard Error&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;DAPI&quot;)
abline(0,1, col = &quot;royalblue&quot;)</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/ash-position-2.png" width="672" style="display: block; margin: auto;" /></p>
<p>Plate effect.</p>
<pre class="r"><code>library(ashr)
gfp.plates.ash &lt;- ash(gfp.plates$lsmean, gfp.plates$SE, mixcompdist = &quot;uniform&quot;,
                   lik = lik_t(df=gfp.plates$df[1]), mode = &quot;estimate&quot;)
rfp.plates.ash &lt;- ash(rfp.plates$lsmean, rfp.plates$SE, mixcompdist = &quot;uniform&quot;,
                   lik = lik_t(df=rfp.plates$df[1]), mode = &quot;estimate&quot;)
dapi.plates.ash &lt;- ash(dapi.plates$lsmean, dapi.plates$SE, mixcompdist = &quot;uniform&quot;,
                    lik = lik_t(df=dapi.plates$df[1]), mode = &quot;estimate&quot;)
  
par(mfrow=c(2,2))
plot(gfp.plates.ash$result$betahat, gfp.plates.ash$result$PosteriorMean,
     xlab = &quot;beta hat&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;GFP&quot;)
abline(0,1, col = &quot;royalblue&quot;)
plot(rfp.plates.ash$result$betahat, rfp.plates.ash$result$PosteriorMean,
     xlab = &quot;beta hat&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;RFP&quot;)
abline(0,1, col = &quot;royalblue&quot;)
plot(dapi.plates.ash$result$betahat, dapi.plates.ash$result$PosteriorMean,
     xlab = &quot;beta hat&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;DAPI&quot;)
abline(0,1, col = &quot;royalblue&quot;)
     
par(mfrow=c(2,2))</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/ash-plate-1.png" width="672" style="display: block; margin: auto;" /></p>
<pre class="r"><code>plot(gfp.plates.ash$result$sebetahat, gfp.plates.ash$result$PosteriorSD,
     xlab = &quot;Standard Error&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;GFP&quot;)
abline(0,1, col = &quot;royalblue&quot;)
plot(rfp.plates.ash$result$sebetahat, rfp.plates.ash$result$PosteriorSD,
     xlab = &quot;Standard Error&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;RFP&quot;)
abline(0,1, col = &quot;royalblue&quot;)
plot(dapi.plates.ash$result$sebetahat, dapi.plates.ash$result$PosteriorSD,
     xlab = &quot;Standard Error&quot;, ylab = &quot;Shrunken estimate&quot;, main = &quot;DAPI&quot;)
abline(0,1, col = &quot;royalblue&quot;)</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/ash-plate-2.png" width="672" style="display: block; margin: auto;" /></p>
<p>Substract plate effect from the raw estimates.</p>
<pre class="r"><code>## RFP
pdata$rfp.median.log10sum.adjust.ash &lt;- pdata$rfp.median.log10sum
rfp.plates$experiment &lt;- as.character(rfp.plates$experiment)
rfp.pos$experiment &lt;- as.character(rfp.pos$image_label)
pdata$experiment &lt;- as.character(pdata$experiment)

exps &lt;- unique(pdata$experiment)
for (i in 1:uniqueN(exps)) {
  exp &lt;- exps[i]
  ii_exp &lt;- which(pdata$experiment == exp)
  est_exp &lt;- rfp.plates.ash$result$PosteriorMean[which(rfp.plates$experiment==exp)]
  pdata$rfp.median.log10sum.adjust.ash[ii_exp] &lt;- (pdata$rfp.median.log10sum[ii_exp] - est_exp)
}

pos &lt;- unique(pdata$image_label)
for (i in 1:uniqueN(pos)) {
  p &lt;- pos[i]
  ii_pos &lt;- which(pdata$image_label == p)
  est_pos &lt;- rfp.pos.ash$result$PosteriorMean[which(rfp.pos$image_label==p)]
  pdata$rfp.median.log10sum.adjust.ash[ii_pos] &lt;- (pdata$rfp.median.log10sum[ii_pos] - est_pos)
}


## GFP
pdata$gfp.median.log10sum.adjust.ash &lt;- pdata$gfp.median.log10sum
gfp.plates$experiment &lt;- as.character(gfp.plates$experiment)
gfp.pos$experiment &lt;- as.character(gfp.pos$image_label)
pdata$experiment &lt;- as.character(pdata$experiment)

exps &lt;- unique(pdata$experiment)
for (i in 1:uniqueN(exps)) {
  exp &lt;- exps[i]
  ii_exp &lt;- which(pdata$experiment == exp)
  est_exp &lt;- gfp.plates.ash$result$PosteriorMean[which(gfp.plates$experiment==exp)]
  pdata$gfp.median.log10sum.adjust.ash[ii_exp] &lt;- (pdata$gfp.median.log10sum[ii_exp] - est_exp)
}

pos &lt;- unique(pdata$image_label)
for (i in 1:uniqueN(pos)) {
  p &lt;- pos[i]
  ii_pos &lt;- which(pdata$image_label == p)
  est_pos &lt;- gfp.pos.ash$result$PosteriorMean[which(gfp.pos$image_label==p)]
  pdata$gfp.median.log10sum.adjust.ash[ii_pos] &lt;- (pdata$gfp.median.log10sum[ii_pos] - est_pos)
}



## DAPI
pdata$dapi.median.log10sum.adjust.ash &lt;- pdata$dapi.median.log10sum
dapi.plates$experiment &lt;- as.character(dapi.plates$experiment)
dapi.pos$experiment &lt;- as.character(dapi.pos$image_label)
pdata$experiment &lt;- as.character(pdata$experiment)

exps &lt;- unique(pdata$experiment)
for (i in 1:uniqueN(exps)) {
  exp &lt;- exps[i]
  ii_exp &lt;- which(pdata$experiment == exp)
  est_exp &lt;- dapi.plates.ash$result$PosteriorMean[which(dapi.plates$experiment==exp)]
  pdata$dapi.median.log10sum.adjust.ash[ii_exp] &lt;- (pdata$dapi.median.log10sum[ii_exp] - est_exp)
}

pos &lt;- unique(pdata$image_label)
for (i in 1:uniqueN(pos)) {
  p &lt;- pos[i]
  ii_pos &lt;- which(pdata$image_label == p)
  est_pos &lt;- dapi.pos.ash$result$PosteriorMean[which(dapi.pos$image_label==p)]
  pdata$dapi.median.log10sum.adjust.ash[ii_pos] &lt;- (pdata$dapi.median.log10sum[ii_pos] - est_pos)
}</code></pre>
<p>After adjustment</p>
<p><img src="figure/images-normalize-anova.Rmd/boxplot-adjusted-ash-1.png" width="1152" style="display: block; margin: auto;" /><img src="figure/images-normalize-anova.Rmd/boxplot-adjusted-ash-2.png" width="1152" style="display: block; margin: auto;" /><img src="figure/images-normalize-anova.Rmd/boxplot-adjusted-ash-3.png" width="1152" style="display: block; margin: auto;" /></p>
<pre class="r"><code>## These are four corners previously found more likely to have high gene expression values in sequencing data.
par(mfrow=c(1,1))
plot(1:7, 1:7, pch=&quot;&quot;, axes=F, ann=F)
legend(&quot;center&quot;, legend = c(&quot;A_a&quot;, &quot;H_a&quot;, &quot;A_b&quot;, &quot;H_b&quot;), col=colbrew[c(1,2,3,4)],
       pch=16)</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/unnamed-chunk-11-1.png" width="672" style="display: block; margin: auto;" /></p>
<pre class="r"><code>par(mfrow=c(3,1))
boxplot(rfp.median.log10sum.adjust.ash ~ factor(image_label, levels=ord.rfp), 
        data=pdata, ylab = &quot;RFP&quot;,
        col=well.pp$cols[as.numeric(ord.rfp)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
boxplot(gfp.median.log10sum.adjust.ash ~ factor(image_label, levels=ord.gfp), 
        data=pdata, ylab = &quot;GFP&quot;,
        col=well.pp$cols[as.numeric(ord.gfp)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
boxplot(dapi.median.log10sum.adjust.ash ~ factor(image_label, levels=ord.dapi), 
        data=pdata, ylab = &quot;GFP&quot;,
        col=well.pp$cols[as.numeric(ord.dapi)])
abline(h=0, lwd=2, col=&quot;royalblue&quot;)
title(&quot;Position variation&quot;, outer=TRUE, line = -1)</code></pre>
<p><img src="figure/images-normalize-anova.Rmd/plot-position-adjusted-ash-1.png" width="960" style="display: block; margin: auto;" /></p>
<hr />
</div>
<div id="output-results-1" class="section level2">
<h2>Output results</h2>
<p>Save corrected data to a temporary output folder.</p>
<pre class="r"><code>saveRDS(pdata, file = &quot;../output/images-normalize-anova.Rmd/pdata.adj.rds&quot;)</code></pre>
<hr />
</div>
<div id="session-information" class="section level2">
<h2>Session information</h2>
<pre><code>R version 3.4.1 (2017-06-30)
Platform: x86_64-redhat-linux-gnu (64-bit)
Running under: Scientific Linux 7.2 (Nitrogen)

Matrix products: default
BLAS/LAPACK: /usr/lib64/R/lib/libRblas.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] bindrcpp_0.2        lsmeans_2.27-61     ashr_2.2-4         
 [4] car_2.1-6           scales_0.5.0        Biobase_2.38.0     
 [7] BiocGenerics_0.24.0 RColorBrewer_1.1-2  cowplot_0.9.2      
[10] ggplot2_2.2.1       dplyr_0.7.4         data.table_1.10.4-3

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.15       mvtnorm_1.0-7      lattice_0.20-35   
 [4] Rmosek_7.1.3       zoo_1.8-1          assertthat_0.2.0  
 [7] rprojroot_1.3-2    digest_0.6.15      foreach_1.4.4     
[10] truncnorm_1.0-7    R6_2.2.2           plyr_1.8.4        
[13] backports_1.1.2    MatrixModels_0.4-1 evaluate_0.10.1   
[16] coda_0.19-1        pillar_1.1.0       rlang_0.2.0       
[19] lazyeval_0.2.1     pscl_1.5.2         multcomp_1.4-8    
[22] minqa_1.2.4        SparseM_1.77       nloptr_1.0.4      
[25] Matrix_1.2-10      rmarkdown_1.8      labeling_0.3      
[28] splines_3.4.1      lme4_1.1-15        stringr_1.3.0     
[31] REBayes_1.3        munsell_0.4.3      compiler_3.4.1    
[34] pkgconfig_2.0.1    etrunct_0.1        SQUAREM_2017.10-1 
[37] mgcv_1.8-17        htmltools_0.3.6    nnet_7.3-12       
[40] tibble_1.4.2       codetools_0.2-15   MASS_7.3-47       
[43] grid_3.4.1         nlme_3.1-131       xtable_1.8-2      
[46] gtable_0.2.0       git2r_0.21.0       magrittr_1.5      
[49] estimability_1.3   stringi_1.1.6      doParallel_1.0.11 
[52] sandwich_2.4-0     TH.data_1.0-8      iterators_1.0.9   
[55] tools_3.4.1        glue_1.2.0         pbkrtest_0.4-7    
[58] survival_2.41-3    yaml_2.1.16        colorspace_1.3-2  
[61] knitr_1.20         bindr_0.1          quantreg_5.35     </code></pre>
</div>

<!-- Adjust MathJax settings so that all math formulae are shown using
TeX fonts only; see
http://docs.mathjax.org/en/latest/configuration.html.  This will make
the presentation more consistent at the cost of the webpage sometimes
taking slightly longer to load. Note that this only works because the
footer is added to webpages before the MathJax javascript. -->
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    "HTML-CSS": { availableFonts: ["TeX"] }
  });
</script>

<hr>
<p>
    This <a href="http://rmarkdown.rstudio.com">R Markdown</a> site was created with <a href="https://github.com/jdblischak/workflowr">workflowr</a>
</p>
<hr>

<!-- To enable disqus, uncomment the section below and provide your disqus_shortname -->

<!-- disqus
  <div id="disqus_thread"></div>
    <script type="text/javascript">
        /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
        var disqus_shortname = 'rmarkdown'; // required: replace example with your forum shortname

        /* * * DON'T EDIT BELOW THIS LINE * * */
        (function() {
            var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
            dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
            (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
        })();
    </script>
    <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    <a href="http://disqus.com" class="dsq-brlink">comments powered by <span class="logo-disqus">Disqus</span></a>
-->


</div>
</div>

</div>

<script>

// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
  $('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
  bootstrapStylePandocTables();
});


</script>

<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
  (function () {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src  = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
    document.getElementsByTagName("head")[0].appendChild(script);
  })();
</script>

</body>
</html>