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