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