|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | + |
| 4 | +"""usage: blobtools bam2cov -i FASTA -b BAM [-h|--help] |
| 5 | + |
| 6 | + Options: |
| 7 | + -h --help show this |
| 8 | + -i, --infile FASTA FASTA file of assembly. Headers are split at whitespaces. |
| 9 | + -b, --bam <BAM> BAM file (requires samtools in $PATH) |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import division |
| 13 | +import lib.BtLog as BtLog |
| 14 | +from docopt import docopt |
| 15 | +import re |
| 16 | +import subprocess |
| 17 | +import os |
| 18 | + |
| 19 | +class Fasta(): |
| 20 | + def __init__(self, name, seq): |
| 21 | + self.name = name |
| 22 | + self.length = len(seq) |
| 23 | + self.n_count = seq.count('N') |
| 24 | + self.agct_count = self.length - self.n_count |
| 25 | + self.cov = 0.0 |
| 26 | + |
| 27 | +def which(program): |
| 28 | + def is_exe(fpath): |
| 29 | + return os.path.isfile(fpath) and os.access(fpath, os.X_OK) |
| 30 | + fpath, fname = os.path.split(program) |
| 31 | + if fpath: |
| 32 | + if is_exe(program): |
| 33 | + return program |
| 34 | + else: |
| 35 | + for path in os.environ["PATH"].split(os.pathsep): |
| 36 | + path = path.strip('"') |
| 37 | + exe_file = os.path.join(path, program) |
| 38 | + if is_exe(exe_file): |
| 39 | + return exe_file |
| 40 | + return None |
| 41 | + |
| 42 | +def runCmd(command): |
| 43 | + cmd = command.split() # sanitation |
| 44 | + p = subprocess.Popen(cmd, |
| 45 | + stdout=subprocess.PIPE, |
| 46 | + stderr=subprocess.STDOUT) |
| 47 | + return iter(p.stdout.readline, b'') |
| 48 | + |
| 49 | +def readFasta(infile): |
| 50 | + with open(infile) as fh: |
| 51 | + header, seqs = '', [] |
| 52 | + for l in fh: |
| 53 | + if l[0] == '>': |
| 54 | + if (header): |
| 55 | + yield header, ''.join(seqs) |
| 56 | + header, seqs = l[1:-1].split()[0], [] # Header is split at first whitespace |
| 57 | + else: |
| 58 | + seqs.append(l[:-1]) |
| 59 | + yield header, ''.join(seqs) |
| 60 | + |
| 61 | +def parseFasta(infile): |
| 62 | + fasta_dict = {} |
| 63 | + for name, seq in readFasta(infile): |
| 64 | + fasta = Fasta(name, seq) |
| 65 | + fasta_dict[fasta.name] = fasta |
| 66 | + return fasta_dict |
| 67 | + |
| 68 | +def checkBam(infile): |
| 69 | + print BtLog.status_d['10'] |
| 70 | + if not (which('samtools')): |
| 71 | + BtLog.error('7') |
| 72 | + reads_mapped_re = re.compile(r"(\d+)\s\+\s\d+\smapped") |
| 73 | + reads_total_re = re.compile(r"(\d+)\s\+\s\d+\sin total") |
| 74 | + reads_total, reads_mapped = 0, 0 |
| 75 | + output = '' |
| 76 | + command = "samtools flagstat " + infile |
| 77 | + for line in runCmd(command): |
| 78 | + output += line |
| 79 | + reads_mapped = int(reads_mapped_re.search(output).group(1)) |
| 80 | + reads_total = int(reads_total_re.search(output).group(1)) |
| 81 | + print BtLog.status_d['11'] % ('{:,}'.format(reads_mapped), '{:,}'.format(reads_total), '{0:.1%}'.format(reads_mapped/reads_total)) |
| 82 | + return reads_total, reads_mapped |
| 83 | + |
| 84 | +def readBam(infile, fasta_headers): |
| 85 | + reads_total, reads_mapped = checkBam(infile) |
| 86 | + progress_unit = int(int(reads_total)/1000) |
| 87 | + base_cov_dict = {} |
| 88 | + cigar_match_re = re.compile(r"(\d+)M") # only gets digits before M's |
| 89 | + # execute samtools to get only mapped reads |
| 90 | + command = "samtools view -F 4 " + infile |
| 91 | + # only one counter since only yields mapped reads |
| 92 | + parsed_reads = 0 |
| 93 | + for line in runCmd(command): |
| 94 | + match = line.split("\t") |
| 95 | + if match >= 11: |
| 96 | + seq_name = match[2] |
| 97 | + base_cov = sum([int(matching) for matching in cigar_match_re.findall(match[5])]) |
| 98 | + if (base_cov): |
| 99 | + parsed_reads += 1 |
| 100 | + if seq_name not in fasta_headers: |
| 101 | + print BtLog.warn_d['2'] % (seq_name, infile) |
| 102 | + else: |
| 103 | + base_cov_dict[seq_name] = base_cov_dict.get(seq_name, 0) + base_cov |
| 104 | + BtLog.progress(parsed_reads, progress_unit, reads_total) |
| 105 | + BtLog.progress(reads_total, progress_unit, reads_total) |
| 106 | + |
| 107 | + if not int(reads_mapped) == int(parsed_reads): |
| 108 | + print warn_d['3'] % (reads_mapped, parsed_reads) |
| 109 | + return base_cov_dict, reads_total, parsed_reads |
| 110 | + |
| 111 | +def parseBam(bam_f, fasta_dict): |
| 112 | + base_cov_dict, reads_total, reads_mapped = readBam(bam_f, set(fasta_dict.keys())) |
| 113 | + if reads_total == 0: |
| 114 | + print BtLog.warn_d['4'] % bam_f |
| 115 | + for name, base_cov in base_cov_dict.items(): |
| 116 | + fasta_dict[name].cov = base_cov / fasta_dict[name].agct_count |
| 117 | + return fasta_dict |
| 118 | + |
| 119 | +def writeCov(fasta_dict, out_f): |
| 120 | + with open(out_f, 'w') as fh: |
| 121 | + for name, fasta_obj in fasta_dict.items(): |
| 122 | + fh.write("%s\t%s\n" % (name, fasta_obj.cov)) |
| 123 | + |
| 124 | +if __name__ == '__main__': |
| 125 | + args = docopt(__doc__) |
| 126 | + |
| 127 | + fasta_f = args['--infile'] |
| 128 | + bam_f = args['--bam'] |
| 129 | + out_f = os.path.basename(bam_f) + ".cov" |
| 130 | + |
| 131 | + fasta_dict = parseFasta(fasta_f) |
| 132 | + fasta_dict = parseBam(bam_f, fasta_dict) |
| 133 | + writeCov(fasta_dict, out_f) |
| 134 | + |
0 commit comments