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