scripts/last-dotplot
author Martin C. Frith
Wed Nov 08 17:02:56 2017 +0900 (2017-11-08)
changeset 910 42653029d900
parent 909 92dfad507286
child 911 4080f3f6f73d
permissions -rwxr-xr-x
Add gap-cutting options to 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@875
    12
import gzip
Martin@896
    13
from fnmatch import fnmatchcase
Martin@906
    14
from operator import itemgetter
Martin@903
    15
import subprocess
Martin@896
    16
import itertools, optparse, os, re, sys
Martin@475
    17
Martin@475
    18
# Try to make PIL/PILLOW work:
Martin@475
    19
try: from PIL import Image, ImageDraw, ImageFont, ImageColor
Martin@475
    20
except ImportError: import Image, ImageDraw, ImageFont, ImageColor
Martin@1
    21
Martin@844
    22
def myOpen(fileName):  # faster than fileinput
Martin@904
    23
    if fileName is None:
Martin@904
    24
        return []
Martin@844
    25
    if fileName == "-":
Martin@844
    26
        return sys.stdin
Martin@875
    27
    if fileName.endswith(".gz"):
Martin@875
    28
        return gzip.open(fileName)
Martin@844
    29
    return open(fileName)
Martin@844
    30
Martin@644
    31
def warn(message):
Martin@866
    32
    if opts.verbose:
Martin@866
    33
        prog = os.path.basename(sys.argv[0])
Martin@866
    34
        sys.stderr.write(prog + ": " + message + "\n")
Martin@644
    35
Martin@908
    36
def croppedBlocks(blocks, ranges1, ranges2):
Martin@908
    37
    headBeg1, headBeg2, headSize = blocks[0]
Martin@908
    38
    for r1 in ranges1:
Martin@908
    39
        for r2 in ranges2:
Martin@908
    40
            cropBeg1, cropEnd1 = r1
Martin@908
    41
            if headBeg1 < 0:
Martin@908
    42
                cropBeg1, cropEnd1 = -cropEnd1, -cropBeg1
Martin@908
    43
            cropBeg2, cropEnd2 = r2
Martin@908
    44
            if headBeg2 < 0:
Martin@908
    45
                cropBeg2, cropEnd2 = -cropEnd2, -cropBeg2
Martin@908
    46
            for beg1, beg2, size in blocks:
Martin@908
    47
                b1 = max(cropBeg1, beg1)
Martin@908
    48
                e1 = min(cropEnd1, beg1 + size)
Martin@908
    49
                if b1 >= e1: continue
Martin@908
    50
                offset = beg2 - beg1
Martin@908
    51
                b2 = max(cropBeg2, b1 + offset)
Martin@908
    52
                e2 = min(cropEnd2, e1 + offset)
Martin@908
    53
                if b2 >= e2: continue
Martin@908
    54
                yield b2 - offset, b2, e2 - b2
Martin@840
    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@847
   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@847
   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@897
   115
def seqRequestFromText(text):
Martin@840
   116
    if ":" in text:
Martin@840
   117
        pattern, interval = text.rsplit(":", 1)
Martin@840
   118
        if "-" in interval:
Martin@840
   119
            beg, end = interval.rsplit("-", 1)
Martin@840
   120
            return pattern, int(beg), int(end)  # beg may be negative
Martin@840
   121
    return text, 0, sys.maxsize
Martin@840
   122
Martin@909
   123
def rangesFromSeqName(seqRequests, name, seqLen):
Martin@908
   124
    if seqRequests:
Martin@908
   125
        base = name.split(".")[-1]  # allow for names like hg19.chr7
Martin@908
   126
        for pat, beg, end in seqRequests:
Martin@908
   127
            if fnmatchcase(name, pat) or fnmatchcase(base, pat):
Martin@909
   128
                yield max(beg, 0), min(end, seqLen)
Martin@908
   129
    else:
Martin@909
   130
        yield 0, seqLen
Martin@651
   131
Martin@909
   132
def updateSeqs(coverDict, seqRanges, seqName, ranges, coveredRange):
Martin@909
   133
    beg, end = coveredRange
Martin@909
   134
    if beg < 0:
Martin@909
   135
        coveredRange = -end, -beg
Martin@909
   136
    if seqName in coverDict:
Martin@909
   137
        coverDict[seqName].append(coveredRange)
Martin@839
   138
    else:
Martin@909
   139
        coverDict[seqName] = [coveredRange]
Martin@909
   140
        for beg, end in ranges:
Martin@909
   141
            r = seqName, beg, end
Martin@909
   142
            seqRanges.append(r)
Martin@839
   143
Martin@651
   144
def readAlignments(fileName, opts):
Martin@839
   145
    '''Get alignments and sequence limits, from MAF or tabular format.'''
Martin@897
   146
    seqRequests1 = map(seqRequestFromText, opts.seq1)
Martin@897
   147
    seqRequests2 = map(seqRequestFromText, opts.seq2)
Martin@840
   148
Martin@482
   149
    alignments = []
Martin@909
   150
    seqRanges1 = []
Martin@909
   151
    seqRanges2 = []
Martin@909
   152
    coverDict1 = {}
Martin@909
   153
    coverDict2 = {}
Martin@844
   154
    lines = myOpen(fileName)
Martin@838
   155
    for seqName1, seqLen1, seqName2, seqLen2, blocks in alignmentInput(lines):
Martin@909
   156
        ranges1 = sorted(rangesFromSeqName(seqRequests1, seqName1, seqLen1))
Martin@909
   157
        if not ranges1: continue
Martin@909
   158
        ranges2 = sorted(rangesFromSeqName(seqRequests2, seqName2, seqLen2))
Martin@909
   159
        if not ranges2: continue
Martin@909
   160
        b = list(croppedBlocks(list(blocks), ranges1, ranges2))
Martin@840
   161
        if not b: continue
Martin@840
   162
        aln = seqName1, seqName2, b
Martin@482
   163
        alignments.append(aln)
