| 1 |
#! /usr/bin/env python3 |
| 2 |
# Author: Martin C. Frith 2014 |
| 3 |
|
| 4 |
# Read MAF-format alignments, and write those that have a segment with |
| 5 |
# score >= threshold, with gentle masking of lowercase letters. There |
| 6 |
# must be a lastal header with score parameters. |
| 7 |
|
| 8 |
# Gentle masking is described in: MC Frith, PLoS One 2011;6(12):e28819 |
| 9 |
# "Gentle masking of low-complexity sequences improves homology search" |
| 10 |
|
| 11 |
# Limitations: doesn't (yet) handle sequence quality data, |
| 12 |
# frameshifts, or generalized affine gaps. |
| 13 |
|
| 14 |
from __future__ import print_function |
| 15 |
|
| 16 |
import gzip |
| 17 |
import optparse, os, signal, sys |
| 18 |
|
| 19 |
try: |
| 20 |
from future_builtins import zip |
| 21 |
except ImportError: |
| 22 |
pass |
| 23 |
|
| 24 |
def myOpen(fileName): |
| 25 |
if fileName == "-": |
| 26 |
return sys.stdin |
| 27 |
if fileName.endswith(".gz"): |
| 28 |
return gzip.open(fileName, "rt") # xxx dubious for Python2 |
| 29 |
return open(fileName) |
| 30 |
|
| 31 |
def complement(base): |
| 32 |
x = "ACGTRYKMBDHV" |
| 33 |
y = "TGCAYRMKVHDB" |
| 34 |
i = x.find(base) |
| 35 |
return y[i] if i >= 0 else base |
| 36 |
|
| 37 |
def fastScoreMatrix(rowHeads, colHeads, matrix, deleteCost, insertCost): |
| 38 |
matrixLen = 128 |
| 39 |
defaultScore = min(map(min, matrix)) |
| 40 |
fastMatrix = [[defaultScore for i in range(matrixLen)] |
| 41 |
for j in range(matrixLen)] |
| 42 |
for i, x in enumerate(rowHeads): |
| 43 |
for j, y in enumerate(colHeads): |
| 44 |
xu = ord(x.upper()) |
| 45 |
xl = ord(x.lower()) |
| 46 |
yu = ord(y.upper()) |
| 47 |
yl = ord(y.lower()) |
| 48 |
score = matrix[i][j] |
| 49 |
maskScore = min(score, 0) |
| 50 |
fastMatrix[xu][yu] = score |
| 51 |
fastMatrix[xu][yl] = maskScore |
| 52 |
fastMatrix[xl][yu] = maskScore |
| 53 |
fastMatrix[xl][yl] = maskScore |
| 54 |
for i in range(matrixLen): |
| 55 |
fastMatrix[i][ord("-")] = -deleteCost |
| 56 |
fastMatrix[ord("-")][i] = -insertCost |
| 57 |
return fastMatrix |
| 58 |
|
| 59 |
def matrixPerStrand(rowHeads, colHeads, matrix, deleteCost, insertCost): |
| 60 |
rowComps = [complement(i) for i in rowHeads] |
| 61 |
colComps = [complement(i) for i in colHeads] |
| 62 |
fwd = fastScoreMatrix(rowHeads, colHeads, matrix, deleteCost, insertCost) |
| 63 |
rev = fastScoreMatrix(rowComps, colComps, matrix, deleteCost, insertCost) |
| 64 |
return fwd, rev |
| 65 |
|
| 66 |
def isGoodAlignment(columns, scoreMatrix, delOpenCost, insOpenCost, minScore): |
| 67 |
"""Does the alignment have a segment with score >= minScore?""" |
| 68 |
score = 0 |
| 69 |
xOld = yOld = " " |
| 70 |
for x, y in columns: |
| 71 |
score += scoreMatrix[ord(x)][ord(y)] |
| 72 |
if score >= minScore: |
| 73 |
return True |
| 74 |
if x == "-" and xOld != "-": |
| 75 |
score -= insOpenCost |
| 76 |
if y == "-" and yOld != "-": |
| 77 |
score -= delOpenCost |
| 78 |
if score < 0: |
| 79 |
score = 0 |
| 80 |
xOld = x |
| 81 |
yOld = y |
| 82 |
return False |
| 83 |
|
| 84 |
def printIfGood(maf, seqs, scoreMatrix, delOpenCost, insOpenCost, minScore): |
| 85 |
cols = zip(*seqs) |
| 86 |
if isGoodAlignment(cols, scoreMatrix, delOpenCost, insOpenCost, minScore): |
| 87 |
for line in maf: |
| 88 |
print(line, end="") |
| 89 |
print() |
| 90 |
|
| 91 |
def doOneFile(lines): |
| 92 |
aDel = bDel = aIns = bIns = minScore = matrices = None |
| 93 |
strandParam = 0 |
| 94 |
scoreMatrix = [] |
| 95 |
rowHeads = [] |
| 96 |
colHeads = [] |
| 97 |
maf = [] |
| 98 |
seqs = [] |
| 99 |
|
| 100 |
for line in lines: |
| 101 |
if line[0] == "#": |
| 102 |
print(line, end="") |
| 103 |
fields = line.split() |
| 104 |
nf = len(fields) |
| 105 |
if not colHeads: |
| 106 |
for i in fields: |
| 107 |
if i.startswith("a="): aDel = int(i[2:]) |
| 108 |
if i.startswith("b="): bDel = int(i[2:]) |
| 109 |
if i.startswith("A="): aIns = int(i[2:]) |
| 110 |
if i.startswith("B="): bIns = int(i[2:]) |
| 111 |
if i.startswith("e="): minScore = int(i[2:]) |
| 112 |
if i.startswith("S="): strandParam = int(i[2:]) |
| 113 |
if nf > 2 and max(map(len, fields)) == 1: |
| 114 |
colHeads = fields[1:] |
| 115 |
elif nf == len(colHeads) + 2 and len(fields[1]) == 1: |
| 116 |
rowHeads.append(fields[1]) |
| 117 |
scoreMatrix.append([int(i) for i in fields[2:]]) |
| 118 |
elif line.isspace(): |
| 119 |
if seqs: printIfGood(maf, seqs, matrix, aDel, aIns, minScore) |
| 120 |
maf = [] |
| 121 |
seqs = [] |
| 122 |
else: |
| 123 |
maf.append(line) |
| 124 |
if line[0] == "s": |
| 125 |
if not matrices: |
| 126 |
if None in (aDel, bDel, aIns, bIns, minScore): |
| 127 |
raise Exception("can't read alignment header") |
| 128 |
matrices = matrixPerStrand(rowHeads, colHeads, |
| 129 |
scoreMatrix, bDel, bIns) |
| 130 |
fields = line.split() |
| 131 |
seqs.append(fields[6]) |
| 132 |
if len(seqs) == 2: |
| 133 |
isReverse = (fields[4] == "-") |
| 134 |
matrix = matrices[isReverse * strandParam] |
| 135 |
if seqs: printIfGood(maf, seqs, matrix, aDel, aIns, minScore) |
| 136 |
|
| 137 |
def lastPostmask(args): |
| 138 |
if not args: |
| 139 |
args = ["-"] |
| 140 |
for i in args: |
| 141 |
f = myOpen(i) |
| 142 |
doOneFile(f) |
| 143 |
f.close() |
| 144 |
|
| 145 |
if __name__ == "__main__": |
| 146 |
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # avoid silly error message |
| 147 |
|
| 148 |
usage = "%prog in.maf > out.maf" |
| 149 |
description = "Get alignments that have a segment with score >= threshold, with gentle masking of lowercase letters." |
| 150 |
op = optparse.OptionParser(usage=usage, description=description) |
| 151 |
(opts, args) = op.parse_args() |
| 152 |
|
| 153 |
try: lastPostmask(args) |
| 154 |
except KeyboardInterrupt: pass # avoid silly error message |
| 155 |
except Exception as e: |
| 156 |
prog = os.path.basename(sys.argv[0]) |
| 157 |
sys.exit(prog + ": error: " + str(e)) |