Debian Codegraph @

lamassemble

raw
1 #! /usr/bin/env python3
2 # Author: Martin C. Frith 2019
3 # SPDX-License-Identifier: MIT
4
5 from __future__ import print_function
6
7 import collections
8 import gzip
9 import itertools
10 import logging
11 import math
12 import optparse
13 import os
14 import shutil
15 import signal
16 import subprocess
17 import sys
18 import tempfile
19 from operator import itemgetter
20
21 def openFile(fileName):
22 if fileName == "-":
23 return sys.stdin
24 if fileName.endswith(".gz"):
25 return gzip.open(fileName, "rt") # xxx dubious for Python2
26 return open(fileName)
27
28 def fastxInput(lines):
29 s = []
30 for i in lines:
31 if i[0] == ">" and s and s[0][0] == ">" or i[0] == "@" and len(s) == 4:
32 yield s
33 s = []
34 if not i.isspace():
35 s.append(i.rstrip())
36 if s:
37 yield s
38
39 def nameAndSeqFromFastx(seqLines):
40 title = seqLines[0]
41 name = title[1:].split()[0]
42 if title[0] == ">":
43 seq = "".join(seqLines[1:])
44 else:
45 seq = seqLines[1]
46 return name, seq
47
48 ##### Routines for getting score parameters from a last-train file:
49
50 builtinTrainFiles = {
51 "promethion-2019": """
52 # scale of score parameters: 4.5512
53 # delOpenProb: 0.0369615
54 # insOpenProb: 0.0340916
55 # delExtendProb: 0.439744
56 # insExtendProb: 0.403943
57 # probability matrix (query letters = columns, reference letters = rows):
58 # A C G T
59 # A 0.278908 0.00109169 0.012899 0.00107855
60 # C 0.00154506 0.197869 0.00044938 0.00272089
61 # G 0.0272926 0.000508552 0.177789 0.000859018
62 # T 0.00126293 0.00328421 0.000545484 0.291896
63 """,
64 "promethion-rna-2019" :"""
65 # scale of score parameters: 4.5512
66 # delOpenProb: 0.0578071
67 # insOpenProb: 0.0297262
68 # delExtendProb: 0.438808
69 # insExtendProb: 0.380129
70 # probability matrix (query letters = columns, reference letters = rows):
71 # A C G T
72 # A 0.246603 0.00134 0.00742782 0.00762015
73 # C 0.00168584 0.221462 0.000388905 0.0143456
74 # G 0.00693157 0.000421241 0.239649 0.000805103
75 # T 0.00803073 0.0131941 0.000617237 0.229477
76 """,
77 "sequel-ii-clr-2019": """
78 # scale of score parameters: 4.5512
79 # delOpenProb: 0.0329087
80 # insOpenProb: 0.0343556
81 # delExtendProb: 0.0674455
82 # insExtendProb: 0.288643
83 # probability matrix (query letters = columns, reference letters = rows):
84 # A C G T
85 # A 0.292742 0.00340172 0.000378204 0.00239594
86 # C 0.000849175 0.20731 0.000104201 0.00037284
87 # G 0.0013137 0.000304338 0.187333 0.00680248
88 # T 0.0135957 0.000785525 0.00475765 0.277554
89 """
90 }
91
92 def parametersFromLastTrain(trainFile):
93 builtin = builtinTrainFiles.get(trainFile.lower())
94 lines = builtin.splitlines() if builtin else openFile(trainFile)
95
96 alphabetSize = 4
97 scale = delOpenProb = delExtendProb = insOpenProb = insExtendProb = -1
98 probMatrix = range(alphabetSize)
99 for line in lines:
100 fields = line.split()
101 if "scale of score parameters" in line:
102 scale = float(fields[5])
103 if "delOpenProb" in line:
104 delOpenProb = float(fields[2])
105 if "insOpenProb" in line:
106 insOpenProb = float(fields[2])
107 if "delExtendProb" in line:
108 delExtendProb = float(fields[2])
109 if "insExtendProb" in line:
110 insExtendProb = float(fields[2])
111 if "probability matrix" in line:
112 probMatrix = []
113 if len(fields) == 2 + alphabetSize and len(probMatrix) < alphabetSize:
114 probMatrix.append([float(i) for i in fields[2:]])
115 gapProbs = delOpenProb, delExtendProb, insOpenProb, insExtendProb
116 if scale < 0 or -1 in gapProbs or len(probMatrix) != alphabetSize:
117 raise RuntimeError("can't read the last-train data")
118 return scale, probMatrix, gapProbs
119
120 def scoreFromProb(scale, prob):
121 assert prob > 0
122 logProb = math.log(prob)
123 return scale * logProb
124
125 def costFromProb(scale, prob):
126 return -scoreFromProb(scale, prob)
127
128 def matrixWithComplementSymmetricRows(matrix): # xxx breaks matrix symmetry
129 for i, j in zip(matrix, reversed(matrix)):
130 avg = (sum(i) + sum(j)) * 0.5
131 yield [k * avg / sum(i) for k in i]
132
133 def substitutionProbMatrix(refMatrix, qryMatrix):
134 r = range(4)
135 s = [sum(row) for row in refMatrix]
136 m = [[None for j in r] for i in r]
137 for i in r:
138 for j in r:
139 m[i][j] = sum(refMatrix[k][i] * qryMatrix[k][j] / s[k] for k in r)
140 return m
141
142 def scoreMatrixFromProbMatrix(scale, probMatrix):
143 r = range(len(probMatrix))
144 rowSums = [sum(probMatrix[i][j] for j in r) for i in r]
145 colSums = [sum(probMatrix[i][j] for i in r) for j in r]
146 out = [[None for j in r] for i in r]
147 for i in r:
148 for j in r:
149 ratio = probMatrix[i][j] / (rowSums[i] * colSums[j])
150 out[i][j] = scoreFromProb(scale, ratio)
151 return out
152
153 def substitutionScoreMatrix(scale, refMatrix, qryMatrix):
154 p = substitutionProbMatrix(refMatrix, qryMatrix)
155 return scoreMatrixFromProbMatrix(scale, p)
156
157 def newGapExtendProb(gapProbs):
158 delOpenProb, delExtendProb, insOpenProb, insExtendProb = gapProbs
159 delFrac = delOpenProb / (1 - delExtendProb)
160 insFrac = insOpenProb / (1 - insExtendProb)
161 gapFrac = delFrac + insFrac
162 return (delFrac * delExtendProb + insFrac * insExtendProb) / gapFrac
163
164 def gapScoresFromProbs(scale, gapProbs):
165 delOpenProb, delExtendProb, insOpenProb, insExtendProb = gapProbs
166 gapOpenProb = 1 - (1 - delOpenProb) * (1 - insOpenProb)
167 gapExtendProb = newGapExtendProb(gapProbs)
168 logging.info("gapOpenProb: {0:.6}".format(gapOpenProb))
169 logging.info("gapExtendProb: {0:.6}".format(gapExtendProb))
170 gapCloseProb = 1 - gapExtendProb
171 firstGapProb = gapOpenProb * gapCloseProb
172 gapExtendProb += firstGapProb
173 gapExistProb = firstGapProb / gapExtendProb
174 gapExistCost = costFromProb(scale, gapExistProb)
175 gapExtendCost = costFromProb(scale, gapExtendProb)
176 return gapExistCost, gapExtendCost
177
178 def alignmentScoresFromProbs(scale, probMatrix, gapProbs):
179 compMatrix = [row[::-1] for row in reversed(probMatrix)]
180 fwdMatrix = substitutionScoreMatrix(scale, probMatrix, probMatrix)
181 revMatrix = substitutionScoreMatrix(scale, probMatrix, compMatrix)
182 gapExistCost, gapExtendCost = gapScoresFromProbs(scale, gapProbs)
183 return fwdMatrix, revMatrix, gapExistCost, gapExtendCost
184
185 ##### Routines for printing the score parameters in MAFFT format:
186
187 def mafftNum(x):
188 return format(x, ".3")
189
190 def mafftGapOptions(scores):
191 fwdMatrix, revMatrix, gapExistCost, gapExtendCost = scores
192 alphSize = len(fwdMatrix)
193 # xxx assume a, c, g, t have equal frequency:
194 meanMatch = sum(fwdMatrix[i][i] for i in range(alphSize)) / alphSize
195 meanUnrelated = sum(map(sum, fwdMatrix)) / (alphSize ** 2)
196 meanDiff = meanMatch - meanUnrelated
197 gapExistCostMafft = gapExistCost / meanDiff
198 gapExtendCostMafft = (gapExtendCost * 2 + meanUnrelated) / meanDiff
199 op = mafftNum(gapExistCostMafft)
200 gop = mafftNum(-gapExistCostMafft)
201 ep = mafftNum(gapExtendCostMafft)
202 gep = mafftNum(-gapExtendCostMafft)
203 lep = mafftNum(-meanUnrelated / meanDiff)
204 lexp = mafftNum(-gapExtendCost / meanDiff)
205 return ["--op", op, "--gop", gop, "--ep", ep, "--gep", gep, "--gexp", "0",
206 "--lop", gop, "--lep", lep, "--lexp", lexp]
207
208 def printMafftMatrix(mafftAlphabet, fwdMatrix, revMatrix, outFile):
209 d = {"A": (0,0), "C": (0,1), "G": (0,2), "T": (0,3), # + strand bases
210 "E": (1,0), "Q": (1,1), "F": (1,2), "P": (1,3)} # - strand bases
211
212 print(" ", *[format(i, ">5") for i in mafftAlphabet], file=outFile)
213
214 for i, x in enumerate(mafftAlphabet):
215 outFile.write(x)
216 j = i + 1
217 for y in mafftAlphabet[:j]:
218 score = 0.0
219 if x in d and y in d:
220 xm, xi = d[x]
221 ym, yi = d[y]
222 if xm == 0 and ym == 0:
223 score = fwdMatrix[xi][yi]
224 if xm == 0 and ym == 1:
225 score = revMatrix[xi][yi]
226 if xm == 1 and ym == 0:
227 score = revMatrix[3-xi][3-yi]
228 if xm == 1 and ym == 1:
229 score = fwdMatrix[3-xi][3-yi]
230 outFile.write(" " + format(score, "5.3"))
231 outFile.write("\n")
232
233 def printMafftParams(fwdMatrix, revMatrix, mafftGapOpts, outFile):
234 mafftAlphabet = "ARNDCQEGHILKMFPSTWYV"
235 print("# MAFFT cost:", *mafftGapOpts, file=outFile)
236 printMafftMatrix(mafftAlphabet, fwdMatrix, revMatrix, outFile)
237 mafftFrequencies = [(0.0, 0.25)[i in "ACGT"] for i in mafftAlphabet]
238 # must be consistent with meanMatch
239 print("frequency", *mafftFrequencies, file=outFile)
240
241 ##### Routines for making a consensus sequence:
242
243 def alignmentColumnsForConsensus(opts, rows):
244 alignmentLength = max(map(len, rows))
245 seqNumChange = [0] * (alignmentLength + 1)
246 for i in rows:
247 beg = len(i) - len(i.lstrip("-"))
248 end = len(i.rstrip("-"))
249 seqNumChange[beg] += 1
250 seqNumChange[end] -= 1
251
252 if opts.seq_min.endswith("%"):
253 minPercent = float(opts.seq_min[:-1])
254 minSeqs = len(rows) * (minPercent / 100)
255 else:
256 minSeqs = int(opts.seq_min)
257
258 beg = end = alignmentLength
259 seqNum = 0
260 for i, x in enumerate(seqNumChange):
261 seqNum += x
262 if seqNum >= minSeqs:
263 if beg > i:
264 beg = i
265 end = i + 1
266
267 # xxx try using gapProbs?
268
269 columns = zip(*rows)
270 seqNum = len(rows) if opts.end else 0
271 for i, z in enumerate(zip(seqNumChange, columns)):
272 x, y = z
273 if not opts.end:
274 seqNum += x
275 if i >= beg and i < end:
276 gapNum = seqNum + y.count("-") - len(y)
277 if gapNum * 100 <= seqNum * opts.gap_max:
278 yield "".join(y)
279
280 def strandScore(scoreRow, column, bases):
281 return sum(scoreRow[i] * column.count(x) for i, x in enumerate(bases))
282
283 def columnScore(priorScores, scoreMatrix, column, fwdBaseIndex):
284 revBaseIndex = 3 - fwdBaseIndex
285 fwdScore = strandScore(scoreMatrix[fwdBaseIndex], column, "ACGT")
286 revScore = strandScore(scoreMatrix[revBaseIndex], column, "tgca")
287 return priorScores[fwdBaseIndex] + fwdScore + revScore
288
289 def asciiFromInvProb(invProb):
290 errProb = 1 - 1 / invProb
291 s = int(math.floor(-10 * math.log10(max(errProb, 1e-10))))
292 return chr(min(s + 33, 126))
293
294 def consensusCol(priorScores, scoreMatrix, column):
295 bases = "acgt"
296 column = column.replace("U", "T") # keep
297 scores = [columnScore(priorScores, scoreMatrix, column, i)
298 for i in range(len(bases))]
299 j, m = max(enumerate(scores), key=itemgetter(1))
300 invProb = sum(math.exp(i - m) for i in scores)
301 return bases[j], invProb
302
303 def consensusSeq(opts, probMatrix, alignedSequences):
304 if not alignedSequences:
305 raise RuntimeError("can't make a consensus of zero sequences")
306
307 baseProbs = [sum(row) for row in probMatrix]
308 priorScores = [math.log(i) for i in baseProbs]
309 scoreMatrix = [[math.log(x / sum(row)) for x in row] for row in probMatrix]
310
311 rows = [seq for name, seq in alignedSequences]
312 cols = alignmentColumnsForConsensus(opts, rows)
313 return [consensusCol(priorScores, scoreMatrix, i) for i in cols]
314
315 def printConsensusSeq(opts, probMatrix, alignedSequences):
316 c = consensusSeq(opts, probMatrix, alignedSequences)
317 seq = "".join(i[0] for i in c)
318 if opts.format.lower() in ("fastq", "fq"):
319 qual = "".join(asciiFromInvProb(i[1]) for i in c)
320 print("@" + opts.name, seq, "+", qual, sep="\n")
321 else:
322 print(">" + opts.name, seq, sep="\n")
323
324 ##### Routines for aligning the sequences:
325
326 def toInt(x):
327 return int(round(x))
328
329 def printScoreParameters(scoreMatrix, gapExistCost, gapExtendCost, out):
330 alphabet = "ACGT"
331 print("#last", "-a", toInt(gapExistCost), "-b", toInt(gapExtendCost),
332 file=out)
333 print(" ", *alphabet, file=out)
334 for i, j in zip(alphabet, scoreMatrix):
335 print(i, *map(toInt, j), file=out)
336
337 xCrazyComplement = "ACGT" "RYKMBDHV" "U" # uracil
338 yCrazyComplement = "PFQE" "YRMKVHDB" "E"
339 def crazyComplement(base):
340 i = xCrazyComplement.find(base)
341 return yCrazyComplement[i] if i >= 0 else base
342
343 def transliteratedFastaLines(lines):
344 for i in lines:
345 if i[0] == ">":
346 isRev = i.startswith(">_R_")
347 elif isRev:
348 i = i.replace(*"Ea").replace(*"Qc").replace(*"Fg").replace(*"Pt")
349 i = i.lower()
350 yield i
351
352 def printFasta(name, seq, out):
353 print(">", name, sep="", file=out)
354 print(seq, file=out)
355
356 def printNumberedSequences(sequences, out):
357 for i, x in enumerate(sequences):
358 name, seq = x
359 printFasta(i, seq, out)
360
361 def printSequencesWithFakeAlphabet(opts, seqsZip, out):
362 for seqRank, s, isRev, beg, end in seqsZip:
363 if seqRank < 1:
364 continue
365 name, seq = s
366 seq = seq.upper() # xxx ???
367 if isRev:
368 name = "_R_" + name
369 seq = "".join(map(crazyComplement, reversed(seq)))
370 else:
371 seq = seq.replace("U", "T")
372 if not opts.all:
373 if beg >= end:
374 beg = end = 0
375 seq = seq[beg:end]
376 printFasta(name, seq, out)
377
378 def alignmentInput(opts, lines):
379 for line in lines:
380 if opts.verbose > 1:
381 sys.stderr.write(line)
382 fields = line.split()
383 if line[0] == "#":
384 if line.count("=") > 9:
385 logging.info(line.rstrip())
386 elif line[0] == "a":
387 for i in fields:
388 if i.startswith("score="):
389 score = int(i[6:])
390 seqRecords = []
391 elif line[0] == "s":
392 seqNum = int(fields[1])
393 seqBeg = int(fields[2])
394 seqEnd = seqBeg + int(fields[3])
395 strand = fields[4]
396 seqLen = int(fields[5])
397 seqAln = fields[6]
398 seqRecords.append((seqNum, seqLen, strand, seqBeg, seqEnd, seqAln))
399 elif line[0] == "p":
400 ref, qry = seqRecords
401 if ref[0] != qry[0]:
402 probCodes = fields[1]
403 yield -score, qry, ref, probCodes
404
405 def rankPerSeq(groupNumPerSeq, keptGroupNum):
406 rank = 0
407 for i in groupNumPerSeq:
408 if i == keptGroupNum:
409 rank += 1 # the first rank is 1, not 0, for MAFFT
410 yield rank
411 else:
412 yield 0
413
414 def findRange(oldRanges, newRange):
415 qryBeg, qryEnd, refBeg, refEnd = newRange
416 for i, x in enumerate(oldRanges):
417 qb, qe, rb, re = x
418 if qryBeg < qb and qryEnd < qe and refBeg < rb and refEnd < re:
419 return i
420 if qryBeg <= qb or qryEnd <= qe or refBeg <= rb or refEnd <= re:
421 return -1
422 return len(oldRanges)
423
424 def isBigDiagonalChange(opts, oldRanges, newRange, newRangeIndex):
425 qryBeg, qryEnd, refBeg, refEnd = newRange
426 if newRangeIndex > 0:
427 qb, qe, rb, re = oldRanges[newRangeIndex - 1]
428 if abs((re - qe) - (refBeg - qryBeg)) > opts.diagonal_max:
429 return True
430 if newRangeIndex < len(oldRanges):
431 qb, qe, rb, re = oldRanges[newRangeIndex]
432 if abs((rb - qb) - (refEnd - qryEnd)) > opts.diagonal_max:
433 return True
434 return False
435
436 def layoutOfSeqs(opts, numOfSequences, alignmentsSortedByScore):
437 dataPerSeq = [(i, False) for i in range(numOfSequences)]
438 alignmentOrder = []
439 keptAlignments = []
440 alignedRanges = collections.defaultdict(list)
441 for aln in alignmentsSortedByScore:
442 negScore, qry, ref, probCodes = aln
443 if qry[0] > ref[0]:
444 qry, ref = ref, qry
445 refNum, refLen, refStrand, refBeg, refEnd, refAln = ref
446 qryNum, qryLen, qryStrand, qryBeg, qryEnd, qryAln = qry
447 refGroupNum, isRevRef = dataPerSeq[refNum]
448 qryGroupNum, isRevQry = dataPerSeq[qryNum]
449 isOpposite = (isRevQry != isRevRef)
450 isRevAln = (qryStrand != refStrand)
451 isFlip = (isRevAln != isOpposite)
452 oldRanges = alignedRanges[qryNum, refNum]
453 if refStrand == "-":
454 refBeg, refEnd = refLen - refEnd, refLen - refBeg
455 qryBeg, qryEnd = qryLen - qryEnd, qryLen - qryBeg
456 newRange = qryBeg, qryEnd, refBeg, refEnd
457 rpos = findRange(oldRanges, newRange)
458 if refGroupNum == qryGroupNum:
459 if (isFlip or rpos < 0 or
460 isBigDiagonalChange(opts, oldRanges, newRange, rpos)):
461 continue
462 else:
463 minGroupNum = min(refGroupNum, qryGroupNum)
464 maxGroupNum = max(refGroupNum, qryGroupNum)
465 alignmentOrder.append((minGroupNum, maxGroupNum))
466 for i, x in enumerate(dataPerSeq):
467 groupNum, isRev = x
468 if groupNum == maxGroupNum:
469 dataPerSeq[i] = minGroupNum, isRev != isFlip
470 keptAlignments.append(aln)
471 oldRanges.insert(rpos, newRange)
472 return dataPerSeq, alignmentOrder, keptAlignments
473
474 def updateRange(begPerSeq, endPerSeq, isRevPerSeq, seqRecord):
475 seqNum, seqLen, seqStrand, seqBeg, seqEnd, seqAln = seqRecord
476 if (seqStrand == "-") != isRevPerSeq[seqNum]:
477 seqBeg, seqEnd = seqLen - seqEnd, seqLen - seqBeg
478 begPerSeq[seqNum] = min(begPerSeq[seqNum], seqBeg)
479 endPerSeq[seqNum] = max(endPerSeq[seqNum], seqEnd)
480
481 def alignedRangePerSeq(keptAlignments, isRevPerSeq):
482 begPerSeq = [sys.maxsize] * len(isRevPerSeq)
483 endPerSeq = [0] * len(isRevPerSeq)
484 for negScore, qry, ref, probCodes in keptAlignments:
485 updateRange(begPerSeq, endPerSeq, isRevPerSeq, ref)
486 updateRange(begPerSeq, endPerSeq, isRevPerSeq, qry)
487 return begPerSeq, endPerSeq
488
489 def pairwiseAnchors(opts, minProbCode, alns, seqRanks, isRevPerSeq, begPerSeq):
490 for negScore, qry, ref, probCodes in alns:
491 if qry[0] > ref[0]:
492 qry, ref = ref, qry
493 refNum, refLen, refStrand, refBeg, refEnd, refAln = ref
494 qryNum, qryLen, qryStrand, qryBeg, qryEnd, qryAln = qry
495 refRank = seqRanks[refNum]
496 qryRank = seqRanks[qryNum]
497 if refRank < 1 or qryRank < 1:
498 continue
499 if isRevPerSeq[refNum] != (refStrand == "-"):
500 refAln = refAln[::-1]
501 qryAln = qryAln[::-1]
502 probCodes = probCodes[::-1]
503 refBeg = refLen - refEnd
504 qryBeg = qryLen - qryEnd
505 if not opts.all:
506 refBeg -= begPerSeq[refNum]
507 qryBeg -= begPerSeq[qryNum]
508 qBeg = rBeg = size = 0
509 for p, q, r in zip(probCodes, qryAln, refAln):
510 if q != "-":
511 if r != "-":
512 if p >= minProbCode:
513 if qBeg + size < qryBeg or rBeg + size < refBeg:
514 if size:
515 yield qryRank, refRank, qBeg, rBeg, size
516 qBeg = qryBeg
517 rBeg = refBeg
518 size = 0
519 size += 1
520 refBeg += 1
521 qryBeg += 1
522 elif r != "-":
523 refBeg += 1
524 if size:
525 yield qryRank, refRank, qBeg, rBeg, size
526
527 def prepareToAlign(opts, scores, sequences, tmpdir):
528 optP = "-P" + str(opts.P)
529 fwdMatrix, revMatrix, gapExistCost, gapExtendCost = scores
530
531 fwdMat = os.path.join(tmpdir, "fwd.mat")
532 with open(fwdMat, "w") as f:
533 printScoreParameters(fwdMatrix, gapExistCost, gapExtendCost, f)
534
535 revMat = os.path.join(tmpdir, "rev.mat")
536 with open(revMat, "w") as f:
537 printScoreParameters(revMatrix, gapExistCost, gapExtendCost, f)
538
539 seqFile = os.path.join(tmpdir, "x.fa")
540 with open(seqFile, "w") as f:
541 printNumberedSequences(sequences, f)
542
543 db = os.path.join(tmpdir, "db")
544 if opts.u:
545 cmd = "lastdb", "-c", optP, "-uRY" + str(opts.u), db, seqFile
546 else:
547 cmd = "lastdb", "-c", optP, "-uNEAR", "-W" + str(opts.W), db, seqFile
548 logging.info(" ".join(cmd))
549 subprocess.check_call(cmd)
550
551 return fwdMat, revMat, seqFile, db
552
553 def addStrandAlignments(alignments, opts, db, seqFile, matFile, strandNum):
554 optP = "-P" + str(opts.P)
555 optD = "-D1e9"
556 mOpt = "-m" + str(opts.m)
557 zOpt = "-z" + str(opts.z) + "g"
558 sOpt = "-s" + str(strandNum)
559 cmd = ("lastal", sOpt, "-j4", optD, optP, mOpt, zOpt, "-p", matFile,
560 db, seqFile)
561 logging.info(" ".join(cmd))
562 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
563 universal_newlines=True)
564 alignments.extend(alignmentInput(opts, proc.stdout))
565 retcode = proc.wait()
566 if retcode:
567 raise subprocess.CalledProcessError(retcode, cmd)
568
569 def pairwiseAlignments(opts, fwdMat, revMat, seqFile, db):
570 alignments = []
571 addStrandAlignments(alignments, opts, db, seqFile, fwdMat, 1)
572 addStrandAlignments(alignments, opts, db, seqFile, revMat, 0)
573 alignments.sort()
574 return alignments
575
576 def checkMafftVersion():
577 cmd = "mafft", "--version"
578 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
579 universal_newlines=True)
580 out, err = p.communicate()
581 if not err.startswith("v"):
582 raise RuntimeError("can't get MAFFT version")
583 logging.info("MAFFT " + err.rstrip())
584 v = err.split()[0]
585 minVersion = "v4.442"
586 if len(v) <= len(minVersion) and v < minVersion:
587 raise RuntimeError("MAFFT version must be >= " + minVersion)
588
589 def assemble(opts, scale, probMatrix, gapProbs, sequences, tmpdir):
590 scores = alignmentScoresFromProbs(scale, probMatrix, gapProbs)
591 fwdMatrix, revMatrix, gapExistCost, gapExtendCost = scores
592 mafftGapOpts = mafftGapOptions(scores)
593 tmpFileNames = prepareToAlign(opts, scores, sequences, tmpdir)
594
595 alignments = pairwiseAlignments(opts, *tmpFileNames)
596 layoutData = layoutOfSeqs(opts, len(sequences), alignments)
597 dataPerSeq, alignmentOrder, keptAlignments = layoutData
598 groupNumPerSeq, isRevPerSeq = zip(*dataPerSeq)
599
600 numOfSeqsPerGroup = [0] * len(sequences)
601 for i in groupNumPerSeq:
602 numOfSeqsPerGroup[i] += 1
603 maxSeqsPerGroup = max(numOfSeqsPerGroup)
604
605 numOfGroups = len(sequences) - len(alignmentOrder)
606 text = "groups (of sequences linked by pairwise alignments): {0}"
607 logging.info(text.format(numOfGroups))
608
609 if maxSeqsPerGroup < len(sequences):
610 text = "using {0} out of {1} sequences (linked by pairwise alignments)"
611 logging.warning(text.format(maxSeqsPerGroup, len(sequences)))
612
613 keptGroupNum = numOfSeqsPerGroup.index(maxSeqsPerGroup)
614 seqRanks = list(rankPerSeq(groupNumPerSeq, keptGroupNum))
615
616 begPerSeq, endPerSeq = alignedRangePerSeq(keptAlignments, isRevPerSeq)
617
618 outName = opts.out if opts.out else os.path.join(tmpdir, "mafft")
619
620 with open(outName + ".fa", "w") as f:
621 seqsZip = zip(seqRanks, sequences, isRevPerSeq, begPerSeq, endPerSeq)
622 printSequencesWithFakeAlphabet(opts, seqsZip, f)
623
624 with open(outName + ".tree", "w") as f:
625 for i, j in alignmentOrder:
626 iRank = seqRanks[i]
627 jRank = seqRanks[j]
628 if iRank > 0 and jRank > 0:
629 print(iRank, jRank, 0.1, 0.1, file=f)
630
631 minProbScore = int(math.ceil(-10 * math.log10(opts.prob)))
632 minProbCode = chr(33 + minProbScore)
633 logging.info("minProbScore: " + str(minProbScore))
634 logging.info("minProbCode: " + minProbCode)
635
636 with open(outName + ".pair", "w") as f:
637 # the following groupby saves memory:
638 for negScore, alns in itertools.groupby(keptAlignments, itemgetter(0)):
639 p = pairwiseAnchors(opts, minProbCode, alns,
640 seqRanks, isRevPerSeq, begPerSeq)
641 for k, v in itertools.groupby(sorted(p)):
642 qryRank, refRank, qBeg, rBeg, size = k
643 print(qryRank, refRank, qBeg+1, qBeg+size, rBeg+1, rBeg+size,
644 -negScore, file=f)
645
646 with open(outName + ".mtx", "w") as f:
647 printMafftParams(fwdMatrix, revMatrix, mafftGapOpts, f)
648
649 if opts.out:
650 return
651
652 checkMafftVersion()
653
654 cmd = ["mafft", "--amino"] + mafftGapOpts
655 if not opts.verbose:
656 cmd += ["--quiet"]
657 if opts.mafft:
658 cmd += opts.mafft.split()
659 cmd += ["--aamatrix", outName+".mtx", "--treein", outName+".tree",
660 "--anchors", outName+".pair", outName+".fa"]
661 logging.info(" ".join(cmd))
662 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
663 universal_newlines=True)
664 fastaLines = transliteratedFastaLines(proc.stdout)
665
666 if opts.alignment:
667 for i in fastaLines:
668 print(i, end="")
669 else:
670 alignedSeqs = [nameAndSeqFromFastx(i) for i in fastxInput(fastaLines)]
671 printConsensusSeq(opts, probMatrix, alignedSeqs)
672
673 def main(opts, trainFile, seqFile):
674 logLevel = logging.INFO if opts.verbose else logging.WARNING
675 logging.basicConfig(format="%(filename)s: %(message)s", level=logLevel)
676
677 scale, probMatrix, gapProbs = parametersFromLastTrain(trainFile)
678 probMatrix = list(matrixWithComplementSymmetricRows(probMatrix))
679
680 fastx = fastxInput(openFile(seqFile))
681 sequences = [nameAndSeqFromFastx(i) for i in fastx]
682
683 okSymbols = "ACGT" "U" "MRWSYKVHDBN" "-"
684 okSet = set(okSymbols.upper() + okSymbols.lower())
685 for name, seq in sequences:
686 diff = set(seq).difference(okSet)
687 if diff:
688 bad = "".join(sorted(diff))
689 raise RuntimeError("not allowed in nucleotide sequences: " + bad)
690
691 if opts.consensus:
692 return printConsensusSeq(opts, probMatrix, sequences)
693
694 if not sequences:
695 raise RuntimeError("zero sequences")
696
697 sequences = [(name, seq.replace("-", "")) for name, seq in sequences]
698
699 tmpdir = tempfile.mkdtemp(prefix="lamassemble")
700 try:
701 assemble(opts, scale, probMatrix, gapProbs, sequences, tmpdir)
702 finally:
703 shutil.rmtree(tmpdir)
704
705 if __name__ == "__main__":
706 signal.signal(signal.SIGPIPE, signal.SIG_DFL) # avoid silly error message
707 usage = "%prog [options] last-train.out sequences.fx > consensus.fa"
708 descr = "Merge DNA sequences into a consensus sequence."
709 op = optparse.OptionParser(usage=usage, description=descr)
710 op.add_option("-a", "--alignment", action="store_true",
711 help="print an alignment, not a consensus")
712 op.add_option("-c", "--consensus", action="store_true",
713 help="just make a consensus, of already-aligned sequences")
714 op.add_option("-f", "--format", metavar="FMT", default="fasta", help=
715 "output format: fasta/fa or fastq/fq (default=%default)")
716 op.add_option("-g", "--gap-max", metavar="G", type="float", default=50,
717 help="use alignment columns with <= G% gaps "
718 "(default=%default)")
719 op.add_option("--end", action="store_true",
720 help="... including gaps past the ends of the sequences")
721 op.add_option("-s", "--seq-min", metavar="S", default="1", help="omit "
722 "consensus flanks with < S sequences (default=%default)")
723 op.add_option("-n", "--name", default="lamassembled",
724 help="name of the consensus sequence (default=%default)")
725 op.add_option("-o", "--out", metavar="BASE",
726 help="just write MAFFT input files, named BASE.xxx")
727 op.add_option("-p", "--prob", metavar="P", type="float", default=0.002,
728 help="use pairwise restrictions with error probability <= P "
729 "(default=%default)")
730 op.add_option("-d", "--diagonal-max", type="int", default=1000,
731 metavar="D", help="max change in alignment diagonal "
732 "between pairwise alignments (default=%default)")
733 op.add_option("-v", "--verbose", action="count", default=0,
734 help="show progress messages")
735 op.add_option("--all", action="store_true",
736 help="use all of each sequence, not just aligning part")
737 op.add_option("--mafft", metavar="ARGS",
738 help="additional arguments for MAFFT")
739
740 og = optparse.OptionGroup(op, "LAST options")
741 og.add_option("-P", type="int", default=1,
742 help="number of parallel threads (default=%default)")
743 og.add_option("-u", metavar="RY", type="int", help=
744 "use ~1 per this many initial matches")
745 og.add_option("-W", type="int", default=19, help="use minimum positions "
746 "in length-W windows (default=%default)")
747 og.add_option("-m", type="int", default=5, help=
748 "max initial matches per query position (default=%default)")
749 og.add_option("-z", type="int", default=30,
750 help="max gap length (default=%default)")
751 op.add_option_group(og)
752
753 opts, args = op.parse_args()
754 if len(args) == 2:
755 try:
756 main(opts, *args)
757 except RuntimeError as e:
758 prog = os.path.basename(sys.argv[0])
759 sys.exit(prog + ": error: " + str(e))
760 else:
761 op.print_help()