scripts/last-dotplot
author Martin C. Frith
Wed Sep 24 13:13:14 2014 +0900 (2014-09-24)
changeset 479 e707702f53f8
parent 475 scripts/last-dotplot.py@4cf8170b3538
child 482 f5b731ee703e
permissions -rwxr-xr-x
Removed .py and .sh suffixes from script names.
     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 sys, os, re, itertools, optparse
    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 my_name = os.path.basename(sys.argv[0])
    19 usage = """
    20   %prog --help
    21   %prog [options] last-tabular-output dotplot.png
    22   %prog [options] last-tabular-output dotplot.gif
    23   etc."""
    24 parser = optparse.OptionParser(usage=usage)
    25 # Replace "width" & "height" with a single "length" option?
    26 parser.add_option("-x", "--width", type="int", dest="width", default=1000,
    27                   help="maximum width in pixels (default: %default)")
    28 parser.add_option("-y", "--height", type="int", dest="height", default=1000,
    29                   help="maximum height in pixels (default: %default)")
    30 parser.add_option("-f", "--fontfile", dest="fontfile",
    31                   help="TrueType or OpenType font file")
    32 parser.add_option("-s", "--fontsize", type="int", dest="fontsize", default=11,
    33                   help="TrueType or OpenType font size (default: %default)")
    34 parser.add_option("-c", "--forwardcolor", dest="forwardcolor", default="red",
    35                   help="Color for forward alignments (default: %default)")
    36 parser.add_option("-r", "--reversecolor", dest="reversecolor", default="blue",
    37                   help="Color for reverse alignments (default: %default)")
    38 (opts, args) = parser.parse_args()
    39 if len(args) != 2: parser.error("2 arguments needed")
    40 
    41 if opts.fontfile:  font = ImageFont.truetype(opts.fontfile, opts.fontsize)
    42 else:              font = ImageFont.load_default()
    43 
    44 # Make these options too?
    45 text_color = "black"
    46 background_color = "white"
    47 pix_tween_seqs = 2  # number of border pixels between sequences
    48 border_shade = 239, 239, 239  # the shade of grey to use for border pixels
    49 label_space = 5     # minimum number of pixels between axis labels
    50 
    51 image_mode = 'RGB'
    52 forward_color = ImageColor.getcolor(opts.forwardcolor, image_mode)
    53 reverse_color = ImageColor.getcolor(opts.reversecolor, image_mode)
    54 overlap_color = tuple([(i+j)//2 for i, j in zip(forward_color, reverse_color)])
    55 
    56 def isGapless(alignmentColumn):
    57     return "-" not in alignmentColumn
    58 
    59 def matchAndInsertLengths(alignmentColumns):
    60     for k, v in itertools.groupby(alignmentColumns, isGapless):
    61         if k:
    62             matchLength = sum(1 for i in v)
    63             yield str(matchLength)
    64         else:
    65             blockRows = itertools.izip(*v)
    66             insertLengths = (len(i) - i.count("-") for i in blockRows)
    67             yield ":".join(map(str, insertLengths))
    68 
    69 def alignmentInput(lines):  # read alignments in either tabular or MAF format
    70     for line in lines:
    71         w = line.split()
    72         if line[0].isdigit():  # tabular format
    73             yield w
    74         elif line[0] == "a":  # MAF format
    75             sLines = []
    76         elif line[0] == "s":  # MAF format
    77             sLines.append(w)
    78             if len(sLines) == 2:
    79                 alignmentRows = (i[6] for i in sLines)
    80                 alignmentColumns = itertools.izip(*alignmentRows)
    81                 blocks = ",".join(matchAndInsertLengths(alignmentColumns))
    82                 yield sLines[0][0:6] + sLines[1][1:6] + [blocks]
    83 
    84 seq_size_dic1 = {}  # sizes of the first set of sequences
    85 seq_size_dic2 = {}  # sizes of the second set of sequences
    86 alignments = []
    87 
    88 f = open(args[0])
    89 sys.stderr.write(my_name + ": reading alignments...\n")
    90 for w in alignmentInput(f):
    91     seq1, pos1, strand1, size1 = w[1], int(w[2]), w[4], int(w[5])
    92     seq2, pos2, strand2, size2 = w[6], int(w[7]), w[9], int(w[10])
    93     blocks = w[11]
    94     seq_size_dic1[seq1] = size1
    95     seq_size_dic2[seq2] = size2
    96     aln = seq1, seq2, pos1, pos2, strand1, strand2, blocks
    97     alignments.append(aln)
    98 sys.stderr.write(my_name + ": done\n")
    99 f.close()
   100 
   101 if not alignments:
   102     sys.exit(my_name + ": there are no alignments")
   103 
   104 def natural_sort_key(my_string):
   105     '''Return a sort key for "natural" ordering, e.g. chr9 < chr10.'''
   106     parts = re.split(r'(\d+)', my_string)
   107     parts[1::2] = map(int, parts[1::2])
   108     return parts
   109 
   110 def get_text_sizes(my_strings):
   111     '''Get widths & heights, in pixels, of some strings.'''
   112     if opts.fontsize == 0: return [(0, 0) for i in my_strings]
   113     image_size = 1, 1
   114     im = Image.new(image_mode, image_size)
   115     draw = ImageDraw.Draw(im)
   116     return [draw.textsize(i, font=font) for i in my_strings]
   117 
   118 def get_seq_info(seq_size_dic):
   119     '''Return miscellaneous information about the sequences.'''
   120     seq_names = seq_size_dic.keys()
   121     seq_names.sort(key=natural_sort_key)
   122     seq_sizes = [seq_size_dic[i] for i in seq_names]
   123     name_sizes = get_text_sizes(seq_names)
   124     margin = max(zip(*name_sizes)[1])  # maximum text height
   125     return seq_names, seq_sizes, name_sizes, margin
   126 
   127 seq_names1, seq_sizes1, name_sizes1, margin1 = get_seq_info(seq_size_dic1)
   128 seq_names2, seq_sizes2, name_sizes2, margin2 = get_seq_info(seq_size_dic2)
   129 
   130 def div_ceil(x, y):
   131     '''Return x / y rounded up.'''
   132     q, r = divmod(x, y)
   133     return q + (r != 0)
   134 
   135 def tot_seq_pix(seq_sizes, bp_per_pix):
   136     '''Return the total pixels needed for sequences of the given sizes.'''
   137     return sum([div_ceil(i, bp_per_pix) for i in seq_sizes])
   138 
   139 def get_bp_per_pix(seq_sizes, pix_limit):
   140     '''Get the minimum bp-per-pixel that fits in the size limit.'''
   141     seq_num = len(seq_sizes)
   142     seq_pix_limit = pix_limit - pix_tween_seqs * (seq_num - 1)
   143     if seq_pix_limit < seq_num:
   144         sys.exit(my_name + ": can't fit the image: too many sequences?")
   145     lower_bound = div_ceil(sum(seq_sizes), seq_pix_limit)
   146     for bp_per_pix in itertools.count(lower_bound):  # slow linear search
   147         if tot_seq_pix(seq_sizes, bp_per_pix) <= seq_pix_limit: break
   148     return bp_per_pix
   149 
   150 sys.stderr.write(my_name + ": choosing bp per pixel...\n")
   151 bp_per_pix1 = get_bp_per_pix(seq_sizes1, opts.width  - margin1)
   152 bp_per_pix2 = get_bp_per_pix(seq_sizes2, opts.height - margin2)
   153 bp_per_pix = max(bp_per_pix1, bp_per_pix2)
   154 sys.stderr.write(my_name + ": bp per pixel = " + str(bp_per_pix) + "\n")
   155 
   156 def get_seq_starts(seq_pix, pix_tween_seqs, margin):
   157     '''Get the start pixel for each sequence.'''
   158     seq_starts = []
   159     pix_tot = margin - pix_tween_seqs
   160     for i in seq_pix:
   161         pix_tot += pix_tween_seqs
   162         seq_starts.append(pix_tot)
   163         pix_tot += i
   164     return seq_starts
   165 
   166 def get_pix_info(seq_sizes, margin):
   167     '''Return pixel information about the sequences.'''
   168     seq_pix = [div_ceil(i, bp_per_pix) for i in seq_sizes]
   169     seq_starts = get_seq_starts(seq_pix, pix_tween_seqs, margin)
   170     tot_pix = seq_starts[-1] + seq_pix[-1]
   171     return seq_pix, seq_starts, tot_pix
   172 
   173 seq_pix1, seq_starts1, width  = get_pix_info(seq_sizes1, margin1)
   174 seq_pix2, seq_starts2, height = get_pix_info(seq_sizes2, margin2)
   175 seq_start_dic1 = dict(zip(seq_names1, seq_starts1))
   176 seq_start_dic2 = dict(zip(seq_names2, seq_starts2))
   177 hits = [0] * (width * height)  # the image data
   178 
   179 sys.stderr.write(my_name + ": processing alignments...\n")
   180 for aln in alignments:
   181     seq1, seq2, pos1, pos2, strand1, strand2, blocks = aln
   182     last1 = seq_size_dic1[seq1] - 1
   183     last2 = seq_size_dic2[seq2] - 1
   184     seq_start1 = seq_start_dic1[seq1]
   185     seq_start2 = seq_start_dic2[seq2]
   186     my_start = seq_start2 * width + seq_start1
   187     if strand1 == strand2: store_value = 1
   188     else:                  store_value = 2
   189     for i in blocks.split(","):
   190         if ":" in i:  # it's a gap region: skip over it
   191             insertLength1, insertLength2 = i.split(":")
   192             pos1 += int(insertLength1)
   193             pos2 += int(insertLength2)
   194         else:  # it's a match region: draw pixels for it
   195             matchLength = int(i)
   196             end1 = pos1 + matchLength
   197             end2 = pos2 + matchLength
   198             if strand1 == '+': j = xrange(pos1, end1)
   199             else:              j = xrange(last1 - pos1, last1 - end1, -1)
   200             if strand2 == '+': k = xrange(pos2, end2)
   201             else:              k = xrange(last2 - pos2, last2 - end2, -1)
   202             for real_pos1, real_pos2 in itertools.izip(j, k):
   203                 pix1 = real_pos1 // bp_per_pix
   204                 pix2 = real_pos2 // bp_per_pix
   205                 hits[my_start + pix2 * width + pix1] |= store_value
   206             pos1 = end1
   207             pos2 = end2
   208 sys.stderr.write(my_name + ": done\n")
   209 
   210 def make_label(text, text_size, range_start, range_size):
   211     '''Return an axis label with endpoint & sort-order information.'''
   212     text_width  = text_size[0]
   213     label_start = range_start + (range_size - text_width) // 2
   214     label_end   = label_start + text_width
   215     sort_key    = text_width - range_size
   216     return sort_key, label_start, label_end, text
   217 
   218 def get_nonoverlapping_labels(labels):
   219     '''Get a subset of non-overlapping axis labels, greedily.'''
   220     nonoverlapping_labels = []
   221     for i in labels:
   222         if True not in [i[1] < j[2] + label_space and j[1] < i[2] + label_space
   223                         for j in nonoverlapping_labels]:
   224             nonoverlapping_labels.append(i)
   225     return nonoverlapping_labels
   226 
   227 def get_axis_image(seq_names, name_sizes, seq_starts, seq_pix):
   228     '''Make an image of axis labels.'''
   229     min_pos = seq_starts[0]
   230     max_pos = seq_starts[-1] + seq_pix[-1]
   231     height = max(zip(*name_sizes)[1])
   232     labels = [make_label(i, j, k, l) for i, j, k, l in
   233               zip(seq_names, name_sizes, seq_starts, seq_pix)]
   234     labels = [i for i in labels if i[1] >= min_pos and i[2] <= max_pos]
   235     labels.sort()
   236     labels = get_nonoverlapping_labels(labels)
   237     image_size = max_pos, height
   238     im = Image.new(image_mode, image_size, border_shade)
   239     draw = ImageDraw.Draw(im)
   240     for i in labels:
   241         position = i[1], 0
   242         draw.text(position, i[3], font=font, fill=text_color)
   243     return im
   244 
   245 image_size = width, height
   246 im = Image.new(image_mode, image_size, background_color)
   247 
   248 for i in range(height):
   249     for j in range(width):
   250         store_value = hits[i * width + j]
   251         xy = j, i
   252         if   store_value == 1: im.putpixel(xy, forward_color)
   253         elif store_value == 2: im.putpixel(xy, reverse_color)
   254         elif store_value == 3: im.putpixel(xy, overlap_color)
   255 
   256 if opts.fontsize != 0:
   257     axis1 = get_axis_image(seq_names1, name_sizes1, seq_starts1, seq_pix1)
   258     axis2 = get_axis_image(seq_names2, name_sizes2, seq_starts2, seq_pix2)
   259     axis2 = axis2.rotate(270)
   260     im.paste(axis1, (0, 0))
   261     im.paste(axis2, (0, 0))
   262 
   263 for i in seq_starts1[1:]:
   264     box = i - pix_tween_seqs, margin2, i, height
   265     im.paste(border_shade, box)
   266 
   267 for i in seq_starts2[1:]:
   268     box = margin1, i - pix_tween_seqs, width, i
   269     im.paste(border_shade, box)
   270 
   271 im.save(args[1])