28
|
1 #!/usr/bin/env python
|
|
2
|
0
|
3 import argparse
|
|
4 import os
|
|
5 import pandas
|
|
6 import pypandoc
|
|
7 import re
|
|
8 import subprocess
|
|
9 import sys
|
|
10
|
|
11 from Bio import SeqIO
|
|
12 from datetime import date
|
|
13 from mdutils.mdutils import MdUtils
|
14
|
14 # FIXME: TableOfContents doesn't work.
|
|
15 # from mdutils.tools import TableOfContents
|
0
|
16
|
|
17 CDC_ADVISORY = 'The analysis and report presented here should be treated as preliminary. Please contact the CDC/BDRD with any results regarding _Bacillus anthracis_.'
|
|
18
|
|
19
|
|
20 class PimaReport:
|
|
21
|
21
|
22 def __init__(self, analysis_name=None, amr_deletions_file=None, amr_matrix_files=None, assembler_version=None,
|
|
23 assembly_fasta_file=None, assembly_name=None, bedtools_version=None, blastn_version=None,
|
|
24 circos_files=None, compute_sequence_length_file=None, contig_coverage_file=None, dbkey=None,
|
26
|
25 dnadiff_snps_file=None, dnadiff_version=None, errors_file=None, feature_bed_files=None,
|
21
|
26 feature_png_files=None, flye_assembly_info_file=None, genome_insertions_file=None, gzipped=None,
|
26
|
27 illumina_forward_read_file=None, illumina_reverse_read_file=None, kraken2_report_file=None,
|
28
|
28 kraken2_version=None, lrn_risk_amr_file=None, lrn_risk_blacklist_file=None, lrn_risk_vf_file=None,
|
|
29 minimap2_version=None, mutation_regions_bed_file=None, mutation_regions_tsv_files=None,
|
|
30 ont_file=None, pima_css=None, plasmids_file=None, quast_report_file=None, read_type=None,
|
|
31 reference_insertions_file=None, samtools_version=None, varscan_version=None):
|
0
|
32
|
|
33 # General
|
|
34 self.doc = None
|
|
35 self.report_md = 'pima_report.md'
|
|
36
|
|
37 # Inputs
|
1
|
38 self.amr_deletions_file = amr_deletions_file
|
|
39 self.amr_matrix_files = amr_matrix_files
|
13
|
40 self.analysis_name = analysis_name.split('_')[0]
|
21
|
41 if assembler_version is None:
|
|
42 self.assembler_version = 'assembler (version unknown)'
|
|
43 else:
|
|
44 if read_type == 'ont':
|
|
45 # Assembler is flye.
|
|
46 assembler_version = assembler_version.rstrip(' _assembly info_')
|
|
47 else:
|
|
48 # Assembler is spades.
|
|
49 assembler_version = assembler_version.rstrip(' _contigs')
|
|
50 self.assembler_version = re.sub('_', '.', assembler_version)
|
0
|
51 self.assembly_fasta_file = assembly_fasta_file
|
12
|
52 self.assembly_name = re.sub('_', '.', assembly_name.rstrip(' _consensus_'))
|
|
53 if bedtools_version is None:
|
|
54 self.bedtools_version = 'bedtools (version unknown)'
|
|
55 else:
|
|
56 self.bedtools_version = re.sub('_', '.', bedtools_version.rstrip(' _genome insertions'))
|
|
57 if blastn_version is None:
|
|
58 self.blastn_version = 'blastn (version unknown)'
|
|
59 else:
|
|
60 self.blastn_version = re.sub('_', '.', blastn_version.rstrip(' _features_'))
|
13
|
61 self.circos_files = circos_files
|
1
|
62 self.compute_sequence_length_file = compute_sequence_length_file
|
|
63 self.contig_coverage_file = contig_coverage_file
|
|
64 self.dbkey = dbkey
|
|
65 self.dnadiff_snps_file = dnadiff_snps_file
|
12
|
66 if dnadiff_version is None:
|
|
67 self.dnadiff_version = 'dnadiff (version unknown)'
|
|
68 else:
|
|
69 self.dnadiff_version = re.sub('_', '.', dnadiff_version.rstrip(' _snps_'))
|
18
|
70 self.errors_file = errors_file
|
0
|
71 self.feature_bed_files = feature_bed_files
|
|
72 self.feature_png_files = feature_png_files
|
1
|
73 self.flye_assembly_info_file = flye_assembly_info_file
|
0
|
74 self.gzipped = gzipped
|
1
|
75 self.genome_insertions_file = genome_insertions_file
|
26
|
76 self.illumina_forward_read_file = illumina_forward_read_file
|
|
77 self.illumina_reverse_read_file = illumina_reverse_read_file
|
2
|
78 self.kraken2_report_file = kraken2_report_file
|
12
|
79 if kraken2_version is None:
|
|
80 self.kraken2_version = 'kraken2 (version unknown)'
|
|
81 else:
|
|
82 self.kraken2_version = re.sub('_', '.', kraken2_version.rstrip(' _report_'))
|
28
|
83 self.lrn_risk_amr_file = lrn_risk_amr_file
|
|
84 self.lrn_risk_blacklist_file = lrn_risk_blacklist_file
|
|
85 self.lrn_risk_vf_file = lrn_risk_vf_file
|
12
|
86 if minimap2_version is None:
|
|
87 self.minimap2_version = 'minimap2 (version unknown)'
|
|
88 else:
|
|
89 self.minimap2_version = re.sub('_', '.', minimap2_version)
|
0
|
90 self.mutation_regions_bed_file = mutation_regions_bed_file
|
|
91 self.mutation_regions_tsv_files = mutation_regions_tsv_files
|
|
92 self.pima_css = pima_css
|
1
|
93 self.plasmids_file = plasmids_file
|
13
|
94 self.quast_report_file = quast_report_file
|
18
|
95 self.read_type = read_type.upper()
|
13
|
96 self.reference_insertions_file = reference_insertions_file
|
1
|
97 self.reference_insertions_file = reference_insertions_file
|
12
|
98 if samtools_version is None:
|
|
99 self.samtools_version = 'samtools (version unknown)'
|
|
100 else:
|
|
101 self.samtools_version = re.sub('_', '.', samtools_version)
|
|
102 if varscan_version is None:
|
|
103 self.varscan_version = 'varscan (version unknown)'
|
|
104 else:
|
|
105 self.varscan_version = re.sub('_', '.', varscan_version)
|
0
|
106
|
|
107 # Titles
|
|
108 self.alignment_title = 'Comparison with reference'
|
|
109 self.alignment_notes_title = 'Alignment notes'
|
|
110 self.amr_matrix_title = 'AMR matrix'
|
|
111 self.assembly_methods_title = 'Assembly'
|
|
112 self.assembly_notes_title = 'Assembly notes'
|
|
113 self.basecalling_title = 'Basecalling'
|
|
114 self.basecalling_methods_title = 'Basecalling'
|
|
115 self.contamination_methods_title = 'Contamination check'
|
|
116 self.contig_alignment_title = 'Alignment vs. reference contigs'
|
|
117 self.feature_title = 'Features found in the assembly'
|
|
118 self.feature_methods_title = 'Feature annotation'
|
|
119 self.feature_plot_title = 'Feature annotation plots'
|
|
120 self.large_indel_title = 'Large insertions & deletions'
|
28
|
121 self.lrn_risk_title = 'LRNRisk isolate classification'
|
0
|
122 self.methods_title = 'Methods'
|
18
|
123 self.mutation_errors_title = 'Errors finding mutations in the sample'
|
0
|
124 self.mutation_title = 'Mutations found in the sample'
|
|
125 self.mutation_methods_title = 'Mutation screening'
|
|
126 self.plasmid_methods_title = 'Plasmid annotation'
|
1
|
127 self.plasmid_title = 'Plasmid annotation'
|
21
|
128 self.reference_genome_title = 'Reference genome'
|
0
|
129 self.reference_methods_title = 'Reference comparison'
|
|
130 self.snp_indel_title = 'SNPs and small indels'
|
13
|
131 self.summary_title = 'Summary'
|
0
|
132
|
|
133 # Methods
|
|
134 self.methods = pandas.Series(dtype='float64')
|
|
135 self.methods[self.contamination_methods_title] = pandas.Series(dtype='float64')
|
|
136 self.methods[self.assembly_methods_title] = pandas.Series(dtype='float64')
|
21
|
137 self.methods[self.reference_genome_title] = pandas.Series(dtype='float64')
|
0
|
138 self.methods[self.reference_methods_title] = pandas.Series(dtype='float64')
|
|
139 self.methods[self.mutation_methods_title] = pandas.Series(dtype='float64')
|
|
140 self.methods[self.feature_methods_title] = pandas.Series(dtype='float64')
|
|
141 self.methods[self.plasmid_methods_title] = pandas.Series(dtype='float64')
|
|
142
|
|
143 # Notes
|
|
144 self.assembly_notes = pandas.Series(dtype=object)
|
|
145 self.alignment_notes = pandas.Series(dtype=object)
|
|
146 self.contig_alignment = pandas.Series(dtype=object)
|
|
147
|
|
148 # Values
|
|
149 self.assembly_size = 0
|
|
150 self.contig_info = None
|
|
151 self.feature_hits = pandas.Series(dtype='float64')
|
26
|
152 self.ont_fast5 = None
|
|
153 self.ont_file = ont_file
|
|
154 self.ont_n50 = None
|
|
155 self.ont_read_count = None
|
14
|
156 # TODO: should the following be passed as a parameter?
|
|
157 self.ont_coverage_min = 30
|
|
158 # TODO: should the following be passed as a parameter?
|
1
|
159 self.ont_n50_min = 2500
|
26
|
160
|
21
|
161 if self.read_type == 'ONT':
|
|
162 self.ont_raw_fastq = self.analysis_name
|
26
|
163 self.ont_bases = 0
|
|
164 self.illumina_bases = None
|
21
|
165 self.illumina_fastq = None
|
26
|
166 self.illumina_length_mean = None
|
|
167 self.illumina_read_count = None
|
21
|
168 else:
|
26
|
169 self.illumina_fastq = self.analysis_name
|
|
170 self.illumina_bases = 0
|
|
171 self.illumina_length_mean = 0
|
|
172 self.illumina_read_count = 0
|
|
173 self.ont_bases = None
|
21
|
174 self.ont_raw_fastq = None
|
0
|
175
|
|
176 # Actions
|
|
177 self.did_guppy_ont_fast5 = False
|
|
178 self.did_qcat_ont_fastq = False
|
21
|
179 if self.read_type == 'ONT':
|
26
|
180 self.info_ont_fastq(self.ont_file)
|
21
|
181 else:
|
26
|
182 self.info_illumina_fastq([self.illumina_forward_read_file, self.illumina_reverse_read_file])
|
0
|
183 self.load_contig_info()
|
|
184
|
|
185 def run_command(self, command):
|
|
186 try:
|
|
187 return re.split('\\n', subprocess.check_output(command, shell=True).decode('utf-8'))
|
|
188 except Exception:
|
|
189 message = 'Command %s failed: exiting...' % command
|
|
190 sys.exit(message)
|
|
191
|
|
192 def format_kmg(self, number, decimals=0):
|
|
193 if number == 0:
|
|
194 return '0'
|
|
195 magnitude_powers = [10**9, 10**6, 10**3, 1]
|
|
196 magnitude_units = ['G', 'M', 'K', '']
|
|
197 for i in range(len(magnitude_units)):
|
|
198 if number >= magnitude_powers[i]:
|
|
199 magnitude_power = magnitude_powers[i]
|
|
200 magnitude_unit = magnitude_units[i]
|
|
201 return ('{:0.' + str(decimals) + 'f}').format(number / magnitude_power) + magnitude_unit
|
|
202
|
|
203 def load_contig_info(self):
|
|
204 self.contig_info = pandas.Series(dtype=object)
|
|
205 self.contig_info[self.read_type] = pandas.read_csv(self.contig_coverage_file, header=None, index_col=None, sep='\t').sort_values(1, axis=0, ascending=False)
|
|
206 self.contig_info[self.read_type].columns = ['contig', 'size', 'coverage']
|
26
|
207 mean_coverage = (self.contig_info[self.read_type].iloc[:, 1] * self.contig_info[self.read_type].iloc[:, 2]).sum() / self.contig_info[self.read_type].iloc[:, 1].sum()
|
|
208 if mean_coverage <= self.ont_coverage_min:
|
|
209 warning = '%s mean coverage ({:.0f}X) is less than the recommended minimum ({:.0f}X).'.format(mean_coverage, self.ont_coverage_min) % self.read_type
|
1
|
210 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
|
211 # Report if some contigs have low coverage.
|
|
212 low_coverage = self.contig_info[self.read_type].loc[self.contig_info[self.read_type]['coverage'] < self.ont_coverage_min, :]
|
|
213 if low_coverage.shape[0] >= 0:
|
|
214 for contig_i in range(low_coverage.shape[0]):
|
|
215 warning = '%s coverage of {:s} ({:.0f}X) is less than the recommended minimum ({:.0f}X).'.format(low_coverage.iloc[contig_i, 0], low_coverage.iloc[contig_i, 2], self.ont_coverage_min) % self.read_type
|
|
216 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
26
|
217 # See if some contigs have anonymously low coverage.
|
|
218 fold_coverage = self.contig_info[self.read_type]['coverage'] / mean_coverage
|
1
|
219 low_coverage = self.contig_info[self.read_type].loc[fold_coverage < 1 / 5, :]
|
8
|
220 if low_coverage.shape[0] >= 0:
|
1
|
221 for contig_i in range(low_coverage.shape[0]):
|
26
|
222 warning = '%s coverage of {:s} ({:.0f}X) is less than 1/5 the mean coverage ({:.0f}X).'.format(low_coverage.iloc[contig_i, 0], low_coverage.iloc[contig_i, 2], mean_coverage) % self.read_type
|
1
|
223 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
0
|
224
|
|
225 def load_fasta(self, fasta):
|
|
226 sequence = pandas.Series(dtype=object)
|
|
227 for contig in SeqIO.parse(fasta, 'fasta'):
|
|
228 sequence[contig.id] = contig
|
|
229 return sequence
|
|
230
|
|
231 def load_assembly(self):
|
|
232 self.assembly = self.load_fasta(self.assembly_fasta_file)
|
|
233 self.num_assembly_contigs = len(self.assembly)
|
26
|
234 self.assembly_size = self.format_kmg(sum([len(x) for x in self.assembly]), decimals=1)
|
0
|
235
|
26
|
236 def info_illumina_fastq(self, illumina_read_files):
|
0
|
237 if self.gzipped:
|
|
238 opener = 'gunzip -c'
|
|
239 else:
|
|
240 opener = 'cat'
|
26
|
241 for fastq_file in illumina_read_files:
|
|
242 command = ' '.join([opener,
|
|
243 fastq_file,
|
|
244 '| awk \'{getline;s += length($1);getline;getline;}END{print s/(NR/4)"\t"(NR/4)"\t"s}\''])
|
|
245 values = []
|
|
246 for i in re.split('\\t', self.run_command(command)[0]):
|
|
247 if i == '':
|
|
248 values.append(float('nan'))
|
|
249 else:
|
|
250 values.append(float(i))
|
|
251 self.illumina_length_mean += values[0]
|
|
252 self.illumina_read_count += int(values[1])
|
|
253 self.illumina_bases += int(values[2])
|
|
254 self.illumina_length_mean /= 2
|
0
|
255 self.illumina_bases = self.format_kmg(self.illumina_bases, decimals=1)
|
|
256
|
|
257 def start_doc(self):
|
13
|
258 header_text = 'Analysis of ' + self.analysis_name
|
|
259 self.doc = MdUtils(file_name=self.report_md, title=header_text)
|
0
|
260
|
14
|
261 def add_table_of_contents(self):
|
|
262 self.doc.create_marker(text_marker="TableOfContents")
|
|
263 self.doc.new_line()
|
|
264 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
265 self.doc.new_line()
|
|
266
|
0
|
267 def add_run_information(self):
|
|
268 self.doc.new_line()
|
|
269 self.doc.new_header(1, 'Run information')
|
|
270 # Tables in md.utils are implemented as a wrapping function.
|
|
271 Table_list = [
|
|
272 "Category",
|
|
273 "Information",
|
|
274 "Date",
|
|
275 date.today(),
|
|
276 "ONT FAST5",
|
14
|
277 self.wordwrap_markdown(self.ont_fast5),
|
0
|
278 "ONT FASTQ",
|
14
|
279 self.wordwrap_markdown(self.ont_raw_fastq),
|
0
|
280 "Illumina FASTQ",
|
21
|
281 self.wordwrap_markdown(self.illumina_fastq),
|
0
|
282 "Assembly",
|
|
283 self.wordwrap_markdown(self.assembly_name),
|
|
284 "Reference",
|
|
285 self.wordwrap_markdown(self.dbkey),
|
|
286 ]
|
|
287 self.doc.new_table(columns=2, rows=7, text=Table_list, text_align='left')
|
|
288 self.doc.new_line()
|
14
|
289 # FIXME: the following doesn't work.
|
|
290 # self.add_table_of_contents()
|
0
|
291 self.doc.new_line()
|
|
292
|
|
293 def add_ont_library_information(self):
|
|
294 if self.ont_n50 is None:
|
|
295 return
|
|
296 self.doc.new_line()
|
|
297 self.doc.new_header(2, 'ONT library statistics')
|
|
298 Table_List = [
|
|
299 "Category",
|
|
300 "Quantity",
|
|
301 "ONT N50",
|
|
302 '{:,}'.format(self.ont_n50),
|
|
303 "ONT reads",
|
|
304 '{:,}'.format(self.ont_read_count),
|
|
305 "ONT bases",
|
|
306 '{:s}'.format(self.ont_bases),
|
|
307 "Illumina FASTQ",
|
17
|
308 "N/A",
|
0
|
309 "Assembly",
|
|
310 self.wordwrap_markdown(self.assembly_name),
|
|
311 "Reference",
|
|
312 self.wordwrap_markdown(self.dbkey),
|
|
313 ]
|
|
314 self.doc.new_table(columns=2, rows=7, text=Table_List, text_align='left')
|
|
315 self.doc.new_line()
|
|
316
|
|
317 def add_illumina_library_information(self):
|
14
|
318 if self.illumina_length_mean is None:
|
0
|
319 return
|
|
320 self.doc.new_line()
|
|
321 self.doc.new_header(2, 'Illumina library statistics')
|
|
322 Table_List = [
|
|
323 "Illumina Info.",
|
|
324 "Quantity",
|
|
325 'Illumina mean length',
|
|
326 '{:.1f}'.format(self.illumina_length_mean),
|
|
327 'Illumina reads',
|
|
328 '{:,}'.format(self.illumina_read_count),
|
|
329 'Illumina bases',
|
|
330 '{:s}'.format(self.illumina_bases)
|
|
331 ]
|
|
332 self.doc.new_table(columns=2, rows=4, text=Table_List, text_align='left')
|
|
333
|
8
|
334 def evaluate_assembly(self):
|
1
|
335 assembly_info = pandas.read_csv(self.compute_sequence_length_file, sep='\t', header=None)
|
|
336 assembly_info.columns = ['contig', 'length']
|
|
337 self.contig_sizes = assembly_info
|
|
338 # Take a look at the number of contigs, their sizes,
|
|
339 # and circularity. Warn if things don't look good.
|
|
340 if assembly_info.shape[0] > 4:
|
|
341 warning = 'Assembly produced {:d} contigs, more than ususally expected; assembly may be fragmented'.format(assembly_info.shape[0])
|
|
342 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
|
343 small_contigs = assembly_info.loc[assembly_info['length'] <= 3000, :]
|
|
344 if small_contigs.shape[0] > 0:
|
|
345 warning = 'Assembly produced {:d} small contigs ({:s}); assembly may include spurious sequences.'.format(small_contigs.shape[0], ', '.join(small_contigs['contig']))
|
|
346 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
|
347
|
0
|
348 def add_assembly_information(self):
|
|
349 if self.assembly_fasta_file is None:
|
|
350 return
|
|
351 self.load_assembly()
|
|
352 self.doc.new_line()
|
|
353 self.doc.new_header(2, 'Assembly statistics')
|
|
354 Table_List = [
|
|
355 "Category",
|
|
356 "Information",
|
|
357 "Contigs",
|
|
358 str(self.num_assembly_contigs),
|
|
359 "Assembly size",
|
|
360 str(self.assembly_size),
|
|
361 ]
|
|
362 self.doc.new_table(columns=2, rows=3, text=Table_List, text_align='left')
|
|
363
|
|
364 def info_ont_fastq(self, fastq_file):
|
|
365 opener = 'cat'
|
|
366 if self.gzipped:
|
|
367 opener = 'gunzip -c'
|
|
368 else:
|
|
369 opener = 'cat'
|
|
370 command = ' '.join([opener,
|
|
371 fastq_file,
|
|
372 '| awk \'{getline;print length($0);s += length($1);getline;getline;}END{print "+"s}\'',
|
|
373 '| sort -gr',
|
|
374 '| awk \'BEGIN{bp = 0;f = 0}',
|
|
375 '{if(NR == 1){sub(/+/, "", $1);s=$1}else{bp += $1;if(bp > s / 2 && f == 0){n50 = $1;f = 1}}}',
|
|
376 'END{printf "%d\\t%d\\t%d\\n", n50, (NR - 1), s;exit}\''])
|
|
377 result = list(re.split('\\t', self.run_command(command)[0]))
|
|
378 if result[1] == '0':
|
21
|
379 warning = 'No ONT reads found'
|
|
380 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
14
|
381 self.ont_n50, self.ont_read_count, ont_raw_bases = [int(i) for i in result]
|
0
|
382 command = ' '.join([opener,
|
|
383 fastq_file,
|
|
384 '| awk \'{getline;print length($0);getline;getline;}\''])
|
|
385 result = self.run_command(command)
|
|
386 result = list(filter(lambda x: x != '', result))
|
14
|
387 self.ont_bases = self.format_kmg(ont_raw_bases, decimals=1)
|
|
388 if self.ont_n50 <= self.ont_n50_min:
|
|
389 warning = 'ONT N50 (%s) is less than the recommended minimum (%s)' % (str(self.ont_n50), str(self.ont_n50_min))
|
1
|
390 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
0
|
391
|
|
392 def wordwrap_markdown(self, string):
|
|
393 if string:
|
|
394 if len(string) < 35:
|
|
395 return string
|
|
396 else:
|
|
397 if '/' in string:
|
|
398 adjust = string.split('/')
|
|
399 out = ''
|
|
400 max = 35
|
|
401 for i in adjust:
|
|
402 out = out + '/' + i
|
|
403 if len(out) > max:
|
|
404 out += '<br>'
|
|
405 max += 35
|
|
406 return out
|
|
407 else:
|
|
408 out = [string[i:i + 35] for i in range(0, len(string), 50)]
|
|
409 return '<br>'.join(out)
|
|
410 else:
|
|
411 return string
|
|
412
|
|
413 def add_contig_info(self):
|
26
|
414 if self.contig_info is None or self.read_type not in self.contig_info.index:
|
0
|
415 return
|
26
|
416 self.doc.new_line()
|
|
417 self.doc.new_header(2, 'Assembly coverage by ' + self.read_type)
|
|
418 Table_List = ["Contig", "Length (bp)", "Coverage (X)"]
|
|
419 formatted = self.contig_info[self.read_type].copy()
|
|
420 formatted.iloc[:, 1] = formatted.iloc[:, 1].apply(lambda x: '{:,}'.format(x))
|
|
421 for i in range(self.contig_info[self.read_type].shape[0]):
|
|
422 Table_List = Table_List + formatted.iloc[i, :].values.tolist()
|
|
423 row_count = int(len(Table_List) / 3)
|
|
424 self.doc.new_table(columns=3, rows=row_count, text=Table_List, text_align='left')
|
0
|
425
|
|
426 def add_assembly_notes(self):
|
|
427 if len(self.assembly_notes) == 0:
|
|
428 return
|
|
429 self.doc.new_line()
|
|
430 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
431 self.doc.new_line()
|
|
432 self.doc.new_header(2, self.assembly_notes_title)
|
1
|
433 for note in self.assembly_notes:
|
|
434 self.doc.new_line(note)
|
0
|
435
|
|
436 def add_contamination(self):
|
2
|
437 if self.kraken2_report_file is None:
|
0
|
438 return
|
2
|
439 # Read in the Kraken fractions and pull out the useful parts
|
8
|
440 kraken_fracs = pandas.read_csv(self.kraken2_report_file, delimiter='\t', header=None)
|
|
441 kraken_fracs.index = kraken_fracs.iloc[:, 4].values
|
|
442 kraken_fracs = kraken_fracs.loc[kraken_fracs.iloc[:, 3].str.match('[UG]1?'), :]
|
|
443 kraken_fracs = kraken_fracs.loc[(kraken_fracs.iloc[:, 0] >= 1) | (kraken_fracs.iloc[:, 3] == 'U'), :]
|
|
444 kraken_fracs = kraken_fracs.iloc[:, [0, 1, 3, 5]]
|
|
445 kraken_fracs.columns = ['Fraction', 'Reads', 'Level', 'Taxa']
|
|
446 kraken_fracs['Fraction'] = (kraken_fracs['Fraction'] / 100).round(4)
|
|
447 kraken_fracs.sort_values(by='Fraction', inplace=True, ascending=False)
|
|
448 kraken_fracs['Taxa'] = kraken_fracs['Taxa'].str.lstrip()
|
0
|
449 self.doc.new_line()
|
|
450 self.doc.new_header(2, 'Contamination check')
|
10
|
451 self.doc.new_line(self.read_type + ' classifications')
|
|
452 self.doc.new_line()
|
|
453 Table_List = ["Percent of Reads", "Reads", "Level", "Label"]
|
|
454 for index, row in kraken_fracs.iterrows():
|
|
455 Table_List = Table_List + row.tolist()
|
|
456 row_count = int(len(Table_List) / 4)
|
|
457 self.doc.new_table(columns=4, rows=row_count, text=Table_List, text_align='left')
|
|
458 if self.contamination_methods_title not in self.methods:
|
|
459 self.methods[self.contamination_methods_title] = ''
|
11
|
460 method = '%s was used to assign the raw reads into taxa.' % self.kraken2_version.rstrip('report')
|
0
|
461 self.methods[self.contamination_methods_title] = self.methods[self.contamination_methods_title].append(pandas.Series(method))
|
|
462
|
|
463 def add_alignment(self):
|
13
|
464 if self.quast_report_file is not None:
|
|
465 # Process quast values.
|
|
466 quast_report = pandas.read_csv(self.quast_report_file, header=0, index_col=0, sep='\t')
|
32
|
467 try:
|
|
468 quast_mismatches = int(float(quast_report.loc['# mismatches per 100 kbp', :][0]) * (float(quast_report.loc['Total length (>= 0 bp)', :][0]) / 100000.))
|
|
469 quast_indels = int(float(quast_report.loc['# indels per 100 kbp', :][0]) * (float(quast_report.loc['Total length (>= 0 bp)', :][0]) / 100000.))
|
|
470 self.doc.new_line()
|
|
471 self.doc.new_header(level=2, title=self.alignment_title)
|
|
472 self.doc.new_line()
|
|
473 self.doc.new_header(level=3, title=self.snp_indel_title)
|
|
474 Table_1 = [
|
|
475 "Category",
|
|
476 "Quantity",
|
|
477 'SNPs',
|
|
478 '{:,}'.format(quast_mismatches),
|
|
479 'Small indels',
|
|
480 '{:,}'.format(quast_indels)
|
|
481 ]
|
33
|
482 self.doc.new_table(columns=2, rows=3, text=Table_1, text_align='left')
|
|
483 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
484 self.doc.new_line()
|
32
|
485 except Exception:
|
|
486 # Likely a high dissimilarity bewteen the sample
|
|
487 # and the reference, resulting in a failed alignment.
|
|
488 pass
|
13
|
489 # TODO: self.alignment_notes is not currently populated.
|
0
|
490 if len(self.alignment_notes) > 0:
|
|
491 self.doc.new_header(level=3, title=self.alignment_notes_title)
|
|
492 for note in self.alignment_notes:
|
|
493 self.doc.new_line(note)
|
13
|
494 if len(self.circos_files) > 0:
|
|
495 # Add circos PNG files.
|
|
496 for circos_file in self.circos_files:
|
|
497 contig = os.path.basename(circos_file)
|
|
498 contig_title = 'Alignment to %s' % contig
|
|
499 self.doc.new_line()
|
|
500 self.doc.new_header(level=3, title=contig_title)
|
31
|
501 self.doc.new_line('Blue indicates query sequences aligned to the reference sequence, yellow indicates no alignment')
|
13
|
502 self.doc.new_line(self.doc.new_inline_image(text='contig_title', path=os.path.abspath(circos_file)))
|
|
503 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
504 self.doc.new_line()
|
21
|
505 if self.dbkey == 'ref_genome':
|
|
506 headers = ["* Chromosome - NC_007530.2 Bacillus anthracis str. 'Ames Ancestor', complete sequence",
|
|
507 "* pXO1 - NC_007322.2 Bacillus anthracis str. 'Ames Ancestor' plasmid pXO1, complete sequence",
|
|
508 "* pXO2 - NC_007323.3 Bacillus anthracis str. 'Ames Ancestor' plasmid pXO2, complete sequence"]
|
|
509 method = '\n'.join(headers)
|
|
510 self.methods[self.reference_genome_title] = self.methods[self.reference_genome_title].append(pandas.Series(method))
|
|
511 method = 'The genome assembly was aligned against the reference sequence using %s.' % self.dnadiff_version
|
0
|
512 self.methods[self.reference_methods_title] = self.methods[self.reference_methods_title].append(pandas.Series(method))
|
|
513
|
|
514 def add_features(self):
|
|
515 if len(self.feature_bed_files) == 0:
|
|
516 return
|
|
517 for bbf in self.feature_bed_files:
|
|
518 if os.path.getsize(bbf) > 0:
|
|
519 best = pandas.read_csv(filepath_or_buffer=bbf, sep='\t', header=None)
|
|
520 self.feature_hits[os.path.basename(bbf)] = best
|
|
521 if len(self.feature_hits) == 0:
|
|
522 return
|
|
523 self.doc.new_line()
|
|
524 self.doc.new_header(level=2, title=self.feature_title)
|
|
525 for feature_name in self.feature_hits.index.tolist():
|
|
526 features = self.feature_hits[feature_name].copy()
|
|
527 if features.shape[0] == 0:
|
|
528 continue
|
|
529 features.iloc[:, 1] = features.iloc[:, 1].apply(lambda x: '{:,}'.format(x))
|
|
530 features.iloc[:, 2] = features.iloc[:, 2].apply(lambda x: '{:,}'.format(x))
|
|
531 self.doc.new_line()
|
|
532 self.doc.new_header(level=3, title=feature_name)
|
|
533 if (features.shape[0] == 0):
|
|
534 continue
|
|
535 for contig in pandas.unique(features.iloc[:, 0]):
|
|
536 self.doc.new_line(contig)
|
|
537 contig_features = features.loc[(features.iloc[:, 0] == contig), :]
|
|
538 Table_List = ['Start', 'Stop', 'Feature', 'Identity (%)', 'Strand']
|
|
539 for i in range(contig_features.shape[0]):
|
|
540 feature = contig_features.iloc[i, :].copy(deep=True)
|
|
541 feature[4] = '{:.3f}'.format(feature[4])
|
2
|
542 Table_List = Table_List + feature[1:].values.tolist()
|
0
|
543 row_count = int(len(Table_List) / 5)
|
|
544 self.doc.new_line()
|
1
|
545 self.doc.new_table(columns=5, rows=row_count, text=Table_List, text_align='left')
|
12
|
546 blastn_version = 'The genome assembly was queried for features using %s.' % self.blastn_version
|
|
547 bedtools_version = 'Feature hits were clustered using %s and the highest scoring hit for each cluster was reported.' % self.bedtools_version
|
0
|
548 method = '%s %s' % (blastn_version, bedtools_version)
|
|
549 self.methods[self.feature_methods_title] = self.methods[self.feature_methods_title].append(pandas.Series(method))
|
|
550
|
|
551 def add_feature_plots(self):
|
|
552 if len(self.feature_png_files) == 0:
|
|
553 return
|
|
554 self.doc.new_line()
|
|
555 self.doc.new_header(level=2, title='Feature Plots')
|
|
556 self.doc.new_paragraph('Only contigs with features are shown')
|
|
557 for feature_png_file in self.feature_png_files:
|
|
558 self.doc.new_line(self.doc.new_inline_image(text='Analysis', path=os.path.abspath(feature_png_file)))
|
|
559
|
|
560 def add_mutations(self):
|
|
561 if len(self.mutation_regions_tsv_files) == 0:
|
|
562 return
|
8
|
563 try:
|
0
|
564 mutation_regions = pandas.read_csv(self.mutation_regions_bed_file, sep='\t', header=0, index_col=False)
|
|
565 except Exception:
|
|
566 # Likely an empty file.
|
|
567 return
|
|
568 amr_mutations = pandas.Series(dtype=object)
|
|
569 for region_i in range(mutation_regions.shape[0]):
|
|
570 region = mutation_regions.iloc[region_i, :]
|
|
571 region_name = str(region['name'])
|
|
572 region_mutations_tsv_name = '%s_mutations.tsv' % region_name
|
|
573 if region_mutations_tsv_name not in self.mutation_regions_tsv_files:
|
|
574 continue
|
|
575 region_mutations_tsv = self.mutation_regions_tsv_files[region_mutations_tsv_name]
|
8
|
576 try:
|
0
|
577 region_mutations = pandas.read_csv(region_mutations_tsv, sep='\t', header=0, index_col=False)
|
|
578 except Exception:
|
|
579 region_mutations = pandas.DataFrame()
|
|
580 if region_mutations.shape[0] == 0:
|
|
581 continue
|
1
|
582 # Figure out what kind of mutations are in this region.
|
0
|
583 region_mutation_types = pandas.Series(['snp'] * region_mutations.shape[0], name='TYPE', index=region_mutations.index)
|
|
584 region_mutation_types[region_mutations['REF'].str.len() != region_mutations['ALT'].str.len()] = 'small-indel'
|
|
585 region_mutation_drugs = pandas.Series(region['drug'] * region_mutations.shape[0], name='DRUG', index=region_mutations.index)
|
|
586 region_notes = pandas.Series(region['note'] * region_mutations.shape[0], name='NOTE', index=region_mutations.index)
|
|
587 region_mutations = pandas.concat([region_mutations, region_mutation_types, region_mutation_drugs, region_notes], axis=1)
|
|
588 region_mutations = region_mutations[['#CHROM', 'POS', 'TYPE', 'REF', 'ALT', 'DRUG', 'NOTE']]
|
|
589 amr_mutations[region['name']] = region_mutations
|
2
|
590 if (amr_mutations.shape[0] > 0):
|
|
591 # Report the mutations.
|
0
|
592 self.doc.new_line()
|
2
|
593 self.doc.new_header(level=2, title=self.mutation_title)
|
|
594 for region_name in amr_mutations.index.tolist():
|
|
595 region_mutations = amr_mutations[region_name].copy()
|
|
596 self.doc.new_line()
|
|
597 self.doc.new_header(level=3, title=region_name)
|
|
598 if (region_mutations.shape[0] == 0):
|
|
599 self.doc.append('None')
|
|
600 continue
|
|
601 region_mutations.iloc[:, 1] = region_mutations.iloc[:, 1].apply(lambda x: '{:,}'.format(x))
|
|
602 Table_List = ['Reference contig', 'Position', 'Reference', 'Alternate', 'Drug', 'Note']
|
|
603 for i in range(region_mutations.shape[0]):
|
|
604 Table_List = Table_List + region_mutations.iloc[i, [0, 1, 3, 4, 5, 6]].values.tolist()
|
|
605 row_count = int(len(Table_List) / 6)
|
|
606 self.doc.new_table(columns=6, rows=row_count, text=Table_List, text_align='left')
|
18
|
607 if os.path.getsize(self.errors_file) > 0:
|
|
608 # Report the errors encountered when attempting
|
|
609 # to find mutations in the sample.
|
|
610 self.doc.new_line()
|
|
611 self.doc.new_header(level=2, title=self.mutation_errors_title)
|
|
612 with open(self.errors_file, 'r') as efh:
|
|
613 for i, line in enumerate(efh):
|
|
614 line = line.strip()
|
|
615 if line:
|
|
616 self.doc.new_line('* %s' % line)
|
12
|
617 method = '%s reads were mapped to the reference sequence using %s.' % (self.read_type, self.minimap2_version)
|
0
|
618 self.methods[self.mutation_methods_title] = self.methods[self.mutation_methods_title].append(pandas.Series(method))
|
13
|
619 method = 'Mutations were identified using %s and %s.' % (self.samtools_version, self.varscan_version)
|
0
|
620 self.methods[self.mutation_methods_title] = self.methods[self.mutation_methods_title].append(pandas.Series(method))
|
|
621
|
|
622 def add_amr_matrix(self):
|
|
623 # Make sure that we have an AMR matrix to plot
|
1
|
624 if len(self.amr_matrix_files) == 0:
|
|
625 return
|
|
626 self.doc.new_line()
|
|
627 self.doc.new_header(level=2, title=self.amr_matrix_title)
|
31
|
628 amr_matrix_text = 'AMR genes and mutations with their corresponding drugs: dark blue indicates the presence of a gene/mutation, light blue indicates the absence of a gene/mutation'
|
|
629 self.doc.new_line(amr_matrix_text)
|
1
|
630 for amr_matrix_file in self.amr_matrix_files:
|
31
|
631 self.doc.new_line(self.doc.new_inline_image(text=amr_matrix_text, path=os.path.abspath(amr_matrix_file)))
|
0
|
632
|
|
633 def add_large_indels(self):
|
1
|
634 large_indels = pandas.Series(dtype='float64')
|
|
635 # Pull in insertions.
|
|
636 try:
|
|
637 reference_insertions = pandas.read_csv(filepath_or_buffer=self.reference_insertions_file, sep='\t', header=None)
|
|
638 except Exception:
|
|
639 reference_insertions = pandas.DataFrame()
|
|
640 try:
|
|
641 genome_insertions = pandas.read_csv(filepath_or_buffer=self.genome_insertions_file, sep='\t', header=None)
|
|
642 except Exception:
|
|
643 genome_insertions = pandas.DataFrame()
|
|
644 large_indels['Reference insertions'] = reference_insertions
|
|
645 large_indels['Query insertions'] = genome_insertions
|
|
646 # Pull in deletions.
|
|
647 try:
|
|
648 amr_deletions = pandas.read_csv(filepath_or_buffer=self.amr_deletion_file, sep='\t', header=None)
|
|
649 except Exception:
|
|
650 amr_deletions = pandas.DataFrame()
|
|
651 if amr_deletions.shape[0] > 0:
|
|
652 amr_deletions.columns = ['contig', 'start', 'stop', 'name', 'type', 'drug', 'note']
|
|
653 amr_deletions = amr_deletions.loc[amr_deletions['type'].isin(['large-deletion', 'any']), :]
|
|
654 self.doc.new_line()
|
|
655 self.doc.new_header(level=2, title=self.large_indel_title)
|
25
|
656 self.doc.new_line('This section is informative only when your isolates were identified as *Bacillus anthracis* strains')
|
1
|
657 for genome in ['Reference insertions', 'Query insertions']:
|
|
658 genome_indels = large_indels[genome].copy()
|
|
659 self.doc.new_line()
|
|
660 self.doc.new_header(level=3, title=genome)
|
|
661 if (genome_indels.shape[0] == 0):
|
|
662 continue
|
|
663 genome_indels.iloc[:, 1] = genome_indels.iloc[:, 1].apply(lambda x: '{:,}'.format(x))
|
|
664 genome_indels.iloc[:, 2] = genome_indels.iloc[:, 2].apply(lambda x: '{:,}'.format(x))
|
|
665 genome_indels.iloc[:, 3] = genome_indels.iloc[:, 3].apply(lambda x: '{:,}'.format(x))
|
|
666 Table_List = [
|
|
667 'Reference contig', 'Start', 'Stop', 'Size (bp)'
|
|
668 ]
|
|
669 for i in range(genome_indels.shape[0]):
|
|
670 Table_List = Table_List + genome_indels.iloc[i, :].values.tolist()
|
|
671 row_count = int(len(Table_List) / 4)
|
|
672 self.doc.new_table(columns=4, rows=row_count, text=Table_List, text_align='left')
|
12
|
673 method = 'Large insertions or deletions were found as the complement of aligned regions using %s.' % self.bedtools_version
|
1
|
674 self.methods[self.reference_methods_title] = self.methods[self.reference_methods_title].append(pandas.Series(method))
|
|
675 self.doc.new_line()
|
|
676 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
677 self.doc.new_line()
|
0
|
678
|
28
|
679 def add_lrn_risk_info(self):
|
|
680 if self.lrn_risk_amr_file is None and self.lrn_risk_blacklist_file is None and self.lrn_risk_vf_file is None:
|
|
681 return
|
30
|
682 if not os.path.isfile(self.lrn_risk_amr_file) and not os.path.isfile(self.lrn_risk_blacklist_file) and not os.path.isfile(self.lrn_risk_vf_file):
|
|
683 return
|
|
684 if os.path.getsize(self.lrn_risk_amr_file) == 0 and os.path.getsize(self.lrn_risk_blacklist_file) == 0 and os.path.getsize(self.lrn_risk_vf_file) == 0:
|
|
685 return
|
28
|
686 self.doc.new_line()
|
|
687 self.doc.new_header(level=2, title=self.lrn_risk_title)
|
|
688 # Process self.lrn_risk_amr_file.
|
|
689 try:
|
|
690 lrn_risk_amr = pandas.read_csv(filepath_or_buffer=self.lrn_risk_amr_file, sep='\t', header=0)
|
|
691 except Exception:
|
|
692 lrn_risk_amr = pandas.DataFrame()
|
|
693 if lrn_risk_amr.shape[0] > 0:
|
|
694 self.doc.new_line()
|
|
695 self.doc.new_header(level=2, title="AMR Determinant Distribution")
|
|
696 self.doc.new_line()
|
|
697 Table_List = ["Gene", "Contig", "% Identity", "% Coverage", "E-Value", "Annotation", "Comparison to Publicly Available Genomes"]
|
|
698 for index, row in lrn_risk_amr.iterrows():
|
|
699 Table_List = Table_List + row.tolist()
|
|
700 row_count = int(len(Table_List) / 7)
|
|
701 self.doc.new_table(columns=7, rows=row_count, text=Table_List, text_align='left')
|
|
702 # Process self.lrn_risk_blacklist_file.
|
|
703 try:
|
|
704 lrn_risk_blacklist = pandas.read_csv(filepath_or_buffer=self.lrn_risk_blacklist_file, sep='\t', header=0)
|
|
705 except Exception:
|
|
706 lrn_risk_blacklist = pandas.DataFrame()
|
|
707 if lrn_risk_blacklist.shape[0] > 0:
|
|
708 self.doc.new_line()
|
|
709 self.doc.new_header(level=2, title="Blacklisted High-risk Virulence Factors")
|
|
710 self.doc.new_line()
|
|
711 Table_List = ["Blacklisted Gene", "Reason", "Risk Category"]
|
|
712 for index, row in lrn_risk_blacklist.iterrows():
|
|
713 Table_List = Table_List + row.tolist()
|
|
714 row_count = int(len(Table_List) / 3)
|
|
715 self.doc.new_table(columns=3, rows=row_count, text=Table_List, text_align='left')
|
|
716 # Process self.lrn_risk_vf_file.
|
|
717 try:
|
|
718 lrn_risk_vf = pandas.read_csv(filepath_or_buffer=self.lrn_risk_vf_file, sep='\t', header=0)
|
|
719 except Exception:
|
|
720 lrn_risk_vf = pandas.DataFrame()
|
|
721 if lrn_risk_vf.shape[0] > 0:
|
|
722 self.doc.new_line()
|
|
723 self.doc.new_header(level=2, title="Virulence Factor Distribution")
|
|
724 self.doc.new_line()
|
|
725 Table_List = ["Gene", "Contig", "% Identity", "% Coverage", "E-Value", "Annotation", "Comparison to Publicly Available Genomes"]
|
|
726 for index, row in lrn_risk_vf.iterrows():
|
|
727 Table_List = Table_List + row.tolist()
|
|
728 row_count = int(len(Table_List) / 7)
|
|
729 self.doc.new_table(columns=7, rows=row_count, text=Table_List, text_align='left')
|
|
730 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
731 self.doc.new_line()
|
|
732
|
0
|
733 def add_plasmids(self):
|
8
|
734 try:
|
1
|
735 plasmids = pandas.read_csv(filepath_or_buffer=self.plasmids_file, sep='\t', header=0)
|
|
736 except Exception:
|
0
|
737 return
|
|
738 plasmids = plasmids.copy()
|
|
739 self.doc.new_line()
|
1
|
740 self.doc.new_header(level=2, title=self.plasmid_title)
|
0
|
741 if (plasmids.shape[0] == 0):
|
|
742 self.doc.new_line('None')
|
|
743 return
|
|
744 plasmids.iloc[:, 3] = plasmids.iloc[:, 3].apply(lambda x: '{:,}'.format(x))
|
|
745 plasmids.iloc[:, 4] = plasmids.iloc[:, 4].apply(lambda x: '{:,}'.format(x))
|
|
746 plasmids.iloc[:, 5] = plasmids.iloc[:, 5].apply(lambda x: '{:,}'.format(x))
|
1
|
747 Table_List = ['Genome contig', 'Plasmid hit', 'Plasmid acc.', 'Contig size', 'Aliged', 'Plasmid size']
|
0
|
748 for i in range(plasmids.shape[0]):
|
|
749 Table_List = Table_List + plasmids.iloc[i, 0:6].values.tolist()
|
|
750 row_count = int(len(Table_List) / 6)
|
|
751 self.doc.new_table(columns=6, rows=row_count, text=Table_List, text_align='left')
|
12
|
752 method = 'The plasmid reference database was queried against the genome assembly using %s.' % self.minimap2_version
|
0
|
753 self.methods[self.plasmid_methods_title] = self.methods[self.plasmid_methods_title].append(pandas.Series(method))
|
2
|
754 method = 'The resulting BAM was converted to a PSL using a custom version of sam2psl.'
|
0
|
755 self.methods[self.plasmid_methods_title] = self.methods[self.plasmid_methods_title].append(pandas.Series(method))
|
|
756 method = 'Plasmid-to-genome hits were resolved using the pChunks algorithm.'
|
|
757 self.methods[self.plasmid_methods_title] = self.methods[self.plasmid_methods_title].append(pandas.Series(method))
|
|
758
|
|
759 def add_methods(self):
|
|
760 if len(self.methods) == 0:
|
|
761 return
|
|
762 self.doc.new_line()
|
|
763 self.doc.new_header(level=2, title=self.methods_title)
|
|
764 for methods_section in self.methods.index.tolist():
|
|
765 if self.methods[methods_section] is None or len(self.methods[methods_section]) == 0:
|
|
766 continue
|
|
767 self.doc.new_line()
|
|
768 self.doc.new_header(level=3, title=methods_section)
|
|
769 self.doc.new_paragraph(' '.join(self.methods[methods_section]))
|
24
|
770 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
771 self.doc.new_line()
|
0
|
772
|
|
773 def add_summary(self):
|
|
774 # Add summary title
|
|
775 self.doc.new_header(level=1, title=self.summary_title)
|
|
776 # First section of Summary
|
|
777 self.doc.new_header(level=1, title='CDC Advisory')
|
|
778 self.doc.new_paragraph(CDC_ADVISORY)
|
|
779 self.doc.new_line()
|
|
780 self.add_run_information()
|
|
781 self.add_ont_library_information()
|
|
782 methods = []
|
|
783 if self.did_guppy_ont_fast5:
|
|
784 methods += ['ONT reads were basecalled using guppy']
|
|
785 if self.did_qcat_ont_fastq:
|
|
786 methods += ['ONT reads were demultiplexed and trimmed using qcat']
|
|
787 self.methods[self.basecalling_methods_title] = pandas.Series(methods)
|
26
|
788 self.add_illumina_library_information()
|
|
789 self.add_assembly_information()
|
1
|
790 self.add_contig_info()
|
|
791 self.evaluate_assembly()
|
21
|
792 if self.assembler_version is not None:
|
|
793 if self.read_type == 'ONT':
|
|
794 method = 'ONT reads were assembled using %s' % self.assembler_version
|
|
795 self.methods[self.assembly_methods_title] = self.methods[self.assembly_methods_title].append(pandas.Series(method))
|
|
796 # Pull in the assembly summary and look at the coverage.
|
|
797 assembly_info = pandas.read_csv(self.flye_assembly_info_file, header=0, index_col=0, sep='\t')
|
|
798 # Look for non-circular contigs.
|
|
799 open_contigs = assembly_info.loc[assembly_info['circ.'] == 'N', :]
|
|
800 if open_contigs.shape[0] > 0:
|
|
801 open_contig_ids = open_contigs.index.values
|
|
802 warning = 'Flye reported {:d} open contigs ({:s}); assembly may be incomplete.'.format(open_contigs.shape[0], ', '.join(open_contig_ids))
|
|
803 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
|
804 else:
|
|
805 method = 'Illumina reads were assembled using %s' % self.assembler_version
|
26
|
806 method = 'The genome assembly was polished using ONT reads and medaka.'
|
27
|
807 self.methods[self.assembly_methods_title] = self.methods[self.assembly_methods_title].append(pandas.Series(method))
|
1
|
808 self.add_assembly_notes()
|
0
|
809
|
|
810 def make_tex(self):
|
|
811 self.doc.new_table_of_contents(table_title='detailed run information', depth=2, marker="tableofcontents")
|
|
812 text = self.doc.file_data_text
|
|
813 text = text.replace("##--[", "")
|
|
814 text = text.replace("]--##", "")
|
|
815 self.doc.file_data_text = text
|
|
816 self.doc.create_md_file()
|
|
817
|
|
818 def make_report(self):
|
|
819 self.start_doc()
|
|
820 self.add_summary()
|
|
821 self.add_contamination()
|
|
822 self.add_alignment()
|
|
823 self.add_features()
|
|
824 self.add_feature_plots()
|
|
825 self.add_mutations()
|
|
826 self.add_large_indels()
|
|
827 self.add_plasmids()
|
|
828 self.add_amr_matrix()
|
28
|
829 self.add_lrn_risk_info()
|
0
|
830 # self.add_snps()
|
|
831 self.add_methods()
|
|
832 self.make_tex()
|
|
833 # It took me quite a long time to find out that the value of the -t
|
|
834 # (implied) argument in the following command must be 'html' instead of
|
|
835 # the more logical 'pdf'. see the answer from snsn in this thread:
|
|
836 # https://github.com/jessicategner/pypandoc/issues/186
|
|
837 pypandoc.convert_file(self.report_md,
|
|
838 'html',
|
|
839 extra_args=['--pdf-engine=weasyprint', '-V', '-css=%s' % self.pima_css],
|
|
840 outputfile='pima_report.pdf')
|
|
841
|
|
842
|
|
843 parser = argparse.ArgumentParser()
|
|
844
|
1
|
845 parser.add_argument('--amr_deletions_file', action='store', dest='amr_deletions_file', help='AMR deletions BED file')
|
|
846 parser.add_argument('--amr_matrix_png_dir', action='store', dest='amr_matrix_png_dir', help='Directory of AMR matrix PNG files')
|
0
|
847 parser.add_argument('--analysis_name', action='store', dest='analysis_name', help='Sample identifier')
|
21
|
848 parser.add_argument('--assembler_version', action='store', dest='assembler_version', default=None, help='Assembler version string')
|
0
|
849 parser.add_argument('--assembly_fasta_file', action='store', dest='assembly_fasta_file', help='Assembly fasta file')
|
|
850 parser.add_argument('--assembly_name', action='store', dest='assembly_name', help='Assembly identifier')
|
12
|
851 parser.add_argument('--bedtools_version', action='store', dest='bedtools_version', default=None, help='Bedtools version string')
|
2
|
852 parser.add_argument('--blastn_version', action='store', dest='blastn_version', default=None, help='Blastn version string')
|
13
|
853 parser.add_argument('--circos_png_dir', action='store', dest='circos_png_dir', help='Directory of circos PNG files')
|
1
|
854 parser.add_argument('--compute_sequence_length_file', action='store', dest='compute_sequence_length_file', help='Comnpute sequence length tabular file')
|
|
855 parser.add_argument('--contig_coverage_file', action='store', dest='contig_coverage_file', help='Contig coverage TSV file')
|
|
856 parser.add_argument('--dbkey', action='store', dest='dbkey', help='Reference genome identifier')
|
|
857 parser.add_argument('--dnadiff_snps_file', action='store', dest='dnadiff_snps_file', help='DNAdiff snps tabular file')
|
12
|
858 parser.add_argument('--dnadiff_version', action='store', dest='dnadiff_version', default=None, help='DNAdiff version string')
|
18
|
859 parser.add_argument('--errors_file', action='store', dest='errors_file', default=None, help='AMR mutations errors encountered txt file')
|
0
|
860 parser.add_argument('--feature_bed_dir', action='store', dest='feature_bed_dir', help='Directory of best feature hits bed files')
|
|
861 parser.add_argument('--feature_png_dir', action='store', dest='feature_png_dir', help='Directory of best feature hits png files')
|
1
|
862 parser.add_argument('--flye_assembly_info_file', action='store', dest='flye_assembly_info_file', default=None, help='Flye assembly info tabular file')
|
|
863 parser.add_argument('--genome_insertions_file', action='store', dest='genome_insertions_file', help='Genome insertions BED file')
|
26
|
864 parser.add_argument('--gzipped', action='store_true', dest='gzipped', default=False, help='Sample(s) is/are gzipped')
|
|
865 parser.add_argument('--illumina_forward_read_file', action='store', dest='illumina_forward_read_file', help='Illumina forward read file')
|
|
866 parser.add_argument('--illumina_reverse_read_file', action='store', dest='illumina_reverse_read_file', help='Illumina reverse read file')
|
2
|
867 parser.add_argument('--kraken2_report_file', action='store', dest='kraken2_report_file', default=None, help='kraken2 report file')
|
|
868 parser.add_argument('--kraken2_version', action='store', dest='kraken2_version', default=None, help='kraken2 version string')
|
28
|
869 parser.add_argument('--lrn_risk_amr_file', action='store', dest='lrn_risk_amr_file', default=None, help='LRN RISK AMR TSV file')
|
|
870 parser.add_argument('--lrn_risk_blacklist_file', action='store', dest='lrn_risk_blacklist_file', default=None, help='LRN RISK blacklist TSV file')
|
|
871 parser.add_argument('--lrn_risk_vf_file', action='store', dest='lrn_risk_vf_file', default=None, help='LRN RISK virulence factors TSV file')
|
12
|
872 parser.add_argument('--minimap2_version', action='store', dest='minimap2_version', default=None, help='minimap2 version string')
|
0
|
873 parser.add_argument('--mutation_regions_bed_file', action='store', dest='mutation_regions_bed_file', help='AMR mutation regions BRD file')
|
|
874 parser.add_argument('--mutation_regions_dir', action='store', dest='mutation_regions_dir', help='Directory of mutation regions TSV files')
|
26
|
875 parser.add_argument('--ont_file', action='store', dest='ont_file', help='ONT single read file')
|
0
|
876 parser.add_argument('--pima_css', action='store', dest='pima_css', help='PIMA css stypesheet')
|
23
|
877 parser.add_argument('--plasmids_file', action='store', dest='plasmids_file', default=None, help='pChunks plasmids TSV file')
|
13
|
878 parser.add_argument('--quast_report_file', action='store', dest='quast_report_file', help='Quast report tabular file')
|
18
|
879 parser.add_argument('--read_type', action='store', dest='read_type', help='Sample read type (ONT or Illumina)')
|
1
|
880 parser.add_argument('--reference_insertions_file', action='store', dest='reference_insertions_file', help='Reference insertions BED file')
|
12
|
881 parser.add_argument('--samtools_version', action='store', dest='samtools_version', default=None, help='Samtools version string')
|
|
882 parser.add_argument('--varscan_version', action='store', dest='varscan_version', default=None, help='Varscan version string')
|
0
|
883
|
|
884 args = parser.parse_args()
|
|
885
|
1
|
886 # Prepare the AMR matrix PNG files.
|
|
887 amr_matrix_files = []
|
|
888 for file_name in sorted(os.listdir(args.amr_matrix_png_dir)):
|
|
889 file_path = os.path.abspath(os.path.join(args.amr_matrix_png_dir, file_name))
|
|
890 amr_matrix_files.append(file_path)
|
13
|
891 # Prepare the circos PNG files.
|
|
892 circos_files = []
|
|
893 for file_name in sorted(os.listdir(args.circos_png_dir)):
|
|
894 file_path = os.path.abspath(os.path.join(args.circos_png_dir, file_name))
|
|
895 circos_files.append(file_path)
|
0
|
896 # Prepare the features BED files.
|
|
897 feature_bed_files = []
|
|
898 for file_name in sorted(os.listdir(args.feature_bed_dir)):
|
|
899 file_path = os.path.abspath(os.path.join(args.feature_bed_dir, file_name))
|
|
900 feature_bed_files.append(file_path)
|
|
901 # Prepare the features PNG files.
|
|
902 feature_png_files = []
|
|
903 for file_name in sorted(os.listdir(args.feature_png_dir)):
|
|
904 file_path = os.path.abspath(os.path.join(args.feature_png_dir, file_name))
|
|
905 feature_png_files.append(file_path)
|
|
906 # Prepare the mutation regions TSV files.
|
|
907 mutation_regions_files = []
|
|
908 for file_name in sorted(os.listdir(args.mutation_regions_dir)):
|
|
909 file_path = os.path.abspath(os.path.join(args.feature_png_dir, file_name))
|
|
910 mutation_regions_files.append(file_path)
|
|
911
|
|
912 markdown_report = PimaReport(args.analysis_name,
|
1
|
913 args.amr_deletions_file,
|
|
914 amr_matrix_files,
|
21
|
915 args.assembler_version,
|
0
|
916 args.assembly_fasta_file,
|
|
917 args.assembly_name,
|
12
|
918 args.bedtools_version,
|
2
|
919 args.blastn_version,
|
13
|
920 circos_files,
|
1
|
921 args.compute_sequence_length_file,
|
|
922 args.contig_coverage_file,
|
|
923 args.dbkey,
|
|
924 args.dnadiff_snps_file,
|
2
|
925 args.dnadiff_version,
|
18
|
926 args.errors_file,
|
0
|
927 feature_bed_files,
|
|
928 feature_png_files,
|
1
|
929 args.flye_assembly_info_file,
|
|
930 args.genome_insertions_file,
|
0
|
931 args.gzipped,
|
26
|
932 args.illumina_forward_read_file,
|
|
933 args.illumina_reverse_read_file,
|
2
|
934 args.kraken2_report_file,
|
|
935 args.kraken2_version,
|
28
|
936 args.lrn_risk_amr_file,
|
|
937 args.lrn_risk_blacklist_file,
|
|
938 args.lrn_risk_vf_file,
|
12
|
939 args.minimap2_version,
|
0
|
940 args.mutation_regions_bed_file,
|
|
941 mutation_regions_files,
|
26
|
942 args.ont_file,
|
1
|
943 args.pima_css,
|
|
944 args.plasmids_file,
|
13
|
945 args.quast_report_file,
|
18
|
946 args.read_type,
|
12
|
947 args.reference_insertions_file,
|
|
948 args.samtools_version,
|
|
949 args.varscan_version)
|
0
|
950 markdown_report.make_report()
|