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