scripts/last-dotplot
author Martin C. Frith
Tue Oct 20 16:26:13 2015 +0900 (2015-10-20)
changeset 650 157301c5c6fd
parent 649 94f7cda3507b
child 651 fbb4c3b60998
permissions -rwxr-xr-x
Added unsequenced gap options to last-dotplot.
     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 fileinput, 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 warn(message):
    19     prog = os.path.basename(sys.argv[0])
    20     sys.stderr.write(prog + ": " + message + "\n")
    21 
    22 def tabBlocks(beg1, beg2, blocks):
    23     '''Get the gapless blocks of an alignment, from LAST tabular format.'''
    24     for i in blocks.split(","):
    25         if ":" in i:
    26             x, y = i.split(":")
    27             beg1 += int(x)
    28             beg2 += int(y)
    29         else:
    30             size = int(i)
    31             yield beg1, beg2, size
    32             beg1 += size
    33             beg2 += size
    34 
    35 def mafBlocks(beg1, beg2, seq1, seq2):
    36     '''Get the gapless blocks of an alignment, from MAF format.'''
    37     size = 0
    38     for x, y in itertools.izip(seq1, seq2):
    39         if x == "-":
    40             if size:
    41                 yield beg1, beg2, size
    42                 beg1 += size
    43                 beg2 += size
    44                 size = 0
    45             beg2 += 1
    46         elif y == "-":
    47             if size:
    48                 yield beg1, beg2, size
    49                 beg1 += size
    50                 beg2 += size
    51                 size = 0
    52             beg1 += 1
    53         else:
    54             size += 1
    55     if size: yield beg1, beg2, size
    56 
    57 def alignmentInput(lines):
    58     '''Get alignments and sequence lengths, from MAF or tabular format.'''
    59     mafCount = 0
    60     for line in lines:
    61         w = line.split()
    62         if line[0].isdigit():  # tabular format
    63             chr1, beg1, seqlen1 = w[1], int(w[2]), int(w[5])
    64             if w[4] == "-": beg1 -= seqlen1
    65             chr2, beg2, seqlen2 = w[6], int(w[7]), int(w[10])
    66             if w[9] == "-": beg2 -= seqlen2
    67             blocks = tabBlocks(beg1, beg2, w[11])
    68             yield chr1, seqlen1, chr2, seqlen2, blocks
    69         elif line[0] == "s":  # MAF format
    70             if mafCount == 0:
    71                 chr1, beg1, seqlen1, seq1 = w[1], int(w[2]), int(w[5]), w[6]
    72                 if w[4] == "-": beg1 -= seqlen1
    73                 mafCount = 1
    74             else:
    75                 chr2, beg2, seqlen2, seq2 = w[1], int(w[2]), int(w[5]), w[6]
    76                 if w[4] == "-": beg2 -= seqlen2
    77                 blocks = mafBlocks(beg1, beg2, seq1, seq2)
    78                 yield chr1, seqlen1, chr2, seqlen2, blocks
    79                 mafCount = 0
    80 
    81 def readAlignments(lines):
    82     '''Get alignments and sequence lengths, from MAF or tabular format.'''
    83     alignments = []
    84     seqLengths1 = {}
    85     seqLengths2 = {}
    86     for chr1, seqlen1, chr2, seqlen2, blocks in alignmentInput(lines):
    87         aln = chr1, chr2, blocks
    88         alignments.append(aln)
    89         seqLengths1[chr1] = seqlen1
    90         seqLengths2[chr2] = seqlen2
    91     return alignments, seqLengths1, seqLengths2
    92 
    93 def natural_sort_key(my_string):
    94     '''Return a sort key for "natural" ordering, e.g. chr9 < chr10.'''
    95     parts = re.split(r'(\d+)', my_string)
    96     parts[1::2] = map(int, parts[1::2])
    97     return parts
    98 
    99 def get_text_sizes(my_strings, font, fontsize, image_mode):
   100     '''Get widths & heights, in pixels, of some strings.'''
   101     if fontsize == 0: return [(0, 0) for i in my_strings]
   102     image_size = 1, 1
   103     im = Image.new(image_mode, image_size)
   104     draw = ImageDraw.Draw(im)
   105     return [draw.textsize(i, font=font) for i in my_strings]
   106 
   107 def get_seq_info(seq_size_dic, font, fontsize, image_mode):
   108     '''Return miscellaneous information about the sequences.'''
   109     seq_names = seq_size_dic.keys()
   110     seq_names.sort(key=natural_sort_key)
   111     seq_sizes = [seq_size_dic[i] for i in seq_names]
   112     name_sizes = get_text_sizes(seq_names, font, fontsize, image_mode)
   113     margin = max(zip(*name_sizes)[1])  # maximum text height
   114     return seq_names, seq_sizes, name_sizes, margin
   115 
   116 def div_ceil(x, y):
   117     '''Return x / y rounded up.'''
   118     q, r = divmod(x, y)
   119     return q + (r != 0)
   120 
   121 def tot_seq_pix(seq_sizes, bp_per_pix):
   122     '''Return the total pixels needed for sequences of the given sizes.'''
   123     return sum([div_ceil(i, bp_per_pix) for i in seq_sizes])
   124 
   125 def get_bp_per_pix(seq_sizes, pix_tween_seqs, pix_limit):
   126     '''Get the minimum bp-per-pixel that fits in the size limit.'''
   127     seq_num = len(seq_sizes)
   128     seq_pix_limit = pix_limit - pix_tween_seqs * (seq_num - 1)
   129     if seq_pix_limit < seq_num:
   130         raise Exception("can't fit the image: too many sequences?")
   131     lower_bound = div_ceil(sum(seq_sizes), seq_pix_limit)
   132     for bp_per_pix in itertools.count(lower_bound):  # slow linear search
   133         if tot_seq_pix(seq_sizes, bp_per_pix) <= seq_pix_limit: break
   134     return bp_per_pix
   135 
   136 def get_seq_starts(seq_pix, pix_tween_seqs, margin):
   137     '''Get the start pixel for each sequence.'''
   138     seq_starts = []
   139     pix_tot = margin - pix_tween_seqs
   140     for i in seq_pix:
   141         pix_tot += pix_tween_seqs
   142         seq_starts.append(pix_tot)
   143         pix_tot += i
   144     return seq_starts
   145 
   146 def get_pix_info(seq_sizes, bp_per_pix, pix_tween_seqs, margin):
   147     '''Return pixel information about the sequences.'''
   148     seq_pix = [div_ceil(i, bp_per_pix) for i in seq_sizes]
   149     seq_starts = get_seq_starts(seq_pix, pix_tween_seqs, margin)
   150     tot_pix = seq_starts[-1] + seq_pix[-1]
   151     return seq_pix, seq_starts, tot_pix
   152 
   153 def drawLineForward(hits, width, bp_per_pix, origin, beg1, beg2, size):
   154     while True:
   155         q1, r1 = divmod(beg1, bp_per_pix)
   156         q2, r2 = divmod(beg2, bp_per_pix)
   157         hits[origin + q2 * width + q1] |= 1
   158         next_pix = min(bp_per_pix - r1, bp_per_pix - r2)
   159         if next_pix >= size: break
   160         beg1 += next_pix
   161         beg2 += next_pix
   162         size -= next_pix
   163 
   164 def drawLineReverse(hits, width, bp_per_pix, origin, beg1, beg2, size):
   165     beg2 = -1 - beg2
   166     while True:
   167         q1, r1 = divmod(beg1, bp_per_pix)
   168         q2, r2 = divmod(beg2, bp_per_pix)
   169         hits[origin + q2 * width + q1] |= 2
   170         next_pix = min(bp_per_pix - r1, r2 + 1)
   171         if next_pix >= size: break
   172         beg1 += next_pix
   173         beg2 -= next_pix
   174         size -= next_pix
   175 
   176 def alignmentPixels(width, height, alignments, bp_per_pix,
   177                     seq_start_dic1, seq_start_dic2):
   178     hits = [0] * (width * height)  # the image data
   179     for seq1, seq2, blocks in alignments:
   180         seq_start1 = seq_start_dic1[seq1]
   181         seq_start2 = seq_start_dic2[seq2]
   182         origin = seq_start2 * width + seq_start1
   183         for beg1, beg2, size in blocks:
   184             if beg1 < 0:
   185                 beg1 = -(beg1 + size)
   186                 beg2 = -(beg2 + size)
   187             if beg2 >= 0:
   188                 drawLineForward(hits, width, bp_per_pix, origin,
   189                                 beg1, beg2, size)
   190             else:
   191                 drawLineReverse(hits, width, bp_per_pix, origin,
   192                                 beg1, beg2, size)
   193     return hits
   194 
   195 def expandedSeqDict(seqDict):
   196     '''Allow lookup by short sequence names, e.g. chr7 as well as hg19.chr7.'''
   197     newDict = {}
   198     for name, x in seqDict.items():
   199         base = name.split(".")[-1]
   200         newDict[name] = x
   201         newDict[base] = x
   202     return newDict
   203 
   204 def isExtraFirstGapField(fields):
   205     return fields[4].isdigit()
   206 
   207 def readGaps(fileName):
   208     '''Read locations of unsequenced gaps, from an agp or gap file.'''
   209     if not fileName: return
   210     for line in fileinput.input(fileName):
   211         w = line.split()
   212         if not w or w[0][0] == "#": continue
   213         if isExtraFirstGapField(w): w = w[1:]
   214         if w[4] not in "NU": continue
   215         seqName = w[0]
   216         end = int(w[2])
   217         beg = end - int(w[5])  # zero-based coordinate
   218         bridgedText = w[7]
   219         yield seqName, beg, end, bridgedText
   220 
   221 def drawUnsequencedGaps(im, gaps, start_dic, margin, limit, isTop, bridgedText,
   222                         bp_per_pix, color):
   223     '''Draw rectangles representing unsequenced gaps.'''
   224     for seqName, beg, end, b in gaps:
   225         if b != bridgedText: continue
   226         if seqName not in start_dic: continue
   227         origin = start_dic[seqName]
   228         b = div_ceil(beg, bp_per_pix)  # use fully-covered pixels only
   229         e = end // bp_per_pix
   230         if e <= b: continue
   231         if isTop: box = origin + b, margin, origin + e, limit
   232         else:     box = margin, origin + b, limit, origin + e
   233         im.paste(color, box)
   234 
   235 def make_label(text, text_size, range_start, range_size):
   236     '''Return an axis label with endpoint & sort-order information.'''
   237     text_width  = text_size[0]
   238     label_start = range_start + (range_size - text_width) // 2
   239     label_end   = label_start + text_width
   240     sort_key    = text_width - range_size
   241     return sort_key, label_start, label_end, text
   242 
   243 def get_nonoverlapping_labels(labels, label_space):
   244     '''Get a subset of non-overlapping axis labels, greedily.'''
   245     nonoverlapping_labels = []
   246     for i in labels:
   247         if True not in [i[1] < j[2] + label_space and j[1] < i[2] + label_space
   248                         for j in nonoverlapping_labels]:
   249             nonoverlapping_labels.append(i)
   250     return nonoverlapping_labels
   251 
   252 def get_axis_image(seq_names, name_sizes, seq_starts, seq_pix,
   253                    font, image_mode, opts):
   254     '''Make an image of axis labels.'''
   255     min_pos = seq_starts[0]
   256     max_pos = seq_starts[-1] + seq_pix[-1]
   257     height = max(zip(*name_sizes)[1])
   258     labels = [make_label(i, j, k, l) for i, j, k, l in
   259               zip(seq_names, name_sizes, seq_starts, seq_pix)]
   260     labels = [i for i in labels if i[1] >= min_pos and i[2] <= max_pos]
   261     labels.sort()
   262     labels = get_nonoverlapping_labels(labels, opts.label_space)
   263     image_size = max_pos, height
   264     im = Image.new(image_mode, image_size, opts.border_shade)
   265     draw = ImageDraw.Draw(im)
   266     for i in labels:
   267         position = i[1], 0
   268         draw.text(position, i[3], font=font, fill=opts.text_color)
   269     return im
   270 
   271 def lastDotplot(opts, args):
   272     if opts.fontfile:  font = ImageFont.truetype(opts.fontfile, opts.fontsize)
   273     else:              font = ImageFont.load_default()
   274 
   275     image_mode = 'RGB'
   276     forward_color = ImageColor.getcolor(opts.forwardcolor, image_mode)
   277     reverse_color = ImageColor.getcolor(opts.reversecolor, image_mode)
   278     zipped_colors = zip(forward_color, reverse_color)
   279     overlap_color = tuple([(i + j) // 2 for i, j in zipped_colors])
   280 
   281     warn("reading alignments...")
   282     input = fileinput.input(args[0])
   283     alignments, seq_size_dic1, seq_size_dic2 = readAlignments(input)
   284     warn("done")
   285 
   286     if not alignments: raise Exception("there are no alignments")
   287 
   288     seq_info1 = get_seq_info(seq_size_dic1, font, opts.fontsize, image_mode)
   289     seq_info2 = get_seq_info(seq_size_dic2, font, opts.fontsize, image_mode)
   290     seq_names1, seq_sizes1, name_sizes1, margin1 = seq_info1
   291     seq_names2, seq_sizes2, name_sizes2, margin2 = seq_info2
   292 
   293     warn("choosing bp per pixel...")
   294     pix_limit1 = opts.width  - margin1
   295     pix_limit2 = opts.height - margin2
   296     bp_per_pix1 = get_bp_per_pix(seq_sizes1, opts.pix_tween_seqs, pix_limit1)
   297     bp_per_pix2 = get_bp_per_pix(seq_sizes2, opts.pix_tween_seqs, pix_limit2)
   298     bp_per_pix = max(bp_per_pix1, bp_per_pix2)
   299     warn("bp per pixel = " + str(bp_per_pix))
   300 
   301     seq_pix1, seq_starts1, width  = get_pix_info(seq_sizes1, bp_per_pix,
   302                                                  opts.pix_tween_seqs, margin1)
   303     seq_pix2, seq_starts2, height = get_pix_info(seq_sizes2, bp_per_pix,
   304                                                  opts.pix_tween_seqs, margin2)
   305     seq_start_dic1 = dict(zip(seq_names1, seq_starts1))
   306     seq_start_dic2 = dict(zip(seq_names2, seq_starts2))
   307 
   308     warn("processing alignments...")
   309     hits = alignmentPixels(width, height, alignments, bp_per_pix,
   310                            seq_start_dic1, seq_start_dic2)
   311     warn("done")
   312 
   313     image_size = width, height
   314     im = Image.new(image_mode, image_size, opts.background_color)
   315 
   316     start_dic1 = expandedSeqDict(seq_start_dic1)
   317     start_dic2 = expandedSeqDict(seq_start_dic2)
   318     gaps1 = list(readGaps(opts.gap1))
   319     gaps2 = list(readGaps(opts.gap2))
   320     # draw bridged gaps first, then unbridged gaps on top:
   321     drawUnsequencedGaps(im, gaps1, start_dic1, margin2, height, True, "yes",
   322                         bp_per_pix, opts.bridged_color)
   323     drawUnsequencedGaps(im, gaps2, start_dic2, margin1, width, False, "yes",
   324                         bp_per_pix, opts.bridged_color)
   325     drawUnsequencedGaps(im, gaps1, start_dic1, margin2, height, True, "no",
   326                         bp_per_pix, opts.unbridged_color)
   327     drawUnsequencedGaps(im, gaps2, start_dic2, margin1, width, False, "no",
   328                         bp_per_pix, opts.unbridged_color)
   329 
   330     for i in range(height):
   331         for j in range(width):
   332             store_value = hits[i * width + j]
   333             xy = j, i
   334             if   store_value == 1: im.putpixel(xy, forward_color)
   335             elif store_value == 2: im.putpixel(xy, reverse_color)
   336             elif store_value == 3: im.putpixel(xy, overlap_color)
   337 
   338     if opts.fontsize != 0:
   339         axis1 = get_axis_image(seq_names1, name_sizes1, seq_starts1, seq_pix1,
   340                                font, image_mode, opts)
   341         axis2 = get_axis_image(seq_names2, name_sizes2, seq_starts2, seq_pix2,
   342                                font, image_mode, opts)
   343         axis2 = axis2.rotate(270)
   344         im.paste(axis1, (0, 0))
   345         im.paste(axis2, (0, 0))
   346 
   347     for i in seq_starts1[1:]:
   348         box = i - opts.pix_tween_seqs, margin2, i, height
   349         im.paste(opts.border_shade, box)
   350 
   351     for i in seq_starts2[1:]:
   352         box = margin1, i - opts.pix_tween_seqs, width, i
   353         im.paste(opts.border_shade, box)
   354 
   355     im.save(args[1])
   356 
   357 if __name__ == "__main__":
   358     usage = """%prog --help
   359    or: %prog [options] maf-or-tab-alignments dotplot.png
   360    or: %prog [options] maf-or-tab-alignments dotplot.gif
   361    or: ..."""
   362     description = "Draw a dotplot of pair-wise sequence alignments in MAF or tabular format."
   363     op = optparse.OptionParser(usage=usage, description=description)
   364     # Replace "width" & "height" with a single "length" option?
   365     op.add_option("-x", "--width", type="int", default=1000,
   366                   help="maximum width in pixels (default: %default)")
   367     op.add_option("-y", "--height", type="int", default=1000,
   368                   help="maximum height in pixels (default: %default)")
   369     op.add_option("-f", "--fontfile", metavar="FILE",
   370                   help="TrueType or OpenType font file")
   371     op.add_option("-s", "--fontsize", metavar="SIZE", type="int", default=11,
   372                   help="TrueType or OpenType font size (default: %default)")
   373     op.add_option("-c", "--forwardcolor", metavar="COLOR", default="red",
   374                   help="color for forward alignments (default: %default)")
   375     op.add_option("-r", "--reversecolor", metavar="COLOR", default="blue",
   376                   help="color for reverse alignments (default: %default)")
   377     og = optparse.OptionGroup(op, "Unsequenced gap options")
   378     og.add_option("--gap1", metavar="FILE",
   379                   help="read genome1 unsequenced gaps from agp or gap file")
   380     og.add_option("--gap2", metavar="FILE",
   381                   help="read genome2 unsequenced gaps from agp or gap file")
   382     og.add_option("--bridged-color", metavar="COLOR", default="yellow",
   383                   help="color for bridged gaps (default: %default)")
   384     og.add_option("--unbridged-color", metavar="COLOR", default="pink",
   385                   help="color for unbridged gaps (default: %default)")
   386     op.add_option_group(og)
   387     (opts, args) = op.parse_args()
   388     if len(args) != 2: op.error("2 arguments needed")
   389 
   390     opts.text_color = "black"
   391     opts.background_color = "white"
   392     opts.pix_tween_seqs = 2  # number of border pixels between sequences
   393     opts.border_shade = 239, 239, 239  # the shade of grey for border pixels
   394     opts.label_space = 5     # minimum number of pixels between axis labels
   395 
   396     try: lastDotplot(opts, args)
   397     except KeyboardInterrupt: pass  # avoid silly error message
   398     except Exception, e:
   399         prog = os.path.basename(sys.argv[0])
   400         sys.exit(prog + ": error: " + str(e))