<!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>Call Peaks by Species</title>

<script src="site_libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cosmo.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/textmate.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-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">comparitive_threeprime</a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li>
  <a href="index.html">Home</a>
</li>
<li>
  <a href="about.html">About</a>
</li>
<li>
  <a href="license.html">License</a>
</li>
      </ul>
      <ul class="nav navbar-nav navbar-right">
        <li>
  <a href="https://github.com/jdblischak/workflowr">
    <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">Call Peaks by Species</h1>
<h4 class="author"><em>Briana Mittleman</em></h4>
<h4 class="date"><em>8/16/2018</em></h4>

</div>


<p><strong>Last updated:</strong> 2018-08-21</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(20180801)</code> </summary></p>
<p>The command <code>set.seed(20180801)</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/comparative_threeprime/tree/843d7d158052d7015b88aeaacc7470102a6b5b6f" target="_blank">843d7d1</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:    .RData
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/

Untracked files:
    Untracked:  com_threeprime.Rproj
    Untracked:  data/dist_upexon/
    Untracked:  data/liftover/
    Untracked:  data/map.stats.csv
    Untracked:  data/map.stats.xlsx
    Untracked:  docs/figure/

Unstaged changes:
    Modified:   _workflowr.yml
    Deleted:    comparitive_threeprime.Rproj

</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;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/brimittleman/comparative_threeprime/7bdbd4879a6dc220e9bdad9d025028dadb50e936/docs/callPeaksbySpecies.html" target="_blank">7bdbd48</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-17
</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/comparative_threeprime/blob/392aed91236f58fd34f66fd6ea55d135450b4545/analysis/callPeaksbySpecies.Rmd" target="_blank">392aed9</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-17
</td>
<td style="text-align:left;">
lift code and add to index
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/brimittleman/comparative_threeprime/471aec3cd01bd028099834c40079529c29a31cba/docs/callPeaksbySpecies.html" target="_blank">471aec3</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-17
</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/comparative_threeprime/blob/356e3d8259000b250532ea4738dfed98ab9ead4d/analysis/callPeaksbySpecies.Rmd" target="_blank">356e3d8</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-17
</td>
<td style="text-align:left;">
full protocol for HC peaks
</td>
</tr>
<tr>
<td style="text-align:left;">
html
</td>
<td style="text-align:left;">
<a href="https://cdn.rawgit.com/brimittleman/comparative_threeprime/50b7e982ac2e15fce5b6a9cdd47cc5a0d09bba0f/docs/callPeaksbySpecies.html" target="_blank">50b7e98</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-17
</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/comparative_threeprime/blob/89d642443ab6d5b67819d0ecb4b00a90dbd0b6e8/analysis/callPeaksbySpecies.Rmd" target="_blank">89d6424</a>
</td>
<td style="text-align:left;">
brimittleman
</td>
<td style="text-align:left;">
2018-08-17
</td>
<td style="text-align:left;">
start peak calling human
</td>
</tr>
</tbody>
</table>
</ul>
<p></details></p>
<hr />
<div id="human-peaks" class="section level3">
<h3>Human Peaks</h3>
<p>First I will call peaks in the merged human data like I did in <a href="https://brimittleman.github.io/threeprimeseq/peak.cov.pipeline.html" class="uri">https://brimittleman.github.io/threeprimeseq/peak.cov.pipeline.html</a></p>
<ul>
<li>Merge BW</li>
</ul>
<pre class="bash"><code>#!/bin/bash

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

module load Anaconda3
source activate comp_threeprime_env

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

bigWigMerge -inList /project2/gilad/briana/comparitive_threeprime/human/data/list_bw/list_of_bigwig.txt /project2/gilad/briana/comparitive_threeprime/human/data/mergedBW/merged_human-threeprimeseq.bg</code></pre>
<ul>
<li>Convert to coverage</li>
</ul>
<p>Copy the bg_to_cov.py to the code directory then run it with. ERROR HERE!</p>
<pre class="bash"><code>#!/bin/bash

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

