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