Debian Codegraph @

bin/maf-convert

raw
1 #! /usr/bin/env python3
2 # Copyright 2010, 2011, 2013, 2014 Martin C. Frith
3 # SPDX-License-Identifier: GPL-3.0-or-later
4 # Seems to work with Python 2.x, x>=6
5
6 # By "MAF" we mean "multiple alignment format" described in the UCSC
7 # Genome FAQ, not e.g. "MIRA assembly format".
8
9 from __future__ import print_function
10
11 from itertools import *
12 import collections
13 import functools
14 import gzip
15 import logging
16 import math
17 import operator
18 import optparse
19 import os
20 import signal
21 import sys
22
23 try:
24 from future_builtins import map, zip
25 except ImportError:
26 pass
27
28 aminoAcidCodes = {"ALA": "A",
29 "CYS": "C",
30 "ASP": "D",
31 "GLU": "E",
32 "PHE": "F",
33 "GLY": "G",
34 "HIS": "H",
35 "ILE": "I",
36 "LYS": "K",
37 "LEU": "L",
38 "MET": "M",
39 "ASN": "N",
40 "PRO": "P",
41 "GLN": "Q",
42 "ARG": "R",
43 "SER": "S",
44 "THR": "T",
45 "VAL": "V",
46 "TRP": "W",
47 "TYR": "Y",
48 "***": "*",
49 "XAA": "X"}
50
51 ambiguousBases = {"R": "AG",
52 "Y": "CT",
53 "S": "CG",
54 "W": "AT",
55 "K": "GT",
56 "M": "AC",
57 "B": "CGT",
58 "D": "AGT",
59 "H": "ACT",
60 "V": "ACG",
61 "N": "ACGT"}
62
63 def standardGeneticCode():
64 aa = "FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG"
65 b1 = "TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG"
66 b2 = "TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG"
67 b3 = "TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG"
68 return {x + y + z: a for a, x, y, z in zip(aa, b1, b2, b3)}
69
70 def myOpen(fileName):
71 if fileName == "-":
72 return sys.stdin
73 if fileName.endswith(".gz"):
74 return gzip.open(fileName, "rt") # xxx dubious for Python2
75 return open(fileName)
76
77 def maxlen(s):
78 return max(map(len, s))
79
80 complementLookup = bytearray(range(128))
81 for x, y in zip("ACGTRYKMBDHVU",
82 "TGCAYRMKVHDBA"):
83 complementLookup[ord(x.upper())] = ord(y.upper())
84 complementLookup[ord(x.lower())] = ord(y.lower())
85 def revcomp(seq):
86 return "".join(chr(complementLookup[ord(i)]) for i in reversed(seq))
87
88 def pairOrDie(sLines, formatName):
89 if len(sLines) != 2:
90 e = "for %s, each alignment must have 2 sequences" % formatName
91 raise RuntimeError(e)
92 return sLines
93
94 def isMatch(alignmentColumn):
95 # No special treatment of ambiguous bases/residues: same as NCBI BLAST.
96 first = alignmentColumn[0].upper()
97 for i in alignmentColumn[1:]:
98 if i.upper() != first: return False
99 return True
100
101 def gapRunCount(row):
102 """Get the number of runs of gap characters."""
103 return sum(k == "-" for k, v in groupby(row))
104
105 def alignmentRowsFromColumns(columns):
106 return map(''.join, zip(*columns))
107
108 def symbolSize(symbol, letterSize):
109 if symbol == "\\": return 1
110 if symbol == "/": return -1
111 return letterSize
112
113 def insertSize(row, letterSize):
114 """Get the length of sequence included in the row."""
115 x = len(row) - row.count("-")
116 if letterSize:
117 return x * letterSize - 4 * row.count("/") - 2 * row.count("\\")
118 return x // 3 # assume it's divisible by 3
119
120 def matchAndInsertSizes(alignmentColumns, letterSizes):
121 """Get sizes of gapless blocks, and of the inserts between them."""
122 letterSizeA, letterSizeB = letterSizes
123 delInc = max(letterSizeA, 1)
124 delDiv = 1 if letterSizeA else 3
125 insInc = max(letterSizeB, 1)
126 insDiv = 1 if letterSizeB else 3
127 sizeDiv = max(delDiv, insDiv)
128 delSize = insSize = subSize = 0
129 for x, y in alignmentColumns:
130 if x == "-":
131 if subSize:
132 if delSize or insSize:
133 yield str(delSize // delDiv) + ":" + str(insSize // insDiv)
134 yield str(subSize // sizeDiv)
135 delSize = insSize = subSize = 0
136 insSize += symbolSize(y, insInc)
137 elif y == "-":
138 if subSize:
139 if delSize or insSize:
140 yield str(delSize // delDiv) + ":" + str(insSize // insDiv)
141 yield str(subSize // sizeDiv)
142 delSize = insSize = subSize = 0
143 delSize += symbolSize(x, delInc)
144 else:
145 subSize += 1
146 if delSize or insSize:
147 yield str(delSize // delDiv) + ":" + str(insSize // insDiv)
148 if subSize:
149 yield str(subSize // sizeDiv)
150
151 ##### Routines for reading MAF format: #####
152
153 def updateEvalueParameters(opts, fields):
154 for field in fields:
155 try:
156 k, v = field.split("=")
157 x = float(v)
158 if k == "lambda":
159 opts.bitScoreA = x / math.log(2)
160 if k == "K":
161 opts.bitScoreB = math.log(x, 2)
162 except ValueError:
163 pass
164
165 def scoreAndEvalue(aLine):
166 score = evalue = None
167 for i in aLine.split():
168 if i.startswith("score="):
169 score = i[6:]
170 elif i.startswith("E="):
171 evalue = i[2:]
172 return score, evalue
173
174 def mafInput(opts, lines):
175 opts.scoreMatrix = {}
176 matrixColumnNames = []
177 aLine = ""
178 sLines = []
179 qLines = []
180 pLines = []
181 for line in lines:
182 if line[0] == "s":
183 junk, seqName, beg, span, strand, seqLen, row = line.split()
184 beg = int(beg)
185 span = int(span)
186 seqLen = int(seqLen)
187 rowLetters = len(row) - row.count("-")
188 if "\\" in row or "/" in row or rowLetters < span:
189 letterSize = 3
190 elif rowLetters > span:
191 letterSize = 0 # xxx means 3-letter codes like AlaCysAsp
192 else:
193 letterSize = 1
194 fields = seqName, seqLen, strand, letterSize, beg, beg + span, row
195 sLines.append(fields)
196 elif line[0] == "a":
197 aLine = line
198 opts.headerMode &= 1
199 elif line[0] == "q":
200 qLines.append(line)
201 elif line[0] == "p":
202 pLines.append(line)
203 elif line.isspace():
204 if sLines: yield aLine, sLines, qLines, pLines
205 aLine = ""
206 sLines = []
207 qLines = []
208 pLines = []
209 elif line[0] == "#":
210 fields = line.split()
211 updateEvalueParameters(opts, fields)
212 if len(fields) == 65 and all(len(i) == 3 for i in fields[1:]):
213 matrixColumnNames = [i.upper() for i in fields[1:]]
214 if len(fields) == 66 and len(fields[1]) == 1:
215 r = fields[1].upper()
216 for c, x in zip(matrixColumnNames, fields[2:]):
217 opts.scoreMatrix[r, c] = int(x)
218 if opts.headerMode == 1:
219 print(line, end="")
220 if opts.headerMode == 2 and line.startswith("# LAST version "):
221 print("@PG\tID:lastal\tPN:lastal\tVN:" + fields[3])
222 if sLines: yield aLine, sLines, qLines, pLines
223
224 def isJoinable(opts, isTouchingInQuery, oldMaf, newMaf):
225 x = oldMaf[1]
226 y = newMaf[1]
227 if x[-1][2] == "-":
228 x, y = y, x
229 if isTouchingInQuery and x[1][5] < y[1][4]:
230 return False
231 return all(i[:4] == j[:4] and i[5] <= j[4] and j[4] - i[5] <= opts.join
232 for i, j in zip(x, y))
233
234 def fixOrder(mafs):
235 sLines = mafs[0][1]
236 if sLines[-1][2] == "-":
237 mafs.reverse()
238
239 def mafGroupInput(opts, isTouchingInQuery, lines):
240 x = []
241 for i in mafInput(opts, lines):
242 if x and not isJoinable(opts, isTouchingInQuery, x[-1], i):
243 fixOrder(x)
244 yield x
245 x = []
246 x.append(i)
247 if x:
248 fixOrder(x)
249 yield x
250
251 def linkedMafBegSortKey(sequenceNumber, mafAndLinks):
252 return operator.itemgetter(0, 2, 4)(mafAndLinks[0][1][sequenceNumber])
253
254 def colinearMafInput(opts, lines):
255 mafs = list(mafInput(opts, lines))
256 if not mafs:
257 return
258 numOfSeqs = max(len(maf[1]) for maf in mafs)
259 linkedMafs = [(maf, [None] * numOfSeqs) for maf in mafs]
260 for s in range(numOfSeqs):
261 begFunc = functools.partial(linkedMafBegSortKey, s)
262 linkedMafs.sort(key=begFunc)
263 maxEnd = "", "+", 0
264 for j in range(1, len(linkedMafs)):
265 xMaf, xLinks = linkedMafs[j - 1]
266 yMaf, yLinks = linkedMafs[j]
267 x = xMaf[1][s]
268 y = yMaf[1][s]
269 newEnd = x[0], x[2], x[5]
270 if newEnd > maxEnd:
271 maxEnd = newEnd
272 if (x[:4] == y[:4] and 0 <= y[4] - x[5] <= opts.Join):
273 k = j + 1
274 yBeg = y[0], y[2], y[4]
275 if k == len(linkedMafs) or yBeg < begFunc(linkedMafs[k]):
276 yLinks[s] = xMaf
277 colinearMafs = []
278 for maf, links in linkedMafs:
279 if colinearMafs:
280 if any(i is not colinearMafs[-1] for i in links):
281 yield colinearMafs
282 colinearMafs = []
283 colinearMafs.append(maf)
284 yield colinearMafs
285
286 ##### Routines for converting to AXT format: #####
287
288 def sLineFlipped(seqName, seqLen, strand, letterSize, beg, end, row):
289 strand = "+-"[strand == "+"]
290 row = revcomp(row)
291 return seqName, seqLen, strand, letterSize, seqLen - end, seqLen - beg, row
292
293 axtCounter = count()
294
295 def writeAxt(maf):
296 aLine, sLines, qLines, pLines = maf
297
298 if sLines[0][2] != "+":
299 sLines = [sLineFlipped(*i) for i in sLines]
300
301 # Convert to AXT's 1-based coordinates:
302 ranges = [(i[0], str(i[4] + 1), str(i[5]), i[2]) for i in sLines]
303
304 head, body = ranges[0], ranges[1:]
305
306 outWords = [str(next(axtCounter))]
307 outWords.extend(head[:3])
308 for i in body:
309 outWords.extend(i)
310
311 score, evalue = scoreAndEvalue(aLine)
312 if score:
313 outWords.append(score)
314
315 print(*outWords)
316 for i in sLines:
317 print(i[6])
318 print() # print a blank line at the end
319
320 def mafConvertToAxt(opts, lines):
321 for maf in mafInput(opts, lines):
322 writeAxt(maf)
323
324 ##### Routines for converting to tabular format: #####
325
326 def writeTab(maf):
327 aLine, sLines, qLines, pLines = maf
328
329 score = "0"
330 endWords = []
331 for i in aLine.split():
332 if i.startswith("score="):
333 score = i[6:]
334 elif len(i) > 1:
335 endWords.append(i)
336
337 outWords = [score]
338
339 for seqName, seqLen, strand, letterSize, beg, end, row in sLines:
340 x = seqName, str(beg), str(end - beg), strand, str(seqLen)
341 outWords.extend(x)
342
343 letterSizes = [i[3] for i in sLines]
344 rows = [i[6] for i in sLines]
345 alignmentColumns = zip(*rows)
346 gapWord = ",".join(matchAndInsertSizes(alignmentColumns, letterSizes))
347 outWords.append(gapWord)
348
349 print("\t".join(outWords + endWords))
350
351 def mafConvertToTab(opts, lines):
352 for maf in mafInput(opts, lines):
353 writeTab(maf)
354
355 ##### Routines for converting to chain format: #####
356
357 def writeChain(maf):
358 aLine, sLines, qLines, pLines = maf
359
360 score = "0"
361 for i in aLine.split():
362 if i.startswith("score="):
363 score = i[6:]
364
365 outWords = ["chain", score]
366
367 for seqName, seqLen, strand, letterSize, beg, end, row in sLines:
368 x = seqName, str(seqLen), strand, str(beg), str(end)
369 outWords.extend(x)
370
371 outWords.append(str(next(axtCounter) + 1))
372
373 print(*outWords)
374
375 letterSizes = [i[3] for i in sLines]
376 rows = [i[6] for i in sLines]
377 alignmentColumns = zip(*rows)
378 size = "0"
379 for i in matchAndInsertSizes(alignmentColumns, letterSizes):
380 if ":" in i:
381 print(size + "\t" + i.replace(":", "\t"))
382 size = "0"
383 else:
384 size = i
385 print(size)
386 print()
387
388 def mafConvertToChain(opts, lines):
389 for maf in mafInput(opts, lines):
390 writeChain(maf)
391
392 ##### Routines for converting to BED format: #####
393
394 def bedBlocksFromMafs(mafs, ref):
395 for i, x in enumerate(mafs):
396 beg, end = x[1][ref][4:6]
397 if not i:
398 origin = beg
399 yield end - beg, beg - origin
400
401 def writeBed(opts, mafs):
402 headLines = mafs[0][1]
403 tailLines = mafs[-1][1]
404
405 if opts.subject:
406 ref = opts.subject - 1
407 elif len(headLines) > 1 and headLines[0][3] < headLines[1][3]:
408 ref = 1 # protein-to-DNA alignment
409 else:
410 ref = 0
411
412 if len(headLines) <= ref:
413 raise RuntimeError("alignment has too few sequences")
414
415 qry = 0 if ref > 0 else 1
416 qryName = headLines[qry][0] if len(headLines) > qry else "."
417 qryStrand = headLines[qry][2] if len(headLines) > qry else "+"
418
419 seqName, seqLen, strand, junk, beg = headLines[ref][:5]
420 end = tailLines[ref][5]
421 blocks = list(bedBlocksFromMafs(mafs, ref))
422
423 if strand == "-":
424 beg, end = seqLen - end, seqLen - beg
425 origin = sum(blocks[-1])
426 blocks = [(s, origin - b - s) for s, b in reversed(blocks)]
427
428 outStrand = "+" if qryStrand == strand else "-"
429 blockLens = ",".join(str(i[0]) for i in blocks)
430 blockBegs = ",".join(str(i[1]) for i in blocks)
431 print(seqName, beg, end, qryName, 0, outStrand, beg, beg, 0,
432 len(blocks), blockLens, blockBegs, sep="\t")
433
434 def mafConvertToBed(opts, lines):
435 if opts.Join:
436 for i in colinearMafInput(opts, lines):
437 writeBed(opts, i)
438 elif opts.join:
439 for i in mafGroupInput(opts, False, lines):
440 writeBed(opts, i)
441 else:
442 for i in mafInput(opts, lines):
443 writeBed(opts, [i])
444
445 ##### Routines for converting to PSL format: #####
446
447 def pslBlocks(opts, geneticCode, mafs, outCounts):
448 """Get sizes and start coordinates of gapless blocks in an alignment."""
449 # repMatches is always zero
450 # for proteins, nCount is always zero, because that's what BLATv34 does
451 normalBases = "ACGTU"
452 mismatches = repMatches = nCount = 0
453
454 for maf in mafs:
455 sLines = maf[1]
456 fieldsA, fieldsB = pairOrDie(sLines, "PSL")
457 letterSizeA, begA, endA, rowA = fieldsA[3:7]
458 letterSizeB, begB, endB, rowB = fieldsB[3:7]
459 rowA = rowA.upper()
460 rowB = rowB.upper()
461
462 if letterSizeA * letterSizeB < 1:
463 letterSpanA = 3 - letterSizeA * 2
464 letterSpanB = 3 - letterSizeB * 2
465 codeA = geneticCode if letterSizeA else aminoAcidCodes
466 codeB = geneticCode if letterSizeB else aminoAcidCodes
467 loopEnd = len(rowA)
468 i = j = 0
469 while j < loopEnd:
470 if rowA[j] == "-":
471 if j > i:
472 size = j - i
473 yield size // 3, begA, begB
474 begA += size // letterSpanA
475 begB += size // letterSpanB
476 begB += 1
477 j += letterSpanB
478 i = j
479 elif rowB[j] == "-":
480 if j > i:
481 size = j - i
482 yield size // 3, begA, begB
483 begA += size // letterSpanA
484 begB += size // letterSpanB
485 begA += 1
486 j += letterSpanA
487 i = j
488 else:
489 k = j + 3
490 if codeA.get(rowA[j:k], "X") != codeB.get(rowB[j:k], "X"):
491 mismatches += 1
492 j = k
493 if j > i:
494 yield (j - i) // 3, begA, begB
495 else:
496 isProtein = opts.protein or letterSizeA * letterSizeB > 1
497 size = 0
498 for x, y in zip(rowA, rowB):
499 if x == "-":
500 if size:
501 yield size, begA, begB
502 begA += size * letterSizeA
503 begB += size * letterSizeB
504 size = 0
505 begB += symbolSize(y, letterSizeB)
506 elif y == "-":
507 if size:
508 yield size, begA, begB
509 begA += size * letterSizeA
510 begB += size * letterSizeB
511 size = 0
512 begA += symbolSize(x, letterSizeA)
513 else:
514 size += 1
515 if x in normalBases and y in normalBases or isProtein:
516 if x != y:
517 mismatches += 1
518 else:
519 nCount += 1
520 if size:
521 yield size, begA, begB
522
523 outCounts[0:3] = mismatches, repMatches, nCount
524
525 def pslNumInserts(blocks, letterSizeA, letterSizeB):
526 numInsertA = numInsertB = 0
527 for i, x in enumerate(blocks):
528 size, begA, begB = x
529 if i:
530 if begA > endA:
531 numInsertA += 1
532 if begB > endB:
533 numInsertB += 1
534 endA = begA + size * letterSizeA
535 endB = begB + size * letterSizeB
536 return numInsertA, numInsertB
537
538 def pslCommaString(things):
539 # UCSC software seems to prefer a trailing comma
540 return ",".join(map(str, things)) + ","
541
542 def pslEnds(seqLen, strand, beg, end):
543 if strand == "-":
544 return seqLen - end, seqLen - beg
545 return beg, end
546
547 def writePsl(opts, geneticCode, mafs):
548 matchCounts = [0] * 3
549 blocks = list(pslBlocks(opts, geneticCode, mafs, matchCounts))
550 mismatches, repMatches, nCount = matchCounts
551 numGaplessColumns = sum(i[0] for i in blocks)
552 matches = numGaplessColumns - sum(matchCounts)
553
554 if not blocks:
555 return
556
557 fieldsA, fieldsB = mafs[0][1]
558
559 if opts.subject == 2 or fieldsA[3] < fieldsB[3] and opts.subject != 1:
560 # default for protein-to-DNA alignment
561 fieldsA, fieldsB = fieldsB, fieldsA
562 blocks = [(s, b, a) for s, a, b in blocks]
563
564 seqNameA, seqLenA, strandA, letterSizeA = fieldsA[0:4]
565 seqNameB, seqLenB, strandB, letterSizeB = fieldsB[0:4]
566
567 sizeMulA = 3 if letterSizeA > letterSizeB else 1
568 sizeMulB = 3 if letterSizeB > letterSizeA else 1
569
570 headSize, headBegA, headBegB = blocks[0]
571 tailSize, tailBegA, tailBegB = blocks[-1]
572
573 tailEndA = tailBegA + tailSize * sizeMulA
574 begA, endA = pslEnds(seqLenA, strandA, headBegA, tailEndA)
575 baseInsertA = endA - begA - numGaplessColumns * sizeMulA
576
577 tailEndB = tailBegB + tailSize * sizeMulB
578 begB, endB = pslEnds(seqLenB, strandB, headBegB, tailEndB)
579 baseInsertB = endB - begB - numGaplessColumns * sizeMulB
580
581 numInsertA, numInsertB = pslNumInserts(blocks, sizeMulA, sizeMulB)
582
583 if sizeMulA > 1 or sizeMulB > 1:
584 strand = strandB + strandA
585 else:
586 strand = "+" if strandA == strandB else "-"
587 if strandA == "-":
588 blocks = [(s, seqLenA - a - s, seqLenB - b - s)
589 for s, a, b in reversed(blocks)]
590
591 blockCount = len(blocks)
592 blockSizes, blockStartsA, blockStartsB = map(pslCommaString, zip(*blocks))
593
594 print(matches, mismatches, repMatches, nCount,
595 numInsertB, baseInsertB, numInsertA, baseInsertA, strand,
596 seqNameB, seqLenB, begB, endB, seqNameA, seqLenA, begA, endA,
597 blockCount, blockSizes, blockStartsB, blockStartsA, sep="\t")
598
599 def mafConvertToPsl(opts, lines):
600 geneticCode = standardGeneticCode()
601 if opts.Join:
602 for i in colinearMafInput(opts, lines):
603 writePsl(opts, geneticCode, i)
604 elif opts.join:
605 for i in mafGroupInput(opts, False, lines):
606 writePsl(opts, geneticCode, i)
607 else:
608 for i in mafInput(opts, lines):
609 writePsl(opts, geneticCode, [i])
610
611 ##### Routines for converting to SAM format: #####
612
613 def readGroupId(readGroupItems):
614 for i in readGroupItems:
615 if i.startswith("ID:"):
616 return i[3:]
617 raise RuntimeError("readgroup must include ID")
618
619 def readSequenceLengths(fileNames):
620 """Read name & length of topmost sequence in each maf block."""
621 for i in fileNames:
622 f = myOpen(i)
623 fields = None
624 for line in f:
625 if fields:
626 if line.isspace():
627 fields = None
628 else:
629 if line[0] == "s":
630 fields = line.split()
631 yield fields[1], fields[5]
632 f.close()
633
634 def naturalSortKey(s):
635 """Return a key that sorts strings in "natural" order."""
636 return [(str, int)[k]("".join(v)) for k, v in groupby(s, str.isdigit)]
637
638 def karyotypicSortKey(s):
639 """Attempt to sort chromosomes in GATK's ridiculous order."""
640 if s == "chrM": return []
641 if s == "MT": return ["~"]
642 return naturalSortKey(s)
643
644 def copyDictFile(lines):
645 for line in lines:
646 if line.startswith("@SQ"):
647 sys.stdout.write(line)
648 elif not line[0] == "@":
649 break
650
651 def writeSamHeader(opts, fileNames):
652 print("@HD\tVN:1.3\tSO:unsorted")
653
654 if opts.dictionary:
655 sequenceLengths = dict(readSequenceLengths(fileNames))
656 for k in sorted(sequenceLengths, key=karyotypicSortKey):
657 print("@SQ\tSN:%s\tLN:%s" % (k, sequenceLengths[k]))
658
659 if opts.dictfile:
660 f = myOpen(opts.dictfile)
661 copyDictFile(f)
662 f.close()
663
664 if opts.readgroup:
665 print("@RG\t" + "\t".join(opts.readgroup.split()))
666
667 mapqMissing = "255"
668 mapqMaximum = "254"
669 mapqMaximumNum = float(mapqMaximum)
670
671 def mismapProbabilityFromText(probString):
672 try:
673 p = float(probString)
674 except ValueError:
675 raise ValueError("bad probability: " + probString)
676 if math.isnan(p):
677 logging.warning("bad probability: " + probString)
678 return 2.0
679 if p < 0 or p > 1:
680 raise ValueError("bad probability: " + probString)
681 return p
682
683 def smallParts(size, symbol):
684 maxSize = 268435455
685 q, r = divmod(size, maxSize)
686 return (str(maxSize) + symbol) * q + (str(r) + symbol) * (r > 0)
687
688 def cigarParts(alignmentColumns):
689 # (doesn't handle translated alignments)
690 # uses "read-ahead" technique, aiming to be as fast as possible:
691 isActive = True
692 for x, y in alignmentColumns: break
693 else: isActive = False
694 while isActive:
695 size = 1
696 if x == y: # xxx assumes no gap-gap columns, ignores ambiguous bases
697 for x, y in alignmentColumns:
698 if x != y: break
699 size += 1
700 else: isActive = False
701 yield str(size) + "="
702 elif x == "-":
703 for x, y in alignmentColumns:
704 if x != "-": break
705 size += 1
706 else: isActive = False
707 yield str(size) + "I"
708 elif y == "-":
709 for x, y in alignmentColumns:
710 if y != "-": break
711 size += 1
712 else: isActive = False
713 yield str(size) + "D"
714 else:
715 for x, y in alignmentColumns:
716 if x == y or x == "-" or y == "-": break
717 size += 1
718 else: isActive = False
719 yield str(size) + "X"
720
721 def writeSam(readGroup, mafs):
722 seq = qual = score = evalue = ""
723 cigar = []
724 mismapProb = 2.0
725 editDistance = 0
726 for maf in mafs:
727 aLine, sLines, qLines, pLines = maf
728 fieldsA, fieldsB = pairOrDie(sLines, "SAM")
729 seqNameA, seqLenA, strandA, letterSizeA, begA, endA, rowA = fieldsA
730 seqNameB, seqLenB, strandB, letterSizeB, begB, endB, rowB = fieldsB
731
732 if letterSizeA * letterSizeB != 1:
733 raise RuntimeError("looks like DNA-to-protein alignment - can't convert to SAM format")
734
735 isSplice = False
736 for i in aLine.split():
737 if i.startswith("score="):
738 score = i[6:]
739 elif i.startswith("E="):
740 evalue = i[2:]
741 elif i.startswith("mismap="):
742 mismapProb = min(mismapProb, mismapProbabilityFromText(i[7:]))
743 elif i.startswith(("don=", "acc=")):
744 isSplice = True
745
746 if seq:
747 d = begA - oldEndA
748 cigar.append(str(d) + "DN"[isSplice])
749 if not isSplice: editDistance += d
750 else:
751 pos = begA
752 cigar.append(smallParts(begB, "H"))
753 oldEndA = endA
754
755 alignmentColumns = list(zip(rowA.upper(), rowB.upper()))
756 cigar.extend(cigarParts(iter(alignmentColumns)))
757 editDistance += sum(x != y for x, y in alignmentColumns)
758 # no special treatment of ambiguous bases: might be a minor bug
759
760 seq += rowB.replace("-", "")
761
762 if qLines:
763 qFields = qLines[-1].split()
764 if qFields[1] == seqNameB:
765 z = zip(rowB, qFields[2])
766 qual += ''.join(j for i, j in z if i != "-")
767
768 cigar.append(smallParts(seqLenB - endB, "H"))
769
770 if strandA == "-":
771 seq = revcomp(seq)
772 qual = qual[::-1]
773 cigar = reversed(cigar)
774 pos = seqLenA - endA
775
776 if mismapProb > 1:
777 mapq = mapqMissing
778 elif mismapProb <= 0:
779 mapq = mapqMaximum
780 else:
781 mapq = -10 * math.log(mismapProb, 10)
782 mapq = str(int(round(mapq))) if mapq < mapqMaximumNum else mapqMaximum
783
784 # It's hard to get all the pair info, so this is very
785 # incomplete, but hopefully good enough.
786 # I'm not sure whether to add 2 and/or 8 to flag.
787 if seqNameB.endswith("/1"):
788 seqNameB = seqNameB[:-2]
789 if strandB == strandA: flag = "99" # 1 + 2 + 32 + 64
790 else: flag = "83" # 1 + 2 + 16 + 64
791 elif seqNameB.endswith("/2"):
792 seqNameB = seqNameB[:-2]
793 if strandB == strandA: flag = "163" # 1 + 2 + 32 + 128
794 else: flag = "147" # 1 + 2 + 16 + 128
795 else:
796 if strandB == strandA: flag = "0"
797 else: flag = "16"
798
799 if len(qual) < len(seq): qual = "*"
800 pos += 1 # convert to 1-based coordinate
801 cigar = "".join(cigar)
802 out = [seqNameB, flag, seqNameA, pos, mapq, cigar, "*\t0\t0", seq, qual]
803 out.append("NM:i:" + str(editDistance))
804 if len(mafs) < 2:
805 if score.isdigit(): out.append("AS:i:" + score) # must be an integer
806 if evalue: out.append("EV:Z:" + evalue)
807 if readGroup: out.append(readGroup)
808 print(*out, sep="\t")
809
810 def mafConvertToSam(opts, lines):
811 readGroup = ""
812 if opts.readgroup:
813 readGroup = "RG:Z:" + readGroupId(opts.readgroup.split())
814 if opts.join:
815 for i in mafGroupInput(opts, True, lines):
816 writeSam(readGroup, i)
817 else:
818 for i in mafInput(opts, lines):
819 writeSam(readGroup, [i])
820
821 ##### Routines for converting to BLAST-like format: #####
822
823 def codonMatchSymbols(opts, geneticCode, aaSeq, ntSeq):
824 scoreSymbols = " ", "...", ":::"
825 seqLen = len(aaSeq)
826 i = 0
827 while i < seqLen:
828 if aaSeq[i] == "-":
829 yield " "
830 i += 1
831 else:
832 j = i + 3
833 a = aminoAcidCodes.get(aaSeq[i:j], "X")
834 b = ntSeq[i:j]
835 if geneticCode.get(b, "Z") == a:
836 yield "|||"
837 else:
838 score = opts.scoreMatrix.get((a, b), -1)
839 yield scoreSymbols[(score >= 0) + (score > 0)]
840 i = j
841
842 def translatedSeq(codon2triplet, aaSeq, ntSeq):
843 seqLen = len(aaSeq)
844 i = 0
845 while i < seqLen:
846 if aaSeq[i] == "-":
847 j = i + 1
848 while j < seqLen and aaSeq[j] == "-":
849 j += 1
850 if (j - i) % 3 == 0:
851 for b in range(i, j, 3):
852 e = b + 3
853 yield codon2triplet.get(ntSeq[b:e], " ")
854 else:
855 yield " " * (j - i)
856 else:
857 j = i + 3
858 yield codon2triplet.get(ntSeq[i:j], " ")
859 i = j
860
861 def strandText(strand):
862 if strand == "+":
863 return "Plus"
864 else:
865 return "Minus"
866
867 def blastBegCoordinate(zeroBasedCoordinate, strand, seqLen):
868 if strand == "+":
869 return str(zeroBasedCoordinate + 1)
870 else:
871 return str(seqLen - zeroBasedCoordinate)
872
873 def blastEndCoordinate(zeroBasedCoordinate, strand, seqLen):
874 if strand == "+":
875 return str(zeroBasedCoordinate)
876 else:
877 return str(seqLen - zeroBasedCoordinate + 1)
878
879 def nextCoordinate(coordinate, row, letterSize):
880 return coordinate + insertSize(row, letterSize)
881
882 def chunker(things, chunkSize):
883 for i in range(0, len(things), chunkSize):
884 yield things[i:i+chunkSize]
885
886 def blastChunker(sLines, lineSize, alignmentColumns):
887 seqLens = [i[1] for i in sLines]
888 strands = [i[2] for i in sLines]
889 letterSizes = [i[3] for i in sLines]
890 coords = [i[4] for i in sLines]
891 for chunkCols in chunker(alignmentColumns, lineSize):
892 chunkRows = list(alignmentRowsFromColumns(chunkCols))
893 begs = list(map(blastBegCoordinate, coords, strands, seqLens))
894 coords = list(map(nextCoordinate, coords, chunkRows, letterSizes))
895 ends = list(map(blastEndCoordinate, coords, strands, seqLens))
896 yield chunkCols, chunkRows, begs, ends
897
898 def blastDataFromMafFields(fields):
899 seqName, seqLen, strand, letterSize, beg, end, row = fields
900 maxPos = end
901 if strand == "-":
902 beg -= seqLen
903 maxPos = -beg
904 return seqName, seqLen, strand, letterSize, beg, maxPos, row, row.upper()
905
906 def blastLineData(letterSize, beg, line):
907 end = beg + insertSize(line, letterSize)
908 begStr = str(beg + 1 if beg >= 0 else -beg)
909 endStr = str(end if end > 0 else 1 - end)
910 return begStr, line, endStr, end
911
912 def writeBlast(opts, geneticCode, codon2triplet, maf, oldQueryName):
913 aLine, sLines, qLines, pLines = maf
914 fieldsA, fieldsB = pairOrDie(sLines, "Blast")
915 if opts.subject == 2:
916 fieldsA, fieldsB = fieldsB, fieldsA
917 dataA = blastDataFromMafFields(fieldsA)
918 dataB = blastDataFromMafFields(fieldsB)
919 seqNameA, seqLenA, strandA, letterSizeA, begA, maxPosA, rowA, upA = dataA
920 seqNameB, seqLenB, strandB, letterSizeB, begB, maxPosB, rowB, upB = dataB
921
922 if seqNameB != oldQueryName:
923 print("Query= " + seqNameB)
924 print(" (%s letters)" % seqLenB)
925 print()
926
927 print(">" + seqNameA)
928 print(" Length = %s" % seqLenA)
929 print()
930
931 score, evalue = scoreAndEvalue(aLine)
932
933 if score and opts.bitScoreA is not None and opts.bitScoreB is not None:
934 bitScore = opts.bitScoreA * float(score) - opts.bitScoreB
935 scoreLine = " Score = %.3g bits (%s)" % (bitScore, score)
936 else:
937 scoreLine = " Score = %s" % score
938
939 if evalue:
940 scoreLine += ", Expect = %s" % evalue
941
942 print(scoreLine)
943
944 if letterSizeA * letterSizeB < 1:
945 c = codonMatchCounts(geneticCode, letterSizeA, letterSizeB, upA, upB)
946 matches, mismatches, gaps, dangles = c
947 alnSize = matches + mismatches + gaps
948 (aaSeq, ntSeq) = (upA, upB) if letterSizeB else (upB, upA)
949 sySeq = "".join(codonMatchSymbols(opts, geneticCode, aaSeq, ntSeq))
950 txSeq = "".join(translatedSeq(codon2triplet, aaSeq, ntSeq))
951 lineSize = max(opts.linesize, 3)
952 else:
953 sySeq = "".join(" |"[x == y] for x, y in zip(upA, upB))
954 matches = sySeq.count("|")
955 gaps = upA.count("-") + upB.count("-")
956 alnSize = len(sySeq)
957 lineSize = opts.linesize
958
959 matchPercent = 100 * matches // alnSize # round down, like BLAST
960 identLine = " Identities = %s/%s (%s%%)" % (matches, alnSize, matchPercent)
961 if gaps:
962 gapPercent = 100 * gaps // alnSize # round down, like BLAST
963 identLine += ", Gaps = %s/%s (%s%%)" % (gaps, alnSize, gapPercent)
964 print(identLine)
965
966 print(" Strand = %s / %s" % (strandText(strandB), strandText(strandA)))
967 print()
968
969 begWidth = len(str(max(maxPosA, maxPosB)))
970 pad = " " * (begWidth + 7)
971
972 numOfColumns = len(sySeq)
973 i = 0
974 while i < numOfColumns:
975 j = min(i + lineSize, numOfColumns)
976 rem = 0
977 if letterSizeA * letterSizeB < 1 and j < numOfColumns:
978 rem = ((j - i - aaSeq.count("-", i, j)) % 3 or
979 (j - i - txSeq.count(" ", i, j)) % 3)
980 j -= rem
981 bA, lineA, eA, begA = blastLineData(letterSizeA, begA, rowA[i:j])
982 bB, lineB, eB, begB = blastLineData(letterSizeB, begB, rowB[i:j])
983 if letterSizeA == 0: print(pad, txSeq[i:j])
984 print("Query: %-*s" % (begWidth, bB), lineB + " " * rem, eB)
985 print(pad, sySeq[i:j])
986 print("Sbjct: %-*s" % (begWidth, bA), lineA + " " * rem, eA)
987 if letterSizeB == 0: print(pad, txSeq[i:j])
988 print()
989 i = j
990
991 def mafConvertToBlast(opts, lines):
992 geneticCode = standardGeneticCode()
993 aa2triplet = dict((j, i.title()) for i, j in aminoAcidCodes.items())
994 codon2triplet = dict((i, aa2triplet[j]) for i, j in geneticCode.items())
995
996 for i in "ACGT":
997 for j in "ACGT":
998 for k, v in ambiguousBases.items():
999 a = set(geneticCode[i + j + x] for x in v)
1000 if len(a) == 1: codon2triplet[i + j + k] = aa2triplet[min(a)]
1001 a = set(geneticCode[x + i + j] for x in v)
1002 if len(a) == 1: codon2triplet[k + i + j] = aa2triplet[min(a)]
1003
1004 qryNum = 0 if opts.subject == 2 else 1
1005
1006 oldQueryName = ""
1007 for maf in mafInput(opts, lines):
1008 writeBlast(opts, geneticCode, codon2triplet, maf, oldQueryName)
1009 sLines = maf[1]
1010 oldQueryName = sLines[qryNum][0]
1011
1012 def btabData(fields):
1013 seqName, seqLen, strand, letterSize, beg, end, row = fields
1014 if strand == "+":
1015 beg += 1
1016 else:
1017 beg = seqLen - beg
1018 end = seqLen - end + 1
1019 return seqName, seqLen, letterSize, str(beg), str(end), row.upper()
1020
1021 def codonMatchCounts(geneticCode, letterSizeA, letterSizeB, rowA, rowB):
1022 codeA = geneticCode if letterSizeA else aminoAcidCodes
1023 codeB = geneticCode if letterSizeB else aminoAcidCodes
1024 loopEnd = len(rowA)
1025 matches = mismatches = gaps = dangles = 0
1026 i = 0
1027 while i < loopEnd:
1028 if rowA[i] == "-":
1029 gaps += 1
1030 if i+2 < loopEnd and rowA[i+1] == "-" and rowA[i+2] == "-":
1031 i += 3
1032 else:
1033 if i > 0 and rowB[i-1] == "-":
1034 dangles += 1
1035 i += 1
1036 elif rowB[i] == "-":
1037 gaps += 1
1038 if i+2 < loopEnd and rowB[i+1] == "-" and rowB[i+2] == "-":
1039 i += 3
1040 else:
1041 if i > 0 and rowA[i-1] == "-":
1042 dangles += 1
1043 i += 1
1044 else:
1045 j = i + 3
1046 if codeA.get(rowA[i:j], "X") == codeB.get(rowB[i:j], "X"):
1047 matches += 1
1048 else:
1049 mismatches += 1
1050 i = j
1051 return matches, mismatches, gaps, dangles
1052
1053 def writeBlastTab(opts, formatName, geneticCode, maf):
1054 aLine, sLines, qLines, pLines = maf
1055 fieldsA, fieldsB = pairOrDie(sLines, "BlastTab")
1056 if opts.subject == 2:
1057 fieldsA, fieldsB = fieldsB, fieldsA
1058 seqNameA, seqLenA, letterSizeA, begA, endA, rowA = btabData(fieldsA)
1059 seqNameB, seqLenB, letterSizeB, begB, endB, rowB = btabData(fieldsB)
1060 gapOpens = gapRunCount(rowA) + gapRunCount(rowB)
1061
1062 if letterSizeA * letterSizeB < 1:
1063 c = codonMatchCounts(geneticCode, letterSizeA, letterSizeB, rowA, rowB)
1064 matches, mismatches, gaps, dangles = c
1065 alnSize = matches + mismatches + gaps
1066 gapOpens -= dangles
1067 else:
1068 alignmentColumns = list(zip(rowA, rowB))
1069 alnSize = len(alignmentColumns)
1070 matches = sum(x == y for x, y in alignmentColumns)
1071 mismatches = alnSize - matches - rowA.count("-") - rowB.count("-")
1072
1073 matchPercent = "%.2f" % (100.0 * matches / alnSize)
1074
1075 out = [seqNameB, seqNameA, matchPercent, alnSize, mismatches,
1076 gapOpens, begB, endB, begA, endA]
1077
1078 score, evalue = scoreAndEvalue(aLine)
1079
1080 bitScore = None
1081 if score and opts.bitScoreA is not None and opts.bitScoreB is not None:
1082 bitScore = opts.bitScoreA * float(score) - opts.bitScoreB
1083 bitScore = "%.3g" % bitScore
1084
1085 if formatName == "blasttab+":
1086 if not evalue: evalue = 'NA'
1087 if not bitScore: bitScore = 'NA'
1088
1089 if evalue:
1090 out.append(evalue)
1091 if bitScore:
1092 out.append(bitScore)
1093 if formatName == "blasttab+":
1094 out += [seqLenB, seqLenA, score]
1095
1096 print(*out, sep="\t")
1097
1098 def mafConvertToBlastTab(opts, formatName, lines):
1099 geneticCode = standardGeneticCode()
1100 for maf in mafInput(opts, lines):
1101 writeBlastTab(opts, formatName, geneticCode, maf)
1102
1103 ##### Routines for converting to GFF format: #####
1104
1105 def writeGffHeader():
1106 print("##gff-version 3")
1107
1108 def gffFromMaf(opts, maf):
1109 aLine, sLines, qLines, pLines = maf
1110 fieldsA, fieldsB = pairOrDie(sLines, "GFF")
1111
1112 if opts.subject == 2 or fieldsA[3] < fieldsB[3] and opts.subject != 1:
1113 # default for protein-to-DNA alignment
1114 fieldsA, fieldsB = fieldsB, fieldsA
1115
1116 seqNameA, seqLenA, strandA, letterSizeA, begA, endA, rowA = fieldsA
1117 seqNameB, seqLenB, strandB, letterSizeB, begB, endB, rowB = fieldsB
1118
1119 score = "."
1120 for i in aLine.split():
1121 if i.startswith("score="):
1122 score = i[6:]
1123
1124 if strandA == "-":
1125 begA, endA = seqLenA - endA, seqLenA - begA
1126 if strandB == "-":
1127 begB, endB = seqLenB - endB, seqLenB - begB
1128 begA += 1
1129 begB += 1
1130
1131 strand = "+" if strandA == strandB else "-"
1132
1133 return seqNameA, begA, endA, strand, score, seqNameB, begB, endB
1134
1135 def writeOneGff(gff, typeOfThing, parentId):
1136 seqNameA, begA, endA, strand, score, seqNameB, begB, endB = gff
1137 target = "Target={0} {1} {2}".format(seqNameB, begB, endB)
1138 name = "Name={0}:{1}-{2}".format(seqNameB, begB, endB)
1139 attributes = [target, name]
1140 if parentId:
1141 attributes.append("Parent=" + parentId)
1142 print(seqNameA, "maf-convert", typeOfThing, begA, endA, score, strand, ".",
1143 ";".join(attributes), sep="\t")
1144
1145 def writeGffGroup(opts, qryNameCounts, mafs):
1146 gffs = sorted(gffFromMaf(opts, i) for i in mafs)
1147 seqNameA, begA, endA, strand, score, seqNameB, begB, endB = gffs[0]
1148 endA = gffs[-1][2]
1149 if strand == "+":
1150 endB = gffs[-1][7]
1151 else:
1152 begB = gffs[-1][6]
1153 qryNameCounts[seqNameB] += 1
1154 parentId = "{0}.{1}".format(seqNameB, qryNameCounts[seqNameB])
1155 myId = "ID=" + parentId
1156 name = "Name={0}:{1}-{2}".format(seqNameB, begB, endB)
1157 attributes = [myId, name]
1158 print(seqNameA, "maf-convert", "match", begA, endA, ".", strand, ".",
1159 ";".join(attributes), sep="\t")
1160 for i in gffs:
1161 writeOneGff(i, "match_part", parentId)
1162
1163 def mafConvertToGff(opts, lines):
1164 qryNameCounts = collections.defaultdict(int)
1165 if opts.Join:
1166 for i in colinearMafInput(opts, lines):
1167 writeGffGroup(opts, qryNameCounts, i)
1168 elif opts.join:
1169 for i in mafGroupInput(opts, False, lines):
1170 writeGffGroup(opts, qryNameCounts, i)
1171 else:
1172 for i in mafInput(opts, lines):
1173 writeOneGff(gffFromMaf(opts, i), "match", None)
1174
1175 ##### Routines for converting to HTML format: #####
1176
1177 def writeHtmlHeader():
1178 print('''
1179 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
1180 "http://www.w3.org/TR/html4/strict.dtd">
1181 <html lang="en"><head>
1182 <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
1183 <title>Reliable Alignments</title>
1184 <style type="text/css">
1185 /* Try to force monospace, working around browser insanity: */
1186 pre {font-family: "Courier New", monospace, serif; font-size: 0.8125em}
1187 .a {background-color: #3333FF}
1188 .b {background-color: #9933FF}
1189 .c {background-color: #FF66CC}
1190 .d {background-color: #FF3333}
1191 .e {background-color: #FF9933}
1192 .f {background-color: #FFFF00}
1193 .key {display:inline; margin-right:2em}
1194 </style>
1195 </head><body>
1196
1197 <div style="line-height:1">
1198 <pre class="key"><span class="a"> </span> prob &gt; 0.999</pre>
1199 <pre class="key"><span class="b"> </span> prob &gt; 0.99 </pre>
1200 <pre class="key"><span class="c"> </span> prob &gt; 0.95 </pre>
1201 <pre class="key"><span class="d"> </span> prob &gt; 0.9 </pre>
1202 <pre class="key"><span class="e"> </span> prob &gt; 0.5 </pre>
1203 <pre class="key"><span class="f"> </span> prob &le; 0.5 </pre>
1204 </div>
1205 ''')
1206
1207 def probabilityClass(probabilityColumn):
1208 p = ord(min(probabilityColumn)) - 33
1209 if p >= 30: return 'a'
1210 elif p >= 20: return 'b'
1211 elif p >= 13: return 'c'
1212 elif p >= 10: return 'd'
1213 elif p >= 3: return 'e'
1214 else: return 'f'
1215
1216 def identicalRuns(s):
1217 """Yield (item, start, end) for each run of identical items in s."""
1218 beg = 0
1219 for k, v in groupby(s):
1220 end = beg + len(list(v))
1221 yield k, beg, end
1222 beg = end
1223
1224 def htmlSpan(text, classRun):
1225 key, beg, end = classRun
1226 textbit = text[beg:end]
1227 if key: return '<span class="%s">%s</span>' % (key, textbit)
1228 else: return textbit
1229
1230 def multipleMatchSymbol(alignmentColumn):
1231 if isMatch(alignmentColumn): return "*"
1232 else: return " "
1233
1234 def writeHtml(opts, maf):
1235 aLine, sLines, qLines, pLines = maf
1236
1237 scoreLine = "Alignment"
1238 score, evalue = scoreAndEvalue(aLine)
1239 if score:
1240 scoreLine += " score=" + score
1241 if evalue:
1242 scoreLine += ", expect=" + evalue
1243 print("<h3>%s:</h3>" % scoreLine)
1244
1245 if pLines:
1246 probRows = [i.split()[1] for i in pLines]
1247 probCols = zip(*probRows)
1248 classes = map(probabilityClass, probCols)
1249 else:
1250 classes = repeat(None)
1251
1252 seqNames = [i[0] for i in sLines]
1253 nameWidth = maxlen(seqNames)
1254 rows = [i[6] for i in sLines]
1255 alignmentColumns = list(zip(*rows))
1256
1257 print('<pre>')
1258 for chunk in blastChunker(sLines, opts.linesize, alignmentColumns):
1259 cols, rows, begs, ends = chunk
1260 begWidth = maxlen(begs)
1261 endWidth = maxlen(ends)
1262 matchSymbols = ''.join(map(multipleMatchSymbol, cols))
1263 classChunk = islice(classes, opts.linesize)
1264 classRuns = list(identicalRuns(classChunk))
1265 for n, b, r, e in zip(seqNames, begs, rows, ends):
1266 spans = [htmlSpan(r, i) for i in classRuns]
1267 spans = ''.join(spans)
1268 formatParams = nameWidth, n, begWidth, b, spans, endWidth, e
1269 print('%-*s %*s %s %*s' % formatParams)
1270 print(' ' * nameWidth, ' ' * begWidth, matchSymbols)
1271 print()
1272 print('</pre>')
1273
1274 def mafConvertToHtml(opts, lines):
1275 for maf in mafInput(opts, lines):
1276 writeHtml(opts, maf)
1277
1278 ##### Main program: #####
1279
1280 def isFormat(myString, myFormat):
1281 return myFormat.startswith(myString)
1282
1283 def mafConvertOneFile(opts, formatName, lines):
1284 if isFormat(formatName, "axt"):
1285 mafConvertToAxt(opts, lines)
1286 elif isFormat(formatName, "bed"):
1287 mafConvertToBed(opts, lines)
1288 elif isFormat(formatName, "blast"):
1289 mafConvertToBlast(opts, lines)
1290 elif isFormat(formatName, "blasttab+"):
1291 mafConvertToBlastTab(opts, formatName, lines)
1292 elif isFormat(formatName, "chain"):
1293 mafConvertToChain(opts, lines)
1294 elif isFormat(formatName, "gff"):
1295 mafConvertToGff(opts, lines)
1296 elif isFormat(formatName, "html"):
1297 mafConvertToHtml(opts, lines)
1298 elif isFormat(formatName, "psl"):
1299 mafConvertToPsl(opts, lines)
1300 elif isFormat(formatName, "sam"):
1301 mafConvertToSam(opts, lines)
1302 elif isFormat(formatName, "tabular"):
1303 mafConvertToTab(opts, lines)
1304 else:
1305 raise RuntimeError("unknown format: " + formatName)
1306
1307 def mafConvert(opts, args):
1308 logging.basicConfig(format="%(filename)s: %(message)s")
1309
1310 formatName = args[0].lower()
1311 fileNames = args[1:]
1312
1313 opts.headerMode = 0
1314 opts.bitScoreA = None
1315 opts.bitScoreB = None
1316
1317 if not opts.noheader:
1318 if isFormat(formatName, "gff"):
1319 writeGffHeader()
1320 if isFormat(formatName, "html"):
1321 writeHtmlHeader()
1322 if isFormat(formatName, "sam"):
1323 writeSamHeader(opts, fileNames)
1324 opts.headerMode = 2
1325 if isFormat(formatName, "tabular"):
1326 opts.headerMode = 1
1327
1328 if not fileNames:
1329 fileNames = ["-"]
1330 for i in fileNames:
1331 f = myOpen(i)
1332 mafConvertOneFile(opts, formatName, f)
1333 f.close()
1334
1335 if not opts.noheader:
1336 if isFormat(formatName, "html"):
1337 print("</body></html>")
1338
1339 if __name__ == "__main__":
1340 signal.signal(signal.SIGPIPE, signal.SIG_DFL) # avoid silly error message
1341
1342 usage = """
1343 %prog --help
1344 %prog axt mafFile(s)
1345 %prog bed mafFile(s)
1346 %prog blast mafFile(s)
1347 %prog blasttab mafFile(s)
1348 %prog blasttab+ mafFile(s)
1349 %prog chain mafFile(s)
1350 %prog gff mafFile(s)
1351 %prog html mafFile(s)
1352 %prog psl mafFile(s)
1353 %prog sam mafFile(s)
1354 %prog tab mafFile(s)"""
1355
1356 description = "Read MAF-format alignments & write them in another format."
1357
1358 op = optparse.OptionParser(usage=usage, description=description)
1359 op.add_option("-s", "--subject", type="int", metavar="N",
1360 help="which sequence to use as subject/reference")
1361 op.add_option("-p", "--protein", action="store_true",
1362 help="assume protein alignments, for psl match counts")
1363 op.add_option("-j", "--join", type="float", metavar="N", help="join "
1364 "consecutive co-linear alignments separated by <= N letters")
1365 op.add_option("-J", "--Join", type="float", metavar="N", help=
1366 "join nearest co-linear alignments separated by <= N letters")
1367 op.add_option("-n", "--noheader", action="store_true",
1368 help="omit any header lines from the output")
1369 op.add_option("-d", "--dictionary", action="store_true",
1370 help="include dictionary of sequence lengths in sam format")
1371 op.add_option("-f", "--dictfile",
1372 help="get sequence dictionary from DICTFILE")
1373 op.add_option("-r", "--readgroup",
1374 help="read group info for sam format")
1375 op.add_option("-l", "--linesize", type="int", default=60, #metavar="CHARS",
1376 help="line length for blast and html formats (default: %default)")
1377 opts, args = op.parse_args()
1378 if opts.linesize <= 0: op.error("option -l: should be >= 1")
1379 if opts.dictionary and opts.dictfile: op.error("can't use both -d and -f")
1380 if len(args) < 1: op.error("I need a format-name and some MAF alignments")
1381 if opts.dictionary and (len(args) == 1 or "-" in args[1:]):
1382 op.error("need file (not pipe) with option -d")
1383
1384 try: mafConvert(opts, args)
1385 except RuntimeError as e:
1386 prog = os.path.basename(sys.argv[0])
1387 sys.exit(prog + ": error: " + str(e))