| 1 |
#! /usr/bin/env python3 |
| 2 |
|
| 3 |
# Copyright 2010, 2011, 2012, 2014 Martin C. Frith |
| 4 |
|
| 5 |
# Read query-genome alignments: write them along with the probability |
| 6 |
# that each alignment is not the true mapping of its query. These |
| 7 |
# probabilities make the risky assumption that one of the alignments |
| 8 |
# reported for each query is correct. |
| 9 |
|
| 10 |
from __future__ import print_function |
| 11 |
|
| 12 |
import gzip |
| 13 |
import sys, os, math, optparse, signal |
| 14 |
|
| 15 |
def myOpen(fileName): |
| 16 |
if fileName == "-": |
| 17 |
return sys.stdin |
| 18 |
if fileName.endswith(".gz"): |
| 19 |
return gzip.open(fileName, "rt") # xxx dubious for Python2 |
| 20 |
return open(fileName) |
| 21 |
|
| 22 |
def logsum(numbers, temperature): |
| 23 |
"""Adds numbers, in log space, to avoid overflow.""" |
| 24 |
m = max(numbers) / temperature |
| 25 |
s = sum(math.exp(i / temperature - m) for i in numbers) |
| 26 |
return m + math.log(s) |
| 27 |
|
| 28 |
def mafScore(aLine): |
| 29 |
for word in aLine.split(): |
| 30 |
if word.startswith("score="): |
| 31 |
return float(word[6:]) |
| 32 |
raise Exception("found an alignment without a score") |
| 33 |
|
| 34 |
def doOneBatch(lines, scores, opts, temperature): |
| 35 |
if scores: |
| 36 |
logDenominator = logsum(scores, temperature) |
| 37 |
|
| 38 |
isWanted = True |
| 39 |
i = 0 |
| 40 |
for line in lines: |
| 41 |
if line[0] == "a": |
| 42 |
s = scores[i] |
| 43 |
p = 1.0 - math.exp(s / temperature - logDenominator) |
| 44 |
i += 1 |
| 45 |
if s < opts.score or p > opts.mismap: |
| 46 |
isWanted = False |
| 47 |
else: |
| 48 |
newLineEnd = " mismap=%.3g\n" % p |
| 49 |
line = line.rstrip() + newLineEnd |
| 50 |
elif line[0].isdigit(): # we have an alignment in tabular format |
| 51 |
s = scores[i] |
| 52 |
p = 1.0 - math.exp(s / temperature - logDenominator) |
| 53 |
i += 1 |
| 54 |
if s < opts.score or p > opts.mismap: continue |
| 55 |
newLineEnd = "\tmismap=%.3g\n" % p |
| 56 |
line = line.rstrip() + newLineEnd |
| 57 |
if isWanted: print(line, end="") |
| 58 |
if line.isspace(): isWanted = True # reset at end of maf paragraph |
| 59 |
|
| 60 |
def readHeaderOrDie(lines): |
| 61 |
t = 0.0 |
| 62 |
e = -1 |
| 63 |
for line in lines: |
| 64 |
if line.startswith("#") or line.isspace(): |
| 65 |
print(line, end="") |
| 66 |
for i in line.split(): |
| 67 |
if i.startswith("t="): t = float(i[2:]) |
| 68 |
elif i.startswith("e="): e = int(i[2:]) |
| 69 |
if t > 0 and e >= 0: break |
| 70 |
else: |
| 71 |
raise Exception("I need a header with t= and e=") |
| 72 |
return t, e |
| 73 |
|
| 74 |
def doOneFile(opts, f): |
| 75 |
temperature, e = readHeaderOrDie(f) |
| 76 |
if opts.score < 0: opts.score = e + round(temperature * math.log(1000)) |
| 77 |
lines = [] |
| 78 |
scores = [] |
| 79 |
queryName = "" |
| 80 |
|
| 81 |
for line in f: |
| 82 |
if line[0] == "a": |
| 83 |
batchEnd = len(lines) |
| 84 |
score = mafScore(line) |
| 85 |
sLineCount = 0 |
| 86 |
elif line[0] == "s": |
| 87 |
sLineCount += 1 |
| 88 |
if sLineCount == 2: |
| 89 |
qName = line.split(None, 2)[1] |
| 90 |
if qName != queryName: |
| 91 |
doOneBatch(lines[:batchEnd], scores, opts, temperature) |
| 92 |
lines = lines[batchEnd:] |
| 93 |
scores = [] |
| 94 |
queryName = qName |
| 95 |
scores.append(score) |
| 96 |
elif line[0].isdigit(): # we have an alignment in tabular format |
| 97 |
fields = line.split(None, 7) |
| 98 |
qName = fields[6] |
| 99 |
if qName != queryName: |
| 100 |
doOneBatch(lines, scores, opts, temperature) |
| 101 |
lines = [] |
| 102 |
scores = [] |
| 103 |
queryName = qName |
| 104 |
scores.append(float(fields[0])) |
| 105 |
lines.append(line) |
| 106 |
|
| 107 |
doOneBatch(lines, scores, opts, temperature) |
| 108 |
|
| 109 |
def lastMapProbs(opts, args): |
| 110 |
if args: |
| 111 |
for i in args: |
| 112 |
doOneFile(opts, myOpen(i)) |
| 113 |
else: |
| 114 |
doOneFile(opts, sys.stdin) |
| 115 |
|
| 116 |
if __name__ == "__main__": |
| 117 |
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # avoid silly error message |
| 118 |
|
| 119 |
usage = """ |
| 120 |
%prog --help |
| 121 |
%prog [options] lastal-alignments""" |
| 122 |
|
| 123 |
description = "Calculate a mismap probability for each alignment. This is the probability that the alignment does not reflect the origin of the query sequence, assuming that one reported alignment does reflect the origin of each query." |
| 124 |
|
| 125 |
op = optparse.OptionParser(usage=usage, description=description) |
| 126 |
op.add_option("-m", "--mismap", type="float", default=0.01, metavar="M", |
| 127 |
help="don't write alignments with mismap probability > M (default: %default)") |
| 128 |
op.add_option("-s", "--score", type="float", default=-1, metavar="S", |
| 129 |
help="don't write alignments with score < S (default: e+t*ln[1000])") |
| 130 |
(opts, args) = op.parse_args() |
| 131 |
if not args and sys.stdin.isatty(): |
| 132 |
op.print_help() |
| 133 |
op.exit() |
| 134 |
|
| 135 |
try: lastMapProbs(opts, args) |
| 136 |
except KeyboardInterrupt: pass # avoid silly error message |
| 137 |
except Exception as e: |
| 138 |
prog = os.path.basename(sys.argv[0]) |
| 139 |
sys.exit(prog + ": error: " + str(e)) |