Martin@909
   164
        coveredRange1 = b[0][0], b[-1][0] + b[-1][2]
Martin@909
   165
        updateSeqs(coverDict1, seqRanges1, seqName1, ranges1, coveredRange1)
Martin@909
   166
        coveredRange2 = b[0][1], b[-1][1] + b[-1][2]
Martin@909
   167
        updateSeqs(coverDict2, seqRanges2, seqName2, ranges2, coveredRange2)
Martin@909
   168
    return alignments, seqRanges1, coverDict1, seqRanges2, coverDict2
Martin@1
   169
Martin@910
   170
def twoValuesFromOption(text, separator):
Martin@910
   171
    if separator in text:
Martin@910
   172
        return text.split(separator)
Martin@910
   173
    return text, text
Martin@910
   174
Martin@910
   175
def mergedRanges(ranges):
Martin@910
   176
    oldBeg, maxEnd = ranges[0]
Martin@910
   177
    for beg, end in ranges:
Martin@910
   178
        if beg > maxEnd:
Martin@910
   179
            yield oldBeg, maxEnd
Martin@910
   180
            oldBeg = beg
Martin@910
   181
            maxEnd = end
Martin@910
   182
        elif end > maxEnd:
Martin@910
   183
            maxEnd = end
Martin@910
   184
    yield oldBeg, maxEnd
Martin@910
   185
Martin@910
   186
def mergedRangesPerSeq(coverDict):
Martin@910
   187
    for k, v in coverDict.iteritems():
Martin@910
   188
        v.sort()
Martin@910
   189
        yield k, list(mergedRanges(v))
Martin@910
   190
Martin@910
   191
def coveredLength(mergedCoverDict):
Martin@910
   192
    return sum(sum(e - b for b, e in v) for v in mergedCoverDict.itervalues())
Martin@910
   193
Martin@910
   194
def trimmed(seqRanges, coverDict, minAlignedBases, maxGapFrac, endPad, midPad):
Martin@910
   195
    maxEndGapFrac, maxMidGapFrac = twoValuesFromOption(maxGapFrac, ",")
Martin@910
   196
    maxEndGap = max(float(maxEndGapFrac) * minAlignedBases, endPad * 1.0)
Martin@910
   197
    maxMidGap = max(float(maxMidGapFrac) * minAlignedBases, midPad * 2.0)
Martin@910
   198
Martin@910
   199
    for seqName, rangeBeg, rangeEnd in seqRanges:
Martin@910
   200
        seqBlocks = coverDict[seqName]
Martin@910
   201
        blocks = [i for i in seqBlocks if i[0] < rangeEnd and i[1] > rangeBeg]
Martin@910
   202
        if blocks[0][0] - rangeBeg > maxEndGap:
Martin@910
   203
            rangeBeg = blocks[0][0] - endPad
Martin@910
   204
        for j, y in enumerate(blocks):
Martin@910
   205
            if j:
Martin@910
   206
                x = blocks[j - 1]
Martin@910
   207
                if y[0] - x[1] > maxMidGap:
Martin@910
   208
                    yield seqName, rangeBeg, x[1] + midPad
Martin@910
   209
                    rangeBeg = y[0] - midPad
Martin@910
   210
        if rangeEnd - blocks[-1][1] > maxEndGap:
Martin@910
   211
            rangeEnd = blocks[-1][1] + endPad
Martin@910
   212
        yield seqName, rangeBeg, rangeEnd
Martin@910
   213
Martin@1
   214
def natural_sort_key(my_string):
Martin@1
   215
    '''Return a sort key for "natural" ordering, e.g. chr9 < chr10.'''
Martin@1
   216
    parts = re.split(r'(\d+)', my_string)
Martin@1
   217
    parts[1::2] = map(int, parts[1::2])
Martin@1
   218
    return parts
Martin@1
   219
Martin@907
   220
def nameKey(oneSeqRanges):
Martin@907
   221
    return natural_sort_key(oneSeqRanges[0][0])
Martin@907
   222
Martin@907
   223
def sizeKey(oneSeqRanges):
Martin@907
   224
    return sum(b - e for n, b, e in oneSeqRanges), nameKey(oneSeqRanges)
Martin@907
   225
Martin@907
   226
def getSortedRanges(seqRanges, sortOpt):
Martin@907
   227
    g = [list(v) for k, v in itertools.groupby(seqRanges, itemgetter(0))]
Martin@907
   228
    if sortOpt == "1":
Martin@907
   229
        g.sort(key=nameKey)
Martin@907
   230
    if sortOpt == "2":
Martin@907
   231
        g.sort(key=sizeKey)
Martin@907
   232
    return [j for i in g for j in i]
Martin@907
   233
Martin@898
   234
def prettyNum(n):
Martin@898
   235
    t = str(n)
Martin@898
   236
    groups = []
Martin@898
   237
    while t:
Martin@898
   238
        groups.append(t[-3:])
Martin@898
   239
        t = t[:-3]
Martin@904
   240
    return ",".join(reversed(groups))
Martin@898
   241
Martin@846
   242
def sizeText(size):
Martin@846
   243
    suffixes = "bp", "kb", "Mb", "Gb"
Martin@846
   244
    for i, x in enumerate(suffixes):
Martin@846
   245
        j = 10 ** (i * 3)
Martin@846
   246
        if size < j * 10:
Martin@846
   247
            return "%.2g" % (1.0 * size / j) + x
Martin@846
   248
        if size < j * 1000 or i == len(suffixes) - 1:
Martin@846
   249
            return "%.0f" % (1.0 * size / j) + x
Martin@846
   250
Martin@898
   251
def labelText(seqRange, labelOpt):
Martin@898
   252
    seqName, beg, end = seqRange
Martin@898
   253
    if labelOpt == 1:
Martin@898
   254
        return seqName + ": " + sizeText(end - beg)
Martin@898
   255
    if labelOpt == 2:
