/
tetraDistPlots.py
executable file
·206 lines (162 loc) · 7.67 KB
/
tetraDistPlots.py
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
###############################################################################
#
# gcPlots.py - Create a GC histogram and delta-GC plot.
#
###############################################################################
# #
# This program is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
###############################################################################
import numpy as np
from checkm.plot.AbstractPlot import AbstractPlot
from checkm.util.seqUtils import readFasta
from checkm.common import readDistribution, findNearest
from checkm.genomicSignatures import GenomicSignatures
from checkm.binTools import BinTools
class TetraDistPlots(AbstractPlot):
def __init__(self, options):
AbstractPlot.__init__(self, options)
def plot(self, fastaFile, tetraSigs, distributionsToPlot):
# Set size of figure
self.fig.clear()
self.fig.set_size_inches(self.options.width, self.options.height)
axesHist = self.fig.add_subplot(121)
axesDeltaTD = self.fig.add_subplot(122)
self.plotOnAxes(fastaFile, tetraSigs,
distributionsToPlot, axesHist, axesDeltaTD)
self.fig.tight_layout(pad=1, w_pad=1)
self.draw()
def plotOnAxes(self, fastaFile, tetraSigs, distributionsToPlot, axesHist, axesDeltaTD):
# Read reference distributions from file
dist = readDistribution('td_dist')
# get tetranucleotide signature for bin
seqs = readFasta(fastaFile)
binTools = BinTools()
binSig = binTools.binTetraSig(seqs, tetraSigs)
# get tetranucleotide distances for windows
genomicSig = GenomicSignatures(K=4, threads=1)
data = []
seqLens = []
deltaTDs = []
for seqId, seq in seqs.items():
start = 0
end = self.options.td_window_size
seqLen = len(seq)
seqLens.append(seqLen)
deltaTDs.append(genomicSig.distance(tetraSigs[seqId], binSig))
while(end < seqLen):
windowSig = genomicSig.seqSignature(seq[start:end])
data.append(genomicSig.distance(windowSig, binSig))
start = end
end += self.options.td_window_size
if len(data) == 0:
axesHist.set_xlabel(
'[Error] No seqs >= %d, the specified window size' % self.options.td_window_size)
return
deltaTDs = np.array(deltaTDs)
# Histogram plot
bins = [0.0]
binWidth = self.options.td_bin_width
binEnd = binWidth
while binEnd <= 1.0:
bins.append(binEnd)
binEnd += binWidth
axesHist.hist(data, bins=bins, density=True, color=(0.5, 0.5, 0.5))
axesHist.set_xlabel(r'$\Delta$ TD')
axesHist.set_ylabel(
'% windows (' + str(self.options.td_window_size) + ' bp)')
# Prettify plot
for a in axesHist.yaxis.majorTicks:
a.tick1On = True
a.tick2On = False
for a in axesHist.xaxis.majorTicks:
a.tick1On = True
a.tick2On = False
for line in axesHist.yaxis.get_ticklines():
line.set_color(self.axesColour)
for line in axesHist.xaxis.get_ticklines():
line.set_color(self.axesColour)
for loc, spine in axesHist.spines.items():
if loc in ['right', 'top']:
spine.set_color('none')
else:
spine.set_color(self.axesColour)
# get CD bin statistics
meanTD, deltaTDs = binTools.tetraDiffDist(
seqs, genomicSig, tetraSigs, binSig)
# Delta-TD vs Sequence length plot
axesDeltaTD.scatter(deltaTDs, seqLens, c=abs(
deltaTDs), s=10, lw=0.5, ec='black', cmap='gray_r')
axesDeltaTD.set_xlabel(r'$\Delta$ TD (mean TD = %.2f)' % meanTD)
axesDeltaTD.set_ylabel('Sequence length (kbp)')
_, yMaxSeqs = axesDeltaTD.get_ylim()
xMinSeqs, xMaxSeqs = axesDeltaTD.get_xlim()
# plot reference distributions
for distToPlot in distributionsToPlot:
boundKey = findNearest(
list(dist[list(dist.keys())[0]].keys()), distToPlot)
x = []
y = []
for windowSize in dist:
x.append(dist[windowSize][boundKey])
y.append(windowSize)
# sort by y-values
sortIndexY = np.argsort(y)
x = np.array(x)[sortIndexY]
y = np.array(y)[sortIndexY]
# make sure x-values are strictly decreasing as y increases
# as this is conservative and visually satisfying
for i in range(0, len(x) - 1):
for j in range(i + 1, len(x)):
if x[j] > x[i]:
if j == len(x) - 1:
x[j] = x[i]
else:
# interpolate values from neighbours
x[j] = (x[j - 1] + x[j + 1]) / 2
if x[j] > x[i]:
x[j] = x[i]
axesDeltaTD.plot(x, y, 'r--', lw=0.5, zorder=0)
# ensure y-axis include zero and covers all sequences
axesDeltaTD.set_ylim([0, yMaxSeqs])
# ensure x-axis is set appropriately for sequences
axesDeltaTD.set_xlim([xMinSeqs, xMaxSeqs])
# draw vertical line at x=0
yticks = axesDeltaTD.get_yticks()
axesDeltaTD.vlines(0, 0, yticks[-1], linestyle='dashed',
color=self.axesColour, zorder=0)
# Change sequence lengths from bp to kbp
kbpLabels = []
for seqLen in yticks:
label = '%.1f' % (float(seqLen) / 1000)
label = label.replace('.0', '') # remove trailing zero
kbpLabels.append(label)
axesDeltaTD.set_yticks(yticks)
axesDeltaTD.set_yticklabels(kbpLabels)
# Prettify plot
for a in axesDeltaTD.yaxis.majorTicks:
a.tick1On = True
a.tick2On = False
for a in axesDeltaTD.xaxis.majorTicks:
a.tick1On = True
a.tick2On = False
for line in axesDeltaTD.yaxis.get_ticklines():
line.set_color(self.axesColour)
for line in axesDeltaTD.xaxis.get_ticklines():
line.set_color(self.axesColour)
for loc, spine in axesDeltaTD.spines.items():
if loc in ['right', 'top']:
spine.set_color('none')
else:
spine.set_color(self.axesColour)