scripts/last-dotplot
author Martin C. Frith
Tue Sep 26 14:25:17 2017 +0900 (2017-09-26)
changeset 875 592295375eb1
parent 866 5182d8528ce9
child 877 f5f93e51ef53
permissions -rwxr-xr-x
Add gz reading to: dotplot postmask train convert
     1 #! /usr/bin/env python
     2 
     3 # Read pair-wise alignments in MAF or LAST tabular format: write an
     4 # "Oxford grid", a.k.a. dotplot.
     5 
     6 # TODO: Currently, pixels with zero aligned nt-pairs are white, and
     7 # pixels with one or more aligned nt-pairs are black.  This can look
     8 # too crowded for large genome alignments.  I tried shading each pixel
     9 # according to the number of aligned nt-pairs within it, but the
    10 # result is too faint.  How can this be done better?
    11 
    12 import gzip
    13 import fnmatch, itertools, optparse, os, re, sys
    14 
    15 # Try to make PIL/PILLOW work:
    16 try: from PIL import Image, ImageDraw, ImageFont, ImageColor
    17 except ImportError: import Image, ImageDraw, ImageFont, ImageColor
    18 
    19 def myOpen(fileName):  # faster than fileinput
    20     if fileName == "-":
    21         return sys.stdin
    22     if fileName.endswith(".gz"):
    23         return gzip.open(fileName)
    24     return open(fileName)
    25 
    26 def warn(message):
    27     if opts.verbose:
    28         prog = os.path.basename(sys.argv[0])
    29         sys.stderr.write(prog + ": " + message + "\n")
    30 
    31 def croppedBlocks(blocks, range1, range2):
    32     cropBeg1, cropEnd1 = range1
    33     cropBeg2, cropEnd2 = range2
    34     if blocks[0][0] < 0: cropBeg1, cropEnd1 = -cropEnd1, -cropBeg1
    35     if blocks[0][1] < 0: cropBeg2, cropEnd2 = -cropEnd2, -cropBeg2
    36     for beg1, beg2, size in blocks:
    37         b1 = max(cropBeg1, beg1)
    38         e1 = min(cropEnd1, beg1 + size)
    39         if b1 >= e1: continue
    40         offset = beg2 - beg1
    41         b2 = max(cropBeg2, b1 + offset)
    42         e2 = min(cropEnd2, e1 + offset)
    43         if b2 >= e2: continue
    44         yield b2 - offset, b2, e2 - b2
    45 
    46 def tabBlocks(beg1, beg2, blocks):
    47     '''Get the gapless blocks of an alignment, from LAST tabular format.'''
    48     for i in blocks.split(","):
    49         if ":" in i:
    50             x, y = i.split(":")
    51             beg1 += int(x)
    52             beg2 += int(y)
    53         else:
    54             size = int(i)
    55             yield beg1, beg2, size
    56             beg1 += size
    57             beg2 += size
    58 
    59 def mafBlocks(beg1, beg2, seq1, seq2):
    60     '''Get the gapless blocks of an alignment, from MAF format.'''
    61     size = 0
    62     for x, y in itertools.izip(seq1, seq2):
    63         if x == "-":
    64             if size:
    65                 yield beg1, beg2, size
    66                 beg1 += size
    67                 beg2 += size
    68                 size = 0
    69             beg2 += 1
    70         elif y == "-":
    71             if size:
    72                 yield beg1, beg2, size
    73                 beg1 += size
    74                 beg2 += size
    75                 size = 0
    76             beg1 += 1
    77         else:
    78             size += 1
    79     if size: yield beg1, beg2, size
    80 
    81 def alignmentInput(lines):
    82     '''Get alignments and sequence lengths, from MAF or tabular format.'''
    83     mafCount = 0
    84     for line in lines:
    85         w = line.split()
    86         if line[0].isdigit():  # tabular format
    87             chr1, beg1, seqlen1 = w[1], int(w[2]), int(w[5])
    88             if w[4] == "-": beg1 -= seqlen1
    89             chr2, beg2, seqlen2 = w[6], int(w[7]), int(w[10])
    90             if w[9] == "-": beg2 -= seqlen2
    91             blocks = tabBlocks(beg1, beg2, w[11])
    92             yield chr1, seqlen1, chr2, seqlen2, blocks
    93         elif line[0] == "s":  # MAF format
    94             if mafCount == 0:
    95                 chr1, beg1, seqlen1, seq1 = w[1], int(w[2]), int(w[5]), w[6]
    96                 if w[4] == "-": beg1 -= seqlen1
    97                 mafCount = 1
    98             else:
    99                 chr2, beg2, seqlen2, seq2 = w[1], int(w[2]), int(w[5]), w[6]
   100                 if w[4] == "-": beg2 -= seqlen2
   101                 blocks = mafBlocks(beg1, beg2, seq1, seq2)
   102                 yield chr1, seqlen1, chr2, seqlen2, blocks
   103                 mafCount = 0
   104 
   105 def seqRangeFromText(text):
   106     if ":" in text:
   107         pattern, interval = text.rsplit(":", 1)
   108         if "-" in interval:
   109             beg, end = interval.rsplit("-", 1)
   110             return pattern, int(beg), int(end)  # beg may be negative
   111     return text, 0, sys.maxsize
   112 
   113 def rangeFromSeqName(seqRanges, name, seqLen):
   114     if not seqRanges: return 0, seqLen
   115     base = name.split(".")[-1]  # allow for names like hg19.chr7
   116     for pat, beg, end in seqRanges:
   117         if fnmatch.fnmatchcase(name, pat) or fnmatch.fnmatchcase(base, pat):
   118             return max(beg, 0), min(end, seqLen)
   119     return None
   120 
   121 def updateSeqs(isTrim, seqNames, seqLimits, seqName, seqRange, blocks, index):
   122     if seqName not in seqLimits:
   123         seqNames.append(seqName)
   124     if isTrim:
   125         beg = blocks[0][index]
   126         end = blocks[-1][index] + blocks[-1][2]
   127         if beg < 0: beg, end = -end, -beg
   128         if seqName in seqLimits:
   129             b, e = seqLimits[seqName]
   130             seqLimits[seqName] = min(b, beg), max(e, end)
   131         else:
   132             seqLimits[seqName] = beg, end
   133     else:
   134         seqLimits[seqName] = seqRange
   135 
   136 def readAlignments(fileName, opts):
   137     '''Get alignments and sequence limits, from MAF or tabular format.'''
   138     seqRanges1 = map(seqRangeFromText, opts.seq1)
   139     seqRanges2 = map(seqRangeFromText, opts.seq2)
   140 
   141     alignments = []
   142     seqNames1 = []
   143     seqNames2 = []
   144     seqLimits1 = {}
   145     seqLimits2 = {}
   146     lines = myOpen(fileName)
   147     for seqName1, seqLen1, seqName2, seqLen2, blocks in alignmentInput(lines):
   148         range1 = rangeFromSeqName(seqRanges1, seqName1, seqLen1)
   149         if not range1: continue
   150         range2 = rangeFromSeqName(seqRanges2, seqName2, seqLen2)
   151         if not range2: continue
   152         b = list(croppedBlocks(list(blocks), range1, range2))
   153         if not b: continue
   154         aln = seqName1, seqName2, b
   155         alignments.append(aln)
   156         updateSeqs(opts.trim1, seqNames1, seqLimits1, seqName1, range1, b, 0)
   157         updateSeqs(opts.trim2, seqNames2, seqLimits2, seqName2, range2, b, 1)
   158     return alignments, seqNames1, seqNames2, seqLimits1, seqLimits2
   159 
   160 def natural_sort_key(my_string):
   161     '''Return a sort key for "natural" ordering, e.g. chr9 < chr10.'''
   162     parts = re.split(r'(\d+)', my_string)
   163     parts[1::2] = map(int, parts[1::2])
   164     return parts
   165 
   166 def get_text_sizes(my_strings, font, fontsize, image_mode):
   167     '''Get widths & heights, in pixels, of some strings.'''
   168     if fontsize == 0: return [(0, 0) for i in my_strings]
   169     image_size = 1, 1
   170     im = Image.new(image_mode, image_size)
   171     draw = ImageDraw.Draw(im)
   172     return [draw.textsize(i, font=font) for i in my_strings]
   173 
   174 def sizeText(size):
   175     suffixes = "bp", "kb", "Mb", "Gb"
   176     for i, x in enumerate(suffixes):
   177         j = 10 ** (i * 3)
   178         if size < j * 10:
   179             return "%.2g" % (1.0 * size / j) + x
   180         if size < j * 1000 or i == len(suffixes) - 1:
   181             return "%.0f" % (1.0 * size / j) + x
   182 
   183 def seqNameAndSizeText(seqName, seqSize):
   184     return seqName + ": " + sizeText(seqSize)
   185 
   186 def getSeqInfo(sortOpt, seqNames, seqLimits,
   187                font, fontsize, image_mode, isShowSize):
   188     '''Return miscellaneous information about the sequences.'''
   189     if sortOpt == 1:
   190         seqNames.sort(key=natural_sort_key)
   191     seqSizes = [seqLimits[i][1] - seqLimits[i][0] for i in seqNames]
   192     for i in seqNames:
   193         r = seqLimits[i]
   194         out = i, str(r[0]), str(r[1])
   195         warn("\t".join(out))
   196     warn("")
   197     if sortOpt == 2:
   198         seqRecords = sorted(zip(seqSizes, seqNames), reverse=True)
   199         seqSizes = [i[0] for i in seqRecords]
   200         seqNames = [i[1] for i in seqRecords]
   201     if isShowSize:
   202         seqLabels = map(seqNameAndSizeText, seqNames, seqSizes)
   203     else:
   204         seqLabels = seqNames
   205     labelSizes = get_text_sizes(seqLabels, font, fontsize, image_mode)
   206     margin = max(zip(*labelSizes)[1])  # maximum text height
   207     return seqNames, seqSizes, seqLabels, labelSizes, margin
   208 
   209 def div_ceil(x, y):
   210     '''Return x / y rounded up.'''
   211     q, r = divmod(x, y)
   212     return q + (r != 0)
   213 
   214 def get_bp_per_pix(seq_sizes, pix_tween_seqs, pix_limit):
   215     '''Get the minimum bp-per-pixel that fits in the size limit.'''
   216     seq_num = len(seq_sizes)
   217     seq_pix_limit = pix_limit - pix_tween_seqs * (seq_num - 1)
   218     if seq_pix_limit < seq_num:
   219         raise Exception("can't fit the image: too many sequences?")
   220     negLimit = -seq_pix_limit
   221     negBpPerPix = sum(seq_sizes) // negLimit
   222     while True:
   223         if sum(i // negBpPerPix for i in seq_sizes) >= negLimit:
   224             return -negBpPerPix
   225         negBpPerPix -= 1
   226 
   227 def get_seq_starts(seq_pix, pix_tween_seqs, margin):
   228     '''Get the start pixel for each sequence.'''
   229     seq_starts = []
   230     pix_tot = margin - pix_tween_seqs
   231     for i in seq_pix:
   232         pix_tot += pix_tween_seqs
   233         seq_starts.append(pix_tot)
   234         pix_tot += i
   235     return seq_starts
   236 
   237 def get_pix_info(seq_sizes, bp_per_pix, pix_tween_seqs, margin):
   238     '''Return pixel information about the sequences.'''
   239     seq_pix = [div_ceil(i, bp_per_pix) for i in seq_sizes]
   240     seq_starts = get_seq_starts(seq_pix, pix_tween_seqs, margin)
   241     tot_pix = seq_starts[-1] + seq_pix[-1]
   242     return seq_pix, seq_starts, tot_pix
   243 
   244 def drawLineForward(hits, width, bp_per_pix, beg1, beg2, size):
   245     while True:
   246         q1, r1 = divmod(beg1, bp_per_pix)
   247         q2, r2 = divmod(beg2, bp_per_pix)
   248         hits[q2 * width + q1] |= 1
   249         next_pix = min(bp_per_pix - r1, bp_per_pix - r2)
   250         if next_pix >= size: break
   251         beg1 += next_pix
   252         beg2 += next_pix
   253         size -= next_pix
   254 
   255 def drawLineReverse(hits, width, bp_per_pix, beg1, beg2, size):
   256     beg2 = -1 - beg2
   257     while True:
   258         q1, r1 = divmod(beg1, bp_per_pix)
   259         q2, r2 = divmod(beg2, bp_per_pix)
   260         hits[q2 * width + q1] |= 2
   261         next_pix = min(bp_per_pix - r1, r2 + 1)
   262         if next_pix >= size: break
   263         beg1 += next_pix
   264         beg2 -= next_pix
   265         size -= next_pix
   266 
   267 def alignmentPixels(width, height, alignments, bp_per_pix, origins1, origins2):
   268     hits = [0] * (width * height)  # the image data
   269     for seq1, seq2, blocks in alignments:
   270         ori1 = origins1[seq1]
   271         ori2 = origins2[seq2]
   272         for beg1, beg2, size in blocks:
   273             if beg1 < 0:
   274                 beg1 = -(beg1 + size)
   275                 beg2 = -(beg2 + size)
   276             if beg2 >= 0:
   277                 drawLineForward(hits, width, bp_per_pix,
   278                                 beg1 + ori1, beg2 + ori2, size)
   279             else:
   280                 drawLineReverse(hits, width, bp_per_pix,
   281                                 beg1 + ori1, beg2 - ori2, size)
   282     return hits
   283 
   284 def expandedSeqDict(seqDict):
   285     '''Allow lookup by short sequence names, e.g. chr7 as well as hg19.chr7.'''
   286     newDict = seqDict.copy()
   287     for name, x in seqDict.items():
   288         if "." in name:
   289             base = name.split(".")[-1]
   290             if base in newDict:  # an ambiguous case was found:
   291                 return seqDict   # so give up completely
   292             newDict[base] = x
   293     return newDict
   294 
   295 def readBed(fileName, seqLimits):
   296     if not fileName: return
   297     for line in myOpen(fileName):
   298         w = line.split()
   299         if not w: continue
   300         seqName = w[0]
   301         if seqName not in seqLimits: continue
   302         beg = int(w[1])
   303         end = int(w[2])
   304         layer = 900
   305         color = "#ffe4ff"
   306         if len(w) > 4:
   307             if w[4] != ".":
   308                 layer = float(w[4])
   309             if len(w) > 5:
   310                 if len(w) > 8 and w[8].count(",") == 2:
   311                     color = "rgb(" + w[8] + ")"
   312                 elif w[5] == "+":
   313                     color = "#fff4f4"
   314                 elif w[5] == "-":
   315                     color = "#f4f4ff"
   316         yield layer, color, seqName, beg, end
   317 
   318 def commaSeparatedInts(text):
   319     return map(int, text.rstrip(",").split(","))
   320 
   321 def readGenePred(opts, fileName, seqLimits):
   322     if not fileName: return
   323     for line in myOpen(fileName):
   324         fields = line.split()
   325         if not fields: continue
   326         if fields[2] not in "+-": fields = fields[1:]
   327         seqName = fields[1]
   328         if seqName not in seqLimits: continue
   329         #strand = fields[2]
   330         cdsBeg = int(fields[5])
   331         cdsEnd = int(fields[6])
   332         exonBegs = commaSeparatedInts(fields[8])
   333         exonEnds = commaSeparatedInts(fields[9])
   334         for beg, end in zip(exonBegs, exonEnds):
   335             yield 300, opts.exon_color, seqName, beg, end
   336             b = max(beg, cdsBeg)
   337             e = min(end, cdsEnd)
   338             if b < e: yield 400, opts.cds_color, seqName, b, e
   339 
   340 def readRmsk(fileName, seqLimits):
   341     if not fileName: return
   342     for line in myOpen(fileName):
   343         fields = line.split()
   344         if len(fields) == 17:  # rmsk.txt
   345             seqName = fields[5]
   346             if seqName not in seqLimits: continue  # do this ASAP for speed
   347             beg = int(fields[6])
   348             end = int(fields[7])
   349             strand = fields[9]
   350             repeatClass = fields[11]
   351         elif len(fields) == 15:  # .out
   352             seqName = fields[4]
   353             if seqName not in seqLimits: continue
   354             beg = int(fields[5]) - 1
   355             end = int(fields[6])
   356             strand = fields[8]
   357             repeatClass = fields[10]
   358         else:
   359             continue
   360         if repeatClass in ("Low_complexity", "Simple_repeat"):
   361             yield 200, "#ffe4ff", seqName, beg, end
   362         elif strand == "+":
   363             yield 100, "#fff4f4", seqName, beg, end
   364         else:
   365             yield 100, "#f4f4ff", seqName, beg, end
   366 
   367 def isExtraFirstGapField(fields):
   368     return fields[4].isdigit()
   369 
   370 def readGaps(opts, fileName, seqLimits):
   371     '''Read locations of unsequenced gaps, from an agp or gap file.'''
   372     if not fileName: return
   373     for line in myOpen(fileName):
   374         w = line.split()
   375         if not w or w[0][0] == "#": continue
   376         if isExtraFirstGapField(w): w = w[1:]
   377         if w[4] not in "NU": continue
   378         seqName = w[0]
   379         if seqName not in seqLimits: continue
   380         end = int(w[2])
   381         beg = end - int(w[5])  # zero-based coordinate
   382         if w[7] == "yes":
   383             yield 3000, opts.bridged_color, seqName, beg, end
   384         else:
   385             yield 2000, opts.unbridged_color, seqName, beg, end
   386 
   387 def bedBoxes(beds, seqLimits, origins, margin, edge, isTop, bpPerPix):
   388     for layer, color, seqName, beg, end in beds:
   389         cropBeg, cropEnd = seqLimits[seqName]
   390         beg = max(beg, cropBeg)
   391         end = min(end, cropEnd)
   392         if beg >= end: continue
   393         ori = origins[seqName]
   394         if layer <= 1000:
   395             # include partly-covered pixels
   396             b = (ori + beg) // bpPerPix
   397             e = div_ceil(ori + end, bpPerPix)
   398         else:
   399             # exclude partly-covered pixels
   400             b = div_ceil(ori + beg, bpPerPix)
   401             e = (ori + end) // bpPerPix
   402             if e <= b: continue
   403         if isTop:
   404             box = b, margin, e, edge
   405         else:
   406             box = margin, b, edge, e
   407         yield layer, color, box
   408 
   409 def drawAnnotations(im, boxes):
   410     # xxx use partial transparency for different-color overlaps?
   411     for layer, color, box in boxes:
   412         im.paste(color, box)
   413 
   414 def make_label(text, text_size, range_start, range_size):
   415     '''Return an axis label with endpoint & sort-order information.'''
   416     text_width  = text_size[0]
   417     label_start = range_start + (range_size - text_width) // 2
   418     label_end   = label_start + text_width
   419     sort_key    = text_width - range_size
   420     return sort_key, label_start, label_end, text
   421 
   422 def get_nonoverlapping_labels(labels, label_space):
   423     '''Get a subset of non-overlapping axis labels, greedily.'''
   424     nonoverlapping_labels = []
   425     for i in labels:
   426         if True not in [i[1] < j[2] + label_space and j[1] < i[2] + label_space
   427                         for j in nonoverlapping_labels]:
   428             nonoverlapping_labels.append(i)
   429     return nonoverlapping_labels
   430 
   431 def get_axis_image(seqNames, name_sizes, seq_starts, seq_pix,
   432                    font, image_mode, opts):
   433     '''Make an image of axis labels.'''
   434     min_pos = seq_starts[0]
   435     max_pos = seq_starts[-1] + seq_pix[-1]
   436     height = max(zip(*name_sizes)[1])
   437     labels = map(make_label, seqNames, name_sizes, seq_starts, seq_pix)
   438     labels = [i for i in labels if i[1] >= min_pos and i[2] <= max_pos]
   439     labels.sort()
   440     labels = get_nonoverlapping_labels(labels, opts.label_space)
   441     image_size = max_pos, height
   442     im = Image.new(image_mode, image_size, opts.border_color)
   443     draw = ImageDraw.Draw(im)
   444     for i in labels:
   445         position = i[1], 0
   446         draw.text(position, i[3], font=font, fill=opts.text_color)
   447     return im
   448 
   449 def seqOrigins(seqNames, seq_starts, seqLimits, bp_per_pix):
   450     for i, j in zip(seqNames, seq_starts):
   451         yield i, bp_per_pix * j - seqLimits[i][0]
   452 
   453 def lastDotplot(opts, args):
   454     if opts.fontfile:  font = ImageFont.truetype(opts.fontfile, opts.fontsize)
   455     else:              font = ImageFont.load_default()
   456 
   457     image_mode = 'RGB'
   458     forward_color = ImageColor.getcolor(opts.forwardcolor, image_mode)
   459     reverse_color = ImageColor.getcolor(opts.reversecolor, image_mode)
   460     zipped_colors = zip(forward_color, reverse_color)
   461     overlap_color = tuple([(i + j) // 2 for i, j in zipped_colors])
   462 
   463     warn("reading alignments...")
   464     alignmentInfo = readAlignments(args[0], opts)
   465     alignments, seqNames1, seqNames2, seqLimits1, seqLimits2 = alignmentInfo
   466     warn("done")
   467     if not alignments: raise Exception("there are no alignments")
   468 
   469     i1 = getSeqInfo(opts.sort1, seqNames1, seqLimits1,
   470                     font, opts.fontsize, image_mode, opts.lengths1)
   471     seqNames1, seqSizes1, seqLabels1, labelSizes1, margin1 = i1
   472 
   473     i2 = getSeqInfo(opts.sort2, seqNames2, seqLimits2,
   474                     font, opts.fontsize, image_mode, opts.lengths2)
   475     seqNames2, seqSizes2, seqLabels2, labelSizes2, margin2 = i2
   476 
   477     warn("choosing bp per pixel...")
   478     pix_limit1 = opts.width  - margin1
   479     pix_limit2 = opts.height - margin2
   480     bpPerPix1 = get_bp_per_pix(seqSizes1, opts.border_pixels, pix_limit1)
   481     bpPerPix2 = get_bp_per_pix(seqSizes2, opts.border_pixels, pix_limit2)
   482     bpPerPix = max(bpPerPix1, bpPerPix2)
   483     warn("bp per pixel = " + str(bpPerPix))
   484 
   485     seq_pix1, seq_starts1, width  = get_pix_info(seqSizes1, bpPerPix,
   486                                                  opts.border_pixels, margin1)
   487     seq_pix2, seq_starts2, height = get_pix_info(seqSizes2, bpPerPix,
   488                                                  opts.border_pixels, margin2)
   489     warn("width:  " + str(width))
   490     warn("height: " + str(height))
   491 
   492     origins1 = dict(seqOrigins(seqNames1, seq_starts1, seqLimits1, bpPerPix))
   493     origins2 = dict(seqOrigins(seqNames2, seq_starts2, seqLimits2, bpPerPix))
   494 
   495     warn("processing alignments...")
   496     hits = alignmentPixels(width, height, alignments, bpPerPix,
   497                            origins1, origins2)
   498     warn("done")
   499 
   500     image_size = width, height
   501     im = Image.new(image_mode, image_size, opts.background_color)
   502 
   503     seqLimits1 = expandedSeqDict(seqLimits1)
   504     seqLimits2 = expandedSeqDict(seqLimits2)
   505     origins1 = expandedSeqDict(origins1)
   506     origins2 = expandedSeqDict(origins2)
   507 
   508     beds1 = itertools.chain(readBed(opts.bed1, seqLimits1),
   509                             readRmsk(opts.rmsk1, seqLimits1),
   510                             readGenePred(opts, opts.genePred1, seqLimits1),
   511                             readGaps(opts, opts.gap1, seqLimits1))
   512     b1 = bedBoxes(beds1, seqLimits1, origins1, margin2, height, True, bpPerPix)
   513 
   514     beds2 = itertools.chain(readBed(opts.bed2, seqLimits2),
   515                             readRmsk(opts.rmsk2, seqLimits2),
   516                             readGenePred(opts, opts.genePred2, seqLimits2),
   517                             readGaps(opts, opts.gap2, seqLimits2))
   518     b2 = bedBoxes(beds2, seqLimits2, origins2, margin1, width, False, bpPerPix)
   519 
   520     boxes = sorted(itertools.chain(b1, b2))
   521     drawAnnotations(im, boxes)
   522 
   523     for i in range(height):
   524         for j in range(width):
   525             store_value = hits[i * width + j]
   526             xy = j, i
   527             if   store_value == 1: im.putpixel(xy, forward_color)
   528             elif store_value == 2: im.putpixel(xy, reverse_color)
   529             elif store_value == 3: im.putpixel(xy, overlap_color)
   530 
   531     if opts.fontsize != 0:
   532         axis1 = get_axis_image(seqLabels1, labelSizes1, seq_starts1, seq_pix1,
   533                                font, image_mode, opts)
   534         axis2 = get_axis_image(seqLabels2, labelSizes2, seq_starts2, seq_pix2,
   535                                font, image_mode, opts)
   536         axis2 = axis2.transpose(Image.ROTATE_270)  # !!! bug hotspot
   537         im.paste(axis1, (0, 0))
   538         im.paste(axis2, (0, 0))
   539 
   540     for i in seq_starts1[1:]:
   541         box = i - opts.border_pixels, margin2, i, height
   542         im.paste(opts.border_color, box)
   543 
   544     for i in seq_starts2[1:]:
   545         box = margin1, i - opts.border_pixels, width, i
   546         im.paste(opts.border_color, box)
   547 
   548     im.save(args[1])
   549 
   550 if __name__ == "__main__":
   551     usage = """%prog --help
   552    or: %prog [options] maf-or-tab-alignments dotplot.png
   553    or: %prog [options] maf-or-tab-alignments dotplot.gif
   554    or: ..."""
   555     description = "Draw a dotplot of pair-wise sequence alignments in MAF or tabular format."
   556     op = optparse.OptionParser(usage=usage, description=description)
   557     op.add_option("-v", "--verbose", action="count",
   558                   help="show progress messages & data about the plot")
   559     op.add_option("-1", "--seq1", metavar="PATTERN", action="append",
   560                   default=[],
   561                   help="which sequences to show from the 1st genome")
   562     op.add_option("-2", "--seq2", metavar="PATTERN", action="append",
   563                   default=[],
   564                   help="which sequences to show from the 2nd genome")
   565     # Replace "width" & "height" with a single "length" option?
   566     op.add_option("-x", "--width", type="int", default=1000,
   567                   help="maximum width in pixels (default: %default)")
   568     op.add_option("-y", "--height", type="int", default=1000,
   569                   help="maximum height in pixels (default: %default)")
   570     op.add_option("-c", "--forwardcolor", metavar="COLOR", default="red",
   571                   help="color for forward alignments (default: %default)")
   572     op.add_option("-r", "--reversecolor", metavar="COLOR", default="blue",
   573                   help="color for reverse alignments (default: %default)")
   574     op.add_option("--sort1", type="int", default=1, metavar="N",
   575                   help="genome1 sequence order: 0=input order, 1=name order, "
   576                   "2=length order (default=%default)")
   577     op.add_option("--sort2", type="int", default=1, metavar="N",
   578                   help="genome2 sequence order: 0=input order, 1=name order, "
   579                   "2=length order (default=%default)")
   580     op.add_option("--trim1", action="store_true",
   581                   help="trim unaligned sequence flanks from the 1st genome")
   582     op.add_option("--trim2", action="store_true",
   583                   help="trim unaligned sequence flanks from the 2nd genome")
   584     op.add_option("--border-pixels", metavar="INT", type="int", default=1,
   585                   help="number of pixels between sequences (default=%default)")
   586     op.add_option("--border-color", metavar="COLOR", default="#dcdcdc",
   587                   help="color for pixels between sequences (default=%default)")
   588     # xxx --margin-color?
   589 
   590     og = optparse.OptionGroup(op, "Text options")
   591     og.add_option("-f", "--fontfile", metavar="FILE",
   592                   help="TrueType or OpenType font file")
   593     og.add_option("-s", "--fontsize", metavar="SIZE", type="int", default=11,
   594                   help="TrueType or OpenType font size (default: %default)")
   595     og.add_option("--lengths1", action="store_true",
   596                   help="show sequence lengths for the 1st (horizontal) genome")
   597     og.add_option("--lengths2", action="store_true",
   598                   help="show sequence lengths for the 2nd (vertical) genome")
   599     op.add_option_group(og)
   600 
   601     og = optparse.OptionGroup(op, "Annotation options")
   602     og.add_option("--bed1", metavar="FILE",
   603                   help="read genome1 annotations from BED file")
   604     og.add_option("--bed2", metavar="FILE",
   605                   help="read genome2 annotations from BED file")
   606     og.add_option("--rmsk1", metavar="FILE", help="read genome1 repeats from "
   607                   "RepeatMasker .out or rmsk.txt file")
   608     og.add_option("--rmsk2", metavar="FILE", help="read genome2 repeats from "
   609                   "RepeatMasker .out or rmsk.txt file")
   610     op.add_option_group(og)
   611 
   612     og = optparse.OptionGroup(op, "Gene options")
   613     og.add_option("--genePred1", metavar="FILE",
   614                   help="read genome1 genes from genePred file")
   615     og.add_option("--genePred2", metavar="FILE",
   616                   help="read genome2 genes from genePred file")
   617     og.add_option("--exon-color", metavar="COLOR", default="#dfd",
   618                   help="color for exons (default=%default)")
   619     og.add_option("--cds-color", metavar="COLOR", default="#bdb",
   620                   help="color for protein-coding regions (default=%default)")
   621     op.add_option_group(og)
   622 
   623     og = optparse.OptionGroup(op, "Unsequenced gap options")
   624     og.add_option("--gap1", metavar="FILE",
   625                   help="read genome1 unsequenced gaps from agp or gap file")
   626     og.add_option("--gap2", metavar="FILE",
   627                   help="read genome2 unsequenced gaps from agp or gap file")
   628     og.add_option("--bridged-color", metavar="COLOR", default="yellow",
   629                   help="color for bridged gaps (default: %default)")
   630     og.add_option("--unbridged-color", metavar="COLOR", default="pink",
   631                   help="color for unbridged gaps (default: %default)")
   632     op.add_option_group(og)
   633     (opts, args) = op.parse_args()
   634     if len(args) != 2: op.error("2 arguments needed")
   635 
   636     opts.text_color = "black"
   637     opts.background_color = "white"
   638     opts.label_space = 5     # minimum number of pixels between axis labels
   639 
   640     try: lastDotplot(opts, args)
   641     except KeyboardInterrupt: pass  # avoid silly error message
   642     except Exception, e:
   643         prog = os.path.basename(sys.argv[0])
   644         sys.exit(prog + ": error: " + str(e))