<!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="Briana Mittleman" />


<title>Pipeline for peak coverage</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/journal.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-5.0.13/css/fa-svg-with-js.css" rel="stylesheet" />
<script src="site_libs/font-awesome-5.0.13/js/fontawesome-all.min.js"></script>
<script src="site_libs/font-awesome-5.0.13/js/fa-v4-shims.min.js"></script>

<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;
}
.html-widget {
  margin-bottom: 20px;
}
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">Three Prime Sequencing in Human LCLs</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/brimittleman/threeprimeseq">
    <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">Pipeline for peak coverage</h1>
<h4 class="author"><em>Briana Mittleman</em></h4>
<h4 class="date"><em>7/26/2018</em></h4>

</div>


<p><strong>Last updated:</strong> 2018-08-08</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(12345)</code> </summary></p>
<p>The command <code>set.seed(12345)</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/brimittleman/threeprimeseq/tree/6be219cc784d3d22815e91d1356f4ffe957f9874" target="_blank">6be219c</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:    output/.DS_Store

Untracked files:
    Untracked:  analysis/snake.config.notes.Rmd
    Untracked:  data/18486.genecov.txt
    Untracked:  data/APApeaksYL.total.inbrain.bed
    Untracked:  data/Totalpeaks_filtered_clean.bed
    Untracked:  data/YL-SP-18486-T_S9_R1_001-genecov.txt
    Untracked:  data/bedgraph_peaks/
    Untracked:  data/bin200.5.T.nuccov.bed
    Untracked:  data/bin200.Anuccov.bed
    Untracked:  data/bin200.nuccov.bed
    Untracked:  data/clean_peaks/
    Untracked:  data/combined_reads_mapped_three_prime_seq.csv
    Untracked:  data/gencov.test.csv
    Untracked:  data/gencov.test.txt
    Untracked:  data/gencov_zero.test.csv
    Untracked:  data/gencov_zero.test.txt
    Untracked:  data/gene_cov/
    Untracked:  data/joined
    Untracked:  data/leafcutter/
    Untracked:  data/merged_combined_YL-SP-threeprimeseq.bg
    Untracked:  data/nuc6up/
    Untracked:  data/reads_mapped_three_prime_seq.csv
    Untracked:  data/smash.cov.results.bed
    Untracked:  data/smash.cov.results.csv
    Untracked:  data/smash.cov.results.txt
    Untracked:  data/smash_testregion/
    Untracked:  data/ssFC200.cov.bed
    Untracked:  data/temp.file1
    Untracked:  data/temp.file2
    Untracked:  data/temp.gencov.test.txt
    Untracked:  data/temp.gencov_zero.test.txt
    Untracked:  output/picard/
    Untracked:  output/plots/
    Untracked:  output/qual.fig2.pdf

Unstaged changes:
    Modified:   analysis/cleanupdtseq.internalpriming.Rmd
    Modified:   analysis/dif.iso.usage.leafcutter.Rmd
    Modified:   analysis/explore.filters.Rmd
    Modified:   analysis/test.max2.Rmd
    Modified:   code/Snakefile

