Debian Codegraph @

bin/last-dotplot

raw
1 #! /usr/bin/env python3
2 # Author: Martin C. Frith 2008
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Read pair-wise alignments: write an "Oxford grid", a.k.a. dotplot.
6
7 # TODO: Currently, pixels with zero aligned nt-pairs are white, and
8 # pixels with one or more aligned nt-pairs are black. This can look
9 # too crowded for large genome alignments. I tried shading each pixel
10 # according to the number of aligned nt-pairs within it, but the
11 # result is too faint. How can this be done better?
12
13 import collections
14 import functools
15 import gzip
16 from fnmatch import fnmatchcase
17 import logging
18 from operator import itemgetter
19 import subprocess
20 import itertools, optparse, os, re, sys
21
22 # Try to make PIL/PILLOW work:
23 try:
24 from PIL import Image, ImageDraw, ImageFont, ImageColor
25 except ImportError:
26 import Image, ImageDraw, ImageFont, ImageColor
27
28 try:
29 from future_builtins import zip
30 except ImportError:
31 pass
32
33 def myOpen(fileName): # faster than fileinput
34 if fileName is None:
35 return []
36 if fileName == "-":
37 return sys.stdin
38 if fileName.endswith(".gz"):
39 return gzip.open(fileName, "rt") # xxx dubious for Python2
40 return open(fileName)
41
42 def groupByFirstItem(things):
43 for k, v in itertools.groupby(things, itemgetter(0)):
44 yield k, [i[1:] for i in v]
45
46 def commaSeparatedInts(text):
47 return map(int, text.rstrip(",").split(","))
48
49 def croppedBlocks(blocks, ranges1, ranges2):
50 headBeg1, headBeg2, headSize = blocks[0]
51 for r1 in ranges1:
52 for r2 in ranges2:
53 cropBeg1, cropEnd1 = r1
54 if headBeg1 < 0:
55 cropBeg1, cropEnd1 = -cropEnd1, -cropBeg1
56 cropBeg2, cropEnd2 = r2
57 if headBeg2 < 0:
58 cropBeg2, cropEnd2 = -cropEnd2, -cropBeg2
59 for beg1, beg2, size in blocks:
60 b1 = max(cropBeg1, beg1)
61 e1 = min(cropEnd1, beg1 + size)
62 if b1 >= e1: continue
63 offset = beg2 - beg1
64 b2 = max(cropBeg2, b1 + offset)
65 e2 = min(cropEnd2, e1 + offset)
66 if b2 >= e2: continue
67 yield b2 - offset, b2, e2 - b2
68
69 def tabBlocks(blocks, beg1, beg2, sizeMul, seq1mul, seq2mul):
70 '''Get the gapless blocks of an alignment, from LAST tabular format.'''
71 for i in blocks:
72 if len(i) > 1:
73 beg1 += i[0]
74 beg2 += i[1]
75 else:
76 size = i[0]
77 yield beg1 * seq1mul, beg2 * seq2mul, size * sizeMul
78 beg1 += size * seq2mul
79 beg2 += size * seq1mul
80
81 def mafBlocks(beg1, beg2, seq1, seq2):
82 '''Get the gapless blocks of an alignment, from MAF format.'''
83 size = 0
84 for x, y in zip(seq1, seq2):
85 if x == "-":
86 if size:
87 yield beg1, beg2, size
88 beg1 += size
89 beg2 += size
90 size = 0
91 beg2 += 1
92 elif y == "-":
93 if size:
94 yield beg1, beg2, size
95 beg1 += size
96 beg2 += size
97 size = 0
98 beg1 += 1
99 else:
100 size += 1
101 if size: yield beg1, beg2, size
102
103 def alignmentFromSegment(qrySeqName, qrySeqLen, segment):
104 refSeqLen = sys.maxsize # XXX
105 refSeqName, refSeqBeg, qrySeqBeg, size = segment
106 block = refSeqBeg, qrySeqBeg, size
107 return refSeqName, refSeqLen, qrySeqName, qrySeqLen, [block]
108
109 def dataFromPsl(strand, seqName, seqLen, alnBeg, alnEnd, blockBegs, blockLens):
110 seqLen = int(seqLen)
111 blockBegs = list(commaSeparatedInts(blockBegs))
112 if strand == "+":
113 end = int(alnEnd)
114 else:
115 end = -int(alnBeg)
116 blockBegs = [i - seqLen for i in blockBegs]
117 isTranslatedDna = blockBegs[-1] + blockLens[-1] < end
118 return seqName, seqLen, blockBegs, isTranslatedDna
119
120 def dataFromTab(blockSum, seqName, alnBeg, span, strand, seqLen):
121 alnBeg = int(alnBeg)
122 seqLen = int(seqLen)
123 if strand == "-": alnBeg -= seqLen
124 isTranslatedDna = blockSum < int(span)
125 return seqName, seqLen, alnBeg, isTranslatedDna
126
127 def dataFromMaf(junk, seqName, alnBeg, span, strand, seqLen, alnSeq):
128 alnBeg = int(alnBeg)
129 seqLen = int(seqLen)
130 if strand == "-": alnBeg -= seqLen
131 if int(span) < len(alnSeq) - alnSeq.count("-"):
132 alnBeg *= 3 # protein coordinate -> DNA coordinate
133 seqLen *= 3 # protein length -> DNA length
134 return seqName, seqLen, alnBeg, alnSeq
135
136 def aaToNtFactors(isTranslatedSeq1, isTranslatedSeq2):
137 if isTranslatedSeq1 and isTranslatedSeq2: return 3, 1, 1
138 if isTranslatedSeq1: return 3, 1, 3 # seq1 is DNA, seq2 is protein
139 if isTranslatedSeq2: return 3, 3, 1 # seq2 is DNA, seq1 is protein
140 return 1, 1, 1
141
142 def alignmentInput(lines):
143 '''Read alignments and sequence lengths.'''
144 mafCount = 0
145 qrySeqName = ""
146 segments = []
147 for line in lines:
148 w = line.split()
149 if line[0] == "#":
150 pass
151 elif len(w) == 1:
152 for i in segments:
153 yield alignmentFromSegment(qrySeqName, qrySeqLen, i)
154 qrySeqName = w[0]
155 qrySeqLen = 0
156 segments = []
157 elif len(w) == 2 and qrySeqName and w[1].isdigit():
158 qrySeqLen += int(w[1])
159 elif len(w) == 4 and qrySeqName and w[1].isdigit() and w[3].isdigit():
160 refSeqName, refSeqBeg, refSeqEnd = w[0], int(w[1]), int(w[3])
161 size = abs(refSeqEnd - refSeqBeg)
162 if refSeqBeg > refSeqEnd:
163 refSeqBeg = -refSeqBeg
164 segments.append((refSeqName, refSeqBeg, qrySeqLen, size))
165 qrySeqLen += size
166 elif len(w) > 20: # PSL format
167 strand = w[8]
168 strand2 = strand[0]
169 strand1 = strand[1] if len(strand) > 1 else "+"
170 sizes = list(commaSeparatedInts(w[18]))
171 d1 = dataFromPsl(strand1, w[13], w[14], w[15], w[16], w[20], sizes)
172 d2 = dataFromPsl(strand2, w[ 9], w[10], w[11], w[12], w[19], sizes)
173 chr1, seqlen1, beg1s, isTransDna1 = d1
174 chr2, seqlen2, beg2s, isTransDna2 = d2
175 sizeMul, seq1mul, seq2mul = aaToNtFactors(isTransDna1, isTransDna2)
176 sizes = [i * sizeMul for i in sizes]
177 beg1s = [i * seq1mul for i in beg1s]
178 beg2s = [i * seq2mul for i in beg2s]
179 blocks = zip(beg1s, beg2s, sizes)
180 yield chr1, seqlen1 * seq1mul, chr2, seqlen2 * seq2mul, blocks
181 elif line[0].isdigit(): # tabular format
182 blocks = w[11].split(",")
183 blocks = [[int(j) for j in i.split(":")] for i in blocks]
184 blockSum1 = sum(i[0] for i in blocks)
185 blockSum2 = sum(i[-1] for i in blocks)
186 chr1, seqlen1, beg1, isTransDna1 = dataFromTab(blockSum1, *w[1:6])
187 chr2, seqlen2, beg2, isTransDna2 = dataFromTab(blockSum2, *w[6:11])
188 sizeMul, seq1mul, seq2mul = aaToNtFactors(isTransDna1, isTransDna2)
189 blocks = tabBlocks(blocks, beg1, beg2, sizeMul, seq1mul, seq2mul)
190 yield chr1, seqlen1 * seq1mul, chr2, seqlen2 * seq2mul, blocks
191 elif line[0] == "s": # MAF format
192 if mafCount == 0:
193 chr1, seqlen1, beg1, seq1 = dataFromMaf(*w)
194 mafCount = 1
195 else:
196 chr2, seqlen2, beg2, seq2 = dataFromMaf(*w)
197 blocks = mafBlocks(beg1, beg2, seq1, seq2)
198 yield chr1, seqlen1, chr2, seqlen2, blocks
199 mafCount = 0
200 for i in segments:
201 yield alignmentFromSegment(qrySeqName, qrySeqLen, i)
202
203 def seqRequestFromText(text):
204 s = text.split()
205 if len(s) == 3:
206 return s[0], int(s[1]), int(s[2])
207 if ":" in text:
208 pattern, interval = text.rsplit(":", 1)
209 if "-" in interval:
210 beg, end = interval.rsplit("-", 1)
211 return pattern, int(beg), int(end) # beg may be negative
212 return text, 0, sys.maxsize
213
214 def rangesFromSeqName(seqRequests, name, seqLen):
215 if seqRequests:
216 base = name.split(".", 1)[-1] # allow for names like hg19.chr7
217 for pat, beg, end in seqRequests:
218 if fnmatchcase(name, pat) or fnmatchcase(base, pat):
219 yield max(beg, 0), min(end, seqLen)
220 else:
221 yield 0, seqLen
222
223 def updateSeqs(coverDict, seqRanges, seqName, ranges, coveredRange):
224 beg, end = coveredRange
225 if beg < 0:
226 coveredRange = -end, -beg
227 if seqName in coverDict:
228 coverDict[seqName].append(coveredRange)
229 else:
230 coverDict[seqName] = [coveredRange]
231 for beg, end in ranges:
232 r = seqName, beg, end
233 seqRanges.append(r)
234
235 def readAlignments(fileName, opts):
236 '''Read alignments and sequence limits.'''
237 seqRequests1 = [seqRequestFromText(i) for i in opts.seq1]
238 seqRequests2 = [seqRequestFromText(i) for i in opts.seq2]
239
240 alignments = []
241 seqRanges1 = []
242 seqRanges2 = []
243 coverDict1 = {}
244 coverDict2 = {}
245 lines = myOpen(fileName)
246 for seqName1, seqLen1, seqName2, seqLen2, blocks in alignmentInput(lines):
247 ranges1 = sorted(rangesFromSeqName(seqRequests1, seqName1, seqLen1))
248 if not ranges1: continue
249 ranges2 = sorted(rangesFromSeqName(seqRequests2, seqName2, seqLen2))
250 if not ranges2: continue
251 b = list(croppedBlocks(list(blocks), ranges1, ranges2))
252 if not b: continue
253 aln = seqName1, seqName2, b
254 alignments.append(aln)
255 coveredRange1 = b[0][0], b[-1][0] + b[-1][2]
256 updateSeqs(coverDict1, seqRanges1, seqName1, ranges1, coveredRange1)
257 coveredRange2 = b[0][1], b[-1][1] + b[-1][2]
258 updateSeqs(coverDict2, seqRanges2, seqName2, ranges2, coveredRange2)
259 return alignments, seqRanges1, coverDict1, seqRanges2, coverDict2
260
261 def nameAndRangesFromDict(cropDict, seqName):
262 if seqName in cropDict:
263 return seqName, cropDict[seqName]
264 n = seqName.split(".", 1)[-1]
265 if n in cropDict:
266 return n, cropDict[n]
267 return seqName, []
268
269 def rangesForSecondaryAlignments(primaryRanges, seqLen):
270 if primaryRanges:
271 return primaryRanges
272 return [(0, seqLen)]
273
274 def readSecondaryAlignments(opts, cropRanges1, cropRanges2):
275 cropDict1 = dict(groupByFirstItem(cropRanges1))
276 cropDict2 = dict(groupByFirstItem(cropRanges2))
277
278 alignments = []
279 seqRanges1 = []
280 seqRanges2 = []
281 coverDict1 = {}
282 coverDict2 = {}
283 lines = myOpen(opts.alignments)
284 for seqName1, seqLen1, seqName2, seqLen2, blocks in alignmentInput(lines):
285 seqName1, ranges1 = nameAndRangesFromDict(cropDict1, seqName1)
286 seqName2, ranges2 = nameAndRangesFromDict(cropDict2, seqName2)
287 if not ranges1 and not ranges2:
288 continue
289 r1 = rangesForSecondaryAlignments(ranges1, seqLen1)
290 r2 = rangesForSecondaryAlignments(ranges2, seqLen2)
291 b = list(croppedBlocks(list(blocks), r1, r2))
292 if not b: continue
293 aln = seqName1, seqName2, b
294 alignments.append(aln)
295 if not ranges1:
296 coveredRange1 = b[0][0], b[-1][0] + b[-1][2]
297 updateSeqs(coverDict1, seqRanges1, seqName1, r1, coveredRange1)
298 if not ranges2:
299 coveredRange2 = b[0][1], b[-1][1] + b[-1][2]
300 updateSeqs(coverDict2, seqRanges2, seqName2, r2, coveredRange2)
301 return alignments, seqRanges1, coverDict1, seqRanges2, coverDict2
302
303 def twoValuesFromOption(text, separator):
304 if separator in text:
305 return text.split(separator)
306 return text, text
307
308 def mergedRanges(ranges):
309 oldBeg, maxEnd = ranges[0]
310 for beg, end in ranges:
311 if beg > maxEnd:
312 yield oldBeg, maxEnd
313 oldBeg = beg
314 maxEnd = end
315 elif end > maxEnd:
316 maxEnd = end
317 yield oldBeg, maxEnd
318
319 def mergedRangesPerSeq(coverDict):
320 for k, v in coverDict.items():
321 v.sort()
322 yield k, list(mergedRanges(v))
323
324 def coveredLength(mergedCoverDict):
325 return sum(sum(e - b for b, e in v) for v in mergedCoverDict.values())
326
327 def trimmed(seqRanges, coverDict, minAlignedBases, maxGapFrac, endPad, midPad):
328 maxEndGapFrac, maxMidGapFrac = twoValuesFromOption(maxGapFrac, ",")
329 maxEndGap = max(float(maxEndGapFrac) * minAlignedBases, endPad * 1.0)
330 maxMidGap = max(float(maxMidGapFrac) * minAlignedBases, midPad * 2.0)
331
332 for seqName, rangeBeg, rangeEnd in seqRanges:
333 seqBlocks = coverDict[seqName]
334 blocks = [i for i in seqBlocks if i[0] < rangeEnd and i[1] > rangeBeg]
335 if blocks[0][0] - rangeBeg > maxEndGap:
336 rangeBeg = blocks[0][0] - endPad
337 for j, y in enumerate(blocks):
338 if j:
339 x = blocks[j - 1]
340 if y[0] - x[1] > maxMidGap:
341 yield seqName, rangeBeg, x[1] + midPad
342 rangeBeg = y[0] - midPad
343 if rangeEnd - blocks[-1][1] > maxEndGap:
344 rangeEnd = blocks[-1][1] + endPad
345 yield seqName, rangeBeg, rangeEnd
346
347 def rangesWithStrandInfo(seqRanges, strandOpt, alignments, seqIndex):
348 if strandOpt == "1":
349 forwardMinusReverse = collections.defaultdict(int)
350 for i in alignments:
351 blocks = i[2]
352 beg1, beg2, size = blocks[0]
353 numOfAlignedLetterPairs = sum(i[2] for i in blocks)
354 if (beg1 < 0) != (beg2 < 0): # opposite-strand alignment
355 numOfAlignedLetterPairs *= -1
356 forwardMinusReverse[i[seqIndex]] += numOfAlignedLetterPairs
357 strandNum = 0
358 for seqName, beg, end in seqRanges:
359 if strandOpt == "1":
360 strandNum = 1 if forwardMinusReverse[seqName] >= 0 else 2
361 yield seqName, beg, end, strandNum
362
363 def natural_sort_key(my_string):
364 '''Return a sort key for "natural" ordering, e.g. chr9 < chr10.'''
365 parts = re.split(r'(\d+)', my_string)
366 parts[1::2] = map(int, parts[1::2])
367 return parts
368
369 def nameKey(oneSeqRanges):
370 return natural_sort_key(oneSeqRanges[0][0])
371
372 def sizeKey(oneSeqRanges):
373 return sum(b - e for n, b, e, s in oneSeqRanges), nameKey(oneSeqRanges)
374
375 def alignmentKey(seqNamesToLists, oneSeqRanges):
376 seqName = oneSeqRanges[0][0]
377 alignmentsOfThisSequence = seqNamesToLists[seqName]
378 numOfAlignedLetterPairs = sum(i[3] for i in alignmentsOfThisSequence)
379 toMiddle = numOfAlignedLetterPairs // 2
380 for i in alignmentsOfThisSequence:
381 toMiddle -= i[3]
382 if toMiddle < 0:
383 return i[1:3] # sequence-rank and "position" of this alignment
384
385 def rankAndFlipPerSeq(seqRanges):
386 rangesGroupedBySeqName = itertools.groupby(seqRanges, itemgetter(0))
387 for rank, group in enumerate(rangesGroupedBySeqName):
388 seqName, ranges = group
389 strandNum = next(ranges)[3]
390 flip = 1 if strandNum < 2 else -1
391 yield seqName, (rank, flip)
392
393 def alignmentSortData(alignments, seqIndex, otherNamesToRanksAndFlips):
394 otherIndex = 1 - seqIndex
395 for i in alignments:
396 blocks = i[2]
397 otherRank, otherFlip = otherNamesToRanksAndFlips[i[otherIndex]]
398 otherPos = otherFlip * abs(blocks[0][otherIndex] +
399 blocks[-1][otherIndex] + blocks[-1][2])
400 numOfAlignedLetterPairs = sum(i[2] for i in blocks)
401 yield i[seqIndex], otherRank, otherPos, numOfAlignedLetterPairs
402
403 def mySortedRanges(seqRanges, sortOpt, seqIndex, alignments, otherRanges):
404 rangesGroupedBySeqName = itertools.groupby(seqRanges, itemgetter(0))
405 g = [list(ranges) for seqName, ranges in rangesGroupedBySeqName]
406 for i in g:
407 if i[0][3] > 1:
408 i.reverse()
409 if sortOpt == "1":
410 g.sort(key=nameKey)
411 if sortOpt == "2":
412 g.sort(key=sizeKey)
413 if sortOpt == "3":
414 otherNamesToRanksAndFlips = dict(rankAndFlipPerSeq(otherRanges))
415 alns = sorted(alignmentSortData(alignments, seqIndex,
416 otherNamesToRanksAndFlips))
417 alnsGroupedBySeqName = itertools.groupby(alns, itemgetter(0))
418 seqNamesToLists = dict((k, list(v)) for k, v in alnsGroupedBySeqName)
419 g.sort(key=functools.partial(alignmentKey, seqNamesToLists))
420 return [j for i in g for j in i]
421
422 def allSortedRanges(opts, alignments, alignmentsB,
423 seqRanges1, seqRangesB1, seqRanges2, seqRangesB2):
424 o1, oB1 = twoValuesFromOption(opts.strands1, ":")
425 o2, oB2 = twoValuesFromOption(opts.strands2, ":")
426 if o1 == "1" and o2 == "1":
427 raise RuntimeError("the strand options have circular dependency")
428 seqRanges1 = list(rangesWithStrandInfo(seqRanges1, o1, alignments, 0))
429 seqRanges2 = list(rangesWithStrandInfo(seqRanges2, o2, alignments, 1))
430 seqRangesB1 = list(rangesWithStrandInfo(seqRangesB1, oB1, alignmentsB, 0))
431 seqRangesB2 = list(rangesWithStrandInfo(seqRangesB2, oB2, alignmentsB, 1))
432
433 o1, oB1 = twoValuesFromOption(opts.sort1, ":")
434 o2, oB2 = twoValuesFromOption(opts.sort2, ":")
435 if o1 == "3" and o2 == "3":
436 raise RuntimeError("the sort options have circular dependency")
437 if o1 != "3":
438 s1 = mySortedRanges(seqRanges1, o1, None, None, None)
439 if o2 != "3":
440 s2 = mySortedRanges(seqRanges2, o2, None, None, None)
441 if o1 == "3":
442 s1 = mySortedRanges(seqRanges1, o1, 0, alignments, s2)
443 if o2 == "3":
444 s2 = mySortedRanges(seqRanges2, o2, 1, alignments, s1)
445 t1 = mySortedRanges(seqRangesB1, oB1, 0, alignmentsB, s2)
446 t2 = mySortedRanges(seqRangesB2, oB2, 1, alignmentsB, s1)
447 return s1 + t1, s2 + t2
448
449 def myTextsize(textDraw, font, text):
450 try:
451 out = textDraw.textsize(text, font=font)
452 except AttributeError:
453 a, b, c, d = textDraw.textbbox((0, 0), text, font=font)
454 out = c, d
455 return out
456
457 def sizesPerText(texts, font, textDraw):
458 sizes = 0, 0
459 for t in texts:
460 if textDraw is not None:
461 sizes = myTextsize(textDraw, font, t)
462 yield t, sizes
463
464 def prettyNum(n):
465 t = str(n)
466 groups = []
467 while t:
468 groups.append(t[-3:])
469 t = t[:-3]
470 return ",".join(reversed(groups))
471
472 def sizeText(size):
473 suffixes = "bp", "kb", "Mb", "Gb"
474 for i, x in enumerate(suffixes):
475 j = 10 ** (i * 3)
476 if size < j * 10:
477 return "%.2g" % (1.0 * size / j) + x
478 if size < j * 1000 or i == len(suffixes) - 1:
479 return "%.0f" % (1.0 * size / j) + x
480
481 def labelText(seqRange, labelOpt):
482 seqName, beg, end, strandNum = seqRange
483 if labelOpt == 1:
484 return seqName + ": " + sizeText(end - beg)
485 if labelOpt == 2:
486 return seqName + ":" + prettyNum(beg) + ": " + sizeText(end - beg)
487 if labelOpt == 3:
488 return seqName + ":" + prettyNum(beg) + "-" + prettyNum(end)
489 return seqName
490
491 def rangeLabels(seqRanges, labelOpt, font, textDraw, textRot):
492 x = y = 0
493 for r in seqRanges:
494 text = labelText(r, labelOpt)
495 if textDraw is not None:
496 x, y = myTextsize(textDraw, font, text)
497 if textRot:
498 x, y = y, x
499 yield text, x, y, r[3]
500
501 def dataFromRanges(sortedRanges, font, textDraw, labelOpt, textRot):
502 for seqName, rangeBeg, rangeEnd, strandNum in sortedRanges:
503 out = [seqName, str(rangeBeg), str(rangeEnd)]
504 if strandNum > 0:
505 out.append(".+-"[strandNum])
506 logging.info("\t".join(out))
507 logging.info("")
508 rangeSizes = [e - b for n, b, e, s in sortedRanges]
509 labs = list(rangeLabels(sortedRanges, labelOpt, font, textDraw, textRot))
510 margin = max(i[2] for i in labs)
511 # xxx the margin may be too big, because some labels may get omitted
512 return rangeSizes, labs, margin
513
514 def div_ceil(x, y):
515 '''Return x / y rounded up.'''
516 q, r = divmod(x, y)
517 return q + (r != 0)
518
519 def get_bp_per_pix(rangeSizes, pixTweenRanges, maxPixels):
520 '''Get the minimum bp-per-pixel that fits in the size limit.'''
521 logging.info("choosing bp per pixel...")
522 numOfRanges = len(rangeSizes)
523 maxPixelsInRanges = maxPixels - pixTweenRanges * (numOfRanges - 1)
524 if maxPixelsInRanges < numOfRanges:
525 raise RuntimeError("can't fit the image: too many sequences?")
526 negLimit = -maxPixelsInRanges
527 negBpPerPix = sum(rangeSizes) // negLimit
528 while True:
529 if sum(i // negBpPerPix for i in rangeSizes) >= negLimit:
530 return -negBpPerPix
531 negBpPerPix -= 1
532
533 def getRangePixBegs(rangePixLens, pixTweenRanges, margin):
534 '''Get the start pixel for each range.'''
535 rangePixBegs = []
536 pix_tot = margin - pixTweenRanges
537 for i in rangePixLens:
538 pix_tot += pixTweenRanges
539 rangePixBegs.append(pix_tot)
540 pix_tot += i
541 return rangePixBegs
542
543 def pixelData(rangeSizes, bp_per_pix, pixTweenRanges, margin):
544 '''Return pixel information about the ranges.'''
545 rangePixLens = [div_ceil(i, bp_per_pix) for i in rangeSizes]
546 rangePixBegs = getRangePixBegs(rangePixLens, pixTweenRanges, margin)
547 tot_pix = rangePixBegs[-1] + rangePixLens[-1]
548 return rangePixBegs, rangePixLens, tot_pix
549
550 def drawLineForward(hits, width, bp_per_pix, beg1, beg2, size):
551 while True:
552 q1, r1 = divmod(beg1, bp_per_pix)
553 q2, r2 = divmod(beg2, bp_per_pix)
554 hits[q2 * width + q1] |= 1
555 next_pix = min(bp_per_pix - r1, bp_per_pix - r2)
556 if next_pix >= size: break
557 beg1 += next_pix
558 beg2 += next_pix
559 size -= next_pix
560
561 def drawLineReverse(hits, width, bp_per_pix, beg1, beg2, size):
562 while True:
563 q1, r1 = divmod(beg1, bp_per_pix)
564 q2, r2 = divmod(beg2, bp_per_pix)
565 hits[q2 * width + q1] |= 2
566 next_pix = min(bp_per_pix - r1, r2 + 1)
567 if next_pix >= size: break
568 beg1 += next_pix
569 beg2 -= next_pix
570 size -= next_pix
571
572 def strandAndOrigin(ranges, beg, size):
573 isReverseStrand = (beg < 0)
574 if isReverseStrand:
575 beg = -(beg + size)
576 for rangeBeg, rangeEnd, isReverseRange, origin in ranges:
577 if rangeEnd > beg: # assumes the ranges are sorted
578 return (isReverseStrand != isReverseRange), origin
579
580 def alignmentPixels(width, height, alignments, bp_per_pix,
581 rangeDict1, rangeDict2):
582 hits = [0] * (width * height) # the image data
583 for seq1, seq2, blocks in alignments:
584 beg1, beg2, size = blocks[0]
585 isReverse1, ori1 = strandAndOrigin(rangeDict1[seq1], beg1, size)
586 isReverse2, ori2 = strandAndOrigin(rangeDict2[seq2], beg2, size)
587 for beg1, beg2, size in blocks:
588 if isReverse1:
589 beg1 = -(beg1 + size)
590 beg2 = -(beg2 + size)
591 if isReverse1 == isReverse2:
592 drawLineForward(hits, width, bp_per_pix,
593 ori1 + beg1, ori2 + beg2, size)
594 else:
595 drawLineReverse(hits, width, bp_per_pix,
596 ori1 + beg1, ori2 - beg2 - 1, size)
597 return hits
598
599 def orientedBlocks(alignments, seqIndex):
600 otherIndex = 1 - seqIndex
601 for a in alignments:
602 seq1, seq2, blocks = a
603 for b in blocks:
604 beg1, beg2, size = b
605 if b[seqIndex] < 0:
606 b = -(beg1 + size), -(beg2 + size), size
607 yield a[seqIndex], b[seqIndex], a[otherIndex], b[otherIndex], size
608
609 def drawJoins(im, alignments, bpPerPix, seqIndex, rangeDict1, rangeDict2):
610 blocks = orientedBlocks(alignments, seqIndex)
611 oldSeq1 = ""
612 for seq1, beg1, seq2, beg2, size in sorted(blocks):
613 isReverse1, ori1 = strandAndOrigin(rangeDict1[seq1], beg1, size)
614 isReverse2, ori2 = strandAndOrigin(rangeDict2[seq2], beg2, size)
615 end1 = beg1 + size - 1
616 end2 = beg2 + size - 1
617 if isReverse1:
618 beg1 = -(beg1 + 1)
619 end1 = -(end1 + 1)
620 if isReverse2:
621 beg2 = -(beg2 + 1)
622 end2 = -(end2 + 1)
623 newPix1 = (ori1 + beg1) // bpPerPix
624 newPix2 = (ori2 + beg2) // bpPerPix
625 if seq1 == oldSeq1:
626 lowerPix2 = min(oldPix2, newPix2)
627 upperPix2 = max(oldPix2, newPix2)
628 midPix1 = (oldPix1 + newPix1) // 2
629 if isReverse1:
630 midPix1 = (oldPix1 + newPix1 + 1) // 2
631 oldPix1, newPix1 = newPix1, oldPix1
632 if upperPix2 - lowerPix2 > 1 and oldPix1 <= newPix1 <= oldPix1 + 1:
633 if seqIndex == 0:
634 box = midPix1, lowerPix2, midPix1 + 1, upperPix2 + 1
635 else:
636 box = lowerPix2, midPix1, upperPix2 + 1, midPix1 + 1
637 im.paste("lightgray", box)
638 oldPix1 = (ori1 + end1) // bpPerPix
639 oldPix2 = (ori2 + end2) // bpPerPix
640 oldSeq1 = seq1
641
642 def expandedSeqDict(seqDict):
643 '''Allow lookup by short sequence names, e.g. chr7 as well as hg19.chr7.'''
644 newDict = seqDict.copy()
645 for name, x in seqDict.items():
646 if "." in name:
647 base = name.split(".", 1)[-1]
648 if base in newDict: # an ambiguous case was found:
649 return seqDict # so give up completely
650 newDict[base] = x
651 return newDict
652
653 def annotsFromBedOrAgp(opts, rangeDict, fields):
654 seqName = fields[0]
655 if seqName not in rangeDict: return
656 end = int(fields[2])
657 if len(fields) > 7 and fields[4].isalpha(): # agp format, or gap.txt
658 if fields[4] in "NU" and fields[5].isdigit():
659 beg = end - int(fields[5]) # zero-based coordinate
660 if fields[7] == "yes":
661 yield 30000, opts.bridged_color, seqName, beg, end, ""
662 else:
663 yield 20000, opts.unbridged_color, seqName, beg, end, ""
664 else: # BED format
665 beg = int(fields[1])
666 itemName = fields[3] if len(fields) > 3 and fields[3] != "." else ""
667 layer = 900
668 color = "#fbf"
669 if len(fields) > 4:
670 if fields[4] != ".":
671 layer = float(fields[4])
672 if len(fields) > 5:
673 if len(fields) > 8 and fields[8].count(",") == 2:
674 color = "rgb(" + fields[8] + ")"
675 else:
676 strand = fields[5]
677 isRev = (rangeDict[seqName][0][3] > 1)
678 if strand == "+" and not isRev or strand == "-" and isRev:
679 color = "#ffe8e8"
680 if strand == "-" and not isRev or strand == "+" and isRev:
681 color = "#e8e8ff"
682 yield layer, color, seqName, beg, end, itemName
683
684 def annotsFromGpd(opts, rangeDict, fields, geneName): # xxx split on tabs?
685 seqName = fields[1]
686 if seqName in rangeDict:
687 cdsBeg = int(fields[5])
688 cdsEnd = int(fields[6])
689 exonBegs = commaSeparatedInts(fields[8])
690 exonEnds = commaSeparatedInts(fields[9])
691 for beg, end in zip(exonBegs, exonEnds):
692 yield 300, opts.exon_color, seqName, beg, end, geneName
693 b = max(beg, cdsBeg)
694 e = min(end, cdsEnd)
695 if b < e: yield 400, opts.cds_color, seqName, b, e, ""
696
697 def annotsFromGff(opts, line, seqName):
698 fields = line.rstrip().split("\t")
699 feature = fields[2]
700 beg = int(fields[3]) - 1
701 end = int(fields[4])
702 if feature == "exon":
703 geneName = fields[8]
704 if ";" in geneName or "=" in geneName:
705 parts = geneName.rstrip(";").split(";")
706 attrs = dict(re.split('[= ]', i.strip(), maxsplit=1)
707 for i in parts)
708 if "gene" in attrs:
709 geneName = attrs["gene"] # seems good for NCBI gff
710 elif "Name" in attrs:
711 geneName = attrs["Name"]
712 else:
713 geneName = ""
714 yield 300, opts.exon_color, seqName, beg, end, geneName
715 elif feature == "CDS":
716 yield 400, opts.cds_color, seqName, beg, end, ""
717
718 def annotsFromRep(rangeDict, seqName, beg, end, strand, repName, repClass):
719 simple = "Low_complexity", "Simple_repeat", "Satellite"
720 if repClass.startswith(simple):
721 yield 200, "#fbf", seqName, beg, end, repName
722 elif (strand == "+") != (rangeDict[seqName][0][3] > 1):
723 yield 100, "#ffe8e8", seqName, beg, end, repName
724 else:
725 yield 100, "#e8e8ff", seqName, beg, end, repName
726
727 def annotsFromFiles(opts, fileNames, rangeDict):
728 isDig = str.isdigit
729 for fileName in fileNames:
730 for line in myOpen(fileName):
731 w = line.split()
732 n = len(w)
733 if n > 10 and w[8] in "+C-" and isDig(w[5]) and isDig(w[6]):
734 seq = w[4] # RepeatMasker .out
735 if seq not in rangeDict: continue # do this ASAP for speed
736 beg = int(w[5]) - 1
737 end = int(w[6])
738 g = annotsFromRep(rangeDict, seq, beg, end, w[8], w[9], w[10])
739 elif n > 11 and w[9] in "+-" and isDig(w[6]) and isDig(w[7]):
740 seq = w[5] # rmsk.txt
741 if seq not in rangeDict: continue
742 beg = int(w[6])
743 end = int(w[7])
744 g = annotsFromRep(rangeDict, seq, beg, end, w[9], w[10], w[11])
745 elif n > 8 and w[6] in "+-." and isDig(w[3]) and isDig(w[4]):
746 seqName = w[0]
747 if seqName not in rangeDict: continue
748 g = annotsFromGff(opts, line, seqName)
749 elif n > 9 and w[2] in "+-" and isDig(w[4] + w[5] + w[6]):
750 geneName = w[12 if n > 12 else 0] # XXX ???
751 g = annotsFromGpd(opts, rangeDict, w, geneName)
752 elif n > 10 and w[3] in "+-" and isDig(w[5] + w[6] + w[7]):
753 geneName = w[12 if n > 12 else 0] # XXX ???
754 g = annotsFromGpd(opts, rangeDict, w[1:], geneName)
755 elif n > 2 and isDig(w[1]) and isDig(w[2]):
756 g = annotsFromBedOrAgp(opts, rangeDict, w)
757 elif n > 3 and isDig(w[2]) and isDig(w[3]):
758 g = annotsFromBedOrAgp(opts, rangeDict, w[1:])
759 else:
760 continue
761 if line[0] == "#": continue
762 for i in g:
763 layer, color, seqName, beg, end, name = i
764 if any(beg < r[2] and end > r[1] for r in rangeDict[seqName]):
765 yield i
766
767 def bedBoxes(annots, rangeDict, limit, isTop, bpPerPix):
768 beds, textSizes, margin = annots
769 cover = [(limit, limit)]
770 for layer, color, seqName, bedBeg, bedEnd, name in reversed(beds):
771 textWidth, textHeight = textSizes[name]
772 for rangeBeg, rangeEnd, isReverseRange, origin in rangeDict[seqName]:
773 beg = max(bedBeg, rangeBeg)
774 end = min(bedEnd, rangeEnd)
775 if beg >= end: continue
776 if isReverseRange:
777 beg, end = -end, -beg
778 if layer <= 10000:
779 # include partly-covered pixels
780 pixBeg = (origin + beg) // bpPerPix
781 pixEnd = div_ceil(origin + end, bpPerPix)
782 else:
783 # exclude partly-covered pixels
784 pixBeg = div_ceil(origin + beg, bpPerPix)
785 pixEnd = (origin + end) // bpPerPix
786 if pixEnd <= pixBeg: continue
787 if bedEnd >= rangeEnd: # include partly-covered end pixels
788 if isReverseRange:
789 pixBeg = (origin + beg) // bpPerPix
790 else:
791 pixEnd = div_ceil(origin + end, bpPerPix)
792 nameBeg = (pixBeg + pixEnd - textHeight) // 2
793 nameEnd = nameBeg + textHeight
794 n = ""
795 if name and all(e <= nameBeg or b >= nameEnd for b, e in cover):
796 if textWidth <= margin:
797 cover.append((nameBeg, nameEnd))
798 n = name
799 yield layer, color, isTop, pixBeg, pixEnd, n, nameBeg, textWidth
800
801 def drawAnnotations(im, boxes, tMargin, bMarginBeg, lMargin, rMarginBeg):
802 # xxx use partial transparency for different-color overlaps?
803 for layer, color, isTop, beg, end, name, nameBeg, nameLen in boxes:
804 if isTop:
805 box = beg, tMargin, end, bMarginBeg
806 else:
807 box = lMargin, beg, rMarginBeg, end
808 im.paste(color, box)
809
810 def placedLabels(labels, rangePixBegs, rangePixLens, beg, end):
811 '''Return axis labels with endpoint & sort-order information.'''
812 maxWidth = end - beg
813 for i, j, k in zip(labels, rangePixBegs, rangePixLens):
814 text, textWidth, textHeight, strandNum = i
815 if textWidth > maxWidth:
816 continue
817 labelBeg = j + (k - textWidth) // 2
818 labelEnd = labelBeg + textWidth
819 sortKey = textWidth - k
820 if labelBeg < beg:
821 sortKey += maxWidth * (beg - labelBeg)
822 labelBeg = beg
823 labelEnd = beg + textWidth
824 if labelEnd > end:
825 sortKey += maxWidth * (labelEnd - end)
826 labelEnd = end
827 labelBeg = end - textWidth
828 yield sortKey, labelBeg, labelEnd, text, textHeight, strandNum
829
830 def nonoverlappingLabels(labels, minPixTweenLabels):
831 '''Get a subset of non-overlapping axis labels, greedily.'''
832 out = []
833 for i in labels:
834 beg = i[1] - minPixTweenLabels
835 end = i[2] + minPixTweenLabels
836 if all(j[2] <= beg or j[1] >= end for j in out):
837 out.append(i)
838 return out
839
840 def axisImage(labels, rangePixBegs, rangePixLens, textRot,
841 textAln, font, image_mode, opts):
842 '''Make an image of axis labels.'''
843 beg = rangePixBegs[0]
844 end = rangePixBegs[-1] + rangePixLens[-1]
845 margin = max(i[2] for i in labels)
846 labels = sorted(placedLabels(labels, rangePixBegs, rangePixLens, beg, end))
847 minPixTweenLabels = 0 if textRot else opts.label_space
848 labels = nonoverlappingLabels(labels, minPixTweenLabels)
849 image_size = (margin, end) if textRot else (end, margin)
850 im = Image.new(image_mode, image_size, opts.margin_color)
851 draw = ImageDraw.Draw(im)
852 for sortKey, labelBeg, labelEnd, text, textHeight, strandNum in labels:
853 base = margin - textHeight if textAln else 0
854 position = (base, labelBeg) if textRot else (labelBeg, base)
855 fill = ("black", opts.forwardcolor, opts.reversecolor)[strandNum]
856 draw.text(position, text, font=font, fill=fill)
857 return im
858
859 def annoTextImage(opts, image_mode, font, margin, length, boxes, isLeftAlign):
860 image_size = margin, length
861 im = Image.new(image_mode, image_size, opts.margin_color)
862 draw = ImageDraw.Draw(im)
863 for layer, color, isTop, beg, end, name, nameBeg, nameLen in boxes:
864 xPosition = 0 if isLeftAlign else margin - nameLen
865 position = xPosition, nameBeg
866 draw.text(position, name, font=font, fill="black")
867 return im
868
869 def rangesPerSeq(sortedRanges):
870 for seqName, group in itertools.groupby(sortedRanges, itemgetter(0)):
871 yield seqName, sorted(group)
872
873 def rangesWithOrigins(sortedRanges, rangePixBegs, rangePixLens, bpPerPix):
874 for i, j, k in zip(sortedRanges, rangePixBegs, rangePixLens):
875 seqName, rangeBeg, rangeEnd, strandNum = i
876 isReverseRange = (strandNum > 1)
877 if isReverseRange:
878 origin = bpPerPix * (j + k) + rangeBeg
879 else:
880 origin = bpPerPix * j - rangeBeg
881 yield seqName, (rangeBeg, rangeEnd, isReverseRange, origin)
882
883 def rangesAndOriginsPerSeq(sortedRanges, rangePixBegs, rangePixLens, bpPerPix):
884 a = rangesWithOrigins(sortedRanges, rangePixBegs, rangePixLens, bpPerPix)
885 for seqName, group in itertools.groupby(a, itemgetter(0)):
886 yield seqName, sorted(i[1] for i in group)
887
888 def getFont(opts):
889 if opts.fontfile:
890 return ImageFont.truetype(opts.fontfile, opts.fontsize)
891 fileNames = []
892 try:
893 x = ["fc-match", "-f%{file}", "arial"]
894 p = subprocess.Popen(x, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
895 universal_newlines=True)
896 out, err = p.communicate()
897 fileNames.append(out)
898 except OSError as e:
899 logging.info("fc-match error: " + str(e))
900 fileNames.append("/Library/Fonts/Arial.ttf") # for Mac
901 for i in fileNames:
902 try:
903 font = ImageFont.truetype(i, opts.fontsize)
904 logging.info("font: " + i)
905 return font
906 except IOError as e:
907 logging.info("font load error: " + str(e))
908 return ImageFont.load_default()
909
910 def sequenceSizesAndNames(seqRanges):
911 for seqName, ranges in itertools.groupby(seqRanges, itemgetter(0)):
912 size = sum(e - b for n, b, e in ranges)
913 yield size, seqName
914
915 def biggestSequences(seqRanges, maxNumOfSequences):
916 s = sorted(sequenceSizesAndNames(seqRanges), reverse=True)
917 if len(s) > maxNumOfSequences:
918 logging.warning("too many sequences - discarding the smallest ones")
919 s = s[:maxNumOfSequences]
920 return set(i[1] for i in s)
921
922 def remainingSequenceRanges(seqRanges, alignments, seqIndex):
923 remainingSequences = set(i[seqIndex] for i in alignments)
924 return [i for i in seqRanges if i[0] in remainingSequences]
925
926 def readAnnots(opts, font, textDraw, sortedRanges, totalLength, fileNames):
927 rangeDict = expandedSeqDict(dict(rangesPerSeq(sortedRanges)))
928 annots = sorted(annotsFromFiles(opts, fileNames, rangeDict))
929 names = set(i[5] for i in annots)
930 textSizes = dict(sizesPerText(names, font, textDraw))
931 maxTextLength = totalLength // 2
932 okLengths = [i[0] for i in textSizes.values() if i[0] <= maxTextLength]
933 margin = max(okLengths) if okLengths else 0
934 return annots, textSizes, margin
935
936 def lastDotplot(opts, args):
937 logLevel = logging.INFO if opts.verbose else logging.WARNING
938 logging.basicConfig(format="%(filename)s: %(message)s", level=logLevel)
939
940 font = getFont(opts)
941 image_mode = 'RGB'
942 forward_color = ImageColor.getcolor(opts.forwardcolor, image_mode)
943 reverse_color = ImageColor.getcolor(opts.reversecolor, image_mode)
944 zipped_colors = zip(forward_color, reverse_color)
945 overlap_color = tuple([(i + j) // 2 for i, j in zipped_colors])
946
947 maxGap1, maxGapB1 = twoValuesFromOption(opts.max_gap1, ":")
948 maxGap2, maxGapB2 = twoValuesFromOption(opts.max_gap2, ":")
949
950 logging.info("reading alignments...")
951 alnData = readAlignments(args[0], opts)
952 alignments, seqRanges1, coverDict1, seqRanges2, coverDict2 = alnData
953 if not alignments: raise RuntimeError("there are no alignments")
954 logging.info("cutting...")
955 coverDict1 = dict(mergedRangesPerSeq(coverDict1))
956 coverDict2 = dict(mergedRangesPerSeq(coverDict2))
957 minAlignedBases = min(coveredLength(coverDict1), coveredLength(coverDict2))
958 pad = int(opts.pad * minAlignedBases)
959 cutRanges1 = list(trimmed(seqRanges1, coverDict1, minAlignedBases,
960 maxGap1, pad, pad))
961 cutRanges2 = list(trimmed(seqRanges2, coverDict2, minAlignedBases,
962 maxGap2, pad, pad))
963
964 biggestSeqs1 = biggestSequences(cutRanges1, opts.maxseqs)
965 cutRanges1 = [i for i in cutRanges1 if i[0] in biggestSeqs1]
966 alignments = [i for i in alignments if i[0] in biggestSeqs1]
967 cutRanges2 = remainingSequenceRanges(cutRanges2, alignments, 1)
968
969 biggestSeqs2 = biggestSequences(cutRanges2, opts.maxseqs)
970 cutRanges2 = [i for i in cutRanges2 if i[0] in biggestSeqs2]
971 alignments = [i for i in alignments if i[1] in biggestSeqs2]
972 cutRanges1 = remainingSequenceRanges(cutRanges1, alignments, 0)
973
974 logging.info("reading secondary alignments...")
975 alnDataB = readSecondaryAlignments(opts, cutRanges1, cutRanges2)
976 alignmentsB, seqRangesB1, coverDictB1, seqRangesB2, coverDictB2 = alnDataB
977 logging.info("cutting...")
978 coverDictB1 = dict(mergedRangesPerSeq(coverDictB1))
979 coverDictB2 = dict(mergedRangesPerSeq(coverDictB2))
980 cutRangesB1 = list(trimmed(seqRangesB1, coverDictB1, minAlignedBases,
981 maxGapB1, 0, 0))
982 cutRangesB2 = list(trimmed(seqRangesB2, coverDictB2, minAlignedBases,
983 maxGapB2, 0, 0))
984
985 logging.info("sorting...")
986 sortOut = allSortedRanges(opts, alignments, alignmentsB,
987 cutRanges1, cutRangesB1, cutRanges2, cutRangesB2)
988 sortedRanges1, sortedRanges2 = sortOut
989
990 textDraw = None
991 if opts.fontsize:
992 textDraw = ImageDraw.Draw(Image.new(image_mode, (1, 1)))
993
994 textRot1 = "vertical".startswith(opts.rot1)
995 i1 = dataFromRanges(sortedRanges1, font, textDraw, opts.labels1, textRot1)
996 rangeSizes1, labelData1, tMargin = i1
997
998 textRot2 = "horizontal".startswith(opts.rot2)
999 i2 = dataFromRanges(sortedRanges2, font, textDraw, opts.labels2, textRot2)
1000 rangeSizes2, labelData2, lMargin = i2
1001
1002 logging.info("reading annotations...")
1003
1004 annots1 = readAnnots(opts, font, textDraw, sortedRanges1, opts.height,
1005 opts.bed1)
1006 bMargin = annots1[-1]
1007
1008 annots2 = readAnnots(opts, font, textDraw, sortedRanges2, opts.width,
1009 opts.bed2)
1010 rMargin = annots2[-1]
1011
1012 maxPixels1 = opts.width - lMargin - rMargin
1013 maxPixels2 = opts.height - tMargin - bMargin
1014 bpPerPix1 = get_bp_per_pix(rangeSizes1, opts.border_pixels, maxPixels1)
1015 bpPerPix2 = get_bp_per_pix(rangeSizes2, opts.border_pixels, maxPixels2)
1016 bpPerPix = max(bpPerPix1, bpPerPix2)
1017 logging.info("bp per pixel = " + str(bpPerPix))
1018
1019 p1 = pixelData(rangeSizes1, bpPerPix, opts.border_pixels, lMargin)
1020 rangePixBegs1, rangePixLens1, rMarginBeg = p1
1021 width = rMarginBeg + rMargin
1022 rangeDict1 = dict(rangesAndOriginsPerSeq(sortedRanges1, rangePixBegs1,
1023 rangePixLens1, bpPerPix))
1024
1025 p2 = pixelData(rangeSizes2, bpPerPix, opts.border_pixels, tMargin)
1026 rangePixBegs2, rangePixLens2, bMarginBeg = p2
1027 height = bMarginBeg + bMargin
1028 rangeDict2 = dict(rangesAndOriginsPerSeq(sortedRanges2, rangePixBegs2,
1029 rangePixLens2, bpPerPix))
1030
1031 logging.info("width: " + str(width))
1032 logging.info("height: " + str(height))
1033
1034 logging.info("processing alignments...")
1035 allAlignments = alignments + alignmentsB
1036 hits = alignmentPixels(width, height, allAlignments, bpPerPix,
1037 rangeDict1, rangeDict2)
1038
1039 rangeDict1 = expandedSeqDict(rangeDict1)
1040 rangeDict2 = expandedSeqDict(rangeDict2)
1041
1042 boxes1 = list(bedBoxes(annots1, rangeDict1, rMarginBeg, True, bpPerPix))
1043 boxes2 = list(bedBoxes(annots2, rangeDict2, bMarginBeg, False, bpPerPix))
1044 boxes = sorted(itertools.chain(boxes1, boxes2))
1045
1046 logging.info("drawing...")
1047
1048 image_size = width, height
1049 im = Image.new(image_mode, image_size, opts.background_color)
1050
1051 drawAnnotations(im, boxes, tMargin, bMarginBeg, lMargin, rMarginBeg)
1052
1053 joinA, joinB = twoValuesFromOption(opts.join, ":")
1054 if joinA in "13":
1055 drawJoins(im, alignments, bpPerPix, 0, rangeDict1, rangeDict2)
1056 if joinB in "13":
1057 drawJoins(im, alignmentsB, bpPerPix, 0, rangeDict1, rangeDict2)
1058 if joinA in "23":
1059 drawJoins(im, alignments, bpPerPix, 1, rangeDict2, rangeDict1)
1060 if joinB in "23":
1061 drawJoins(im, alignmentsB, bpPerPix, 1, rangeDict2, rangeDict1)
1062
1063 for i in range(height):
1064 for j in range(width):
1065 store_value = hits[i * width + j]
1066 xy = j, i
1067 if store_value == 1: im.putpixel(xy, forward_color)
1068 elif store_value == 2: im.putpixel(xy, reverse_color)
1069 elif store_value == 3: im.putpixel(xy, overlap_color)
1070
1071 if opts.fontsize != 0:
1072 axis1 = axisImage(labelData1, rangePixBegs1, rangePixLens1,
1073 textRot1, False, font, image_mode, opts)
1074 if textRot1:
1075 axis1 = axis1.transpose(Image.ROTATE_90)
1076 axis2 = axisImage(labelData2, rangePixBegs2, rangePixLens2,
1077 textRot2, textRot2, font, image_mode, opts)
1078 if not textRot2:
1079 axis2 = axis2.transpose(Image.ROTATE_270)
1080 im.paste(axis1, (0, 0))
1081 im.paste(axis2, (0, 0))
1082
1083 annoImage1 = annoTextImage(opts, image_mode, font, bMargin, width,
1084 boxes1, False)
1085 annoImage1 = annoImage1.transpose(Image.ROTATE_90)
1086 annoImage2 = annoTextImage(opts, image_mode, font, rMargin, height,
1087 boxes2, True)
1088 im.paste(annoImage1, (0, bMarginBeg))
1089 im.paste(annoImage2, (rMarginBeg, 0))
1090
1091 for i in rangePixBegs1[1:]:
1092 box = i - opts.border_pixels, tMargin, i, bMarginBeg
1093 im.paste(opts.border_color, box)
1094
1095 for i in rangePixBegs2[1:]:
1096 box = lMargin, i - opts.border_pixels, rMarginBeg, i
1097 im.paste(opts.border_color, box)
1098
1099 if cutRangesB1 and cutRangesB2: # no 2ndary-versus-2ndary alignments
1100 x = rangePixBegs1[len(cutRanges1)] - opts.border_pixels
1101 y = rangePixBegs2[len(cutRanges2)] - opts.border_pixels
1102 box = x, y, rMarginBeg, bMarginBeg
1103 im.paste(opts.margin_color, box)
1104
1105 base = args[0]
1106 if base.endswith((".maf", ".psl", ".tab", ".tsv", ".txt")):
1107 base = base[:-4]
1108 im.save(args[1] if len(args) > 1 else base + ".png")
1109
1110 if __name__ == "__main__":
1111 usage = """%prog --help
1112 or: %prog [options] maf-or-psl-or-tab-alignments
1113 or: %prog [options] maf-or-psl-or-tab-alignments dotplot.png|gif|..."""
1114 description = "Draw a dotplot of pair-wise sequence alignments."
1115 op = optparse.OptionParser(usage=usage, description=description)
1116 op.add_option("-v", "--verbose", action="count",
1117 help="show progress messages & data about the plot")
1118 # Replace "width" & "height" with a single "length" option?
1119 op.add_option("-x", "--width", metavar="INT", type="int", default=1000,
1120 help="maximum width in pixels (default: %default)")
1121 op.add_option("-y", "--height", metavar="INT", type="int", default=1000,
1122 help="maximum height in pixels (default: %default)")
1123 op.add_option("-m", "--maxseqs", type="int", default=100, metavar="M",
1124 help="maximum number of horizontal or vertical sequences "
1125 "(default=%default)")
1126 op.add_option("-1", "--seq1", metavar="PATTERN", action="append",
1127 default=[],
1128 help="which sequences to show from the 1st genome")
1129 op.add_option("-2", "--seq2", metavar="PATTERN", action="append",
1130 default=[],
1131 help="which sequences to show from the 2nd genome")
1132 op.add_option("--alignments", metavar="FILE", help="secondary alignments")
1133 op.add_option("--sort1", default="1", metavar="N",
1134 help="genome1 sequence order: 0=input order, 1=name order, "
1135 "2=length order, 3=alignment order (default=%default)")
1136 op.add_option("--sort2", default="1", metavar="N",
1137 help="genome2 sequence order: 0=input order, 1=name order, "
1138 "2=length order, 3=alignment order (default=%default)")
1139 op.add_option("--strands1", default="0", metavar="N", help=
1140 "genome1 sequence orientation: 0=forward orientation, "
1141 "1=alignment orientation (default=%default)")
1142 op.add_option("--strands2", default="0", metavar="N", help=
1143 "genome2 sequence orientation: 0=forward orientation, "
1144 "1=alignment orientation (default=%default)")
1145 op.add_option("--max-gap1", metavar="FRAC", default="1,4", help=
1146 "maximum unaligned (end,mid) gap in genome1: "
1147 "fraction of aligned length (default=%default)")
1148 op.add_option("--max-gap2", metavar="FRAC", default="1,4", help=
1149 "maximum unaligned (end,mid) gap in genome2: "
1150 "fraction of aligned length (default=%default)")
1151 op.add_option("--pad", metavar="FRAC", type="float", default=0.04, help=
1152 "pad length when cutting unaligned gaps: "
1153 "fraction of aligned length (default=%default)")
1154 op.add_option("-j", "--join", default="0", metavar="N", help=
1155 "join: 0=nothing, 1=alignments adjacent in genome1, "
1156 "2=alignments adjacent in genome2 (default=%default)")
1157 op.add_option("--border-pixels", metavar="INT", type="int", default=1,
1158 help="number of pixels between sequences (default=%default)")
1159 op.add_option("-a", "--bed1", "--rmsk1", "--genePred1", "--gap1",
1160 action="append", default=[], metavar="FILE",
1161 help="read genome1 annotations")
1162 op.add_option("-b", "--bed2", "--rmsk2", "--genePred2", "--gap2",
1163 action="append", default=[], metavar="FILE",
1164 help="read genome2 annotations")
1165
1166 og = optparse.OptionGroup(op, "Text options")
1167 og.add_option("-f", "--fontfile", metavar="FILE",
1168 help="TrueType or OpenType font file")
1169 og.add_option("-s", "--fontsize", metavar="SIZE", type="int", default=14,
1170 help="TrueType or OpenType font size (default: %default)")
1171 og.add_option("--labels1", type="int", default=0, metavar="N", help=
1172 "genome1 labels: 0=name, 1=name:length, "
1173 "2=name:start:length, 3=name:start-end (default=%default)")
1174 og.add_option("--labels2", type="int", default=0, metavar="N", help=
1175 "genome2 labels: 0=name, 1=name:length, "
1176 "2=name:start:length, 3=name:start-end (default=%default)")
1177 og.add_option("--rot1", metavar="ROT", default="h",
1178 help="text rotation for the 1st genome (default=%default)")
1179 og.add_option("--rot2", metavar="ROT", default="v",
1180 help="text rotation for the 2nd genome (default=%default)")
1181 op.add_option_group(og)
1182
1183 og = optparse.OptionGroup(op, "Color options")
1184 og.add_option("-c", "--forwardcolor", metavar="COLOR", default="red",
1185 help="color for forward alignments (default: %default)")
1186 og.add_option("-r", "--reversecolor", metavar="COLOR", default="blue",
1187 help="color for reverse alignments (default: %default)")
1188 og.add_option("--border-color", metavar="COLOR", default="black",
1189 help="color for pixels between sequences (default=%default)")
1190 # --break-color and/or --break-pixels for intra-sequence breaks?
1191 og.add_option("--margin-color", metavar="COLOR", default="#dcdcdc",
1192 help="margin color")
1193 og.add_option("--exon-color", metavar="COLOR", default="PaleGreen",
1194 help="color for exons (default=%default)")
1195 og.add_option("--cds-color", metavar="COLOR", default="LimeGreen",
1196 help="color for protein-coding regions (default=%default)")
1197 og.add_option("--bridged-color", metavar="COLOR", default="yellow",
1198 help="color for bridged gaps (default: %default)")
1199 og.add_option("--unbridged-color", metavar="COLOR", default="orange",
1200 help="color for unbridged gaps (default: %default)")
1201 op.add_option_group(og)
1202 opts, args = op.parse_args()
1203 if len(args) not in (1, 2): op.error("1 or 2 arguments needed")
1204
1205 opts.background_color = "white"
1206 opts.label_space = 5 # minimum number of pixels between axis labels
1207
1208 try: lastDotplot(opts, args)
1209 except KeyboardInterrupt: pass # avoid silly error message
1210 except RuntimeError as e:
1211 prog = os.path.basename(sys.argv[0])
1212 sys.exit(prog + ": error: " + str(e))