-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevaplot.py
More file actions
344 lines (301 loc) · 9.94 KB
/
devaplot.py
File metadata and controls
344 lines (301 loc) · 9.94 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/env python3
"""Plot genome depth with nucleotide polymorphisms"""
import argparse
import os
import sys
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def get_args():
"""Initiate arguments"""
parser = argparse.ArgumentParser(
description='Plot genome depth with nucleotide polymorphisms',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'vcf_file',
help='VCF file with AD format',
default=sys.stdin,
type=str,
)
def float01(x):
try:
x = float(x)
except ValueError as error:
raise argparse.ArgumentTypeError('%r must be float' % (x,)) from error
if x < 0.0 or x > 1.0:
raise argparse.ArgumentTypeError('%r is out of range, must be in [0.0, 1.0]' % (x,))
return x
parser.add_argument(
'--threshold',
help='Threshold to include variant at position',
type=float01,
metavar='FLOAT',
default=0.1,
)
parser.add_argument(
'-m',
'--minor',
help='Threshold to include base variant',
type=float01,
metavar='FLOAT',
default=0.1,
)
parser.add_argument(
'-e',
'--extend',
help='Extend variant bar for INT position to both sides',
type=int,
metavar='INT',
default=4,
)
parser.add_argument(
'-f',
'--figure',
help='Output figure',
type=str,
metavar='STR',
)
parser.add_argument(
'-F',
'--force',
help='Force overwite output',
action='store_true',
)
parser.add_argument(
'-l',
'--log',
help='Plot depth in log scale',
action='store_true'
)
parser.add_argument(
'-D',
'--dpi',
help='Image DPI',
type=int,
metavar='INT',
default=300
)
parser.add_argument(
'-s',
'--size',
help='Size of output',
metavar='FLOAT,FLOAT',
default='16,9',
)
parser.add_argument(
'-g',
'--gaps',
help='Gap position and size',
type=str,
metavar='INT,INT[,INT,INT[,INT,INT,...]]',
)
parser.add_argument(
'-x',
'--x-tick',
help='Tick interval',
type=int,
default=500,
)
parser.add_argument(
'-t',
'--table-relative',
help="Save relative variant table to STR. Use '' for STDOUT",
type=str,
metavar='STR',
)
parser.add_argument(
'-T',
'--table-absolute',
help="Save aboslute variant table to STR. Use '' for STDOUT",
type=str,
metavar='STR',
)
parser.add_argument(
'depth_file',
help='Depth file from samtools',
type=str,
metavar='depth-file',
)
args = parser.parse_args()
# Check input
if not os.path.isfile(args.vcf_file):
parser.error('Input not exist')
# Check output
if args.figure:
if os.path.isfile(args.figure) and not args.force:
parser.error(f'{args.figure} exist. Use flag -F to overwrite.')
if args.table_relative:
if os.path.isfile(args.table_relative) and not args.force:
parser.error(f'{args.table_relative} exist. Use flag -F to overwrite.')
if args.table_relative == '':
args.table_relative = sys.stdout
if args.table_absolute:
if os.path.isfile(args.table_absolute) and not args.force:
parser.error(f'{args.table_absolute} exist. Use flag -F to overwrite.')
if args.table_absolute == '':
args.table_absolute = sys.stdout
# Check size
try:
fig_size = args.size
fig_size = fig_size.split(',')
if len(fig_size) != 2:
parser.error('Size must contain 2 integers and seperate by ","')
fig_size = [float(x) for x in fig_size]
args.size = fig_size
except ValueError:
parser.error('Size must be integer')
# Check gap
if args.gaps:
try:
gap = args.gaps
gap = gap.split(',')
gap = [float(x) for x in gap]
gap_decimal = [x%1 for x in gap]
if sum(gap_decimal):
parser.error('Gap must be integer')
if len(gap)%2 != 0:
parser.error('Gap size missing')
gap = [int(x) for x in gap]
gap = [[gap[x], gap[x+1]] for x in range(0, len(gap), 2)]
args.gaps = gap
except ValueError:
parser.error('Gap must be integer')
return args
def parse_vcf(vcf_file, threshold):
"""
Read VCF file and return vcf dataframe
Extract pos, ref, A, T, C, G
"""
vcf_lines = [
line.rstrip().split()
for line in vcf_file
if line[0] != '#' and "INDEL" not in line
]
vcf_dict = {}
for line in vcf_lines:
pos = int(line[1])
ref = line[3]
alt = line[4]
info = dict([
j
if len(j)==2
else j+[""]
for j in map(
lambda i: str.split(i, "="), line[7].split(";")
)
])
af = float(info["AF"])
vcf_value = vcf_dict.get(pos, [])
if not vcf_value:
vcf_value = [pos, ref, 0, 0, 0, 0]
if af >= threshold:
vcf_value["ATCG".index(alt)+2] = af
vcf_dict[pos] = vcf_value
vcf_df = pd.DataFrame.from_dict(
vcf_dict,
orient="index",
columns=["pos", "ref", "A", "T", "C", "G"]
)
for nuc in "ATCG":
vcf_df.loc[vcf_df["ref"] == nuc, nuc] = 1 - vcf_df[vcf_df["ref"] == nuc][list("ATCG".replace(nuc, ""))].sum(axis=1)
return vcf_df
def add_gaps(depth_df, gaps):
"""
Add regions with depth = 0 from a list of gaps and return updated DataFrame
Parameters
----------
depth_df DataFrame with ["id", "pos", "depth", "ref", "A", "T", "C", "G"]
gaps List of [position, gap_length]. Ex. [[1, 30], [1024, 600]]
"""
for gap_pos, gap_len, in gaps:
depth_df["pos"] = depth_df.apply(
lambda i: i["pos"] + gap_len if i["pos"] >= gap_pos else i["pos"],
axis=1
)
gap_insert = pd.DataFrame(
{
"id": [depth_df["id"][0]]*gap_len,
"pos": [gap_pos+i for i in range(gap_len)],
"depth":[np.nan]*gap_len
}
)
depth_df = pd.concat([depth_df, gap_insert], ignore_index=True)
depth_df = depth_df.sort_values(by="pos", ignore_index=True)
depth_df.reset_index()
return depth_df
def add_extension(depth_df, ex_len=4):
"""
Return df with extended variant positions
Parameters
----------
depth_df DataFrame with ["id", "pos", "depth", "ref", "A", "T", "C", "G"]
ex_len Number of position to extend upstream and downstream
"""
var_df = depth_df[depth_df[list("ATCG")].any(axis=1)][["pos"]+list("ATCG")]
extended_depth_df = depth_df.copy()
for i in var_df["pos"]:
stamp = depth_df.loc[depth_df["pos"] == i, list("ATCG")]
extended_depth_df.loc[(depth_df["pos"] >= i-ex_len) & (depth_df["pos"] <= i+ex_len), list("ATCG")] = list(stamp.iloc[0])
return extended_depth_df
def main():
"""Plot please"""
args = get_args()
with open(args.vcf_file) as vcf_file:
vcf_df = parse_vcf(vcf_file, args.threshold)
depth_df = pd.read_csv(
args.depth_file,
sep="\t",
names=["id", "pos", "depth"]
)
depth_df = depth_df.merge(vcf_df, how="left")
if args.gaps:
depth_df = add_gaps(depth_df, args.gaps)
extended_depth_df = add_extension(depth_df, args.extend)
# variant_df, extended_variant_df = make_variant_df(depth_df, args.extend)
if args.figure:
colors = ['#5772B2', '#3A9276', '#F0430F', '#B615D6',] # '#DEE0E3']
# fig = plt.figure(figsize=args.size)
plt.rcParams["figure.dpi"] = args.dpi
ax = extended_depth_df.plot.bar(
x='pos',
y=list("ATCG"),
stacked=True,
color=colors,
figsize=args.size, #(10.5,0.75),
rot=30,
width=1,
ylim=[0.0,1.0],
yticks=[0.0, 0.50, 1.00],
xticks=list(range(0, len(depth_df), args.x_tick)),
legend=False,
)
ax2 = ax.twinx()
extended_depth_df.plot.line(
x='pos',
y='depth',
lw=0.5,
secondary_y=True,
# ylim=[1, max(list(depth_df['sum_depth']).remove(np.inf))],
logy=args.log,
color=['black'],
legend=False,
# xticks=list(range(-1, len(depth_df), 500)) + [0],
ax=ax2,
)
ax.ticklabel_format(axis='x', style='plain')
ax.minorticks_off()
ax.figure.savefig(args.figure, bbox_inches='tight')
if args.table_relative:
relative_variant_df = depth_df[
(depth_df['A'] > 0) |
(depth_df['T'] > 0) |
(depth_df['C'] > 0) |
(depth_df['G'] > 0)
]
relative_variant_df.to_csv(
args.table_relative,
columns=['pos', 'A', 'T', 'C', 'G'],
index=False,
)
if __name__ == "__main__":
main()