</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/brimittleman/threeprimeseq/blob/6be219cc784d3d22815e91d1356f4ffe957f9874/analysis/peak.cov.pipeline.Rmd" target="_blank">6be219c</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-08
</td>
<td style="text-align:left;">
add final pipeline
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/brimittleman/threeprimeseq/5566fd699d0caf8ef4703b2887db845d967db1bd/docs/peak.cov.pipeline.html" target="_blank">5566fd6</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-02
</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/brimittleman/threeprimeseq/blob/0f7930425da9ae47673a816142f9c970c753876a/analysis/peak.cov.pipeline.Rmd" target="_blank">0f79304</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-02
</td>
<td style="text-align:left;">
fix cov to peak file problem
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/brimittleman/threeprimeseq/efad65743d277085b6110d077713606c897b189e/docs/peak.cov.pipeline.html" target="_blank">efad657</a>
</td>
<td style="text-align:left;">
Briana Mittleman
</td>
<td style="text-align:left;">
2018-07-31
</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/brimittleman/threeprimeseq/blob/7c203e4453ad83b3f43467b51fe088209ed97a01/analysis/peak.cov.pipeline.Rmd" target="_blank">7c203e4</a>
</td>
<td style="text-align:left;">
Briana Mittleman
</td>
<td style="text-align:left;">
2018-07-31
</td>
<td style="text-align:left;">
format files for yangs peak script
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/brimittleman/threeprimeseq/7fc2ce7c17935c36fa37afd67b6298f805b84714/docs/peak.cov.pipeline.html" target="_blank">7fc2ce7</a>
</td>
<td style="text-align:left;">
Briana Mittleman
</td>
<td style="text-align:left;">
2018-07-30
</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/brimittleman/threeprimeseq/blob/782320dfc427b4fd8e3f5dddb9e9419e5752a831/analysis/peak.cov.pipeline.Rmd" target="_blank">782320d</a>
</td>
<td style="text-align:left;">
Briana Mittleman
</td>
<td style="text-align:left;">
2018-07-30
</td>
<td style="text-align:left;">
look at coverage in merged bw
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/brimittleman/threeprimeseq/e5a8da629657f8df6a23af081905e7dcab9fe98d/docs/peak.cov.pipeline.html" target="_blank">e5a8da6</a>
</td>
<td style="text-align:left;">
Briana Mittleman
</td>
<td style="text-align:left;">
2018-07-30
</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/brimittleman/threeprimeseq/blob/422a428cf40c5283c7dc0ba0d3cc21d8739cddb3/analysis/peak.cov.pipeline.Rmd" target="_blank">422a428</a>
</td>
<td style="text-align:left;">
Briana Mittleman
</td>
<td style="text-align:left;">
2018-07-30
</td>
<td style="text-align:left;">
add peak cove pipeline and combined lane qc
</td>
</tr>
</tbody>
</table>
</ul>
<p></details></p>
<hr />
<p>I need to create a processing pipeline that I can run each time I get more individuals that will do the following:</p>
<ul>
<li><p>combine all total and nuclear libraries (as a bigwig/genome coverage)</p></li>
<li><p>call peaks with Yang’s script</p></li>
<li><p>filter peaks with Yang’s script</p></li>
<li><p>clean peaks</p></li>
<li><p>run feature counts on these peaks for all fo the individuals</p></li>
</ul>
<div id="create-bedgraph-and-bigwig" class="section level2">
<h2>Create bedgraph and bigwig:</h2>
<p>I can do this step in my snakefile. First, I added the following to my environemnt.</p>
<ul>
<li>ucsc-bedgraphtobigwig<br />
</li>
<li>ucsc-bigwigmerge<br />
</li>
<li>ucsc-wigtobigwig<br />
</li>
<li>ucsc-bigwigtobedgraph</li>
</ul>
<p>I want to create bedgraph for each file. I will add a rule to my snakefile that does this and puts them in the bedgraph directory.</p>
<p>I want to add more memory for this rule in the cluster.json</p>
<pre class="bash"><code>&quot;bedgraph&quot; :
    {
            &quot;mem&quot;: 16000
    },
&quot;bedgraph_5&quot; :
    {
            &quot;mem&quot;: 16000
    }</code></pre>
<p>I will use the bedgraphtobigwig tool.</p>
<pre class="bash"><code>#add to directory
dir_bedgraph= dir_data + &quot;bedgraph/&quot;
dir_bigwig= dir_data + &quot;bigwig/&quot;
dir_sortbg= dir_data + &quot;bedgraph_sort/&quot;
dir_bedgraph_5= dir_data + &quot;bedgraph_5prime/&quot;

#add to rule_all  

