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