Martin@904
   256
        return seqName + ":" + prettyNum(beg) + ": " + sizeText(end - beg)
Martin@898
   257
    if labelOpt == 3:
Martin@904
   258
        return seqName + ":" + prettyNum(beg) + "-" + prettyNum(end)
Martin@898
   259
    return seqName
Martin@846
   260
Martin@899
   261
def rangeLabels(seqRanges, labelOpt, font, fontsize, image_mode, textRot):
Martin@899
   262
    if fontsize:
Martin@899
   263
        image_size = 1, 1
Martin@899
   264
        im = Image.new(image_mode, image_size)
Martin@899
   265
        draw = ImageDraw.Draw(im)
Martin@899
   266
    x = y = 0
Martin@899
   267
    for r in seqRanges:
Martin@899
   268
        text = labelText(r, labelOpt)
Martin@899
   269
        if fontsize:
Martin@899
   270
            x, y = draw.textsize(text, font=font)
Martin@899
   271
            if textRot:
Martin@899
   272
                x, y = y, x
Martin@899
   273
        yield text, x, y
Martin@899
   274
Martin@908
   275
def dataFromRanges(seqRanges, sortOpt, font,
Martin@908
   276
                   fontsize, image_mode, labelOpt, textRot):
Martin@907
   277
    s = getSortedRanges(seqRanges, sortOpt)
Martin@907
   278
    for i in s:
Martin@907
   279
        warn("\t".join(map(str, i)))
Martin@866
   280
    warn("")
Martin@907
   281
    rangeSizes = [e - b for n, b, e in s]
Martin@907
   282
    labs = list(rangeLabels(s, labelOpt, font, fontsize, image_mode, textRot))
Martin@907
   283
    margin = max(i[2] for i in labs)
Martin@878
   284
    # xxx the margin may be too big, because some labels may get omitted
Martin@907
   285
    return s, rangeSizes, labs, margin
Martin@1
   286
Martin@1
   287
def div_ceil(x, y):
Martin@1
   288
    '''Return x / y rounded up.'''
Martin@1
   289
    q, r = divmod(x, y)
Martin@1
   290
    return q + (r != 0)
Martin@1
   291
Martin@896
   292
def get_bp_per_pix(rangeSizes, pixTweenRanges, maxPixels):
Martin@1
   293
    '''Get the minimum bp-per-pixel that fits in the size limit.'''
Martin@904
   294
    warn("choosing bp per pixel...")
Martin@896
   295
    numOfRanges = len(rangeSizes)
Martin@896
   296
    maxPixelsInRanges = maxPixels - pixTweenRanges * (numOfRanges - 1)
Martin@896
   297
    if maxPixelsInRanges < numOfRanges:
Martin@649
   298
        raise Exception("can't fit the image: too many sequences?")
Martin@896
   299
    negLimit = -maxPixelsInRanges
Martin@896
   300
    negBpPerPix = sum(rangeSizes) // negLimit
Martin@863
   301
    while True:
