Thanks. This options seems to open up a lot of options.
4 answers
If you use bedtools genomecov you can use a scaling factor.
bedtools genomecov -ibam input.bam -bg -scale X -g genome.chrom.sizes > normalised.bg
where X is the scaling factor. The scale could be for each sample 1,000,000/mapped reads, or each sample divided by the mean of mapped reads for each sample.
You can then use:
wigToBigWig -clip normalised.bg genome.chrom.sizes normalised.bw
pybedtools has a function that will scale your BAM by million mapped reads (the scaling used by many ENCODE data sets) and creates a bigWig file all in one shot:
from pybedtools.contrib.bigwig import bam_to_bigwig
bam_to_bigwig(bam='path/to/bam', genome='hg19', output='path/to/bigwig')
More details in this answer: Converting Bam To Bedgraph For Viewing On Ucsc?
Version of the year 2018, using the recent mosdepth tool and some custom code. Requires samtools, bc, mawk, bedGraphToBigWig (kentUtils) and a file with the chromosome sizes. Output is a per-million normalized bigwig. If you want bedGraph, just skip the bedGraphToBigWig part.
#!/bin/bash
BAM=$1
CHROMSIZES=$2
## 1. Make the depth file:
mosdepth -t 2 ${1%.bam} $1
## 2. Calculate scaling factor:
SCALE_FACTOR=$(bc <<< "scale=8;1000000/$(samtools idxstats $1 | mawk '{SUM+=$3} END {print SUM}')")
## 3. Normalize:
mawk -v SF=${SCALE_FACTOR} 'OFS="\t" {print $1, $2, $3, $4*SF}' <(bgzip -c -d ${BAM%.bam}.per-base.bed.gz) | sort -k1,1 -k2,2n > ${BAM%.bam}_norm.bedGraph.tmp
## 4. to bigwig (cannot read from stdin so far:)
bedGraphToBigWig ${BAM%.bam}_norm.bedGraph.tmp $CHROMSIZES ${BAM%.bam}_CPM.bigwig && rm ${BAM%.bam}_norm.bedGraph.tmp ${BAM%.bam}.per-base* ${BAM%.bam}*mosdepth*
Usage: ./script.sh in.bam chromSizes.txt
For a typical ChIP-seq experiment, it takes about 2' on my machine, and by this far outperforming bedtools genomecov or deeptools bamCoverage (the latter even when using a lot of cores).
As of today, you can use deeptools exactly for these kind of tasks: https://deeptools.readthedocs.io/en/latest/index.html
Log in to answer this question.