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