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