Martin@896
   302
        if sum(i // negBpPerPix for i in rangeSizes) >= negLimit:
Martin@863
   303
            return -negBpPerPix
Martin@863
   304
        negBpPerPix -= 1
Martin@1
   305
Martin@900
   306
def getRangePixBegs(rangePixLens, pixTweenRanges, margin):
Martin@900
   307
    '''Get the start pixel for each range.'''
Martin@900
   308
    rangePixBegs = []
Martin@896
   309
    pix_tot = margin - pixTweenRanges
Martin@900
   310
    for i in rangePixLens:
Martin@896
   311
        pix_tot += pixTweenRanges
Martin@900
   312
        rangePixBegs.append(pix_tot)
Martin@1
   313
        pix_tot += i
Martin@900
   314
    return rangePixBegs
Martin@1
   315
Martin@896
   316
def pixelData(rangeSizes, bp_per_pix, pixTweenRanges, margin):
Martin@900
   317
    '''Return pixel information about the ranges.'''
Martin@900
   318
    rangePixLens = [div_ceil(i, bp_per_pix) for i in rangeSizes]
Martin@900
   319
    rangePixBegs = getRangePixBegs(rangePixLens, pixTweenRanges, margin)
Martin@900
   320
    tot_pix = rangePixBegs[-1] + rangePixLens[-1]
Martin@900
   321
    return rangePixBegs, rangePixLens, tot_pix
Martin@1
   322
Martin@835
   323
def drawLineForward(hits, width, bp_per_pix, beg1, beg2, size):
Martin@639
   324
    while True:
Martin@639
   325
        q1, r1 = divmod(beg1, bp_per_pix)
Martin@639
   326
        q2, r2 = divmod(beg2, bp_per_pix)
Martin@835
   327
        hits[q2 * width + q1] |= 1
Martin@639
   328
        next_pix = min(bp_per_pix - r1, bp_per_pix - r2)
Martin@639
   329
        if next_pix >= size: break
Martin@639
   330
        beg1 += next_pix
Martin@639
   331
        beg2 += next_pix
Martin@639
   332
        size -= next_pix
Martin@639
   333
Martin@835
   334
def drawLineReverse(hits, width, bp_per_pix, beg1, beg2, size):
Martin@639
   335
    beg2 = -1 - beg2
Martin@639
   336
    while True:
Martin@639
   337
        q1, r1 = divmod(beg1, bp_per_pix)
Martin@639
   338
        q2, r2 = divmod(beg2, bp_per_pix)
Martin@835
   339
        hits[q2 * width + q1] |= 2
Martin@639
   340
        next_pix = min(bp_per_pix - r1, r2 + 1)
Martin@639
   341
        if next_pix >= size: break
Martin@639
   342
        beg1 += next_pix
Martin@639
   343
        beg2 -= next_pix
Martin@639
   344
        size -= next_pix
Martin@639
   345
Martin@905
   346
def findOrigin(ranges, beg, size):
Martin@905
   347
    if beg < 0:
Martin@905
   348
        beg = -(beg + size)
Martin@905
   349
    for rangeBeg, rangeEnd, origin in ranges:
Martin@905
   350
        if rangeEnd > beg:
Martin@905
   351
            return origin
Martin@905
   352
Martin@905
   353
def alignmentPixels(width, height, alignments, bp_per_pix,
Martin@905
   354
                    rangeDict1, rangeDict2):
Martin@640
   355
    hits = [0] * (width * height)  # the image data
Martin@640
   356
    for seq1, seq2, blocks in alignments:
Martin@905
   357
        beg1, beg2, size = blocks[0]
Martin@905
   358
        ori1 = findOrigin(rangeDict1[seq1], beg1, size)
Martin@905
   359
        ori2 = findOrigin(rangeDict2[seq2], beg2, size)
Martin@640
   360
        for beg1, beg2, size in blocks:
Martin@640
   361
            if beg1 < 0:
Martin@640
   362
                beg1 = -(beg1 + size)
Martin@640
   363
                beg2 = -(beg2 + size)
Martin@640
   364
            if beg2 >= 0:
Martin@835
   365
                drawLineForward(hits, width, bp_per_pix,
Martin@835
   366
                                beg1 + ori1, beg2 + ori2, size)
Martin@640
   367
            else:
Martin@835
   368
                drawLineReverse(hits, width, bp_per_pix,
Martin@835
   369
                                beg1 + ori1, beg2 - ori2, size)
Martin@640
   370
    return hits
Martin@1
   371
Martin@650
   372
def expandedSeqDict(seqDict):
Martin@650
   373
    '''Allow lookup by short sequence names, e.g. chr7 as well as hg19.chr7.'''
Martin@861
   374
    newDict = seqDict.copy()
Martin@650
   375
    for name, x in seqDict.items():
Martin@861
   376
        if "." in name:
Martin@861
   377
            base = name.split(".")[-1]
Martin@861
   378
            if base in newDict:  # an ambiguous case was found:
Martin@861
   379
                return seqDict   # so give up completely
Martin@861
   380
            newDict[base] = x
Martin@650
   381
    return newDict
Martin@650
   382
Martin@905
   383
def readBed(fileName, rangeDict):
Martin@845
   384
    for line in myOpen(fileName):
Martin@845
   385
        w = line.split()
Martin@847
   386
        if not w: continue
Martin@845
   387
        seqName = w[0]
Martin@905
   388
        if seqName not in rangeDict: continue
Martin@845
   389
        beg = int(w[1])
Martin@845
   390
        end = int(w[2])
Martin@857
   391
        layer = 900
Martin@895
   392
        color = "#fbf"
Martin@858
   393
        if len(w) > 4:
Martin@858
   394
            if w[4] != ".":
Martin@858
   395
                layer = float(w[4])
Martin@858
   396
            if len(w) > 5:
Martin@858
   397
                if len(w) > 8 and w[8].count(",") == 2:
Martin@858
   398
                    color = "rgb(" + w[8] + ")"
Martin@858
   399
                elif w[5] == "+":
Martin@895
   400
                    color = "#ffe8e8"
Martin@858
   401
                elif w[5] == "-":
Martin@895
   402
                    color = "#e8e8ff"
Martin@859
   403
        yield layer, color, seqName, beg, end
Martin@845
   404
Martin@860
   405
def commaSeparatedInts(text):
Martin@860
   406
    return map(int, text.rstrip(",").split(","))
Martin@860
   407
Martin@905
   408
def readGenePred(opts, fileName, rangeDict):
Martin@860
   409
    for line in myOpen(fileName):
Martin@860
   410
        fields = line.split()
Martin@860
   411
        if not fields: continue
Martin@860
   412
        if fields[2] not in "+-": fields = fields[1:]
Martin@860
   413
        seqName = fields[1]
Martin@905
   414
        if seqName not in rangeDict: continue
Martin@860
   415
        #strand = fields[2]
Martin@860
   416
        cdsBeg = int(fields[5])
Martin@860
   417
        cdsEnd = int(fields[6])
Martin@860
   418
        exonBegs = commaSeparatedInts(fields[8])
Martin@860
   419
        exonEnds = commaSeparatedInts(fields[9])
Martin@860
   420
        for beg, end in zip(exonBegs, exonEnds):
Martin@860
   421
            yield 300, opts.exon_color, seqName, beg, end
Martin@860
   422
            b = max(beg, cdsBeg)
Martin@860
   423
            e = min(end, cdsEnd)
Martin@860
   424
            if b < e: yield 400, opts.cds_color, seqName, b, e
Martin@860
   425
Martin@905
   426
def readRmsk(fileName, rangeDict):
Martin@860
   427
    for line in myOpen(fileName):
Martin@860
   428
        fields = line.split()
Martin@860
   429
        if len(fields) == 17:  # rmsk.txt
Martin@860
   430
            seqName = fields[5]
Martin@905
   431
            if seqName not in rangeDict: continue  # do this ASAP for speed
Martin@860
   432
            beg = int(fields[6])
Martin@860
   433
            end = int(fields[7])
Martin@860
   434
            strand = fields[9]
Martin@860
   435
            repeatClass = fields[11]
Martin@860
   436
        elif len(fields) == 15:  # .out
Martin@860
   437
            seqName = fields[4]
Martin@905
   438
            if seqName not in rangeDict: continue
Martin@860
   439
            beg = int(fields[5]) - 1
Martin@860
   440
            end = int(fields[6])
Martin@860
   441
            strand = fields[8]
Martin@860
   442
            repeatClass = fields[10]
Martin@860
   443
        else:
Martin@860
   444
            continue
Martin@860
   445
        if repeatClass in ("Low_complexity", "Simple_repeat"):
Martin@895
   446
            yield 200, "#fbf", seqName, beg, end
Martin@860
   447
        elif strand == "+":
Martin@895
   448
            yield 100, "#ffe8e8", seqName, beg, end
Martin@860
   449
        else:
Martin@895
   450
            yield 100, "#e8e8ff", seqName, beg, end
Martin@860
   451
Martin@650
   452
def isExtraFirstGapField(fields):
Martin@650
   453
    return fields[4].isdigit()
Martin@650
   454
Martin@905
   455
def readGaps(opts, fileName, rangeDict):
Martin@650
   456
    '''Read locations of unsequenced gaps, from an agp or gap file.'''
Martin@844
   457
    for line in myOpen(fileName):
Martin@650
   458
        w = line.split()
Martin@650
   459
        if not w or w[0][0] == "#": continue
Martin@650
   460
        if isExtraFirstGapField(w): w = w[1:]
Martin@650
   461
        if w[4] not in "NU": continue
Martin@650
   462
        seqName = w[0]
Martin@905
   463
        if seqName not in rangeDict: continue
Martin@650
   464
        end = int(w[2])
Martin@650
   465
        beg = end - int(w[5])  # zero-based coordinate
Martin@857
   466
        if w[7] == "yes":
Martin@859
   467
            yield 3000, opts.bridged_color, seqName, beg, end
Martin@857
   468
        else:
Martin@859
   469
            yield 2000, opts.unbridged_color, seqName, beg, end
Martin@650
   470
Martin@905
   471
def bedBoxes(beds, rangeDict, margin, edge, isTop, bpPerPix):
Martin@897
   472
    for layer, color, seqName, bedBeg, bedEnd in beds:
Martin@905
   473
        for rangeBeg, rangeEnd, origin in rangeDict[seqName]:
Martin@905
   474
            beg = max(bedBeg, rangeBeg)
Martin@905
   475
            end = min(bedEnd, rangeEnd)
Martin@905
   476
            if beg >= end: continue
Martin@905
   477
            if layer <= 1000:
Martin@905
   478
                # include partly-covered pixels
Martin@905
   479
                b = (origin + beg) // bpPerPix
Martin@905
   480
                e = div_ceil(origin + end, bpPerPix)
Martin@905
   481
            else:
Martin@905
   482
                # exclude partly-covered pixels
Martin@905
   483
                b = div_ceil(origin + beg, bpPerPix)
Martin@905
   484
                e = (origin + end) // bpPerPix
Martin@905
   485
                if e <= b: continue
Martin@905
   486
            if isTop:
Martin@905
   487
                box = b, margin, e, edge
Martin@905
   488
            else:
Martin@905
   489
                box = margin, b, edge, e
Martin@905
   490
            yield layer, color, box
Martin@845
   491
Martin@857
   492
def drawAnnotations(im, boxes):
Martin@857
   493
    # xxx use partial transparency for different-color overlaps?
Martin@857
   494
    for layer, color, box in boxes:
Martin@650
   495
        im.paste(color, box)
Martin@650
   496
Martin@901
   497
def placedLabels(labels, rangePixBegs, rangePixLens, beg, end):
Martin@901
   498
    '''Return axis labels with endpoint & sort-order information.'''
Martin@901
   499
    maxWidth = end - beg
Martin@901
   500
    for i, j, k in zip(labels, rangePixBegs, rangePixLens):
Martin@901
   501
        text, textWidth, textHeight = i
Martin@901
   502
        if textWidth > maxWidth:
Martin@901
   503
            continue
Martin@901
   504
        labelBeg = j + (k - textWidth) // 2
Martin@901
   505
        labelEnd = labelBeg + textWidth
Martin@901
   506
        sortKey = textWidth - k
Martin@901
   507
        if labelBeg < beg:
Martin@904
   508
            sortKey += maxWidth * (beg - labelBeg)
Martin@901
   509
            labelBeg = beg
Martin@901
   510
            labelEnd = beg + textWidth
Martin@901
   511
        if labelEnd > end:
Martin@904
   512
            sortKey += maxWidth * (labelEnd - end)
Martin@901
   513
            labelEnd = end
Martin@901
   514
            labelBeg = end - textWidth
Martin@901
   515
        yield sortKey, labelBeg, labelEnd, text, textHeight
Martin@1
   516
Martin@897
   517
def nonoverlappingLabels(labels, minPixTweenLabels):
Martin@1
   518
    '''Get a subset of non-overlapping axis labels, greedily.'''
Martin@897
   519
    out = []
Martin@1
   520
    for i in labels:
Martin@897
   521
        beg = i[1] - minPixTweenLabels
Martin@897
   522
        end = i[2] + minPixTweenLabels
Martin@897
   523
        if all(j[2] <= beg or j[1] >= end for j in out):
Martin@897
   524
            out.append(i)
Martin@897
   525
    return out
Martin@1
   526
Martin@901
   527
def axisImage(labels, rangePixBegs, rangePixLens, textRot,
Martin@895
   528
              textAln, font, image_mode, opts):
Martin@1
   529
    '''Make an image of axis labels.'''
Martin@900
   530
    beg = rangePixBegs[0]
Martin@900
   531
    end = rangePixBegs[-1] + rangePixLens[-1]
Martin@901
   532
    margin = max(i[2] for i in labels)
Martin@901
   533
    labels = sorted(placedLabels(labels, rangePixBegs, rangePixLens, beg, end))
Martin@878
   534
    minPixTweenLabels = 0 if textRot else opts.label_space
Martin@897
   535
    labels = nonoverlappingLabels(labels, minPixTweenLabels)
Martin@897
   536
    image_size = (margin, end) if textRot else (end, margin)
Martin@895
   537
    im = Image.new(image_mode, image_size, opts.margin_color)
Martin@1
   538
    draw = ImageDraw.Draw(im)
Martin@1
   539
    for i in labels:
Martin@878
   540
        base = margin - i[4] if textAln else 0
Martin@878
   541
        position = (base, i[1]) if textRot else (i[1], base)
Martin@646
   542
        draw.text(position, i[3], font=font, fill=opts.text_color)
Martin@1
   543
    return im
Martin@1
   544
Martin@906
   545
def rangesWithOrigins(sortedRanges, rangePixBegs, bpPerPix):
Martin@906
   546
    for i, j in zip(sortedRanges, rangePixBegs):
Martin@906
   547
        seqName, rangeBeg, rangeEnd = i
Martin@906
   548
        origin = bpPerPix * j - rangeBeg
Martin@906
   549
        yield seqName, (rangeBeg, rangeEnd, origin)
Martin@906
   550
Martin@906
   551
def rangesPerSeq(sortedRanges, rangePixBegs, bpPerPix):
Martin@906
   552
    a = rangesWithOrigins(sortedRanges, rangePixBegs, bpPerPix)
Martin@906
   553
    for k, v in itertools.groupby(a, itemgetter(0)):
Martin@906
   554
        yield k, [i[1] for i in v]
Martin@836
   555
Martin@903
   556
def getFont(opts):
Martin@903
   557
    if opts.fontfile:
Martin@903
   558
        return ImageFont.truetype(opts.fontfile, opts.fontsize)
Martin@903
   559
    fileNames = []
Martin@903
   560
    try:
Martin@903
   561
        x = ["fc-match", "-f%{file}", "arial"]
Martin@903
   562
        p = subprocess.Popen(x, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Martin@903
   563
        out, err = p.communicate()
Martin@903
   564
        fileNames.append(out)
Martin@903
   565
    except OSError as e:
Martin@903
   566
        warn("fc-match error: " + str(e))
Martin@903
   567
    fileNames.append("/Library/Fonts/Arial.ttf")  # for Mac
Martin@903
   568
    for i in fileNames:
Martin@903
   569
        try:
Martin@903
   570
            font = ImageFont.truetype(i, opts.fontsize)
Martin@903
   571
            warn("font: " + i)
Martin@903
   572
            return font
Martin@903
   573
        except IOError as e:
Martin@903
   574
            warn("font load error: " + str(e))
Martin@903
   575
    return ImageFont.load_default()
Martin@903
   576
Martin@648
   577
def lastDotplot(opts, args):
Martin@903
   578
    font = getFont(opts)
Martin@643
   579
    image_mode = 'RGB'
Martin@643
   580
    forward_color = ImageColor.getcolor(opts.forwardcolor, image_mode)
Martin@643
   581
    reverse_color = ImageColor.getcolor(opts.reversecolor, image_mode)
Martin@643
   582
    zipped_colors = zip(forward_color, reverse_color)
Martin@643
   583
    overlap_color = tuple([(i + j) // 2 for i, j in zipped_colors])
Martin@641
   584
Martin@644
   585
    warn("reading alignments...")
Martin@904
   586
    alnData = readAlignments(args[0], opts)
Martin@909
   587
    alignments, seqRanges1, coverDict1, seqRanges2, coverDict2 = alnData
Martin@649
   588
    if not alignments: raise Exception("there are no alignments")
Martin@910
   589
    warn("cutting...")
Martin@910
   590
    coverDict1 = dict(mergedRangesPerSeq(coverDict1))
Martin@910
   591
    coverDict2 = dict(mergedRangesPerSeq(coverDict2))
Martin@910
   592
    minAlignedBases = min(coveredLength(coverDict1), coveredLength(coverDict2))
Martin@910
   593
    pad = int(opts.pad * minAlignedBases)
Martin@910
   594
    cutRanges1 = list(trimmed(seqRanges1, coverDict1, minAlignedBases,
Martin@910
   595
                              opts.max_gap1, pad, pad))
Martin@910
   596
    cutRanges2 = list(trimmed(seqRanges2, coverDict2, minAlignedBases,
Martin@910
   597
                              opts.max_gap2, pad, pad))
Martin@641
   598
Martin@878
   599
    textRot1 = "vertical".startswith(opts.rot1)
Martin@910
   600
    i1 = dataFromRanges(cutRanges1, opts.sort1, font,
Martin@908
   601
                        opts.fontsize, image_mode, opts.labels1, textRot1)
Martin@906
   602
    sortedRanges1, rangeSizes1, labelData1, tMargin = i1
Martin@846
   603
Martin@878
   604
    textRot2 = "horizontal".startswith(opts.rot2)
Martin@910
   605
    i2 = dataFromRanges(cutRanges2, opts.sort2, font,
Martin@908
   606
                        opts.fontsize, image_mode, opts.labels2, textRot2)
Martin@906
   607
    sortedRanges2, rangeSizes2, labelData2, lMargin = i2
Martin@641
   608
Martin@896
   609
    maxPixels1 = opts.width  - lMargin
Martin@896
   610
    maxPixels2 = opts.height - tMargin
Martin@897
   611
    bpPerPix1 = get_bp_per_pix(rangeSizes1, opts.border_pixels, maxPixels1)
Martin@897
   612
    bpPerPix2 = get_bp_per_pix(rangeSizes2, opts.border_pixels, maxPixels2)
Martin@855
   613
    bpPerPix = max(bpPerPix1, bpPerPix2)
Martin@855
   614
    warn("bp per pixel = " + str(bpPerPix))
Martin@641
   615
Martin@900
   616
    p1 = pixelData(rangeSizes1, bpPerPix, opts.border_pixels, lMargin)
Martin@900
   617
    rangePixBegs1, rangePixLens1, width = p1
Martin@906
   618
    rangeDict1 = dict(rangesPerSeq(sortedRanges1, rangePixBegs1, bpPerPix))
Martin@900
   619
Martin@900
   620
    p2 = pixelData(rangeSizes2, bpPerPix, opts.border_pixels, tMargin)
Martin@900
   621
    rangePixBegs2, rangePixLens2, height = p2
Martin@906
   622
    rangeDict2 = dict(rangesPerSeq(sortedRanges2, rangePixBegs2, bpPerPix))
Martin@900
   623
Martin@847
   624
    warn("width:  " + str(width))
Martin@847
   625
    warn("height: " + str(height))
Martin@839
   626
Martin@644
   627
    warn("processing alignments...")
Martin@855
   628
    hits = alignmentPixels(width, height, alignments, bpPerPix,
Martin@905
   629
                           rangeDict1, rangeDict2)
Martin@641
   630
Martin@904
   631
    warn("reading annotations...")
Martin@134
   632
Martin@905
   633
    rangeDict1 = expandedSeqDict(rangeDict1)
Martin@905
   634
    beds1 = itertools.chain(readBed(opts.bed1, rangeDict1),
Martin@905
   635
                            readRmsk(opts.rmsk1, rangeDict1),
Martin@905
   636
                            readGenePred(opts, opts.genePred1, rangeDict1),
Martin@905
   637
                            readGaps(opts, opts.gap1, rangeDict1))
Martin@905
   638
    b1 = bedBoxes(beds1, rangeDict1, tMargin, height, True, bpPerPix)
Martin@845
   639
Martin@905
   640
    rangeDict2 = expandedSeqDict(rangeDict2)
Martin@905
   641
    beds2 = itertools.chain(readBed(opts.bed2, rangeDict2),
Martin@905
   642
                            readRmsk(opts.rmsk2, rangeDict2),
Martin@905
   643
                            readGenePred(opts, opts.genePred2, rangeDict2),
Martin@905
   644
                            readGaps(opts, opts.gap2, rangeDict2))
Martin@905
   645
    b2 = bedBoxes(beds2, rangeDict2, lMargin, width, False, bpPerPix)
Martin@857
   646
Martin@857
   647
    boxes = sorted(itertools.chain(b1, b2))
Martin@904
   648
Martin@904
   649
    warn("drawing...")
Martin@904
   650
Martin@904
   651
    image_size = width, height
Martin@904
   652
    im = Image.new(image_mode, image_size, opts.background_color)
Martin@904
   653
Martin@857
   654
    drawAnnotations(im, boxes)
Martin@650
   655
Martin@643
   656
    for i in range(height):
Martin@643
   657
        for j in range(width):
Martin@643
   658
            store_value = hits[i * width + j]
Martin@643
   659
            xy = j, i
Martin@643
   660
            if   store_value == 1: im.putpixel(xy, forward_color)
Martin@643
   661
            elif store_value == 2: im.putpixel(xy, reverse_color)
Martin@643
   662
            elif store_value == 3: im.putpixel(xy, overlap_color)
Martin@95
   663
Martin@643
   664
    if opts.fontsize != 0:
Martin@900
   665
        axis1 = axisImage(labelData1, rangePixBegs1, rangePixLens1,
Martin@895
   666
                          textRot1, False, font, image_mode, opts)
Martin@878
   667
        if textRot1:
Martin@878
   668
            axis1 = axis1.transpose(Image.ROTATE_90)
Martin@900
   669
        axis2 = axisImage(labelData2, rangePixBegs2, rangePixLens2,
Martin@895
   670
                          textRot2, textRot2, font, image_mode, opts)
Martin@878
   671
        if not textRot2:
Martin@878
   672
            axis2 = axis2.transpose(Image.ROTATE_270)
Martin@643
   673
        im.paste(axis1, (0, 0))
Martin@643
   674
        im.paste(axis2, (0, 0))
Martin@1
   675
Martin@900
   676
    for i in rangePixBegs1[1:]:
Martin@877
   677
        box = i - opts.border_pixels, tMargin, i, height
Martin@852
   678
        im.paste(opts.border_color, box)
Martin@1
   679
Martin@900
   680
    for i in rangePixBegs2[1:]:
Martin@877
   681
        box = lMargin, i - opts.border_pixels, width, i
Martin@852
   682
        im.paste(opts.border_color, box)
Martin@1
   683
Martin@643
   684
    im.save(args[1])
Martin@648
   685
Martin@648
   686
if __name__ == "__main__":
Martin@649
   687
    usage = """%prog --help
Martin@649
   688
   or: %prog [options] maf-or-tab-alignments dotplot.png
Martin@649
   689
   or: %prog [options] maf-or-tab-alignments dotplot.gif
Martin@649
   690
   or: ..."""
Martin@649
   691
    description = "Draw a dotplot of pair-wise sequence alignments in MAF or tabular format."
Martin@649
   692
    op = optparse.OptionParser(usage=usage, description=description)
Martin@866
   693
    op.add_option("-v", "--verbose", action="count",
Martin@866
   694
                  help="show progress messages & data about the plot")
Martin@651
   695
    op.add_option("-1", "--seq1", metavar="PATTERN", action="append",
Martin@840
   696
                  default=[],
Martin@651
   697
                  help="which sequences to show from the 1st genome")
Martin@651
   698
    op.add_option("-2", "--seq2", metavar="PATTERN", action="append",
Martin@840
   699
                  default=[],
Martin@651
   700
                  help="which sequences to show from the 2nd genome")
Martin@648
   701
    # Replace "width" & "height" with a single "length" option?
Martin@648
   702
    op.add_option("-x", "--width", type="int", default=1000,
Martin@648
   703
                  help="maximum width in pixels (default: %default)")
Martin@648
   704
    op.add_option("-y", "--height", type="int", default=1000,
Martin@648
   705
                  help="maximum height in pixels (default: %default)")
Martin@649
   706
    op.add_option("-c", "--forwardcolor", metavar="COLOR", default="red",
Martin@649
   707
                  help="color for forward alignments (default: %default)")
Martin@649
   708
    op.add_option("-r", "--reversecolor", metavar="COLOR", default="blue",
Martin@649
   709
                  help="color for reverse alignments (default: %default)")
Martin@907
   710
    op.add_option("--sort1", default="1", metavar="N",
Martin@851
   711
                  help="genome1 sequence order: 0=input order, 1=name order, "
Martin@851
   712
                  "2=length order (default=%default)")
Martin@907
   713
    op.add_option("--sort2", default="1", metavar="N",
Martin@851
   714
                  help="genome2 sequence order: 0=input order, 1=name order, "
Martin@851
   715
                  "2=length order (default=%default)")
Martin@910
   716
    op.add_option("--max-gap1", metavar="FRAC", default="0.5,2", help=
Martin@910
   717
                  "maximum unaligned (end,mid) gap in genome1: "
Martin@910
   718
                  "fraction of aligned length (default=%default)")
Martin@910
   719
    op.add_option("--max-gap2", metavar="FRAC", default="0.5,2", help=
Martin@910
   720
                  "maximum unaligned (end,mid) gap in genome2: "
Martin@910
   721
                  "fraction of aligned length (default=%default)")
Martin@910
   722
    op.add_option("--pad", metavar="FRAC", type="float", default=0.04, help=
Martin@910
   723
                  "pad length when cutting unaligned gaps: "
Martin@910
   724
                  "fraction of aligned length (default=%default)")
Martin@852
   725
    op.add_option("--border-pixels", metavar="INT", type="int", default=1,
Martin@852
   726
                  help="number of pixels between sequences (default=%default)")
Martin@895
   727
    op.add_option("--border-color", metavar="COLOR", default="black",
Martin@852
   728
                  help="color for pixels between sequences (default=%default)")
Martin@895
   729
    op.add_option("--margin-color", metavar="COLOR", default="#dcdcdc",
Martin@895
   730
                  help="margin color")
Martin@846
   731
Martin@850
   732
    og = optparse.OptionGroup(op, "Text options")
Martin@850
   733
    og.add_option("-f", "--fontfile", metavar="FILE",
Martin@850
   734
                  help="TrueType or OpenType font file")
Martin@903
   735
    og.add_option("-s", "--fontsize", metavar="SIZE", type="int", default=14,
Martin@850
   736
                  help="TrueType or OpenType font size (default: %default)")
Martin@898
   737
    og.add_option("--labels1", type="int", default=0, metavar="N", help=
Martin@898
   738
                  "genome1 labels: 0=name, 1=name:length, "
Martin@898
   739
                  "2=name:start:length, 3=name:start-end (default=%default)")
Martin@898
   740
    og.add_option("--labels2", type="int", default=0, metavar="N", help=
Martin@898
   741
                  "genome2 labels: 0=name, 1=name:length, "
Martin@898
   742
                  "2=name:start:length, 3=name:start-end (default=%default)")
Martin@878
   743
    og.add_option("--rot1", metavar="ROT", default="h",
Martin@878
   744
                  help="text rotation for the 1st genome (default=%default)")
Martin@878
   745
    og.add_option("--rot2", metavar="ROT", default="v",
Martin@878
   746
                  help="text rotation for the 2nd genome (default=%default)")
Martin@850
   747
    op.add_option_group(og)
Martin@850
   748
Martin@860
   749
    og = optparse.OptionGroup(op, "Annotation options")
Martin@860
   750
    og.add_option("--bed1", metavar="FILE",
Martin@860
   751
                  help="read genome1 annotations from BED file")
Martin@860
   752
    og.add_option("--bed2", metavar="FILE",
Martin@860
   753
                  help="read genome2 annotations from BED file")
Martin@860
   754
    og.add_option("--rmsk1", metavar="FILE", help="read genome1 repeats from "
Martin@860
   755
                  "RepeatMasker .out or rmsk.txt file")
Martin@860
   756
    og.add_option("--rmsk2", metavar="FILE", help="read genome2 repeats from "
Martin@860
   757
                  "RepeatMasker .out or rmsk.txt file")
Martin@860
   758
    op.add_option_group(og)
Martin@860
   759
Martin@860
   760
    og = optparse.OptionGroup(op, "Gene options")
Martin@860
   761
    og.add_option("--genePred1", metavar="FILE",
Martin@860
   762
                  help="read genome1 genes from genePred file")
Martin@860
   763
    og.add_option("--genePred2", metavar="FILE",
Martin@860
   764
                  help="read genome2 genes from genePred file")
Martin@895
   765
    og.add_option("--exon-color", metavar="COLOR", default="PaleGreen",
Martin@860
   766
                  help="color for exons (default=%default)")
Martin@895
   767
    og.add_option("--cds-color", metavar="COLOR", default="LimeGreen",
Martin@860
   768
                  help="color for protein-coding regions (default=%default)")
Martin@860
   769
    op.add_option_group(og)
Martin@860
   770
Martin@650
   771
    og = optparse.OptionGroup(op, "Unsequenced gap options")
Martin@650
   772
    og.add_option("--gap1", metavar="FILE",
Martin@650
   773
                  help="read genome1 unsequenced gaps from agp or gap file")
Martin@650
   774
    og.add_option("--gap2", metavar="FILE",
Martin@650
   775
                  help="read genome2 unsequenced gaps from agp or gap file")
Martin@650
   776
    og.add_option("--bridged-color", metavar="COLOR", default="yellow",
Martin@650
   777
                  help="color for bridged gaps (default: %default)")
Martin@895
   778
    og.add_option("--unbridged-color", metavar="COLOR", default="orange",
Martin@650
   779
                  help="color for unbridged gaps (default: %default)")
Martin@650
   780
    op.add_option_group(og)
Martin@648
   781
    (opts, args) = op.parse_args()
Martin@648
   782
    if len(args) != 2: op.error("2 arguments needed")
Martin@648
   783
Martin@648
   784
    opts.text_color = "black"
Martin@648
   785
    opts.background_color = "white"
Martin@648
   786
    opts.label_space = 5     # minimum number of pixels between axis labels
Martin@648
   787
Martin@649
   788
    try: lastDotplot(opts, args)
Martin@649
   789
    except KeyboardInterrupt: pass  # avoid silly error message
Martin@903
   790
    except Exception as e:
Martin@649
   791
        prog = os.path.basename(sys.argv[0])
Martin@649
   792
        sys.exit(prog + ": error: " + str(e))