Repository navigation
Expand file tree
/
Copy pathtandem-genotypes-plot
More file actions
executable file
·226 lines (209 loc) · 8.25 KB
/
Copy pathtandem-genotypes-plot
File metadata and controls
executable file
·226 lines (209 loc) · 8.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#! /usr/bin/env python
# Copyright 2018 Martin C. Frith
from __future__ import division, print_function
import gzip
import itertools
import logging
import optparse
import signal
import subprocess
import sys
def myOpen(fileName):
if fileName == "-":
return sys.stdin
if fileName.endswith(".gz"):
return gzip.open(fileName, "rt") # xxx dubious for Python2
return open(fileName)
def sequenceLengthsFromFile(lines):
seqType = 0
for line in lines:
if seqType == 0:
if line[0] == ">":
seqType = 1
length = 0
elif line[0] == "@":
seqType = 2
lineType = 1
elif seqType == 1: # fasta
if line[0] == ">":
yield length
length = 0
else:
length += len(line.rstrip())
elif seqType == 2: # fastq
if lineType == 1:
yield len(line.rstrip())
lineType = (lineType + 1) % 4
if seqType == 1:
yield length
def expectedCoveragesFromReadLengths(sortedLengths):
expCov = 0
readCount = 0
for length, g in itertools.groupby(reversed(sortedLengths)):
if readCount and length + 1 < oldLength:
expCov += (oldLength - length - 1) * readCount
yield length + 1, expCov
readCount += len(list(g))
expCov += readCount
yield length, expCov
oldLength = length
if oldLength > 1:
expCov += (oldLength - 1) * readCount
yield 1, expCov
def changesFromText(text):
if text != ".":
for i in text.split(","):
yield int(i.split(":")[0])
def readTandemGenotypes(opts, fileNames):
for fileName in fileNames:
fpd = 2
for line in myOpen(fileName):
fields = line.split()
if line[0] == "#":
fpd = 4 if len(fields) > 1 and fields[1][-1] == "2" else 2
elif fields:
yield fpd, fields
def binsFromSortedValues(values):
maxBins = 50 # xxx ???
minVal = values[0]
maxVal = values[-1]
for s in itertools.count():
step = s * 2 + 1
offset = step // 2
binBeg = (minVal + offset) // step
binEnd = (maxVal + offset) // step + 1
if binEnd - binBeg <= maxBins:
beg = binBeg * step - offset
end = binEnd * step - offset
return beg, end, step
def countsFromBinsAndValues(bins, values):
beg, end, step = bins
num = (end - beg) // step
counts = [0] * num
for i in values:
b = (i - beg) // step
counts[b] += 1
return counts
def rlist(x):
return "c(" + ",".join(map(str, x)) + ")"
def ticRange(minVal, maxVal, maxTics=7):
for i in itertools.count():
for j in 1, 2, 5:
step = j * 10 ** i
minTic = (minVal - 1) // step + 1
maxTic = maxVal // step
if maxTic - minTic + 1 <= maxTics:
return range(minTic * step, maxVal + 1, step)
def stripSuffix(text, s):
if text.endswith(s):
return text[:text.rfind(".")]
return text
def pipe(dest, s):
logging.info(s)
print(s, file=dest.stdin)
def layoutRows(numOfRows, numOfCols):
for i in range(numOfRows):
j = i * numOfCols
yield str(j + 1) + ":" + str(j + numOfCols)
def tandemGenotypesPlot(opts, args):
logLevel = logging.INFO if opts.verbose else logging.WARNING
logging.basicConfig(format="%(message)s", level=logLevel)
outFile = args[-1]
if len(args) == 1:
outFile = stripSuffix(outFile, ".gz")
removeMe = ".txt", ".tsv"
outFile = stripSuffix(outFile, removeMe)
outFile += ".pdf"
inFiles = args
else:
if not outFile.endswith(".pdf"):
outFile += ".pdf"
inFiles = args[:-1]
if opts.reads:
readLengths = sorted(sequenceLengthsFromFile(myOpen(opts.reads)))
coveragePoints = sorted(expectedCoveragesFromReadLengths(readLengths))
covX, covY = zip(*coveragePoints)
maxCovY = max(covY) * 1.0
r = subprocess.Popen(["R", "--slave", "--vanilla"], stdin=subprocess.PIPE,
universal_newlines=True)
width = opts.cols * 1.75
height = opts.rows * 1.75
t = 'pdf("{0}", {1}, {2}, pointsize={3})'
pipe(r, t.format(outFile, width, height, opts.pointsize))
layoutRowsText = ",".join(layoutRows(opts.rows, opts.cols))
pipe(r, 'layout(rbind({0}))'.format(layoutRowsText))
pipe(r, 'par(cex=1)')
pipe(r, 'par(mar=c(1.8, 1.8, 3, 1.8))')
pipe(r, 'par(mgp=c(3, 0.7, 0))')
pipe(r, 'par(tcl=-0.4)')
results = readTandemGenotypes(opts, inFiles)
for fieldsPerDataset, res in itertools.islice(results, opts.num):
chrom, repBeg, repEnd, rep, geneName, genePart = res[:6]
repUnitLen = len(rep)
fwd = res[6 + fieldsPerDataset * opts.sample - 2]
rev = res[6 + fieldsPerDataset * opts.sample - 1]
geneInfo = " ".join(i for i in (geneName, genePart) if i != ".")
repInfo = rep if len(rep) < 11 else rep[:8] + "..."
heading1 = repInfo + ": " + geneInfo if geneInfo else repInfo
heading2 = chrom + ":" + repBeg + "-" + repEnd
fwd = sorted(changesFromText(fwd))
rev = sorted(changesFromText(rev))
both = sorted(fwd + rev)
if not both:
both = [0]
bins = binsFromSortedValues(both)
fBars = countsFromBinsAndValues(bins, fwd)
rBars = countsFromBinsAndValues(bins, rev)
maxHeight = max(countsFromBinsAndValues(bins, both))
beg, end, step = bins
xTics = ticRange(beg, end - 1)
yTics = ticRange(0, maxHeight)
barWidthPerSpace = 5
barStepPerHalfSpace = (barWidthPerSpace + 1) * 2
coordsPerRepUnit = barStepPerHalfSpace * repUnitLen
barWidth = repUnitLen * step * 2 * barWidthPerSpace
begTicPos = (barWidthPerSpace + 1 + step) * repUnitLen
zeroTicPos = begTicPos - beg * coordsPerRepUnit
xTicPos = [zeroTicPos + coordsPerRepUnit * i for i in xTics]
pipe(r, 'f <- ' + rlist(fBars))
pipe(r, 'r <- ' + rlist(rBars))
pipe(r, 'barplot(rbind(f,r), {0}, col=c(2,4), border=NA, '
'ylim=c(0,{1}), axes=FALSE)'.format(barWidth, maxHeight))
if opts.reads:
minAlignedFlank = max(100, repUnitLen) # xxx
refLen = int(repEnd) - int(repBeg) + 2 * minAlignedFlank
zeroPos = zeroTicPos - barStepPerHalfSpace * refLen
x = rlist(zeroPos + barStepPerHalfSpace * i for i in covX)
y = rlist(format(i * maxHeight / maxCovY, '.3') for i in covY)
pipe(r, 'x <- ' + x)
pipe(r, 'y <- ' + y)
pipe(r, 'lines(x, y, col="gray")')
pipe(r, 'axis(1, {0}, {1})'.format(rlist(xTicPos), rlist(xTics)))
pipe(r, 'axis(2, {0})'.format(rlist(yTics)))
pipe(r, 'mtext("{0}", line=1.5)'.format(heading1))
pipe(r, 'mtext("{0}", line=0.5)'.format(heading2))
if __name__ == "__main__":
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # avoid silly error message
usage = "%prog tandem-genotypes.txt [output.pdf]"
description = "Draw graphs of tandem-genotypes output."
op = optparse.OptionParser(usage=usage, description=description)
op.add_option("-r", "--rows", type="int", default=4, help=
"arrange the graphs in this many rows (default=%default)")
op.add_option("-c", "--cols", type="int", default=4, help=
"arrange the graphs in this many columns (default=%default)")
op.add_option("-n", "--num", type="int",
help="graph the top NUM repeat regions (default=ROWS*COLS)")
op.add_option("-s", "--sample", default=1, type="int",
help="select SAMPLE-th sample to plot (default=%default)")
op.add_option("--pointsize", default="8", metavar="POINTS",
help="text size (default=%default)")
op.add_option("--reads", metavar="FILE",
help="show expected coverage for FASTA or FASTQ reads")
op.add_option("-v", "--verbose", action="count", default=0,
help="show more details")
opts, args = op.parse_args()
if not args:
op.error("please give me a file name")
if opts.num is None:
opts.num = opts.rows * opts.cols
tandemGenotypesPlot(opts, args)