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