<!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" />




<title>MASH v FLASH simulation results</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>
<script src="site_libs/navigation-1.1/codefolding.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 -->
<style type="text/css">
.code-folding-btn { margin-bottom: 4px; }
</style>
<script>
$(document).ready(function () {
  window.initializeCodeFolding("hide" === "show");
});
</script>




<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">MASHvFLASH</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>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li>
  <a href="https://github.com/willwerscheid/MASHvFLASH">
    <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">

<div class="btn-group pull-right">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><span>Code</span> <span class="caret"></span></button>
<ul class="dropdown-menu" style="min-width: 50px;">
<li><a id="rmd-show-all-code" href="#">Show All Code</a></li>
<li><a id="rmd-hide-all-code" href="#">Hide All Code</a></li>
</ul>
</div>



<h1 class="title toc-ignore">MASH v FLASH simulation results</h1>

</div>


<p><strong>Last updated:</strong> 2018-08-05</p>
<strong>workflowr checks:</strong> <small>(Click a bullet for more information)</small>
<ul>
<li>
<p><details> <summary> <strong style="color:blue;">✔</strong> <strong>R Markdown file:</strong> up-to-date </summary></p>
<p>Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.</p>
</details>
</li>
<li>
<p><details> <summary> <strong style="color:blue;">✔</strong> <strong>Environment:</strong> empty </summary></p>
<p>Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.</p>
</details>
</li>
<li>
<p><details> <summary> <strong style="color:blue;">✔</strong> <strong>Seed:</strong> <code>set.seed(20180609)</code> </summary></p>
<p>The command <code>set.seed(20180609)</code> was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.</p>
</details>
</li>
<li>
<p><details> <summary> <strong style="color:blue;">✔</strong> <strong>Session information:</strong> recorded </summary></p>
<p>Great job! Recording the operating system, R version, and package versions is critical for reproducibility.</p>
</details>
</li>
<li>
<p><details> <summary> <strong style="color:blue;">✔</strong> <strong>Repository version:</strong> <a href="https://github.com/willwerscheid/MASHvFLASH/tree/c5bf4c488a08ed51bd2a93b5f811ec9ed16e06a1" target="_blank">c5bf4c4</a> </summary></p>
Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility. The version displayed above was the version of the Git repository at the time these results were generated. <br><br> Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use <code>wflow_publish</code> or <code>wflow_git_commit</code>). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:
<pre><code>
Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    data/
    Ignored:    docs/.DS_Store
    Ignored:    docs/images/.DS_Store
    Ignored:    docs/images/.Rapp.history
    Ignored:    output/.DS_Store
    Ignored:    output/.Rapp.history
    Ignored:    output/MASHvFLASHgtex/.DS_Store
    Ignored:    output/MASHvFLASHsims/.DS_Store
    Ignored:    output/MASHvFLASHsims/backfit/.DS_Store
    Ignored:    output/MASHvFLASHsims/backfit/.Rapp.history

