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