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