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