scripts/last-dotplot
author Martin C. Frith
Mon Oct 19 10:53:05 2015 +0900 (2015-10-19)
changeset 639 047baa399047
parent 482 f5b731ee703e
child 640 374bc3ee1115
permissions -rwxr-xr-x
Made last-dotplot much faster.
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@482
    12
import fileinput, itertools, optparse, os, re, sys
Martin@475
    13
Martin@475
    14
# Try to make PIL/PILLOW work:
Martin@475
    15
try: from PIL import Image, ImageDraw, ImageFont, ImageColor
Martin@475
    16
except ImportError: import Image, ImageDraw, ImageFont, ImageColor
Martin@1
    17
Martin@1
    18
my_name = os.path.basename(sys.argv[0])
Martin@1
    19
usage = """
Martin@1
    20
  %prog --help
Martin@1
    21
  %prog [options] last-tabular-output dotplot.png
Martin@1
    22
  %prog [options] last-tabular-output dotplot.gif
Martin@1
    23
  etc."""
Martin@67
    24
parser = optparse.OptionParser(usage=usage)
Martin@51
    25
# Replace "width" & "height" with a single "length" option?
Martin@1
    26
parser.add_option("-x", "--width", type="int", dest="width", default=1000,
Martin@1
    27
                  help="maximum width in pixels (default: %default)")
Martin@1
    28
parser.add_option("-y", "--height", type="int", dest="height", default=1000,
Martin@1
    29
                  help="maximum height in pixels (default: %default)")
Martin@1
    30
parser.add_option("-f", "--fontfile", dest="fontfile",
Martin@1
    31
                  help="TrueType or OpenType font file")
Martin@1
    32
parser.add_option("-s", "--fontsize", type="int", dest="fontsize", default=11,
Martin@95
    33
                  help="TrueType or OpenType font size (default: %default)")
Martin@390
    34
parser.add_option("-c", "--forwardcolor", dest="forwardcolor", default="red",
Martin@134
    35
                  help="Color for forward alignments (default: %default)")
Martin@390
    36
parser.add_option("-r", "--reversecolor", dest="reversecolor", default="blue",
Martin@134
    37
                  help="Color for reverse alignments (default: %default)")
Martin@1
    38
(opts, args) = parser.parse_args()
Martin@1
    39
if len(args) != 2: parser.error("2 arguments needed")
Martin@1
    40
Martin@1
    41
if opts.fontfile:  font = ImageFont.truetype(opts.fontfile, opts.fontsize)
Martin@1
    42
else:              font = ImageFont.load_default()
Martin@1
    43
Martin@1
    44
# Make these options too?
Martin@134
    45
text_color = "black"
Martin@134
    46
background_color = "white"
Martin@390
    47
pix_tween_seqs = 2  # number of border pixels between sequences
Martin@134
    48
border_shade = 239, 239, 239  # the shade of grey to use for border pixels
Martin@1
    49
label_space = 5     # minimum number of pixels between axis labels
Martin@1
    50
Martin@134
    51
image_mode = 'RGB'
Martin@134
    52
forward_color = ImageColor.getcolor(opts.forwardcolor, image_mode)
Martin@134
    53
reverse_color = ImageColor.getcolor(opts.reversecolor, image_mode)
Martin@134
    54
