| 1 |
#! /usr/bin/env python3 |
| 2 |
# Author: Martin C. Frith |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
# Read MAF-format alignments, and write them, after moving the Nth |
| 6 |
# sequence to the top in each alignment. |
| 7 |
|
| 8 |
# Before writing, if the top sequence would be on the - strand, then |
| 9 |
# flip all the strands. But don't do this if the top sequence is |
| 10 |
# translated DNA. |
| 11 |
|
| 12 |
from __future__ import print_function |
| 13 |
|
| 14 |
import gzip |
| 15 |
import itertools |
| 16 |
import optparse |
| 17 |
import os |
| 18 |
import signal |
| 19 |
import sys |
| 20 |
|
| 21 |
try: |
| 22 |
maketrans = str.maketrans |
| 23 |
except AttributeError: |
| 24 |
from string import maketrans |
| 25 |
|
| 26 |
def myOpen(fileName): |
| 27 |
if fileName == "-": |
| 28 |
return sys.stdin |
| 29 |
if fileName.endswith(".gz"): |
| 30 |
return gzip.open(fileName, "rt") # xxx dubious for Python2 |
| 31 |
return open(fileName) |
| 32 |
|
| 33 |
def indexOfNthSequence(mafLines, n): |
| 34 |
for i, line in enumerate(mafLines): |
| 35 |
if line[0] == "s": |
| 36 |
if n == 1: return i |
| 37 |
n -= 1 |
| 38 |
raise Exception("encountered an alignment with too few sequences") |
| 39 |
|
| 40 |
def rangeOfNthSequence(mafLines, n): |
| 41 |
"""Get the range of lines associated with the Nth sequence.""" |
| 42 |
start = indexOfNthSequence(mafLines, n) |
| 43 |
stop = start + 1 |
| 44 |
while stop < len(mafLines): |
| 45 |
line = mafLines[stop] |
| 46 |
if line[0] not in "qi": break |
| 47 |
stop += 1 |
| 48 |
return start, stop |
| 49 |
|
| 50 |
complement = maketrans('ACGTNSWRYKMBDHVacgtnswrykmbdhv', |
| 51 |
'TGCANSWYRMKVHDBtgcanswyrmkvhdb') |
| 52 |
# doesn't handle "U" in RNA sequences |
| 53 |
def revcomp(seq): |
| 54 |
return seq[::-1].translate(complement) |
| 55 |
|
| 56 |
def flippedMafRecords(mafLines): |
| 57 |
for line in mafLines: |
| 58 |
words = line.split() |
| 59 |
if words[0] == "s": |
| 60 |
s, name, start, span, strand, seqlen, alnString = words |
| 61 |
newStart = str(int(seqlen) - int(start) - int(span)) |
| 62 |
newStrand = "+-"[strand == "+"] |
| 63 |
newString = revcomp(alnString) |
| 64 |
yield [s, name, newStart, span, newStrand, seqlen, newString] |
| 65 |
elif words[0] == "p": |
| 66 |
yield words[:1] + [words[1][::-1]] |
| 67 |
elif words[0] == "q": |
| 68 |
yield words[:2] + [words[2][::-1]] |
| 69 |
else: |
| 70 |
yield words |
| 71 |
|
| 72 |
def sLineFieldWidths(mafLines): |
| 73 |
sLines = (i for i in mafLines if i[0] == "s") |
| 74 |
sColumns = zip(*sLines) |
| 75 |
for i in sColumns: |
| 76 |
yield max(map(len, i)) |
| 77 |
|
| 78 |
def joinedMafS(fieldWidths, words): |
| 79 |
formatParams = itertools.chain.from_iterable(zip(fieldWidths, words)) |
| 80 |
return "%*s %-*s %*s %*s %*s %*s %*s\n" % tuple(formatParams) |
| 81 |
|
| 82 |
def joinedMafLine(words, fieldWidths): |
| 83 |
if words[0] == "s": |
| 84 |
return joinedMafS(fieldWidths, words) |
| 85 |
elif words[0] == "q": |
| 86 |
words = words[:2] + [""] * 4 + words[2:] |
| 87 |
return joinedMafS(fieldWidths, words) |
| 88 |
elif words[0] == "p": |
| 89 |
words = words[:1] + [""] * 5 + words[1:] |
| 90 |
return joinedMafS(fieldWidths, words) |
| 91 |
else: |
| 92 |
return " ".join(words) + "\n" |
| 93 |
|
| 94 |
def flippedMaf(mafLines): |
| 95 |
flippedLines = list(flippedMafRecords(mafLines)) |
| 96 |
fieldWidths = list(sLineFieldWidths(flippedLines)) |
| 97 |
return (joinedMafLine(i, fieldWidths) for i in flippedLines) |
| 98 |
|
| 99 |
def isCanonicalStrand(mafLines): |
| 100 |
sLine1 = mafLines[1] |
| 101 |
words = sLine1.split() |
| 102 |
strand = words[4] |
| 103 |
if strand == "+": return True |
| 104 |
alnString = words[6] |
| 105 |
if "/" in alnString or "\\" in alnString: return True # frameshifts |
| 106 |
alnSize = int(words[3]) |
| 107 |
gapCount = alnString.count("-") |
| 108 |
if len(alnString) - gapCount < alnSize: return True # translated DNA |
| 109 |
sLine2 = mafLines[indexOfNthSequence(mafLines, 2)] |
| 110 |
words2 = sLine2.split() |
| 111 |
alnSize2 = int(words2[3]) |
| 112 |
alnString2 = words2[6] |
| 113 |
if len(alnString2) - alnString2.count("-") > alnSize2: |
| 114 |
return True # 3-letter amino acids |
| 115 |
return False |
| 116 |
|
| 117 |
def swapOneMaf(opts, mafLines): |
| 118 |
start, stop = rangeOfNthSequence(mafLines, opts.n) |
| 119 |
mafLines[1:stop] = mafLines[start:stop] + mafLines[1:start] |
| 120 |
if not isCanonicalStrand(mafLines): |
| 121 |
mafLines = flippedMaf(mafLines) |
| 122 |
for i in mafLines: |
| 123 |
print(i, end="") |
| 124 |
print() # blank line after each alignment |
| 125 |
|
| 126 |
def mafSwap(opts, args): |
| 127 |
if not args: |
| 128 |
args = ["-"] |
| 129 |
for fileName in args: |
| 130 |
inputLines = myOpen(fileName) |
| 131 |
mafLines = [] |
| 132 |
for line in inputLines: |
| 133 |
if line[0] == "#": |
| 134 |
print(line, end="") |
| 135 |
elif line.isspace(): |
| 136 |
if mafLines: |
| 137 |
swapOneMaf(opts, mafLines) |
| 138 |
mafLines = [] |
| 139 |
else: |
| 140 |
mafLines.append(line) |
| 141 |
if mafLines: |
| 142 |
swapOneMaf(opts, mafLines) |
| 143 |
|
| 144 |
if __name__ == "__main__": |
| 145 |
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # avoid silly error message |
| 146 |
|
| 147 |
usage = "%prog [options] my-alignments.maf" |
| 148 |
description = "Change the order of sequences in MAF-format alignments." |
| 149 |
op = optparse.OptionParser(usage=usage, description=description) |
| 150 |
op.add_option("-n", type="int", default=2, |
| 151 |
help="move the Nth sequence to the top (default: %default)") |
| 152 |
(opts, args) = op.parse_args() |
| 153 |
if opts.n < 1: op.error("option -n: should be >= 1") |
| 154 |
|
| 155 |
try: mafSwap(opts, args) |
| 156 |
except KeyboardInterrupt: pass # avoid silly error message |
| 157 |
except Exception as e: |
| 158 |
prog = os.path.basename(sys.argv[0]) |
| 159 |
sys.exit(prog + ": error: " + str(e)) |