module load python  

python bg_to_cov.py /project2/gilad/briana/comparitive_threeprime/human/data/mergedBW/merged_human-threeprimeseq.bg /project2/gilad/briana/comparitive_threeprime/human/data/mergedBW/merged_human-threeprimeseq.coverage.txt</code></pre>
<ul>
<li><p>sort -k1,1 -k2,2n /project2/gilad/briana/comparitive_threeprime/human/data/mergedBW/merged_human-threeprimeseq.coverage.txt &gt; /project2/gilad/briana/comparitive_threeprime/human/data/mergedBW/merged_human-threeprimeseq.coverage.sort.txt</p></li>
<li><p>Call Peaks</p></li>
</ul>
<p>get_APA_peaks_human.py</p>
<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()
        chrom= chrom[3:]
        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/comparitive_threeprime/human/data/mergedBW/merged_human-threeprimeseq.coverage.sort.txt&quot; # &quot;/project2/yangili1/threeprimeseq/gencov/TotalBamFiles.split.genomecov.bed&quot;
    outFile = &quot;/project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks/APApeaks_human_chr%s.bed&quot;%chrom
    main(inFile, outFile, chrom)</code></pre>
<p>run_getpeakYL_human.sh</p>
<pre class="bash"><code>#!/bin/bash