expand(dir_bedgraph + &quot;{samples}.split.bg&quot;, samples=samples)
expand(dir_sortbg + &quot;{samples}.sort.bg&quot;, samples=samples)
expand(dir_bigwig + &quot;{samples}.bw&quot;, samples=samples)
expand(dir_bedgraph_5 + &quot;{samples}.5.bg&quot;, samples=samples)

#rule
rule bedgraph_5: 
  input:
    bam = dir_sort + &quot;{samples}-sort.bam&quot;
  output: dir_bedgraph_5 + &quot;{samples}.5.bg&quot;
  shell: &quot;bedtools genomecov -ibam {input.bam} -bg -5 &gt; {output}&quot;
  
rule bedgraph: 
  input:
    bam = dir_sort + &quot;{samples}-sort.bam&quot;
  output: dir_bedgraph + &quot;{samples}.split.bg&quot;
  shell: &quot;bedtools genomecov -ibam {input.bam} -bg -split &gt; {output}&quot;

rule sort_bg:
    input: dir_bedgraph + &quot;{samples}.split.bg&quot;
    output: dir_sortbg + &quot;{samples}.sort.bg&quot;
    shell: &quot;sort -k1,1 -k2,2n {input} &gt; {output}&quot;

rule bg_to_bw:
    input: 
        bg=dir_sortbg + &quot;{samples}.sort.bg&quot;
        len= chrom_length 
    output: dir_bigwig + &quot;{samples}.bw&quot;
    shell: &quot;bedGraphToBigWig {input.bg} {input.len} {output}&quot;</code></pre>
</div>
<div id="merge-bw" class="section level2">
<h2>Merge BW</h2>
<p>This next step will take all of the files in the bigwig directory and merge them. To do this I will create a script that creates a list of all of the files then uses this list in the merge script.</p>
<p>mergeBW.sh</p>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=mergeBW
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=mergeBW.out
#SBATCH --error=mergeBW.err
#SBATCH --partition=broadwl
#SBATCH --mem=40G
#SBATCH --mail-type=END

module load Anaconda3
source activate three-prime-env