overlap_color = tuple([(i+j)//2 for i, j in zip(forward_color, reverse_color)])
Martin@134
    55
Martin@482
    56
def tabBlocks(beg1, beg2, blocks):
Martin@482
    57
    '''Get the gapless blocks of an alignment, from LAST tabular format.'''
Martin@482
    58
    for i in blocks.split(","):
Martin@482
    59
        if ":" in i:
Martin@482
    60
            x, y = i.split(":")
Martin@482
    61
            beg1 += int(x)
Martin@482
    62
            beg2 += int(y)
Martin@482
    63
        else:
Martin@482
    64
            size = int(i)
Martin@482
    65
            yield beg1, beg2, size
Martin@482
    66
            beg1 += size
Martin@482
    67
            beg2 += size
Martin@272
    68
Martin@482
    69
def mafBlocks(beg1, beg2, seq1, seq2):
Martin@482
    70
    '''Get the gapless blocks of an alignment, from MAF format.'''
Martin@482
    71
    size = 0
Martin@482
    72
    for x, y in itertools.izip(seq1, seq2):
Martin@482
    73
        if x == "-":
Martin@482
    74
            if size:
Martin@482
    75
                yield beg1, beg2, size
Martin@482
    76
                beg1 += size
Martin@482
    77
                beg2 += size
Martin@482
    78
                size = 0
Martin@482
    79
            beg2 += 1
Martin@482
    80
        elif y == "-":
Martin@482
    81
            if size:
Martin@482
    82
                yield beg1, beg2, size
Martin@482
    83
                beg1 += size
Martin@482
    84
                beg2 += size
Martin@482
    85
                size = 0
Martin@482
    86
            beg1 += 1
Martin@272
    87
        else:
Martin@482
    88
            size += 1
Martin@482
    89
    if size: yield beg1, beg2, size
Martin@272
    90
Martin@482
    91
def alignmentInput(lines):
Martin@482
    92
    '''Get alignments and sequence lengths, from MAF or tabular format.'''
Martin@482
    93
    mafCount = 0
Martin@272
    94
    for line in lines:
Martin@272
    95
        w = line.split()
Martin@272
    96
        if line[0].isdigit():  # tabular format
Martin@482
    97
            chr1, beg1, seqlen1 = w[1], int(w[2]), int(w[5])
Martin@482
    98
            if w[4] == "-": beg1 -= seqlen1
Martin@482
    99
            chr2, beg2, seqlen2 = w[6], int(w[7]), int(w[10])
Martin@482
   100
            if w[9] == "-": beg2 -= seqlen2
Martin@482
   101
            blocks = tabBlocks(beg1, beg2, w[11])
Martin@482
   102
            yield chr1, seqlen1, chr2, seqlen2, blocks
Martin@272
   103
        elif line[0] == "s":  # MAF format
Martin@482
   104
            if mafCount == 0:
Martin@482
   105
                chr1, beg1, seqlen1, seq1 = w[1], int(w[2]), int(w[5]), w[6]
Martin@482
   106
                if w[4] == "-": beg1 -= seqlen1
Martin@482
   107
                mafCount = 1
Martin@482
   108
            else:
Martin@482
   109
                chr2, beg2, seqlen2, seq2 = w[1], int(w[2]), int(w[5]), w[6]
Martin@482
   110
                if w[4] == "-": beg2 -= seqlen2
Martin@482
   111
                blocks = mafBlocks(beg1, beg2, seq1, seq2)
Martin@482
   112
                yield chr1, seqlen1, chr2, seqlen2, blocks
Martin@482
   113
                mafCount = 0
Martin@272
   114
Martin@482
   115
def readAlignments(lines):
Martin@482
   116
    '''Get alignments and sequence lengths, from MAF or tabular format.'''
Martin@482
   117
    alignments = []
Martin@482
   118
    seqLengths1 = {}
Martin@482
   119
    seqLengths2 = {}
Martin@482
   120
    for chr1, seqlen1, chr2, seqlen2, blocks in alignmentInput(lines):
Martin@482
   121
        aln = chr1, chr2, blocks
Martin@482
   122
        alignments.append(aln)
Martin@482
   123
        seqLengths1[chr1] = seqlen1
Martin@482
   124
        seqLengths2[chr2] = seqlen2
Martin@482
   125
    return alignments, seqLengths1, seqLengths2
Martin@1
   126
Martin@1
   127
sys.stderr.write(my_name + ": reading alignments...\n")
Martin@482
   128
input = fileinput.input(args[0])
Martin@482
   129
alignments, seq_size_dic1, seq_size_dic2 = readAlignments(input)
Martin@1
   130
sys.stderr.write(my_name + ": done\n")
Martin@1
   131
Martin@128
   132
if not alignments:
Martin@128
   133
    sys.exit(my_name + ": there are no alignments")
Martin@128
   134
Martin@1
   135
def natural_sort_key(my_string):
Martin@1
   136
    '''Return a sort key for "natural" ordering, e.g. chr9 < chr10.'''
Martin@1
   137
    parts = re.split(r'(\d+)', my_string)
Martin@1
   138
    parts[1::2] = map(int, parts[1::2])
Martin@1
   139
    return parts
Martin@1
   140
Martin@1
   141
def get_text_sizes(my_strings):
Martin@1
   142
    '''Get widths & heights, in pixels, of some strings.'''
Martin@95
   143
    if opts.fontsize == 0: return [(0, 0) for i in my_strings]
Martin@1
   144
    image_size = 1, 1
Martin@134
   145
    im = Image.new(image_mode, image_size)
Martin@1
   146
    draw = ImageDraw.Draw(im)
Martin@1
   147
    return [draw.textsize(i, font=font) for i in my_strings]
Martin@1
   148
Martin@1
   149
def get_seq_info(seq_size_dic):
Martin@1
   150
    '''Return miscellaneous information about the sequences.'''
Martin@1
   151
    seq_names = seq_size_dic.keys()
Martin@1
   152
    seq_names.sort(key=natural_sort_key)
Martin@1
   153
    seq_sizes = [seq_size_dic[i] for i in seq_names]
Martin@1
   154
    name_sizes = get_text_sizes(seq_names)
Martin@28
   155
    margin = max(zip(*name_sizes)[1])  # maximum text height
Martin@1
   156
    return seq_names, seq_sizes, name_sizes, margin
Martin@1
   157
Martin@1
   158
seq_names1, seq_sizes1, name_sizes1, margin1 = get_seq_info(seq_size_dic1)
Martin@1
   159
seq_names2, seq_sizes2, name_sizes2, margin2 = get_seq_info(seq_size_dic2)
Martin@1
   160
Martin@1
   161
def div_ceil(x, y):
Martin@1
   162
    '''Return x / y rounded up.'''
Martin@1
   163
    q, r = divmod(x, y)
Martin@1
   164
    return q + (r != 0)
Martin@1
   165
Martin@1
   166
def tot_seq_pix(seq_sizes, bp_per_pix):
Martin@1
   167
    '''Return the total pixels needed for sequences of the given sizes.'''
Martin@28
   168
    return sum([div_ceil(i, bp_per_pix) for i in seq_sizes])
Martin@1
   169
Martin@1
   170
def get_bp_per_pix(seq_sizes, pix_limit):
Martin@1
   171
    '''Get the minimum bp-per-pixel that fits in the size limit.'''
Martin@1
   172
    seq_num = len(seq_sizes)
Martin@1
   173
    seq_pix_limit = pix_limit - pix_tween_seqs * (seq_num - 1)
Martin@1
   174
    if seq_pix_limit < seq_num:
Martin@1
   175
        sys.exit(my_name + ": can't fit the image: too many sequences?")
Martin@51
   176
    lower_bound = div_ceil(sum(seq_sizes), seq_pix_limit)
Martin@1
   177
    for bp_per_pix in itertools.count(lower_bound):  # slow linear search
Martin@1
   178
        if tot_seq_pix(seq_sizes, bp_per_pix) <= seq_pix_limit: break
Martin@1
   179
    return bp_per_pix
Martin@1
   180
Martin@1
   181
sys.stderr.write(my_name + ": choosing bp per pixel...\n")
Martin@1
   182
bp_per_pix1 = get_bp_per_pix(seq_sizes1, opts.width  - margin1)
Martin@1
   183
bp_per_pix2 = get_bp_per_pix(seq_sizes2, opts.height - margin2)
Martin@1
   184
bp_per_pix = max(bp_per_pix1, bp_per_pix2)
Martin@1
   185
sys.stderr.write(my_name + ": bp per pixel = " + str(bp_per_pix) + "\n")
Martin@1
   186
Martin@1
   187
def get_seq_starts(seq_pix, pix_tween_seqs, margin):
Martin@1
   188
    '''Get the start pixel for each sequence.'''
Martin@1
   189
    seq_starts = []
Martin@1
   190
    pix_tot = margin - pix_tween_seqs
Martin@1
   191
    for i in seq_pix:
Martin@1
   192
        pix_tot += pix_tween_seqs
Martin@1
   193
        seq_starts.append(pix_tot)
Martin@1
   194
        pix_tot += i
Martin@1
   195
    return seq_starts
Martin@1
   196
Martin@1
   197
def get_pix_info(seq_sizes, margin):
Martin@1
   198
    '''Return pixel information about the sequences.'''
Martin@1
   199
    seq_pix = [div_ceil(i, bp_per_pix) for i in seq_sizes]
Martin@1
   200
    seq_starts = get_seq_starts(seq_pix, pix_tween_seqs, margin)
Martin@1
   201
    tot_pix = seq_starts[-1] + seq_pix[-1]
Martin@1
   202
    return seq_pix, seq_starts, tot_pix
Martin@1
   203
Martin@1
   204
seq_pix1, seq_starts1, width  = get_pix_info(seq_sizes1, margin1)
Martin@1
   205
seq_pix2, seq_starts2, height = get_pix_info(seq_sizes2, margin2)
Martin@1
   206
seq_start_dic1 = dict(zip(seq_names1, seq_starts1))
Martin@1
   207
seq_start_dic2 = dict(zip(seq_names2, seq_starts2))
Martin@639
   208
Martin@639
   209
def drawLineForward(hits, width, bp_per_pix, origin, beg1, beg2, size):
Martin@639
   210
    while True:
Martin@639
   211
        q1, r1 = divmod(beg1, bp_per_pix)
Martin@639
   212
        q2, r2 = divmod(beg2, bp_per_pix)
Martin@639
   213
        hits[origin + q2 * width + q1] |= 1
Martin@639
   214
        next_pix = min(bp_per_pix - r1, bp_per_pix - r2)
Martin@639
   215
        if next_pix >= size: break
Martin@639
   216
        beg1 += next_pix
Martin@639
   217
        beg2 += next_pix
Martin@639
   218
        size -= next_pix
Martin@639
   219
Martin@639
   220
def drawLineReverse(hits, width, bp_per_pix, origin, beg1, beg2, size):
Martin@639
   221
    beg2 = -1 - beg2
Martin@639
   222
    while True:
Martin@639
   223
        q1, r1 = divmod(beg1, bp_per_pix)
Martin@639
   224
        q2, r2 = divmod(beg2, bp_per_pix)
Martin@639
   225
        hits[origin + q2 * width + q1] |= 2
Martin@639
   226
        next_pix = min(bp_per_pix - r1, r2 + 1)
Martin@639
   227
        if next_pix >= size: break
Martin@639
   228
        beg1 += next_pix
Martin@639
   229
        beg2 -= next_pix
Martin@639
   230
        size -= next_pix
Martin@639
   231
Martin@134
   232
hits = [0] * (width * height)  # the image data
Martin@1
   233
Martin@1
   234
sys.stderr.write(my_name + ": processing alignments...\n")
Martin@482
   235
for seq1, seq2, blocks in alignments:
Martin@1
   236
    seq_start1 = seq_start_dic1[seq1]
Martin@1
   237
    seq_start2 = seq_start_dic2[seq2]
Martin@273
   238
    my_start = seq_start2 * width + seq_start1
Martin@482
   239
    for beg1, beg2, size in blocks:
Martin@639
   240
        if beg1 < 0:
Martin@639
   241
            beg1 = -(beg1 + size)
Martin@639
   242
            beg2 = -(beg2 + size)
Martin@639
   243
        if beg2 >= 0:
Martin@639
   244
            drawLineForward(hits, width, bp_per_pix, my_start,
Martin@639
   245
                            beg1, beg2, size)
Martin@639
   246
        else:
Martin@639
   247
            drawLineReverse(hits, width, bp_per_pix, my_start,
Martin@639
   248
                            beg1, beg2, size)
Martin@1
   249
sys.stderr.write(my_name + ": done\n")
Martin@1
   250
Martin@1
   251
def make_label(text, text_size, range_start, range_size):
Martin@1
   252
    '''Return an axis label with endpoint & sort-order information.'''
Martin@1
   253
    text_width  = text_size[0]
Martin@1
   254
    label_start = range_start + (range_size - text_width) // 2
Martin@1
   255
    label_end   = label_start + text_width
Martin@1
   256
    sort_key    = text_width - range_size
Martin@1
   257
    return sort_key, label_start, label_end, text
Martin@1
   258
Martin@1
   259
def get_nonoverlapping_labels(labels):
Martin@1
   260
    '''Get a subset of non-overlapping axis labels, greedily.'''
Martin@1
   261
    nonoverlapping_labels = []
Martin@1
   262
    for i in labels:
Martin@28
   263
        if True not in [i[1] < j[2] + label_space and j[1] < i[2] + label_space
Martin@28
   264
                        for j in nonoverlapping_labels]:
Martin@1
   265
            nonoverlapping_labels.append(i)
Martin@1
   266
    return nonoverlapping_labels
Martin@1
   267
Martin@1
   268
def get_axis_image(seq_names, name_sizes, seq_starts, seq_pix):
Martin@1
   269
    '''Make an image of axis labels.'''
Martin@1
   270
    min_pos = seq_starts[0]
Martin@1
   271
    max_pos = seq_starts[-1] + seq_pix[-1]
Martin@28
   272
    height = max(zip(*name_sizes)[1])
Martin@1
   273
    labels = [make_label(i, j, k, l) for i, j, k, l in
Martin@1
   274
              zip(seq_names, name_sizes, seq_starts, seq_pix)]
Martin@1
   275
    labels = [i for i in labels if i[1] >= min_pos and i[2] <= max_pos]
Martin@1
   276
    labels.sort()
Martin@1
   277
    labels = get_nonoverlapping_labels(labels)
Martin@1
   278
    image_size = max_pos, height
Martin@134
   279
    im = Image.new(image_mode, image_size, border_shade)
Martin@1
   280
    draw = ImageDraw.Draw(im)
Martin@1
   281
    for i in labels:
Martin@1
   282
        position = i[1], 0
Martin@134
   283
        draw.text(position, i[3], font=font, fill=text_color)
Martin@1
   284
    return im
Martin@1
   285
Martin@1
   286
image_size = width, height
Martin@134
   287
im = Image.new(image_mode, image_size, background_color)
Martin@134
   288
Martin@134
   289
for i in range(height):
Martin@134
   290
    for j in range(width):
Martin@134
   291
        store_value = hits[i * width + j]
Martin@134
   292
        xy = j, i
Martin@134
   293
        if   store_value == 1: im.putpixel(xy, forward_color)
Martin@134
   294
        elif store_value == 2: im.putpixel(xy, reverse_color)
Martin@134
   295
        elif store_value == 3: im.putpixel(xy, overlap_color)
Martin@95
   296
Martin@95
   297
if opts.fontsize != 0:
Martin@95
   298
    axis1 = get_axis_image(seq_names1, name_sizes1, seq_starts1, seq_pix1)
Martin@95
   299
    axis2 = get_axis_image(seq_names2, name_sizes2, seq_starts2, seq_pix2)
Martin@95
   300
    axis2 = axis2.rotate(270)
Martin@95
   301
    im.paste(axis1, (0, 0))
Martin@95
   302
    im.paste(axis2, (0, 0))
Martin@1
   303
Martin@1
   304
for i in seq_starts1[1:]:
Martin@1
   305
    box = i - pix_tween_seqs, margin2, i, height
Martin@1
   306
    im.paste(border_shade, box)
Martin@1
   307
Martin@1
   308
for i in seq_starts2[1:]:
Martin@1
   309
    box = margin1, i - pix_tween_seqs, width, i
Martin@1
   310
    im.paste(border_shade, box)
Martin@1
   311
Martin@1
   312
im.save(args[1])