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