ls -d -1 /project2/gilad/briana/threeprimeseq/data/bigwig/* | tail -n +2 &gt; /project2/gilad/briana/threeprimeseq/data/list_bw/list_of_bigwig.txt

bigWigMerge -inList /project2/gilad/briana/threeprimeseq/data/list_bw/list_of_bigwig.txt /project2/gilad/briana/threeprimeseq/data/mergedBW/merged_combined_YL-SP-threeprimeseq.bg
</code></pre>
<p>The result of this script will be a merged bedgraph of all of the files.</p>
</div>
<div id="convert-to-coverage" class="section level2">
<h2>Convert to coverage</h2>
<pre class="r"><code>library(workflowr)</code></pre>
<pre><code>This is workflowr version 1.1.1
Run ?workflowr for help getting started</code></pre>
<pre class="r"><code>library(ggplot2)
library(dplyr)</code></pre>
<pre><code>
Attaching package: &#39;dplyr&#39;</code></pre>
<pre><code>The following objects are masked from &#39;package:stats&#39;:

    filter, lag</code></pre>
<pre><code>The following objects are masked from &#39;package:base&#39;:

    intersect, setdiff, setequal, union</code></pre>
<pre class="bash"><code>#!/usr/bin/env python


main(inFile, outFile):
    fout = open(outFile,&#39;w&#39;)
    for ind,ln in enumerate(open(inFile)):
      print(ind)
      chrom, start, end, count = ln.split()
      i2=int(start)
      while i2 &lt; int(end):
        fout.write(&quot;%s\t%d\t%s\n&quot;%(chrom, i2 + 1, count))
        fout.flush()
        i2 += 1
    fout.close()    
    

if __name__ == &quot;__main__&quot;:
    import numpy as np
    from misc_helper import *
    import sys
    inFile = sys.argv[1]
    outFile = sys.argv[2]
    main(inFile, outFile)</code></pre>
<p>Create a bash script to run this. I want the input and output files to be arguments in the python script.</p>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=run_bgtocov
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=run_bgtocov.out
#SBATCH --error=run_bgtocov.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END

module load Anaconda3
source activate three-prime-env 

python bg_to_cov.py &quot;/project2/gilad/briana/threeprimeseq/data/mergedBW/merged_combined_YL-SP-threeprimeseq.bg&quot; &quot;/project2/gilad/briana/threeprimeseq/data/mergedBW/merged_combined_YL-SP-threeprimeseq.coverage.txt&quot;</code></pre>
<p>Sort result with:</p>
<pre class="bash"><code>sort -k1,1 -k2,2n merged_combined_YL-SP-threeprimeseq.coverage.txt &gt; merged_combined_YL-SP-threeprimeseq.coverage.sort.txt 
</code></pre>
</div>
<div id="call-peaks" class="section level2">
<h2>Call Peaks</h2>
<pre class="bash"><code>
def main(inFile, outFile, ctarget):
    fout = open(outFile,&#39;w&#39;)
    mincount = 10
    ov = 20
    current_peak = []
    
    currentChrom = None
    prevPos = 0
    for ln in open(inFile):
        chrom, pos, count = ln.split()
        if chrom != ctarget: continue
        count = float(count)

        if currentChrom == None:
            currentChrom = chrom
            
        if count == 0 or currentChrom != chrom or int(pos) &gt; prevPos + 1:
            if len(current_peak) &gt; 0:
                print (current_peak)
                M = max([x[1] for x in current_peak])
                if M &gt; mincount:
                    all_peaks = refine_peak(current_peak, M, M*0.1,M*0.05)
                    #refined_peaks = [(x[0][0],x[-1][0], np.mean([y[1] for y in x])) for x in all_peaks]  
                    rpeaks = [(int(x[0][0])-ov,int(x[-1][0])+ov, np.mean([y[1] for y in x])) for x in all_peaks]
                    if len(rpeaks) &gt; 1:
                        for clu in cluster_intervals(rpeaks)[0]:
                            M = max([x[2] for x in clu])
                            merging = []
                            for x in clu:
                                if x[2] &gt; M *0.5:
                                    #print x, M
                                    merging.append(x)
                            c, s,e,mean =  chrom, min([x[0] for x in merging])+ov, max([x[1] for x in merging])-ov, np.mean([x[2] for x in merging])
                            #print c,s,e,mean
                            fout.write(&quot;chr%s\t%d\t%d\t%d\t+\t.\n&quot;%(c,s,e,mean))
                            fout.flush()
                    elif len(rpeaks) == 1:
                        s,e,mean = rpeaks[0]
                        fout.write(&quot;chr%s\t%d\t%d\t%f\t+\t.\n&quot;%(chrom,s+ov,e-ov,mean))
                        print(&quot;chr%s&quot;%chrom+&quot;\t%d\t%d\t%f\t+\t.\n&quot;%rpeaks[0])
                    #print refined_peaks
            current_peak = [(pos,count)]
        else:
            current_peak.append((pos,count))
        currentChrom = chrom
        prevPos = int(pos)

def refine_peak(current_peak, M, thresh, noise, minpeaksize=30):
    
    cpeak = []
    opeak = []
    allcpeaks = []
    allopeaks = []

    for pos, count in current_peak:
        if count &gt; thresh:
            cpeak.append((pos,count))
            opeak = []
            continue
        elif count &gt; noise: 
            opeak.append((pos,count))
        else:
            if len(opeak) &gt; minpeaksize:
                allopeaks.append(opeak) 
            opeak = []

        if len(cpeak) &gt; minpeaksize:
            allcpeaks.append(cpeak)
            cpeak = []
        
    if len(cpeak) &gt; minpeaksize:
        allcpeaks.append(cpeak)
    if len(opeak) &gt; minpeaksize:
        allopeaks.append(opeak)

    allpeaks = allcpeaks
    for opeak in allopeaks:
        M = max([x[1] for x in opeak])
        allpeaks += refine_peak(opeak, M, M*0.3, noise)

    #print [(x[0],x[-1]) for x in allcpeaks], [(x[0],x[-1]) for x in allopeaks], [(x[0],x[-1]) for x in allpeaks]
    #print &#39;---\n&#39;
    return(allpeaks)

if __name__ == &quot;__main__&quot;:
    import numpy as np
    from misc_helper import *
    import sys

    chrom = sys.argv[1]
    inFile = &quot;/project2/gilad/briana/threeprimeseq/data/mergedBW/merged_combined_YL-SP-threeprimeseq.coverage.sort.txt&quot; # &quot;/project2/yangili1/threeprimeseq/gencov/TotalBamFiles.split.genomecov.bed&quot;
    outFile = &quot;/project2/gilad/briana/threeprimeseq/data/mergedPeaks/APApeaks_chr%s.bed&quot;%chrom
    main(inFile, outFile, chrom)</code></pre>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=w_getpeakYLgen
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=w_getpeakYLgen.out
#SBATCH --error=w_getpeakYLgen.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END

module load Anaconda3
source activate three-prime-env


for i in $(seq 1 22); do 
  python callPeaksYL_GEN.py $i
done</code></pre>
<p>Run the file with : sbatch w_getpeakYLGEN.sh</p>
<p>After I have the peaks I will need to use Yangs filter peak function.</p>
</div>
<div id="filter-peaks" class="section level2">
<h2>Filter peaks</h2>
<p>Update each of the following scripts:</p>
<ol style="list-style-type: decimal">
<li>Combine the peaks from all of the chromosome peak files.</li>
</ol>
<pre class="bash"><code>cat /project2/gilad/briana/threeprimeseq/data/mergedPeaks/*.bed &gt; /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/APApeaks_merged_allchrom.bed</code></pre>
<p>bed2saf.py</p>
<ul>
<li>input: peaks bed file<br />
</li>
<li>output: peaks saf file</li>
</ul>
<pre class="bash"><code>
fout = file(&quot;/project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/APApeaks_merged_allchrom.SAF&quot;,&#39;w&#39;)
fout.write(&quot;GeneID\tChr\tStart\tEnd\tStrand\n&quot;)
for ln in open(&quot;/project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/APApeaks_merged_allchrom.bed&quot;):
    chrom, start, end, score, strand, score2 = ln.split()
    ID = &quot;peak_%s_%s_%s&quot;%(chrom,start, end)
    fout.write(&quot;%s\t%s\t%s\t%s\t+\n&quot;%(ID+&quot;_+&quot;, chrom.replace(&quot;chr&quot;,&quot;&quot;), start, end))
    fout.write(&quot;%s\t%s\t%s\t%s\t-\n&quot;%(ID+&quot;_-&quot;, chrom.replace(&quot;chr&quot;,&quot;&quot;), start, end))
fout.close()</code></pre>
<p>Run this with run_bed2saf.sh. I did this because I need to load python2 rather than using the environment,</p>
<ul>
<li>featureCounts -a PEAK.saf -F SAF -o APAquant.fc /project2/gilad/briana/threeprimeseq/data/sort/*-sort.bam -s 1</li>
</ul>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=peak_fc
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=peak_fc.out
#SBATCH --error=peak_fc.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END

module load Anaconda3
source activate three-prime-env


featureCounts -a /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/APApeaks_merged_allchrom.SAF -F SAF -o /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/APAquant.fc /project2/gilad/briana/threeprimeseq/data/sort/*-sort.bam -s 1</code></pre>
<p>This script is peak_fc.sh</p>
<p>filter_peaks.py</p>
<ul>
<li>input: /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/APAquant.fc<br />
</li>
<li>output: project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed</li>
</ul>
<p>I should run this in a bash script with python 2 as well.</p>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=filter_peak
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=filet_peak.out
#SBATCH --error=filter_peak.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END

module load python  


python filter_peaks.py</code></pre>
<p>Name the peaks for the cleanup:</p>
<pre class="bash"><code>
x = wc -l /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed 

seq 1 x &gt; peak.num.txt

paste /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed peak.num.txt | column -s $&#39;\t&#39; -t &gt; temp
awk &#39;{print $1 &quot;\t&quot; $2 &quot;\t&quot; $3 &quot;\t&quot; $7  &quot;\t&quot;  $4 &quot;\t&quot;  $5 &quot;\t&quot; $6}&#39; temp &gt;   /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.named.bed</code></pre>
</div>
<div id="clean-peaks" class="section level2">
<h2>Clean peaks</h2>
<pre class="r"><code>#!/bin/rscripts

# usage: ./cleanupdtseq.R in_bedfile, outfile, cuttoff

#this script takes a putative peak file, and output file name and a cuttoff for classification and outputs the file with all of the seqs classified. 

#use optparse for management of input arguments I want to be able to imput the 6up nuc file and write out a filter file  

#script needs to run outside of conda env. should module load R in bash script when I submit it 
library(optparse)
library(dplyr)
library(tidyr)
library(ggplot2)
library(cleanUpdTSeq)
library(GenomicRanges)
library(BSgenome.Hsapiens.UCSC.hg19)


option_list = list(
  make_option(c(&quot;-f&quot;, &quot;--file&quot;), action=&quot;store&quot;, default=NA, type=&#39;character&#39;,
              help=&quot;input file&quot;),
  make_option(c(&quot;-o&quot;, &quot;--output&quot;), action=&quot;store&quot;, default=NA, type=&#39;character&#39;,
              help=&quot;output file&quot;),
  make_option(c(&quot;-c&quot;, &quot;--cutoff&quot;), action=&quot;store&quot;, default=NA, type=&#39;double&#39;,
              help=&quot;assignment cuttoff&quot;)
)
  

opt_parser &lt;- OptionParser(option_list=option_list)
opt &lt;- parse_args(opt_parser)


#interrupt execution if no file is  supplied
if (is.null(opt$file)){
  print_help(opt_parser)
  stop(&quot;Need input file&quot;, call.=FALSE)
}

#imput file for test data 
testSet &lt;- read.table(file = opt$file, sep=&quot;\t&quot;, col.names =c(&quot;chr&quot;, &quot;start&quot;, &quot;end&quot;, &quot;PeakName&quot;, &quot;Cov&quot;, &quot;Strand&quot;, &quot;score&quot;))
peaks &lt;- BED2GRangesSeq(testSet, withSeq=FALSE)

#build vector with human genome  

testSet.NaiveBayes &lt;- buildFeatureVector(peaks, BSgenomeName=Hsapiens,
                                         upstream=40, downstream=30, 
                                         wordSize=6, alphabet=c(&quot;ACGT&quot;),
                                         sampleType=&quot;unknown&quot;, 
                                         replaceNAdistance=30, 
                                         method=&quot;NaiveBayes&quot;,
                                         ZeroBasedIndex=1, fetchSeq=TRUE)

#classfy sites with built in classsifer

data(classifier)
testResults &lt;- predictTestSet(testSet.NaiveBayes=testSet.NaiveBayes,
                              classifier=classifier,
                              outputFile=NULL, 
                              assignmentCutoff=opt$cutoff)
true_peaks=testResults %&gt;% filter(pred.class==1) 


#write results  

write.table(true_peaks, file=opt$output, quote = F, row.names = F, col.names = T)  </code></pre>
<p>I will create a bash script to run the cleanupdtseq.R code.</p>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=cleanup_comb
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=cleanup_comb.out
#SBATCH --error=cleanup_comb.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END


module load R



Rscript cleanupdtseq.R  -f /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.named.bed -o /project2/gilad/briana/threeprimeseq/data/clean.peaks_comb/truePeaks_clean.bed -c .5
</code></pre>
<p>Do this after. filter_peaksClean.R, run with run_filter_peaksClean.sh</p>
<pre class="r"><code>library(dplyr)

clean=read.table(&quot;/project2/gilad/briana/threeprimeseq/data/clean.peaks_comb/truePeaks_clean.bed&quot;, header=F, col.names=c(&quot;PeakName&quot;, &quot;probFalse&quot;, &quot;probTrue&quot;, &quot;predClass&quot;, &quot;UP&quot;, &quot;Down&quot;), skip=1)


peaks=read.table(&quot;/project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.named.bed&quot;, header=F, col.names=c(&quot;Chr&quot;, &quot;Start&quot;, &quot;End&quot;, &quot;PeakName&quot;, &quot;Cov&quot;, &quot;Strand&quot;, &quot;Score&quot;))
  
true_peaks=clean %&gt;% filter(predClass==1) 

true_peak_bed=semi_join(peaks, clean, by=&quot;PeakName&quot;)

write.table(true_peak_bed, file=&quot;/project2/gilad/briana/threeprimeseq/data/clean.peaks_comb/APApeaks_combined_clean.bed&quot;, row.names = F, col.names = F, quote = F)</code></pre>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=filter_clean
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=filter_clean.out
#SBATCH --error=filter_clean.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END


module load R


Rscript filter_peaksClean.R</code></pre>
<p>may have to run bed to SAF again. bed2saf.peaks.py</p>
<pre class="bash"><code>from misc_helper import *

fout = file(&quot;/project2/gilad/briana/threeprimeseq/data/clean.peaks_comb/APApeaks_combined_clean.saf&quot;,&#39;w&#39;)
fout.write(&quot;GeneID\tChr\tStart\tEnd\tStrand\n&quot;)
for ln in open(&quot;/project2/gilad/briana/threeprimeseq/data/clean.peaks_comb/APApeaks_combined_clean.bed&quot;):
    chrom, start, end, name, score, strand, score2 = ln.split()
    ID = &quot;peak_%s_%s_%s&quot;%(chrom,start, end)
    fout.write(&quot;%s\t%s\t%s\t%s\t+\n&quot;%(ID+&quot;_+&quot;, chrom.replace(&quot;chr&quot;,&quot;&quot;), start, end))
    fout.write(&quot;%s\t%s\t%s\t%s\t-\n&quot;%(ID+&quot;_-&quot;, chrom.replace(&quot;chr&quot;,&quot;&quot;), start, end))
fout.close()</code></pre>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=bed2saf_peaks
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=bed2saf_peak.out
#SBATCH --error=bed2saf_peak.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END

module load python

python bed2saf.peaks.py</code></pre>
</div>
<div id="ind.-coverage-with-feature-counts" class="section level2">
<h2>Ind. Coverage with feature counts</h2>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=clean_peak_fc
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=clean_peak_fc.out
#SBATCH --error=clean_peak_fc.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END

module load Anaconda3
source activate three-prime-env


featureCounts -a /project2/gilad/briana/threeprimeseq/data/clean.peaks_comb/APApeaks_combined_clean.saf -F SAF -o /project2/gilad/briana/threeprimeseq/data/clean_peaks_comb_quant/APAquant.fc.cleanpeaks.fc /project2/gilad/briana/threeprimeseq/data/sort/*-sort.bam -s 1</code></pre>
</div>
<div id="full-pipeline-of-scripts" class="section level2">
<h2>Full pipeline of scripts:</h2>
<ul>
<li><p>mergeBW.sh</p></li>
<li><p>run_bgtocov.sh</p></li>
<li><p>sort -k1,1 -k2,2n merged_combined_YL-SP-threeprimeseq.coverage.txt &gt; merged_combined_YL-SP-threeprimeseq.coverage.sort.txt</p></li>
<li><p>w_getpeakYLGEN.sh</p></li>
<li><p>cat /project2/gilad/briana/threeprimeseq/data/mergedPeaks/*.bed &gt; /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/APApeaks_merged_allchrom.bed</p></li>
<li><p>run_bed2saf.sh</p></li>
<li><p>peak_fc.sh</p></li>
</ul>
<pre class="bash"><code>x = wc -l /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed 

seq 1 x &gt; peak.num.txt

paste /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed peak.num.txt | column -s $&#39;\t&#39; -t &gt; temp
awk &#39;{print $1 &quot;\t&quot; $2 &quot;\t&quot; $3 &quot;\t&quot; $7  &quot;\t&quot;  $4 &quot;\t&quot;  $5 &quot;\t&quot; $6}&#39; temp &gt;   /project2/gilad/briana/threeprimeseq/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.named.bed
</code></pre>
<ul>
<li><p>cleanup_comb.sh</p></li>
<li><p>run_filter_peaksClean.sh</p></li>
<li><p>run_bed2saf_peaks.sh</p></li>
<li><p>clean_peak_fc.sh</p></li>
</ul>
</div>
<div id="extra-stuff-not-used" class="section level2">
<h2>Extra stuff not used</h2>
<div id="problem-with-peak-script-try-with-bam-merge" class="section level3">
<h3>Problem with peak script : try with bam merge</h3>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=comb_gencov
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=comb_gencov.out
#SBATCH --error=comb_gencov.err
#SBATCH --partition=bigmem2
#SBATCH --mem=100G
#SBATCH --mail-type=END


module load Anaconda3
source activate three-prime-env 


samtools merge /project2/gilad/briana/threeprimeseq/data/comb_bam/all_total.nuc_comb.bam  /project2/gilad/briana/threeprimeseq/data/sort/*.bam


bedtools genomecov -ibam /project2/gilad/briana/threeprimeseq/data/comb_bam/all_total.nuc_comb.bam -d -split &gt; /project2/gilad/briana/threeprimeseq/data/comb_bam/all_total.nuc_comb.split.genomecov.bed</code></pre>
<p>Will need to run mergeBW.sh and run_bgtocov.sh then sort with</p>
<pre class="bash"><code>sort -k1,1 -k2,2n merged_combined_YL-SP-threeprimeseq.coverage.txt &gt; merged_combined_YL-SP-threeprimeseq.coverage.sort.txt </code></pre>
<p>then call peaks with the updated callpeaks script from yang (get_APA_peaks.py) I run this with w_getpeakYLGEN.sh.</p>
</div>
</div>
<div id="session-information" class="section level2">
<h2>Session information</h2>
<pre class="r"><code>sessionInfo()</code></pre>
<pre><code>R version 3.5.1 (2018-07-02)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.5/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     

other attached packages:
[1] dplyr_0.7.6     ggplot2_3.0.0   workflowr_1.1.1

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.18      compiler_3.5.1    pillar_1.3.0     
 [4] git2r_0.23.0      plyr_1.8.4        bindr_0.1.1      
 [7] R.methodsS3_1.7.1 R.utils_2.6.0     tools_3.5.1      
[10] digest_0.6.15     evaluate_0.11     tibble_1.4.2     
[13] gtable_0.2.0      pkgconfig_2.0.1   rlang_0.2.1      
[16] rstudioapi_0.7    yaml_2.1.19       bindrcpp_0.2.2   
[19] withr_2.1.2       stringr_1.3.1     knitr_1.20       
[22] rprojroot_1.3-2   grid_3.5.1        tidyselect_0.2.4 
[25] glue_1.3.0        R6_2.2.2          rmarkdown_1.10   
[28] purrr_0.2.5       magrittr_1.5      whisker_0.3-2    
[31] backports_1.1.2   scales_0.5.0      htmltools_0.3.6  
[34] assertthat_0.2.0  colorspace_1.3-2  stringi_1.2.4    
[37] lazyeval_0.2.1    munsell_0.5.0     crayon_1.3.4     
[40] R.oo_1.22.0      </code></pre>
</div>

<hr>
<p>
    
</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>
-->
<!-- 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.1.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>