</code></pre>
Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes. </details>
</li>
</ul>
<details> <summary> <small><strong>Expand here to see past versions:</strong></small> </summary>
<ul>
<table style="border-collapse:separate; border-spacing:5px;">
<thead>
<tr>
<th style="text-align:left;">
File
</th>
<th style="text-align:left;">
Version
</th>
<th style="text-align:left;">
Author
</th>
<th style="text-align:left;">
Date
</th>
<th style="text-align:left;">
Message
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/c5bf4c488a08ed51bd2a93b5f811ec9ed16e06a1/analysis/MASHvFLASHsims.Rmd" target="_blank">c5bf4c4</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-08-05
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/bd4c96b9848224da9c2f0e2189abdb9197541481/docs/MASHvFLASHsims.html" target="_blank">bd4c96b</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-07-28
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/72a220238f1121ae1cc6899aef572cd7d10fd9a4/analysis/MASHvFLASHsims.Rmd" target="_blank">72a2202</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-07-28
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/860aa52c7988a06c33df007c928bfce326e277fe/docs/MASHvFLASHsims.html" target="_blank">860aa52</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-07-22
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/3abd505e1c42acd32d1e7c9f8901f8f50efc9335/analysis/MASHvFLASHsims.Rmd" target="_blank">3abd505</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-07-22
</td>
<td style="text-align:left;">
wflow_publish(c(“analysis/MASHvFLASHsims.Rmd”,
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/36a39f6841360fa0e59164042c3f7ae97935cddf/docs/MASHvFLASHsims.html" target="_blank">36a39f6</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-07-22
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/179099b4e78b6f5586b08e6aab9526e18ddd683e/analysis/MASHvFLASHsims.Rmd" target="_blank">179099b</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-07-22
</td>
<td style="text-align:left;">
wflow_publish(c(“analysis/MASHvFLASHgtex.Rmd”,
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/b7181f2440ca7b53cbc4c4bb890424ac93b5abf1/docs/MASHvFLASHsims.html" target="_blank">b7181f2</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-07-22
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/7f05edf0d238cdf6673bab50cefaba3a4d244a0a/analysis/MASHvFLASHsims.Rmd" target="_blank">7f05edf</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-07-22
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/69cecbc60b8616a3ceaf513a6f169f249bcca6d4/docs/MASHvFLASHsims.html" target="_blank">69cecbc</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-20
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/abf0f70d7c77ab8cba395605aab7ea8116103c02/analysis/MASHvFLASHsims.Rmd" target="_blank">abf0f70</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-20
</td>
<td style="text-align:left;">
workflowr::wflow_publish(c(“analysis/intro.Rmd”,
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/2d8f0919dae1dceed3cd1a6caeaa50c117dfb277/docs/MASHvFLASHsims.html" target="_blank">2d8f091</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-20
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/eda9441e8c6499985d528f54c57489e3fe37414d/analysis/MASHvFLASHsims.Rmd" target="_blank">eda9441</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-20
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/90dd57894e8dd3267d38f69155ac0f01be63fef9/docs/MASHvFLASHsims.html" target="_blank">90dd578</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-19
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/3cf7f0ce18e03e5e81a0f66c56c65029b8a7a8cd/analysis/MASHvFLASHsims.Rmd" target="_blank">3cf7f0c</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-19
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/6fd3720392531d915c7d21cf984f0dba4eb03afc/docs/MASHvFLASHsims.html" target="_blank">6fd3720</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-19
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/358412a77652ea852898bb1b735918b20f7e4b41/docs/MASHvFLASHsims.html" target="_blank">358412a</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/a9a9e11a53e9b935379d8d4ce0c76537328d93d7/analysis/MASHvFLASHsims.Rmd" target="_blank">a9a9e11</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/726168a9cec3280d38929ce716dcb7483b7af67c/docs/MASHvFLASHsims.html" target="_blank">726168a</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/aa46b383b5ef586461f9e8ee43d9adf1c5cb24d8/docs/MASHvFLASHsims.html" target="_blank">aa46b38</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/d3f8191a4d8323b10f600574ea8fefbb74b071ac/analysis/MASHvFLASHsims.Rmd" target="_blank">d3f8191</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/c2699a6b3a91bf348a7780f395328f175ec3c759/docs/MASHvFLASHsims.html" target="_blank">c2699a6</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/3554f17e60c34ba45c678226295c81b8804294e5/analysis/MASHvFLASHsims.Rmd" target="_blank">3554f17</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/willwerscheid/MASHvFLASH/03dc24a7944aca134747c0bdfdb5bfd6875ea2dd/docs/MASHvFLASHsims.html" target="_blank">03dc24a</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
Build site.
</td>
</tr>
<tr>
<td style="text-align:left;">
Rmd
</td>
<td style="text-align:left;">
<a href="https://github.com/willwerscheid/MASHvFLASH/blob/0c0d6b22487b32387084dd31b4353c782cc56c3b/analysis/MASHvFLASHsims.Rmd" target="_blank">0c0d6b2</a>
</td>
<td style="text-align:left;">
Jason Willwerscheid
</td>
<td style="text-align:left;">
2018-06-15
</td>
<td style="text-align:left;">
wflow_publish(“analysis/MASHvFLASHsims.Rmd”)
</td>
</tr>
</tbody>
</table>
</ul>
<p></details></p>
<hr />
<div id="introduction" class="section level2">
<h2>Introduction</h2>
<p>Here I compare MASH and FLASH fits to data simulated from various MASH and FLASH models. In addition to comparing different methods for obtaining FLASH fits, I was interested to see how FLASH performed on data generated from a MASH model (and vice versa). For the code used in this analysis, see <a href="#code">below</a>.</p>
</div>
<div id="fitting-methods" class="section level2">
<h2>Fitting methods</h2>
<p>The MASH fit is produced following the recommendations in the MASH vignettes (using both canonical matrices and data-driven matrices).</p>
<p>Three FLASH fits are produced. The first serves as a baseline. The “Zero” FLASH fit simply adds up to 25 factors greedily, with <code>var_type</code> set to <code>&quot;zero&quot;</code> to reflect the fact that standard errors are fixed at 1.</p>
<p>The other two fits also use parameter option <code>var_type = &quot;zero&quot;</code>. OHL (for “one-hots last”) adds up to 25 factors greedily, then adds “canonical” factors (an all-ones vector and a one-hot vector for each row in the data matrix). It backfits the canonical factors, but not the greedily-added ones.</p>
<p>OHF (for “one-hots first”) adds the canonical factors first, then backfits, then greedily adds up to 25 factors.</p>
<p>I also experimented with doing an additional backfit for each of the three FLASH fits. It increased the time needed to fit (sometimes as much as eightfold), but results were otherwise very similar.</p>
</div>
<div id="simulations" class="section level2">
<h2>Simulations</h2>
<p>All simulated datasets <span class="math inline">\(Y\)</span> are of dimension 25 x 1000. In each case, <span class="math inline">\(Y = X + E\)</span>, where <span class="math inline">\(X\)</span> is the matrix of “true” effects and <span class="math inline">\(E\)</span> is a matrix of <span class="math inline">\(N(0, 1)\)</span> noise. One simulation is from the null model, three are generated according to a MASH model, and two are generated from a FLASH model. See the individual sections below for details.</p>
<p>The MASH fits are evaluated using built-in functions <code>get_pm()</code> to calculate MSE, <code>get_psd()</code> to calculate confidence intervals, and <code>get_lfsr()</code> to calculate true and false positive rates.</p>
<p>For the FLASH fits, only MSE is calculated using a built-in function (<code>flash_get_fitted_values()</code>). Confidence intervals and true and false positive rates are calculated by sampling from the posterior using function <code>flash_sampler()</code>. For details, see the code <a href="#code">below</a>.</p>
</div>
<div id="results-null-model" class="section level2">
<h2>Results: null model</h2>
<p>Here the entries of <span class="math inline">\(X\)</span> are all zero.</p>
<p>While FLASH does very well, MASH does poorly here. I’m not sure why this is the case; in runs with different seeds, MASH performed at least as well as FLASH.</p>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">Zero</th>
<th align="right">OHL</th>
<th align="right">OHF</th>
<th align="right">MASH</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MSE</td>
<td align="right">0</td>
<td align="right">0.001</td>
<td align="right">0.001</td>
<td align="right">0.004</td>
</tr>
<tr class="even">
<td>95% CI cov</td>
<td align="right">1</td>
<td align="right">1.000</td>
<td align="right">1.000</td>
<td align="right">0.783</td>
</tr>
</tbody>
</table>
<div class="figure">
<img src="images/sim1time.png" />

</div>
</div>
<div id="results-mash-models" class="section level2">
<h2>Results: MASH models</h2>
<p>As expected, MASH outperforms FLASH when the data is generated from a MASH model. The MSE obtained using a MASH fit is about half the MSE obtained using any of the FLASH fits, and the 95% confidence intervals given by MASH contain the “true” values in 98-99% of cases, whereas the FLASH coverage can fall a bit short of 95%. Further, the MASH ROC curves consistently dominate the FLASH ROC curves.</p>
<p>Interestingly, however, there is no clear victor among the FLASH methods. Results for the “Zero” and OHL methods are nearly identical. I suspect that this is because loadings for the “canonical” factors are estimated to be essentially zero, so that there is no substantial difference between the two fits. The OHF method tends to do slightly better in terms of MSE and confidence interval coverage, but the OHL ROC curves dominate the OHF ROC curves for FPR &lt; 0.6.</p>
<p>The OHF method is consistently faster than both MASH and the other FLASH methods, while the OHL method is the slowest of the four methods.</p>
<div id="independent-effects" class="section level3">
<h3>Independent effects</h3>
<p>Here the columns <span class="math inline">\(X_{:, j}\)</span> are either identically zero (with probability 0.8) or identically nonzero. In the latter case, the entries of the <span class="math inline">\(j\)</span>th column of <span class="math inline">\(X\)</span> are i.i.d. <span class="math inline">\(N(0, 2^2)\)</span>.</p>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">Zero</th>
<th align="right">OHL</th>
<th align="right">OHF</th>
<th align="right">MASH</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MSE</td>
<td align="right">0.33</td>
<td align="right">0.33</td>
<td align="right">0.31</td>
<td align="right">0.16</td>
</tr>
<tr class="even">
<td>95% CI cov</td>
<td align="right">0.94</td>
<td align="right">0.94</td>
<td align="right">0.95</td>
<td align="right">0.99</td>
</tr>
</tbody>
</table>
<p><img src="images/sim2ROC.png" /> <img src="images/sim2time.png" /></p>
</div>
<div id="independent-and-shared-effects" class="section level3">
<h3>Independent and shared effects</h3>
<p>Again 80% of the columns of <span class="math inline">\(X\)</span> are identically zero. But now, only half of the nonzero columns have entries that are i.i.d. <span class="math inline">\(N(0, 2^2).\)</span> The other half have entries that are identical across rows, with a value that is drawn from a <span class="math inline">\(N(0, 2)\)</span> distribution. (In other words, the covariance matrix for these columns is a matrix whose entries are all equal to 2.)</p>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">Zero</th>
<th align="right">OHL</th>
<th align="right">OHF</th>
<th align="right">MASH</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MSE</td>
<td align="right">0.21</td>
<td align="right">0.20</td>
<td align="right">0.19</td>
<td align="right">0.09</td>
</tr>
<tr class="even">
<td>95% CI cov</td>
<td align="right">0.94</td>
<td align="right">0.94</td>
<td align="right">0.95</td>
<td align="right">0.98</td>
</tr>
</tbody>
</table>
<p><img src="images/sim3ROC.png" /> <img src="images/sim3time.png" /></p>
</div>
<div id="independent-shared-and-unique-effects" class="section level3">
<h3>Independent, shared, and unique effects</h3>
<p>This model is similar to the above two, but now only a third of the nonnull columns have independently distributed entries and a third have shared entries. The other third have a unique nonzero entry. (This corresponds, for example, to a gene that is only expressed in a single condition.) The unique effects are distributed uniformly across rows, and are drawn from a <span class="math inline">\(N(0, 10^2)\)</span> distribution.</p>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">Zero</th>
<th align="right">OHL</th>
<th align="right">OHF</th>
<th align="right">MASH</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MSE</td>
<td align="right">0.19</td>
<td align="right">0.18</td>
<td align="right">0.14</td>
<td align="right">0.07</td>
</tr>
<tr class="even">
<td>95% CI cov</td>
<td align="right">0.94</td>
<td align="right">0.95</td>
<td align="right">0.95</td>
<td align="right">0.99</td>
</tr>
</tbody>
</table>
<p><img src="images/sim4ROC.png" /> <img src="images/sim4time.png" /></p>
</div>
</div>
<div id="results-flash-models" class="section level2">
<h2>Results: FLASH models</h2>
<p>Interestingly, MASH is very competitive with FLASH even when the true model is a FLASH model. Indeed, of the four fits, the MASH fit gives the best results for the rank 5 model.</p>
<p>Results for the “Zero” and OHL fits are again very similar, and both do quite a bit better than the OHF method, which does poorly in terms of MSE on the rank 1 model and in terms of FPR/TPR trade-off on the rank 5 model. (However, it outperforms the “Zero” and OHL fits in terms of confidence interval coverage.) Further, the OHF method is much slower here (if not worryingly so). I suspect that this is because the canonical factors are quickly “zeroed out” when the greedily-added “data-driven” factors (which, I assume, are pretty close to the true <span class="math inline">\(F\)</span>) have already been added, whereas much more time is spent backfitting them when no data-driven factors have yet been added.</p>
<div id="rank-1-model" class="section level3">
<h3>Rank 1 model</h3>
<p>This is the FLASH model <span class="math inline">\(X = LF\)</span>, where <span class="math inline">\(L\)</span> is an <span class="math inline">\(n\)</span> by <span class="math inline">\(k\)</span> matrix and <span class="math inline">\(F\)</span> is a <span class="math inline">\(k\)</span> by <span class="math inline">\(p\)</span> matrix. In this first simulation, <span class="math inline">\(k = 1\)</span>. 80% of the columns in <span class="math inline">\(F\)</span> and 20% of the entries in <span class="math inline">\(L\)</span> are equal to zero. The other entries of <span class="math inline">\(F\)</span> are i.i.d. <span class="math inline">\(N(0, 1)\)</span>; the nonzero entries of <span class="math inline">\(L\)</span> are i.i.d. <span class="math inline">\(N(0, 2^2)\)</span>.</p>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">Zero</th>
<th align="right">OHL</th>
<th align="right">OHF</th>
<th align="right">MASH</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MSE</td>
<td align="right">0.01</td>
<td align="right">0.01</td>
<td align="right">0.10</td>
<td align="right">0.02</td>
</tr>
<tr class="even">
<td>95% CI cov</td>
<td align="right">0.93</td>
<td align="right">0.95</td>
<td align="right">0.97</td>
<td align="right">0.98</td>
</tr>
</tbody>
</table>
<p><img src="images/sim5ROC.png" /> <img src="images/sim5time.png" /></p>
</div>
<div id="rank-5-model" class="section level3">
<h3>Rank 5 model</h3>
<p>This is the same as above with <span class="math inline">\(k = 5\)</span>, with 80% of the entries in <span class="math inline">\(L\)</span> equal to zero, and with the other entries i.i.d. <span class="math inline">\(N(0, 1)\)</span>.</p>
<table>
<thead>
<tr class="header">
<th></th>
<th align="right">Zero</th>
<th align="right">OHL</th>
<th align="right">OHF</th>
<th align="right">MASH</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td>MSE</td>
<td align="right">0.06</td>
<td align="right">0.06</td>
<td align="right">0.10</td>
<td align="right">0.05</td>
</tr>
<tr class="even">
<td>95% CI cov</td>
<td align="right">0.92</td>
<td align="right">0.94</td>
<td align="right">0.95</td>
<td align="right">0.96</td>
</tr>
</tbody>
</table>
<p><img src="images/sim6ROC.png" /> <img src="images/sim6time.png" /></p>
</div>
</div>
<div id="code" class="section level2">
<h2>Code</h2>
<p>for simulating datasets…</p>
<pre class="r"><code>## SIMULATION FUNCTIONS -------------------------------------------------

# n is number of conditions, p is number of genes

# Noise is i.i.d. N(0, 1)
get_E &lt;- function(n, p, sd = 1) {
  matrix(rnorm(n * p, 0, sd), n, p)
}


# Simulate from null model ----------------------------------------------

null_sim &lt;- function(n, p, seed = NULL) {
  set.seed(seed)
  Y &lt;- get_E(n, p)
  true_Y &lt;- matrix(0, n, p)

  list(Y = Y, true_Y = true_Y)
}


# Simulate from MASH model ----------------------------------------------

# Sigma is list of covariance matrices
# pi[j] is probability that effect j has covariance Sigma[[j]]
# s is sparsity (percentage of null effects)
mash_sim &lt;- function(n, p, Sigma, pi = NULL, s = 0.8, seed = NULL) {
  set.seed(NULL)
  if (is.null(pi)) {
    pi = rep(1, length(Sigma)) # default to uniform distribution
  }
  assertthat::are_equal(length(pi), length(Sigma))
  for (j in length(Sigma)) {
    assertthat::are_equal(dim(Sigma[j]), c(n, n))
  }

  pi &lt;- pi / sum(pi) # normalize pi to sum to one
  which_sigma &lt;- sample(1:length(pi), p, replace=TRUE, prob=pi)
  nonnull_fx &lt;- sample(1:p, floor((1 - s)*p), replace=FALSE)

  X &lt;- matrix(0, n, p)
  for (j in nonnull_fx) {
    X[, j] &lt;- MASS::mvrnorm(1, rep(0, n), Sigma[[which_sigma[j]]])
  }
  Y &lt;- X + get_E(n, p)
  list(Y = Y, true_Y = X)
}


# Simulate from FLASH model ---------------------------------------------

# fs is sparsity of factors (percentage of null effects)
# fvar is variance of effects (generated from normal distribution)
# ls is sparsity of loadings
# lvar is variance of loadings
# UVvar is variance of dense rank-one matrix included to mimic something
#   like unwanted variation (set it to 0 to ignore it)
flash_sim &lt;- function(n, p, k, fs, fvar, ls, lvar, UVvar = 0, seed = NULL) {
  set.seed(seed)

  nonnull_ll &lt;- matrix(sample(c(0, 1), n*k, TRUE, c(ls, 1 - ls)), n, k)
  LL &lt;- nonnull_ll * matrix(rnorm(n*k, 0, sqrt(lvar)), nrow=n, ncol=k)

  nonnull_ff &lt;- matrix(sample(c(0, 1), p, TRUE, c(fs, 1 - fs)),
                       nrow=k, ncol=p, byrow=TRUE)
  FF &lt;- nonnull_ff * matrix(rnorm(k*p, 0, sqrt(fvar)), nrow=k, ncol=p)

  X &lt;- LL %*% FF
  Y &lt;- X + get_E(n, p)
  # add unwanted variation
  Y &lt;- Y + outer(rnorm(n, 0, sqrt(UVvar)), rnorm(p, 0, sqrt(UVvar)))
  list(Y = Y, true_Y = X)
}


## SIMULATIONS ----------------------------------------------------------

# Functions to generate six types of datasets. One is null; three are
# from the MASH model; two are from the FLASH model.

sim_fns &lt;- function(n, p, s,
                    indvar, shvar, uniqvar,
                    r1var, r5var) {

  # 1. Everything is null
  sim_null &lt;- function(){ null_sim(n, p) }

  Sigma &lt;- list()

  # 2. Effects are independent across conditions
  Sigma[[1]] &lt;- diag(rep(indvar, n))
  Sigma_ind &lt;- Sigma
  sim_ind &lt;- function(){ mash_sim(n, p, Sigma_ind, s=s) }

  # 3. Effects are either independent or shared
  Sigma[[2]] &lt;- matrix(shvar, n, n)
  Sigma_indsh &lt;- Sigma
  sim_indsh &lt;- function(){ mash_sim(n, p, Sigma_indsh, s=s) }

  # 4. Effects are independent, shared, or unique to a single condition
  for (j in 1:n) {
    Sigma[[2 + j]] &lt;- matrix(0, n, n)
    Sigma[[2 + j]][j, j] &lt;- uniqvar
  }
  pi &lt;- c(n, n, rep(1, n))
  sim_mash &lt;- function(){ mash_sim(n, p, Sigma, pi, s=s) }

  # 5. Rank one model
  sim_rank1 &lt;- function(){ flash_sim(n, p, 1, s, r1var, 0.2, 1) }

  # 6. Rank 5 model
  sim_rank5 &lt;- function(){ flash_sim(n, p, 5, s, r5var, 0.8, 1) }

  # 7. Rank 3 model with unwanted variation
  # sim_UV &lt;- function(){ flash_sim(n, p, 3, s, r3var, 0.5, 1, UVvar) }

  c(sim_null, sim_ind, sim_indsh, sim_mash, sim_rank1, sim_rank5)
}

sim_names &lt;- c(&quot;Null simulation&quot;,
               &quot;All independent effects&quot;,
               &quot;Independent and shared&quot;,
               &quot;Independent, shared, and unique&quot;,
               &quot;Rank 1 FLASH model&quot;,
               &quot;Rank 5 FLASH model&quot;)</code></pre>
<p>…for fitting MASH and FLASH objects…</p>
<pre class="r"><code># Fit using FLASH -------------------------------------------------------
fit_flash_zero &lt;- function(data, Kmax, ebnm_fn=&quot;ebnm_pn&quot;,
                           init_fn=&quot;udv_svd&quot;, greedy=TRUE, backfit=TRUE,
                           warmstart=TRUE) {
  if (is.matrix(data)) {
    data &lt;- flash_set_data(data, S = 1)
  }
  n &lt;- nrow(data$Y)

  t0 &lt;- Sys.time()
  if (greedy) {
    res &lt;- flash_add_greedy(data, Kmax, var_type=&quot;zero&quot;,
                            ebnm_fn=ebnm_fn, init_fn=init_fn,
                            warmstart=warmstart)
    fl &lt;- res$f
  } else {
    fl &lt;- flash_add_factors_from_data(data, Kmax, init_fn=init_fn)
  }
  t1 &lt;- Sys.time()
  if (backfit) {
    res &lt;- flash_backfit(data, fl, var_type=&quot;zero&quot;,
                         ebnm_fn=ebnm_fn)
    fl &lt;- res$f
  }
  t2 &lt;- Sys.time()

  t.greedy &lt;- t1 - t0
  t.backfit &lt;- t2 - t1

  list(f = fl, t.greedy = t.greedy, t.backfit = t.backfit)
}


fit_flash_OHL &lt;- function(data, Kmax, ebnm_fn=&quot;ebnm_pn&quot;,
                          init_fn=&quot;udv_svd&quot;, greedy=TRUE, backfit=TRUE,
                          warmstart=TRUE) {
  if (is.matrix(data)) {
    data &lt;- flash_set_data(data, S = 1)
  }
  n &lt;- nrow(data$Y)
  canonical &lt;- cbind(rep(1, n), diag(rep(1, n)))

  zero.res &lt;- fit_flash_zero(data, Kmax, ebnm_fn, init_fn,
                             greedy, backfit=FALSE, warmstart)

  fl &lt;- flash_add_fixed_l(data, canonical, zero.res$f, init_fn=init_fn)

  t0 &lt;- Sys.time()
  if (backfit) {
    res &lt;- flash_backfit(data, fl,
                         var_type=&quot;zero&quot;, ebnm_fn=ebnm_fn,
                         nullcheck=FALSE)
    fl &lt;- res$f
  } else {
    K &lt;- flashr:::flash_get_k(fl)
    res &lt;- flash_backfit(data, fl, kset=(K - ncol(canonical) + 1):K,
                         var_type=&quot;zero&quot;, ebnm_fn=ebnm_fn,
                         nullcheck=FALSE)
    fl &lt;- res$f
  }
  t1 &lt;- Sys.time()

  t.backfit &lt;- Sys.time() - t0

  list(f = fl, t.greedy = zero.res$t.greedy, t.backfit = t.backfit)
}


fit_flash_OHF &lt;- function(data, Kmax, ebnm_fn=&quot;ebnm_pn&quot;,
                          init_fn=&quot;udv_svd&quot;, greedy=TRUE, backfit=TRUE,
                          warmstart=TRUE) {
  if (is.matrix(data)) {
    data &lt;- flash_set_data(data, S = 1)
  }
  n &lt;- nrow(data$Y)
  canonical &lt;- cbind(rep(1, n), diag(rep(1, n)))

  t0 &lt;- Sys.time()
  fl &lt;- flash_add_fixed_l(data, canonical)
  res &lt;- flash_backfit(data, fl, var_type=&quot;zero&quot;, ebnm_fn=ebnm_fn,
                       nullcheck=FALSE)
  fl &lt;- res$f
  t1 &lt;- Sys.time()

  if (greedy) {
    res &lt;- flash_add_greedy(data, Kmax, fl, var_type=&quot;zero&quot;,
                            ebnm_fn=ebnm_fn, init_fn=init_fn,
                            warmstart=warmstart)
    fl &lt;- res$f
  } else {
    fl &lt;- flash_add_factors_from_data(data, Kmax, fl, init_fn=init_fn)
  }
  t2 &lt;- Sys.time()
  K = flashr:::flash_get_k(fl)
  if (backfit &amp;&amp; K &gt; ncol(canonical)) {
    res &lt;- flash_backfit(data, fl,
                         kset=(ncol(canonical) + 1):K,
                         var_type=&quot;zero&quot;, ebnm_fn=ebnm_fn,
                         nullcheck=FALSE)
    fl &lt;- res$f
  }
  t3 &lt;- Sys.time()

  t.greedy &lt;- t2 - t1
  t.backfit &lt;- (t1 - t0) + (t3 - t2)

  list(f = fl, t.greedy = t.greedy, t.backfit = t.backfit)
}


# Fit using MASH -------------------------------------------------------
fit_mash &lt;- function(data) {
  if (is.matrix(data)) {
    data &lt;- mash_set_data(t(data))
  }
  timing &lt;- list()

  # time to create canonical matrices is negligible
  U = cov_canonical(data)

  t0 &lt;- Sys.time()
  m.1by1 &lt;- mash_1by1(data)
  lvl &lt;- 0.05
  strong &lt;- get_significant_results(m.1by1, lvl)
  while (length(strong) &lt; 5 &amp;&amp; lvl &lt; 0.5) {
    lvl &lt;- lvl + 0.05
    strong &lt;- get_significant_results(m.1by1, lvl)
  }
  if (length(strong) &gt;= 5) {
    U.pca &lt;- cov_pca(data, 5, strong)
    U.ed &lt;- cov_ed(data, U.pca, strong)
    U &lt;- c(U, U.ed)
    t.ed &lt;- Sys.time() - t0
  } else {
    t.ed &lt;- as.difftime(0, units=&quot;secs&quot;)
  }

  t0 &lt;- Sys.time()
  m &lt;- mash(data, U)
  t.mash &lt;- Sys.time() - t0

  list(m = m, t.ed = t.ed, t.mash = t.mash)
}</code></pre>
<p>…for evaluating performance…</p>
<pre class="r"><code># Evaluate methods based on MSE, CI coverage, and TPR vs. FPR -----------

flash_diagnostics &lt;- function(fl, Y, true_Y, nsamp) {
  MSE &lt;- flash_mse(fl, true_Y)

  # Sample from FLASH fit to estimate CI coverage and TPR vs. FPR
  fl_sampler &lt;- flash_sampler(Y, fl, fixed=&quot;loadings&quot;)
  fl_samp &lt;- fl_sampler(nsamp)

  CI &lt;- flash_ci(fl_samp, true_Y)
  ROC &lt;- flash_roc(fl, fl_samp, true_Y)

  list(MSE = MSE, CI = CI, TP = ROC$TP, FP = ROC$FP,
       n_nulls = ROC$n_nulls, n_nonnulls = ROC$n_nonnulls)
}

mash_diagnostics &lt;- function(m, true_Y) {
  MSE &lt;- mash_mse(m, true_Y)
  CI &lt;- mash_ci(m, true_Y)
  ROC &lt;- mash_roc(m, true_Y)

  list(MSE = MSE, CI = CI, TP = ROC$TP, FP = ROC$FP,
       n_nulls = ROC$n_nulls, n_nonnulls = ROC$n_nonnulls)
}


# MSE of posterior means (FLASH) ----------------------------------------
flash_mse &lt;- function(fl, true_Y) {
  mean((flash_get_fitted_values(fl) - true_Y)^2)
}

# MSE for MASH ----------------------------------------------------------
mash_mse &lt;- function(m, true_Y) {
  mean((get_pm(m) - t(true_Y))^2)
}


# 95% CI coverage for FLASH ---------------------------------------------
flash_ci &lt;- function(fl_samp, true_Y) {
  n &lt;- nrow(true_Y)
  p &lt;- ncol(true_Y)
  nsamp &lt;- length(fl_samp)

  flat_samp &lt;- matrix(0, nrow=n*p, ncol=nsamp)
  for (i in 1:nsamp) {
    flat_samp[, i] &lt;- as.vector(fl_samp[[i]])
  }
  CI &lt;- t(apply(flat_samp, 1, function(x) {quantile(x, c(0.025, 0.975))}))
  mean((as.vector(true_Y) &gt;= CI[, 1]) &amp; (as.vector(true_Y) &lt;= CI[, 2]))
}

# 95% CI coverage for MASH ----------------------------------------------
mash_ci &lt;- function(m, true_Y) {
  Y &lt;- t(true_Y)
  mean((Y &gt; get_pm(m) - 1.96 * get_psd(m))
      &amp; (Y &lt; get_pm(m) + 1.96 * get_psd(m)))
}


# LFSR for FLASH --------------------------------------------------------
flash_lfsr &lt;- function(fl_samp) {
  nsamp &lt;- length(fl_samp)
  n &lt;- nrow(fl_samp[[1]])
  p &lt;- ncol(fl_samp[[1]])

  pp &lt;- matrix(0, nrow=n, ncol=p)
  pn &lt;- matrix(0, nrow=n, ncol=p)
  for (i in 1:nsamp) {
    pp &lt;- pp + (fl_samp[[i]] &gt; 0)
    pn &lt;- pn + (fl_samp[[i]] &lt; 0)
  }
  1 - pmax(pp, pn) / nsamp
}


# Quantities for plotting ROC curves -----------------------------------
flash_roc &lt;- function(fl, fl_samp, true_Y, step=0.01) {
  roc_data(flash_get_fitted_values(fl), true_Y, flash_lfsr(fl_samp), step)
}

mash_roc &lt;- function(m, true_Y, step=0.01) {
  roc_data(get_pm(m), t(true_Y), get_lfsr(m), step)
}

roc_data &lt;- function(pm, true_Y, lfsr, step) {
  correct_sign &lt;- pm * true_Y &gt; 0
  is_null &lt;- true_Y == 0
  n_nulls &lt;- sum(is_null)
  n_nonnulls &lt;- length(true_Y) - n_nulls

  ts &lt;- seq(0, 1, by=step)
  tp &lt;- rep(0, length(ts))
  fp &lt;- rep(0, length(ts))

  for (t in 1:length(ts)) {
    signif &lt;- lfsr &lt;= ts[t]
    tp[t] &lt;- sum(signif &amp; correct_sign)
    fp[t] &lt;- sum(signif &amp; is_null)
  }

  list(ts = ts, TP = tp, FP = fp, n_nulls = n_nulls, n_nonnulls = n_nonnulls)
}


# empirical false sign rate vs. local false sign rate
# efsr_by_lfsr &lt;- function(pm, true_Y, lfsr, step) {
#   pred_signs &lt;- sign(pm)
#   pred_zeros &lt;- pred_signs == 0
#   pred_signs[pred_zeros] &lt;- sample(c(0, 1), length(pred_zeros), replace=T)
#
#   gotitright &lt;- (pred_signs == sign(true_Y))
#
#   nsteps &lt;- floor(.5 / step)
#   efsr_by_lfsr &lt;- rep(0, nsteps)
#   for (k in 1:nsteps) {
#     idx &lt;- (lfsr &gt;= (step * (k - 1)) &amp; lfsr &lt; (step * k))
#     efsr_by_lfsr[k] &lt;- ifelse(sum(idx) == 0, NA,
#                               1 - sum(gotitright[idx]) / sum(idx))
#   }
#   efsr_by_lfsr
# }</code></pre>
<p>…for running simulations and plotting results…</p>
<pre class="r"><code># Functions for running simulations and combining results ---------------

run_sims &lt;- function(sim_fn, nsims, plot_title, fpath, Kmax=50,
                     backfit=FALSE) {
  if (nsims == 1) {
    res = run_one_sim(sim_fn, Kmax, backfit)
  } else {
    res = run_many_sims(sim_fn, nsims, Kmax, backfit)
  }

  saveRDS(output_res_mat(res$res), paste0(fpath, &quot;res.rds&quot;))
  if (!(plot_title == &quot;Null simulation&quot;)) {
    png(paste0(fpath, &quot;ROC.png&quot;))
    plot_ROC(res$res, plot_title)
    dev.off()
  }
  png(paste0(fpath, &quot;time.png&quot;))
  plot_timing(res$timing)
  dev.off()

  return(res)
}

run_one_sim &lt;- function(sim_fn, Kmax, nsamp=200, backfit) {
  data &lt;- do.call(sim_fn, list())

  # If there are no strong signals, trying to run ED throws an error, so
  #   we need to do some error handling to fit the MASH object
  mfit &lt;- fit_mash(data$Y)

  flfits &lt;- list()
  flfits$Zero &lt;- fit_flash_zero(data$Y, Kmax, backfit=backfit)
  flfits$OHL &lt;- fit_flash_OHL(data$Y, Kmax, backfit=backfit)
  flfits$OHF &lt;- fit_flash_OHF(data$Y, Kmax, backfit=backfit)

  message(&quot;Running MASH diagnostics&quot;)
  mres &lt;- mash_diagnostics(mfit$m, data$true_Y)

  message(&quot;Running FLASH diagnostics&quot;)
  methods &lt;- names(flfits)
  flres &lt;- list()
  for (method in methods) {
    flres[[method]] &lt;- flash_diagnostics(flfits[[method]]$f, data$Y,
                                         data$true_Y, nsamp)
  }

  # Combine results:
  timing = lapply(flfits,
                  function(method) {
                    list(ed.or.greedy = method$t.greedy,
                         mash.or.backfit = method$t.backfit)
                  })
  timing$MASH &lt;- list(ed.or.greedy = mfit$t.ed,
                      mash.or.backfit = mfit$t.mash)

  all_res &lt;- flres
  all_res$MASH &lt;- mres

  list(timing = timing, res = all_res)
}

run_many_sims &lt;- function(sim_fn, nsims, Kmax, backfit) {
  res &lt;- list()
  combined_res &lt;- list()

  for (i in 1:nsims) {
    message(paste(&quot;  Simulating dataset&quot;, i))
    res[[i]] &lt;- run_one_sim(sim_fn, Kmax, backfit=backfit)
  }
  elems &lt;- names(res[[1]])
  for (elem in elems) {
    combined_res[[elem]] &lt;- list()
    subelems &lt;- names(res[[1]][[elem]])
    for (subelem in subelems) {
      combined_res[[elem]][[subelem]] &lt;- list()
      subsubelems &lt;- names(res[[1]][[elem]][[subelem]])
      for (subsubelem in subsubelems) {
        tmp &lt;- lapply(res, function(x) {x[[elem]][[subelem]][[subsubelem]]})
        combined_res[[elem]][[subelem]][[subsubelem]] &lt;- Reduce(`+`, tmp) / nsims
      }
    }
  }
  return(combined_res)
}


# Plotting and output functions -----------------------------------------

plot_timing &lt;- function(timing, units=&quot;secs&quot;) {
  data &lt;- sapply(timing, unlist)
  data &lt;- data[, c(4, 1, 2, 3)]
  barplot(colSums(data), axes=T,
          main=paste(&quot;Average time to fit in&quot;, units),
          names.arg = colnames(data),
          #legend.text = c(&quot;ED/Greedy&quot;, &quot;MASH/Backfit&quot;),
          ylim = c(0, max(colSums(data))*2),
          cex.names = 0.8)
  # (increasing ylim is easiest way to deal with legend getting in way)
}

plot_ROC &lt;- function(res, main=&quot;ROC curve&quot;) {
  # Number of nulls and nonnulls are identical across methods
  n_nonnulls &lt;- res[[1]]$n_nonnulls
  n_nulls &lt;- res[[1]]$n_nulls

  m_y &lt;- res$MASH$TP / n_nonnulls
  m_x &lt;- res$MASH$FP / n_nulls
  plot(m_x, m_y, xlim=c(0, 1), ylim=c(0, 1), type=&#39;l&#39;,
       xlab=&#39;FPR&#39;, ylab=&#39;TPR&#39;, main=main, col=&quot;orange&quot;)

  idx &lt;- 1:3
  colors &lt;- c(&quot;skyblue&quot;, &quot;seagreen&quot;, &quot;yellow2&quot;)
  for (i in idx) {
    y &lt;- res[[i]]$TP / n_nonnulls
    x &lt;- res[[i]]$FP / n_nulls
    lines(x, y, col=colors[i])
  }
  legend(&quot;bottomright&quot;, c(&quot;MASH&quot;, names(res)[idx]), lty=1,
         col=c(&quot;orange&quot;, colors[idx]), cex=0.8)
}

output_res_mat &lt;- function(res) {
  mat &lt;- rbind(sapply(res, function(method) {method$MSE}),
               sapply(res, function(method) {method$CI}))

  rownames(mat) = c(&quot;MSE&quot;, &quot;95% CI cov&quot;)
  return(mat)
}</code></pre>
<p>…and the main function calls.</p>
<pre class="r"><code># Make sure to use branch &quot;trackObj&quot; when loading flashr.

# devtools::install_github(&quot;stephenslab/flashr&quot;, ref=&quot;trackObj&quot;)
devtools::load_all(&quot;/Users/willwerscheid/GitHub/flashr/&quot;)
# devtools::install_github(&quot;stephenslab/ebnm&quot;)
devtools::load_all(&quot;/Users/willwerscheid/GitHub/ebnm/&quot;)
library(mashr)

source(&quot;./code/sims.R&quot;)
source(&quot;./code/fits.R&quot;)
source(&quot;./code/utils.R&quot;)

source(&quot;./code/mashvflash.R&quot;)

set.seed(1)

# s is sparsity (prop null genes); var parameters define sizes of effects
all_sims &lt;- sim_fns(n=25, p=1000, s=0.8,
                    indvar=4, shvar=2, uniqvar=100,
                    r1var=4, r5var=1)

for (i in 1:length(all_sims)) {
  message(paste(&quot;  Beginning simulation #&quot;, i, sep=&quot;&quot;))
  res &lt;- run_sims(all_sims[[i]], nsims=10, plot_title=sim_names[[i]],
                  fpath = paste0(&quot;./output/MASHvFLASHsims/greedy/sim&quot;, i),
                  Kmax=25, backfit=FALSE)
}

for (i in 1:length(all_sims)) {
  message(paste(&quot;  Beginning simulation #&quot;, i, sep=&quot;&quot;))
  res &lt;- run_sims(all_sims[[i]], nsims=10, plot_title=sim_names[[i]],
                  fpath = paste0(&quot;./output/MASHvFLASHsims/backfit/sim&quot;, i),
                  Kmax=25, backfit=TRUE)
}</code></pre>
</div>
<div id="session-information" class="section level2">
<h2>Session information</h2>
<pre class="r"><code>sessionInfo()</code></pre>
<pre><code>R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.6

Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

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

loaded via a namespace (and not attached):
 [1] workflowr_1.0.1   Rcpp_0.12.17      digest_0.6.15    
 [4] rprojroot_1.3-2   R.methodsS3_1.7.1 backports_1.1.2  
 [7] git2r_0.21.0      magrittr_1.5      evaluate_0.10.1  
[10] highr_0.6         stringi_1.1.6     whisker_0.3-2    
[13] R.oo_1.21.0       R.utils_2.6.0     rmarkdown_1.8    
[16] tools_3.4.3       stringr_1.3.0     yaml_2.1.17      
[19] compiler_3.4.3    htmltools_0.3.6   knitr_1.20       </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 reproducible <a href="http://rmarkdown.rstudio.com">R Markdown</a>
  analysis was created with
  <a href="https://github.com/jdblischak/workflowr">workflowr</a> 1.0.1
</p>
<hr>


</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>