| 1 |
#! /usr/bin/env python3 |
| 2 |
# Author: Martin C. Frith 2018 |
| 3 |
|
| 4 |
from __future__ import print_function |
| 5 |
|
| 6 |
import argparse |
| 7 |
import collections |
| 8 |
import gzip |
| 9 |
import itertools |
| 10 |
import signal |
| 11 |
import sys |
| 12 |
|
| 13 |
def myOpen(fileName): # faster than fileinput |
| 14 |
if fileName == "-": |
| 15 |
return sys.stdin |
| 16 |
if fileName.endswith(".gz"): |
| 17 |
return gzip.open(fileName, "rt") # xxx dubious for Python2 |
| 18 |
return open(fileName) |
| 19 |
|
| 20 |
def alnBegFromSeqBeg(gappedSequence, seqBeg): |
| 21 |
for i, x in enumerate(gappedSequence): |
| 22 |
if x != "-": |
| 23 |
if seqBeg == 0: |
| 24 |
return i |
| 25 |
seqBeg -= 1 |
| 26 |
|
| 27 |
def alnEndFromSeqEnd(gappedSequence, seqEnd): |
| 28 |
for i, x in enumerate(gappedSequence): |
| 29 |
if x != "-": |
| 30 |
seqEnd -= 1 |
| 31 |
if seqEnd == 0: |
| 32 |
return i + 1 |
| 33 |
|
| 34 |
def alignmentRange(cutBeg, cutEnd, sLineFields): |
| 35 |
if sLineFields[4] == "-": |
| 36 |
seqLen = int(sLineFields[5]) |
| 37 |
cutBeg, cutEnd = seqLen - cutEnd, seqLen - cutBeg |
| 38 |
beg = int(sLineFields[2]) |
| 39 |
if beg >= cutEnd: |
| 40 |
return 0, 0 |
| 41 |
span = int(sLineFields[3]) |
| 42 |
end = beg + span |
| 43 |
if end <= cutBeg: |
| 44 |
return 0, 0 |
| 45 |
sequenceWithGaps = sLineFields[6] |
| 46 |
monomerLen = (len(sequenceWithGaps) - sequenceWithGaps.count("-")) // span |
| 47 |
seqBeg = max(cutBeg - beg, 0) * monomerLen |
| 48 |
alnBeg = alnBegFromSeqBeg(sequenceWithGaps, seqBeg) |
| 49 |
seqEnd = min(cutEnd - beg, span) * monomerLen |
| 50 |
alnEnd = alnEndFromSeqEnd(sequenceWithGaps, seqEnd) |
| 51 |
return alnBeg, alnEnd |
| 52 |
|
| 53 |
def findTheSpecifiedSequence(seqName, mafLines): |
| 54 |
for line in mafLines: |
| 55 |
if line[0] == "s": |
| 56 |
fields = line.split() |
| 57 |
if seqName is None or fields[1] == seqName: |
| 58 |
return fields |
| 59 |
return None |
| 60 |
|
| 61 |
def sLineCutData(fields, alnBeg, alnEnd): |
| 62 |
span = int(fields[3]) |
| 63 |
seq = fields[6] |
| 64 |
n = len(seq) |
| 65 |
begSpan = alnBeg - seq.count("-", 0, alnBeg) |
| 66 |
endSpan = n - alnEnd - seq.count("-", alnEnd, n) |
| 67 |
mul = (n - seq.count("-")) // span |
| 68 |
b = begSpan // mul |
| 69 |
e = endSpan // mul |
| 70 |
return int(fields[2]) + b, span - b - e, begSpan % mul, endSpan % mul |
| 71 |
|
| 72 |
def addMafData(dataPerSeq, mafLines, alnBeg, alnEnd): |
| 73 |
for line in mafLines: |
| 74 |
if line[0] == "s": |
| 75 |
fields = line.split() |
| 76 |
seqName = fields[1] # xxx omit theSpecifiedSequence ? |
| 77 |
strand = fields[4] |
| 78 |
seqLen = int(fields[5]) |
| 79 |
beg, span, begRem, endRem = sLineCutData(fields, alnBeg, alnEnd) |
| 80 |
alnBeg -= begRem |
| 81 |
alnEnd += endRem |
| 82 |
end = beg + span |
| 83 |
if strand == "-": |
| 84 |
beg, end = seqLen - end, seqLen - beg |
| 85 |
seqData = seqLen, beg, end |
| 86 |
dataPerSeq[seqName].append(seqData) |
| 87 |
|
| 88 |
def cutMafRecords(mafLines, alnBeg, alnEnd): |
| 89 |
for line in mafLines: |
| 90 |
fields = line.split() |
| 91 |
if line[0] == "s": |
| 92 |
beg, span, begRem, endRem = sLineCutData(fields, alnBeg, alnEnd) |
| 93 |
alnBeg -= begRem |
| 94 |
alnEnd += endRem |
| 95 |
newSeq = fields[6][alnBeg:alnEnd] |
| 96 |
yield fields[:2] + [str(beg), str(span)] + fields[4:6] + [newSeq] |
| 97 |
elif line[0] == "q": |
| 98 |
yield fields[:2] + [fields[2][alnBeg:alnEnd]] |
| 99 |
elif line[0] == "p": |
| 100 |
yield fields[:1] + [fields[1][alnBeg:alnEnd]] |
| 101 |
else: |
| 102 |
yield fields |
| 103 |
|
| 104 |
def mafFieldWidths(mafRecords): |
| 105 |
sRecords = (i for i in mafRecords if i[0] == "s") |
| 106 |
sColumns = zip(*sRecords) |
| 107 |
for i in sColumns: |
| 108 |
yield max(map(len, i)) |
| 109 |
|
| 110 |
def printMafLine(fieldWidths, fields): |
| 111 |
formatParams = itertools.chain.from_iterable(zip(fieldWidths, fields)) |
| 112 |
print("%*s %-*s %*s %*s %*s %*s %*s" % tuple(formatParams)) |
| 113 |
|
| 114 |
def printOneMaf(mafRecords): |
| 115 |
fieldWidths = list(mafFieldWidths(mafRecords)) |
| 116 |
for fields in mafRecords: |
| 117 |
if fields[0] == "s": |
| 118 |
printMafLine(fieldWidths, fields) |
| 119 |
elif fields[0] == "q": |
| 120 |
printMafLine(fieldWidths, fields[:2] + [""] * 4 + fields[2:]) |
| 121 |
elif fields[0] == "p": |
| 122 |
printMafLine(fieldWidths, fields[:1] + [""] * 5 + fields[1:]) |
| 123 |
else: |
| 124 |
print(" ".join(fields)) |
| 125 |
print() |
| 126 |
|
| 127 |
def nameFromTitleLine(line): |
| 128 |
return line[1:].split()[0] |
| 129 |
|
| 130 |
def doOneFastaSequence(dataPerSeq, topLine, seqLines): |
| 131 |
alnData = dataPerSeq.get(nameFromTitleLine(topLine)) |
| 132 |
if alnData: |
| 133 |
seq = "".join(i.rstrip() for i in seqLines) |
| 134 |
seqLen = len(seq) |
| 135 |
alnData = [i for i in alnData if i[0] == seqLen] |
| 136 |
if alnData: |
| 137 |
beg = min(i[1] for i in alnData) |
| 138 |
end = max(i[2] for i in alnData) |
| 139 |
print(topLine, end="") |
| 140 |
print(seq[beg:end]) |
| 141 |
|
| 142 |
def doOneFastqSequence(dataPerSeq, lines): |
| 143 |
alnData = dataPerSeq.get(nameFromTitleLine(lines[0])) |
| 144 |
if alnData: |
| 145 |
seqLen = len(lines[1].rstrip()) |
| 146 |
alnData = [i for i in alnData if i[0] == seqLen] |
| 147 |
if alnData: |
| 148 |
beg = min(i[1] for i in alnData) |
| 149 |
end = max(i[2] for i in alnData) |
| 150 |
print(lines[0], end="") |
| 151 |
print(lines[1][beg:end]) |
| 152 |
print(lines[2], end="") |
| 153 |
print(lines[3][beg:end]) |
| 154 |
|
| 155 |
def printFastaParts(dataPerSeq, topLine, lines): |
| 156 |
seqLines = [] |
| 157 |
for line in lines: |
| 158 |
if line[0] == ">": |
| 159 |
doOneFastaSequence(dataPerSeq, topLine, seqLines) |
| 160 |
topLine = line |
| 161 |
seqLines = [] |
| 162 |
else: |
| 163 |
seqLines.append(line) |
| 164 |
doOneFastaSequence(dataPerSeq, topLine, seqLines) |
| 165 |
|
| 166 |
def printFastqParts(dataPerSeq, topLine, lines): |
| 167 |
b = [topLine] |
| 168 |
for i, x in enumerate(lines): |
| 169 |
b.append(x) |
| 170 |
if i % 4 == 2: |
| 171 |
doOneFastqSequence(dataPerSeq, b) |
| 172 |
b = [] |
| 173 |
|
| 174 |
def printSequenceParts(dataPerSeq, lines): |
| 175 |
for line in lines: |
| 176 |
if line[0] == ">": |
| 177 |
printFastaParts(dataPerSeq, line, lines) |
| 178 |
elif line[0] == "@": |
| 179 |
printFastqParts(dataPerSeq, line, lines) |
| 180 |
else: |
| 181 |
raise RuntimeError("can't read the sequence data") |
| 182 |
break |
| 183 |
|
| 184 |
def cutOneMaf(seqName, cutBeg, cutEnd, dataPerSeq, mafLines): |
| 185 |
sLineFields = findTheSpecifiedSequence(seqName, mafLines) |
| 186 |
if not sLineFields: |
| 187 |
return |
| 188 |
alnBeg, alnEnd = alignmentRange(cutBeg, cutEnd, sLineFields) |
| 189 |
if alnBeg >= alnEnd: |
| 190 |
return |
| 191 |
if dataPerSeq is None: |
| 192 |
mafRecords = list(cutMafRecords(mafLines, alnBeg, alnEnd)) |
| 193 |
printOneMaf(mafRecords) |
| 194 |
else: |
| 195 |
addMafData(dataPerSeq, mafLines, alnBeg, alnEnd) |
| 196 |
|
| 197 |
def wantedRange(cutSpecification): |
| 198 |
seqName = None |
| 199 |
s = cutSpecification.split() |
| 200 |
if len(s) == 3: |
| 201 |
seqName, beg, end = s |
| 202 |
elif len(s) == 2: |
| 203 |
beg, end = s |
| 204 |
else: |
| 205 |
if ":" in cutSpecification: |
| 206 |
seqName, cutSpecification = cutSpecification.rsplit(":", 1) |
| 207 |
beg, end = cutSpecification.rsplit("-", 1) |
| 208 |
return seqName, int(beg), int(end) |
| 209 |
|
| 210 |
def mafCut(args): |
| 211 |
seqName, cutBeg, cutEnd = wantedRange(args.segment) |
| 212 |
dataPerSeq = collections.defaultdict(list) if args.sequences else None |
| 213 |
|
| 214 |
mafLines = [] |
| 215 |
for line in myOpen(args.alignments): |
| 216 |
if line.isspace(): |
| 217 |
cutOneMaf(seqName, cutBeg, cutEnd, dataPerSeq, mafLines) |
| 218 |
mafLines = [] |
| 219 |
elif line[0] != "#": |
| 220 |
mafLines.append(line) |
| 221 |
cutOneMaf(seqName, cutBeg, cutEnd, dataPerSeq, mafLines) |
| 222 |
|
| 223 |
if dataPerSeq: |
| 224 |
for fileName in args.sequences: |
| 225 |
printSequenceParts(dataPerSeq, myOpen(fileName)) |
| 226 |
|
| 227 |
if __name__ == "__main__": |
| 228 |
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # avoid silly error message |
| 229 |
description = "Get parts of MAF-format alignments." |
| 230 |
ap = argparse.ArgumentParser(description=description) |
| 231 |
ap.add_argument("segment", |
| 232 |
help="zero-based sequence range, e.g. chr7:123400-123500") |
| 233 |
ap.add_argument("alignments", nargs="?", default="-", |
| 234 |
help="file of sequence alignments in MAF format") |
| 235 |
ap.add_argument("sequences", nargs="*", default=None, # xxx need default? |
| 236 |
help="file of sequences in fasta or fastq format") |
| 237 |
args = ap.parse_args() |
| 238 |
mafCut(args) |