#SBATCH --job-name=run_getpeakYL_human
#SBATCH --account=pi-yangili1
#SBATCH --time=24:00:00
#SBATCH --output=run_getpeakYL_human.out
#SBATCH --error=run_getpeakYL_human.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 get_APA_peaks_human.py  $i
done
</code></pre>
<ul>
<li>Combine the peaks</li>
</ul>
<p>cat /project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks/*.bed &gt; /project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/APApeaks_merged_allchrom.bed</p>
<ul>
<li>Bed to saf</li>
</ul>
<p>bed2saf_h.py</p>
<pre class="bash"><code>from misc_helper import *

fout = file(&quot;/project2/gilad/briana/comparitive_threeprime/human/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/comparitive_threeprime/human/data/mergedPeaks_comb/APApeaks_merged_allchrom.bed&quot;):
    chrom, start, end, score, strand, score2 = ln.split()
    chrom=chrom[3:]
    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>
<ul>
<li>Peak Feature count</li>
</ul>
<pre class="bash"><code>#!/bin/bash

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

module load Anaconda3
source activate activate comp_threeprime_env

featureCounts -a /project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/APApeaks_merged_allchrom.SAF -F SAF -o /project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/APAquant.fc /project2/gilad/briana/comparitive_threeprime/human/data/sort/*-sort.bam -s 1</code></pre>
<ul>
<li>Filter peaks</li>
</ul>
<p>filter_peaks_human.py</p>
<pre class="bash"><code>from misc_helper import *
import numpy as np

fout = file(&quot;/project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed&quot;,&#39;w&#39;)

#cutoffs
c = 0.9
caveread = 2

# counters
fc, fcaveread = 0, 0
N, Npass = 0, 0

for dic in stream_table(open(&quot;/project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/APAquant.fc&quot;),&#39;\t&#39;):
    #/project2/gilad/briana/threeprimeseq/data/sort/YL-SP-19239-T-combined-sort.bam
    #/project2/gilad/briana/comparitive_threeprime/human/data/sort/human_combined_18498_N-sort.bam
    tot, nuc = [], []
    for k in dic:
        if &quot;human&quot; not in k: continue
        T = k.split(&quot;_&quot;)[-1].split(&quot;-&quot;)[0]
        if T == &quot;T&quot;:
            tot.append(int(dic[k]))
        else:
            nuc.append(int(dic[k]))
    totP = tot.count(0)/float(len(tot))
    nucP = nuc.count(0)/float(len(nuc))
    N += 1
    if totP &gt; c and nucP &gt; c:
        fc += 1
        continue
    if max([np.mean(tot),np.mean(nuc)]) &lt;= caveread:
        fcaveread += 1
        continue
    
    fout.write(&quot;\t&quot;.join([&quot;chr&quot;+dic[&#39;Chr&#39;], dic[&quot;Start&quot;], dic[&quot;End&quot;],str(max([np.mean(tot),np.mean(nuc)])),dic[&quot;Strand&quot;],&quot;.&quot;])+&#39;\n&#39;)
    Npass += 1
fout.close()
    

print(&quot;%d (%.2f%%) did not pass proportion of nonzero cutoff, %d (%.2f%%) did not pass average read cutoff. Total peaks: %d (%.3f%%) of %d peaks remaining&quot;%(fc,float(fc)/N*100, fcaveread, float(fcaveread)/N*100, Npass, 100*Npass/float(N),N))</code></pre>
<p>run_filter_peaks_human.sh</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_h.out
#SBATCH --error=filter_peak_h.err
#SBATCH --partition=broadwl
#SBATCH --mem=12G
#SBATCH --mail-type=END

module load python  


python filter_peaks_human.py</code></pre>
<ul>
<li>Name the peaks</li>
</ul>
<pre class="bash"><code>x = wc -l /project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed 

seq 1 x &gt; peak.num.txt

paste /project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed  /project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/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/comparitive_threeprime/human/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom_named_human.bed </code></pre>
<p>This will be the bed file I use for the liftover</p>
</div>
<div id="chimp-peaks" class="section level3">
<h3>Chimp Peaks</h3>
<ul>
<li>Merge BW</li>
</ul>
<pre class="bash"><code>#!/bin/bash

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

module load Anaconda3
source activate comp_threeprime_env

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

bigWigMerge -inList /project2/gilad/briana/comparitive_threeprime/chimp/data/list_bw/list_of_bigwig.txt /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedBW/merged_chimp-threeprimeseq.bg</code></pre>
<ul>
<li>Convert to coverage</li>
</ul>
<pre class="bash"><code>#!/bin/bash

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

module load python  

python bg_to_cov.py /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedBW/merged_chimp-threeprimeseq.bg /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedBW/merged_chimp-threeprimeseq.coverage.txt</code></pre>
<ul>
<li><p>sort -k1,1 -k2,2n /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedBW/merged_chimp-threeprimeseq.coverage.txt&gt; /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedBW/merged_chimp-threeprimeseq.coverage.sort.txt</p></li>
<li><p>Call Peaks</p></li>
</ul>
<p>get_APA_peaks_chimp.py</p>
<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()
        chrom= chrom[3:]
        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/comparitive_threeprime/chimp/data/mergedBW/merged_chimp-threeprimeseq.coverage.sort.txt&quot; # &quot;/project2/yangili1/threeprimeseq/gencov/TotalBamFiles.split.genomecov.bed&quot;
    outFile = &quot;/project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks/APApeaks_chimp_chr%s.bed&quot;%chrom
    main(inFile, outFile, chrom)</code></pre>
<p>run_getpeakYL_chimp.sh</p>
<pre class="bash"><code>#!/bin/bash

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

module load Anaconda3
source activate comp_threeprime_env


for i in $(seq 1 22); do 
  python get_APA_peaks_chimp.py  $i
done
</code></pre>
<ul>
<li>Combine the peaks</li>
</ul>
<p>cat /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks/*.bed &gt; /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/APApeaks_merged_allchrom.bed</p>
<ul>
<li>Bed to saf</li>
</ul>
<p>bed2saf_c.py</p>
<pre class="bash"><code>from misc_helper import *

fout = file(&quot;/project2/gilad/briana/comparitive_threeprime/chimp/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/comparitive_threeprime/chimp/data/mergedPeaks_comb/APApeaks_merged_allchrom.bed&quot;):
    chrom, start, end, score, strand, score2 = ln.split()
    chrom=chrom[3:]
    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>
<ul>
<li>Peak Feature count<br />
peak_fc_c.sh</li>
</ul>
<pre class="bash"><code>#!/bin/bash

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

module load Anaconda3
source activate activate comp_threeprime_env

featureCounts -a /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/APApeaks_merged_allchrom.SAF -F SAF -o /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/APAquant.fc /project2/gilad/briana/comparitive_threeprime/chimp/data/sort/*-sort.bam -s 1</code></pre>
<ul>
<li>Filter peaks</li>
</ul>
<p>filter_peaks_chimp.py</p>
<pre class="bash"><code>from misc_helper import *
import numpy as np

fout = file(&quot;/project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed&quot;,&#39;w&#39;)

#cutoffs
c = 0.9
caveread = 2

# counters
fc, fcaveread = 0, 0
N, Npass = 0, 0

for dic in stream_table(open(&quot;/project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/APAquant.fc&quot;),&#39;\t&#39;):
    tot, nuc = [], []
    for k in dic:
        if &quot;chimp&quot; not in k: continue
        T = k.split(&quot;_&quot;)[-1].split(&quot;-&quot;)[0]
        if T == &quot;T&quot;:
            tot.append(int(dic[k]))
        else:
            nuc.append(int(dic[k]))
    totP = tot.count(0)/float(len(tot))
    nucP = nuc.count(0)/float(len(nuc))
    N += 1
    if totP &gt; c and nucP &gt; c:
        fc += 1
        continue
    if max([np.mean(tot),np.mean(nuc)]) &lt;= caveread:
        fcaveread += 1
        continue
    
    fout.write(&quot;\t&quot;.join([&quot;chr&quot;+dic[&#39;Chr&#39;], dic[&quot;Start&quot;], dic[&quot;End&quot;],str(max([np.mean(tot),np.mean(nuc)])),dic[&quot;Strand&quot;],&quot;.&quot;])+&#39;\n&#39;)
    Npass += 1
fout.close()
    

print(&quot;%d (%.2f%%) did not pass proportion of nonzero cutoff, %d (%.2f%%) did not pass average read cutoff. Total peaks: %d (%.3f%%) of %d peaks remaining&quot;%(fc,float(fc)/N*100, fcaveread, float(fcaveread)/N*100, Npass, 100*Npass/float(N),N))</code></pre>
<p>run_filter_peaks_chimp.sh</p>
<pre class="bash"><code>#!/bin/bash

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

module load python  


python filter_peaks_chimp.py</code></pre>
<ul>
<li>Name the peaks</li>
</ul>
<pre class="bash"><code>x = wc -l /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed 

seq 1 x &gt; peak.num.txt

paste /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom.bed  /project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/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/comparitive_threeprime/chimp/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom_named_chimp.bed </code></pre>
<p>The final files are:</p>
<ul>
<li><p>/project2/gilad/briana/comparitive_threeprime/human/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom_named_human.bed</p></li>
<li><p>/project2/gilad/briana/comparitive_threeprime/chimp/data/mergedPeaks_comb/filtered_APApeaks_merged_allchrom_named_chimp.bed</p></li>
</ul>
</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     

loaded via a namespace (and not attached):
 [1] workflowr_1.1.1   Rcpp_0.12.18      digest_0.6.15    
 [4] rprojroot_1.3-2   R.methodsS3_1.7.1 backports_1.1.2  
 [7] git2r_0.23.0      magrittr_1.5      evaluate_0.11    
[10] stringi_1.2.4     whisker_0.3-2     R.oo_1.22.0      
[13] R.utils_2.6.0     rmarkdown_1.10    tools_3.5.1      
[16] stringr_1.3.1     yaml_2.1.19       compiler_3.5.1   
[19] 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.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>