scripts/last-dotplot
author Martin C. Frith
Tue May 02 13:18:23 2017 +0900 (2017-05-02)
changeset 850 db0ddc92f2ec
parent 847 3ca7aa4b27a8
child 851 5b2acb7fdb3e
permissions -rwxr-xr-x
Tweak last-dotplot's documentation
     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 fnmatch, itertools, optparse, os, re, sys
    13 
    14 # Try to make PIL/PILLOW work:
    15 try: from PIL import Image, ImageDraw, ImageFont, ImageColor
    16 except ImportError: import Image, ImageDraw, ImageFont, ImageColor
    17 
    18 def myOpen(fileName):  # faster than fileinput
    19     if fileName == "-":
    20         return sys.stdin
    21     return open(fileName)
    22 
    23 def warn(message):
    24     prog = os.path.basename(sys.argv[0])
    25     sys.stderr.write(prog + ": " + message + "\n")
    26 
    27 def croppedBlocks(blocks, range1, range2):
    28     cropBeg1, cropEnd1 = range1
    29     cropBeg2, cropEnd2 = range2
    30     if blocks[0][0] < 0: cropBeg1, cropEnd1 = -cropEnd1, -cropBeg1
    31     if blocks[0][1] < 0: cropBeg2, cropEnd2 = -cropEnd2, -cropBeg2
    32     for beg1, beg2, size in blocks:
    33         b1 = max(cropBeg1, beg1)
    34         e1 = min(cropEnd1, beg1 + size)
    35         if b1 >= e1: continue
    36         offset = beg2 - beg1
    37         b2 = max(cropBeg2, b1 + offset)
    38         e2 = min(cropEnd2, e1 + offset)
    39         if b2 >= e2: continue
    40         yield b2 - offset, b2, e2 - b2
    41 
    42 def tabBlocks(beg1, beg2, blocks):
    43     '''Get the gapless blocks of an alignment, from LAST tabular format.'''
    44     for i in blocks.split(","):
    45         if ":" in i:
    46             x, y = i.split(":")
    47             beg1 += int(x)
    48             beg2 += int(y)
    49         else:
    50             size = int(i)
    51             yield beg1, beg2, size
    52             beg1 += size
    53             beg2 += size
    54 
    55 def mafBlocks(beg1, beg2, seq1, seq2):
    56     '''Get the gapless blocks of an alignment, from MAF format.'''
    57     size = 0
    58     for x, y in itertools.izip(seq1, seq2):
    59         if x == "-":
    60             if size:
    61                 yield beg1, beg2, size
    62                 beg1 += size
    63                 beg2 += size
    64                 size = 0
    65             beg2 += 1
    66         elif y == "-":
    67             if size:
    68                 yield beg1, beg2, size
    69                 beg1 += size
    70                 beg2 += size
    71                 size = 0
    72             beg1 += 1
    73         else:
    74             size += 1
    75     if size: yield beg1, beg2, size
    76 
    77 def alignmentInput(lines):
    78     '''Get alignments and sequence lengths, from MAF or tabular format.'''
    79     mafCount = 0
    80     for line in lines:
    81         w = line.split()
    82         if line[0].isdigit():  # tabular format
    83             chr1, beg1, seqlen1 = w[1], int(w[2]), int(w[5])
    84             if w[4] == "-": beg1 -= seqlen1
    85             chr2, beg2, seqlen2 = w[6], int(w[7]), int(w[10])
    86             if w[9] == "-": beg2 -= seqlen2
    87             blocks = tabBlocks(beg1, beg2, w[11])
    88             yield chr1, seqlen1, chr2, seqlen2, blocks
    89         elif line[0] == "s":  # MAF format
    90             if mafCount == 0:
    91                 chr1, beg1, seqlen1, seq1 = w[1], int(w[2]), int(w[5]), w[6]
    92                 if w[4] == "-": beg1 -= seqlen1
    93                 mafCount = 1
    94             else:
    95                 chr2, beg2, seqlen2, seq2 = w[1], int(w[2]), int(w[5]), w[6]
    96                 if w[4] == "-": beg2 -= seqlen2
    97                 blocks = mafBlocks(beg1, beg2, seq1, seq2)
    98                 yield chr1, seqlen1, chr2, seqlen2, blocks
    99                 mafCount = 0
   100 
   101 def seqRangeFromText(text):
   102     if ":" in text:
   103         pattern, interval = text.rsplit(":", 1)
   104         if "-" in interval:
   105             beg, end = interval.rsplit("-", 1)
   106             return pattern, int(beg), int(end)  # beg may be negative
   107     return text, 0, sys.maxsize
   108 
   109 def rangeFromSeqName(seqRanges, name, seqLen):
   110     if not seqRanges: return 0, seqLen
   111     base = name.split(".")[-1]  # allow for names like hg19.chr7
   112     for pat, beg, end in seqRanges:
   113         if fnmatch.fnmatchcase(name, pat) or fnmatch.fnmatchcase(base, pat):
   114             return max(beg, 0), min(end, seqLen)
   115     return None
   116 
   117 def updateSeqLimits(isTrim, seqLimits, seqName, seqRange, blocks, index):
   118     if isTrim:
   119         beg = blocks[0][index]
   120         end = blocks[-1][index] + blocks[-1][2]
   121         if beg < 0: beg, end = -end, -beg
   122         if seqName in seqLimits:
   123             b, e = seqLimits[seqName]
   124             seqLimits[seqName] = min(b, beg), max(e, end)
   125         else:
   126             seqLimits[seqName] = beg, end
   127     else:
   128         seqLimits[seqName] = seqRange
   129 
   130 def readAlignments(fileName, opts):
   131     '''Get alignments and sequence limits, from MAF or tabular format.'''
   132     seqRanges1 = map(seqRangeFromText, opts.seq1)
   133     seqRanges2 = map(seqRangeFromText, opts.seq2)
   134 
   135     alignments = []
   136     seqLimits1 = {}
   137     seqLimits2 = {}
   138     lines = myOpen(fileName)
   139     for seqName1, seqLen1, seqName2, seqLen2, blocks in alignmentInput(lines):
   140         range1 = rangeFromSeqName(seqRanges1, seqName1, seqLen1)
   141         if not range1: continue
   142         range2 = rangeFromSeqName(seqRanges2, seqName2, seqLen2)
   143         if not range2: continue
   144         b = list(croppedBlocks(list(blocks), range1, range2))
   145         if not b: continue
   146         aln = seqName1, seqName2, b
   147         alignments.append(aln)
   148         updateSeqLimits(opts.trim1, seqLimits1, seqName1, range1, b, 0)
   149         updateSeqLimits(opts.trim2, seqLimits2, seqName2, range2, b, 1)
   150     return alignments, seqLimits1, seqLimits2
   151 
   152 def natural_sort_key(my_string):
   153     '''Return a sort key for "natural" ordering, e.g. chr9 < chr10.'''
   154     parts = re.split(r'(\d+)', my_string)
   155     parts[1::2] = map(int, parts[1::2])
   156     return parts
   157 
   158 def get_text_sizes(my_strings, font, fontsize, image_mode):
   159     '''Get widths & heights, in pixels, of some strings.'''
   160     if fontsize == 0: return [(0, 0) for i in my_strings]
   161     image_size = 1, 1
   162     im = Image.new(image_mode, image_size)
   163     draw = ImageDraw.Draw(im)
   164     return [draw.textsize(i, font=font) for i in my_strings]
   165 
   166 def sizeText(size):
   167     suffixes = "bp", "kb", "Mb", "Gb"
   168     for i, x in enumerate(suffixes):
   169         j = 10 ** (i * 3)
   170         if size < j * 10:
   171             return "%.2g" % (1.0 * size / j) + x
   172         if size < j * 1000 or i == len(suffixes) - 1:
   173             return "%.0f" % (1.0 * size / j) + x
   174 
   175 def seqNameAndSizeText(seqName, seqSize):
   176     return seqName + ": " + sizeText(seqSize)
   177 
   178 def getSeqInfo(seqLimits, font, fontsize, image_mode, isShowSize):
   179     '''Return miscellaneous information about the sequences.'''
   180     seqNames = seqLimits.keys()
   181     seqNames.sort(key=natural_sort_key)
   182     seqSizes = [seqLimits[i][1] - seqLimits[i][0] for i in seqNames]
   183     if isShowSize:
   184         seqLabels = map(seqNameAndSizeText, seqNames, seqSizes)
   185     else:
   186         seqLabels = seqNames
   187     labelSizes = get_text_sizes(seqLabels, font, fontsize, image_mode)
   188     margin = max(zip(*labelSizes)[1])  # maximum text height
   189     return seqNames, seqSizes, seqLabels, labelSizes, margin
   190 
   191 def div_ceil(x, y):
   192     '''Return x / y rounded up.'''
   193     q, r = divmod(x, y)
   194     return q + (r != 0)
   195 
   196 def tot_seq_pix(seq_sizes, bp_per_pix):
   197     '''Return the total pixels needed for sequences of the given sizes.'''
   198     return sum([div_ceil(i, bp_per_pix) for i in seq_sizes])
   199 
   200 def get_bp_per_pix(seq_sizes, pix_tween_seqs, pix_limit):
   201     '''Get the minimum bp-per-pixel that fits in the size limit.'''
   202     seq_num = len(seq_sizes)
   203     seq_pix_limit = pix_limit - pix_tween_seqs * (seq_num - 1)
   204     if seq_pix_limit < seq_num:
   205         raise Exception("can't fit the image: too many sequences?")
   206     lower_bound = div_ceil(sum(seq_sizes), seq_pix_limit)
   207     for bp_per_pix in itertools.count(lower_bound):  # slow linear search
   208         if tot_seq_pix(seq_sizes, bp_per_pix) <= seq_pix_limit: break
   209     return bp_per_pix
   210 
   211 def get_seq_starts(seq_pix, pix_tween_seqs, margin):
   212     '''Get the start pixel for each sequence.'''
   213     seq_starts = []
   214     pix_tot = margin - pix_tween_seqs
   215     for i in seq_pix:
   216         pix_tot += pix_tween_seqs
   217         seq_starts.append(pix_tot)
   218         pix_tot += i
   219     return seq_starts
   220 
   221 def get_pix_info(seq_sizes, bp_per_pix, pix_tween_seqs, margin):
   222     '''Return pixel information about the sequences.'''
   223     seq_pix = [div_ceil(i, bp_per_pix) for i in seq_sizes]
   224     seq_starts = get_seq_starts(seq_pix, pix_tween_seqs, margin)
   225     tot_pix = seq_starts[-1] + seq_pix[-1]
   226     return seq_pix, seq_starts, tot_pix
   227 
   228 def drawLineForward(hits, width, bp_per_pix, beg1, beg2, size):
   229     while True:
   230         q1, r1 = divmod(beg1, bp_per_pix)
   231         q2, r2 = divmod(beg2, bp_per_pix)
   232         hits[q2 * width + q1] |= 1
   233         next_pix = min(bp_per_pix - r1, bp_per_pix - r2)
   234         if next_pix >= size: break
   235         beg1 += next_pix
   236         beg2 += next_pix
   237         size -= next_pix
   238 
   239 def drawLineReverse(hits, width, bp_per_pix, beg1, beg2, size):
   240     beg2 = -1 - beg2
   241     while True:
   242         q1, r1 = divmod(beg1, bp_per_pix)
   243         q2, r2 = divmod(beg2, bp_per_pix)
   244         hits[q2 * width + q1] |= 2
   245         next_pix = min(bp_per_pix - r1, r2 + 1)
   246         if next_pix >= size: break
   247         beg1 += next_pix
   248         beg2 -= next_pix
   249         size -= next_pix
   250 
   251 def alignmentPixels(width, height, alignments, bp_per_pix, origins1, origins2):
   252     hits = [0] * (width * height)  # the image data
   253     for seq1, seq2, blocks in alignments:
   254         ori1 = origins1[seq1]
   255         ori2 = origins2[seq2]
   256         for beg1, beg2, size in blocks:
   257             if beg1 < 0:
   258                 beg1 = -(beg1 + size)
   259                 beg2 = -(beg2 + size)
   260             if beg2 >= 0:
   261                 drawLineForward(hits, width, bp_per_pix,
   262                                 beg1 + ori1, beg2 + ori2, size)
   263             else:
   264                 drawLineReverse(hits, width, bp_per_pix,
   265                                 beg1 + ori1, beg2 - ori2, size)
   266     return hits
   267 
   268 def expandedSeqDict(seqDict):
   269     '''Allow lookup by short sequence names, e.g. chr7 as well as hg19.chr7.'''
   270     newDict = {}
   271     for name, x in seqDict.items():
   272         base = name.split(".")[-1]
   273         newDict[name] = x
   274         newDict[base] = x
   275     return newDict
   276 
   277 def readBed(fileName, seqLimits):
   278     if not fileName: return
   279     for line in myOpen(fileName):
   280         w = line.split()
   281         if not w: continue
   282         seqName = w[0]
   283         if seqName not in seqLimits: continue
   284         cropBeg, cropEnd = seqLimits[seqName]
   285         beg = int(w[1])
   286         end = int(w[2])
   287         b = max(beg, cropBeg)
   288         e = min(end, cropEnd)
   289         if b >= e: continue
   290         if len(w) > 8:
   291             color = tuple(map(int, w[8].split(",")))
   292         elif len(w) > 5:
   293             if   w[5] == "+": color = 255, 244, 244
   294             elif w[5] == "-": color = 244, 244, 255
   295             else:             color = 255, 228, 255
   296         else:
   297             color = 255, 228, 255
   298         yield seqName, b, e, color
   299 
   300 def isExtraFirstGapField(fields):
   301     return fields[4].isdigit()
   302 
   303 def readGaps(fileName, seqLimits):
   304     '''Read locations of unsequenced gaps, from an agp or gap file.'''
   305     if not fileName: return
   306     for line in myOpen(fileName):
   307         w = line.split()
   308         if not w or w[0][0] == "#": continue
   309         if isExtraFirstGapField(w): w = w[1:]
   310         if w[4] not in "NU": continue
   311         seqName = w[0]
   312         if seqName not in seqLimits: continue
   313         cropBeg, cropEnd = seqLimits[seqName]
   314         end = int(w[2])
   315         beg = end - int(w[5])  # zero-based coordinate
   316         b = max(beg, cropBeg)
   317         e = min(end, cropEnd)
   318         if b >= e: continue
   319         bridgedText = w[7]
   320         yield seqName, b, e, bridgedText
   321 
   322 def drawAnnotations(im, beds, origins, margin, limit, isTop, bp_per_pix):
   323     # XXX no consideration of different-color overlaps
   324     for seqName, beg, end, color in beds:
   325         ori = origins[seqName]
   326         b = (ori + beg) // bp_per_pix
   327         e = div_ceil(ori + end, bp_per_pix)
   328         if isTop: box = b, margin, e, limit
   329         else:     box = margin, b, limit, e
   330         im.paste(color, box)
   331 
   332 def drawUnsequencedGaps(im, gaps, origins, margin, limit, isTop, bridgedText,
   333                         bp_per_pix, color):
   334     '''Draw rectangles representing unsequenced gaps.'''
   335     for seqName, beg, end, b in gaps:
   336         if b != bridgedText: continue
   337         ori = origins[seqName]
   338         b = div_ceil(ori + beg, bp_per_pix)  # use fully-covered pixels only
   339         e = (ori + end) // bp_per_pix
   340         if e <= b: continue
   341         if isTop: box = b, margin, e, limit
   342         else:     box = margin, b, limit, e
   343         im.paste(color, box)
   344 
   345 def make_label(text, text_size, range_start, range_size):
   346     '''Return an axis label with endpoint & sort-order information.'''
   347     text_width  = text_size[0]
   348     label_start = range_start + (range_size - text_width) // 2
   349     label_end   = label_start + text_width
   350     sort_key    = text_width - range_size
   351     return sort_key, label_start, label_end, text
   352 
   353 def get_nonoverlapping_labels(labels, label_space):
   354     '''Get a subset of non-overlapping axis labels, greedily.'''
   355     nonoverlapping_labels = []
   356     for i in labels:
   357         if True not in [i[1] < j[2] + label_space and j[1] < i[2] + label_space
   358                         for j in nonoverlapping_labels]:
   359             nonoverlapping_labels.append(i)
   360     return nonoverlapping_labels
   361 
   362 def get_axis_image(seqNames, name_sizes, seq_starts, seq_pix,
   363                    font, image_mode, opts):
   364     '''Make an image of axis labels.'''
   365     min_pos = seq_starts[0]
   366     max_pos = seq_starts[-1] + seq_pix[-1]
   367     height = max(zip(*name_sizes)[1])
   368     labels = map(make_label, seqNames, name_sizes, seq_starts, seq_pix)
   369     labels = [i for i in labels if i[1] >= min_pos and i[2] <= max_pos]
   370     labels.sort()
   371     labels = get_nonoverlapping_labels(labels, opts.label_space)
   372     image_size = max_pos, height
   373     im = Image.new(image_mode, image_size, opts.border_shade)
   374     draw = ImageDraw.Draw(im)
   375     for i in labels:
   376         position = i[1], 0
   377         draw.text(position, i[3], font=font, fill=opts.text_color)
   378     return im
   379 
   380 def seqOrigins(seqNames, seq_starts, seqLimits, bp_per_pix):
   381     for i, j in zip(seqNames, seq_starts):
   382         yield i, bp_per_pix * j - seqLimits[i][0]
   383 
   384 def lastDotplot(opts, args):
   385     if opts.fontfile:  font = ImageFont.truetype(opts.fontfile, opts.fontsize)
   386     else:              font = ImageFont.load_default()
   387 
   388     image_mode = 'RGB'
   389     forward_color = ImageColor.getcolor(opts.forwardcolor, image_mode)
   390     reverse_color = ImageColor.getcolor(opts.reversecolor, image_mode)
   391     zipped_colors = zip(forward_color, reverse_color)
   392     overlap_color = tuple([(i + j) // 2 for i, j in zipped_colors])
   393 
   394     warn("reading alignments...")
   395     alignments, seqLimits1, seqLimits2 = readAlignments(args[0], opts)
   396     warn("done")
   397 
   398     if not alignments: raise Exception("there are no alignments")
   399 
   400     i1 = getSeqInfo(seqLimits1, font, opts.fontsize, image_mode, opts.lengths1)
   401     seqNames1, seqSizes1, seqLabels1, labelSizes1, margin1 = i1
   402 
   403     i2 = getSeqInfo(seqLimits2, font, opts.fontsize, image_mode, opts.lengths2)
   404     seqNames2, seqSizes2, seqLabels2, labelSizes2, margin2 = i2
   405 
   406     warn("choosing bp per pixel...")
   407     pix_limit1 = opts.width  - margin1
   408     pix_limit2 = opts.height - margin2
   409     bp_per_pix1 = get_bp_per_pix(seqSizes1, opts.pix_tween_seqs, pix_limit1)
   410     bp_per_pix2 = get_bp_per_pix(seqSizes2, opts.pix_tween_seqs, pix_limit2)
   411     bp_per_pix = max(bp_per_pix1, bp_per_pix2)
   412     warn("bp per pixel = " + str(bp_per_pix))
   413 
   414     seq_pix1, seq_starts1, width  = get_pix_info(seqSizes1, bp_per_pix,
   415                                                  opts.pix_tween_seqs, margin1)
   416     seq_pix2, seq_starts2, height = get_pix_info(seqSizes2, bp_per_pix,
   417                                                  opts.pix_tween_seqs, margin2)
   418     warn("width:  " + str(width))
   419     warn("height: " + str(height))
   420 
   421     origins1 = dict(seqOrigins(seqNames1, seq_starts1, seqLimits1, bp_per_pix))
   422     origins2 = dict(seqOrigins(seqNames2, seq_starts2, seqLimits2, bp_per_pix))
   423 
   424     warn("processing alignments...")
   425     hits = alignmentPixels(width, height, alignments, bp_per_pix,
   426                            origins1, origins2)
   427     warn("done")
   428 
   429     image_size = width, height
   430     im = Image.new(image_mode, image_size, opts.background_color)
   431 
   432     seqLimits1 = expandedSeqDict(seqLimits1)
   433     seqLimits2 = expandedSeqDict(seqLimits2)
   434     origins1 = expandedSeqDict(origins1)
   435     origins2 = expandedSeqDict(origins2)
   436 
   437     beds1 = list(readBed(opts.bed1, seqLimits1))
   438     beds2 = list(readBed(opts.bed2, seqLimits2))
   439     drawAnnotations(im, beds1, origins1, margin2, height, True, bp_per_pix)
   440     drawAnnotations(im, beds2, origins2, margin1, width, False, bp_per_pix)
   441 
   442     gaps1 = list(readGaps(opts.gap1, seqLimits1))
   443     gaps2 = list(readGaps(opts.gap2, seqLimits2))
   444     # draw bridged gaps first, then unbridged gaps on top:
   445     drawUnsequencedGaps(im, gaps1, origins1, margin2, height, True, "yes",
   446                         bp_per_pix, opts.bridged_color)
   447     drawUnsequencedGaps(im, gaps2, origins2, margin1, width, False, "yes",
   448                         bp_per_pix, opts.bridged_color)
   449     drawUnsequencedGaps(im, gaps1, origins1, margin2, height, True, "no",
   450                         bp_per_pix, opts.unbridged_color)
   451     drawUnsequencedGaps(im, gaps2, origins2, margin1, width, False, "no",
   452                         bp_per_pix, opts.unbridged_color)
   453 
   454     for i in range(height):
   455         for j in range(width):
   456             store_value = hits[i * width + j]
   457             xy = j, i
   458             if   store_value == 1: im.putpixel(xy, forward_color)
   459             elif store_value == 2: im.putpixel(xy, reverse_color)
   460             elif store_value == 3: im.putpixel(xy, overlap_color)
   461 
   462     if opts.fontsize != 0:
   463         axis1 = get_axis_image(seqLabels1, labelSizes1, seq_starts1, seq_pix1,
   464                                font, image_mode, opts)
   465         axis2 = get_axis_image(seqLabels2, labelSizes2, seq_starts2, seq_pix2,
   466                                font, image_mode, opts)
   467         axis2 = axis2.transpose(Image.ROTATE_270)  # !!! bug hotspot
   468         im.paste(axis1, (0, 0))
   469         im.paste(axis2, (0, 0))
   470 
   471     for i in seq_starts1[1:]:
   472         box = i - opts.pix_tween_seqs, margin2, i, height
   473         im.paste(opts.border_shade, box)
   474 
   475     for i in seq_starts2[1:]:
   476         box = margin1, i - opts.pix_tween_seqs, width, i
   477         im.paste(opts.border_shade, box)
   478 
   479     im.save(args[1])
   480 
   481 if __name__ == "__main__":
   482     usage = """%prog --help
   483    or: %prog [options] maf-or-tab-alignments dotplot.png
   484    or: %prog [options] maf-or-tab-alignments dotplot.gif
   485    or: ..."""
   486     description = "Draw a dotplot of pair-wise sequence alignments in MAF or tabular format."
   487     op = optparse.OptionParser(usage=usage, description=description)
   488     op.add_option("-1", "--seq1", metavar="PATTERN", action="append",
   489                   default=[],
   490                   help="which sequences to show from the 1st genome")
   491     op.add_option("-2", "--seq2", metavar="PATTERN", action="append",
   492                   default=[],
   493                   help="which sequences to show from the 2nd genome")
   494     # Replace "width" & "height" with a single "length" option?
   495     op.add_option("-x", "--width", type="int", default=1000,
   496                   help="maximum width in pixels (default: %default)")
   497     op.add_option("-y", "--height", type="int", default=1000,
   498                   help="maximum height in pixels (default: %default)")
   499     op.add_option("-c", "--forwardcolor", metavar="COLOR", default="red",
   500                   help="color for forward alignments (default: %default)")
   501     op.add_option("-r", "--reversecolor", metavar="COLOR", default="blue",
   502                   help="color for reverse alignments (default: %default)")
   503     op.add_option("--trim1", action="store_true",
   504                   help="trim unaligned sequence flanks from the 1st genome")
   505     op.add_option("--trim2", action="store_true",
   506                   help="trim unaligned sequence flanks from the 2nd genome")
   507     op.add_option("--bed1", metavar="FILE",
   508                   help="read genome1 annotations from bed file")
   509     op.add_option("--bed2", metavar="FILE",
   510                   help="read genome2 annotations from bed file")
   511 
   512     og = optparse.OptionGroup(op, "Text options")
   513     og.add_option("-f", "--fontfile", metavar="FILE",
   514                   help="TrueType or OpenType font file")
   515     og.add_option("-s", "--fontsize", metavar="SIZE", type="int", default=11,
   516                   help="TrueType or OpenType font size (default: %default)")
   517     og.add_option("--lengths1", action="store_true",
   518                   help="show sequence lengths for the 1st (horizontal) genome")
   519     og.add_option("--lengths2", action="store_true",
   520                   help="show sequence lengths for the 2nd (vertical) genome")
   521     op.add_option_group(og)
   522 
   523     og = optparse.OptionGroup(op, "Unsequenced gap options")
   524     og.add_option("--gap1", metavar="FILE",
   525                   help="read genome1 unsequenced gaps from agp or gap file")
   526     og.add_option("--gap2", metavar="FILE",
   527                   help="read genome2 unsequenced gaps from agp or gap file")
   528     og.add_option("--bridged-color", metavar="COLOR", default="yellow",
   529                   help="color for bridged gaps (default: %default)")
   530     og.add_option("--unbridged-color", metavar="COLOR", default="pink",
   531                   help="color for unbridged gaps (default: %default)")
   532     op.add_option_group(og)
   533     (opts, args) = op.parse_args()
   534     if len(args) != 2: op.error("2 arguments needed")
   535 
   536     opts.text_color = "black"
   537     opts.background_color = "white"
   538     opts.pix_tween_seqs = 2  # number of border pixels between sequences
   539     opts.border_shade = 239, 239, 239  # the shade of grey for border pixels
   540     opts.label_space = 5     # minimum number of pixels between axis labels
   541 
   542     try: lastDotplot(opts, args)
   543     except KeyboardInterrupt: pass  # avoid silly error message
   544     except Exception, e:
   545         prog = os.path.basename(sys.argv[0])
   546         sys.exit(prog + ": error: " + str(e))