Skip to content

Commit 5d23806

Browse files
committed
Updating gen_mut_model to output and read proper trinucleotide count files
1 parent 3797ca9 commit 5d23806

File tree

2 files changed

+36
-58
lines changed

2 files changed

+36
-58
lines changed

neat/gen_mut_model/runner.py

+26-50
Original file line numberDiff line numberDiff line change
@@ -85,18 +85,23 @@ def runner(reference_index,
8585

8686
# Pre-parsing to find all the matching chromosomes between ref and vcf
8787
_LOG.info('Processing VCF file...')
88-
matching_variants, matching_chromosomes = read_and_filter_variants(vcf_to_process,
89-
reference_index,
90-
ignore)
88+
matching_variants, matching_chromosomes = read_and_filter_variants(
89+
vcf_to_process,
90+
reference_index,
91+
ignore
92+
)
9193

9294
if not matching_variants or not matching_chromosomes:
9395
_LOG.error("No valid variants detected. Check names in vcf versus reference and/or bed.")
9496
sys.exit(1)
9597

96-
trinuc_ref_count, bed_track_length = count_trinucleotides(reference_index,
97-
bed,
98-
outcounts_file,
99-
matching_chromosomes)
98+
trinuc_ref_count, bed_track_length = count_trinucleotides(
99+
reference_index,
100+
bed,
101+
outcounts_file,
102+
matching_chromosomes,
103+
save_trinuc
104+
)
100105

101106
if not trinuc_ref_count:
102107
_LOG.error("No valid trinucleotides detected in reference.")
@@ -296,47 +301,6 @@ def runner(reference_index,
296301
for k in sorted(snp_trans_freq):
297302
_LOG.info(f'p({k[0]} --> {k[1]} | SNP occurs) = {snp_trans_freq[k]}')
298303

299-
# Save counts, if requested
300-
if save_trinuc:
301-
trinuc_output_data = {
302-
'p(snp)': average_snp_freq,
303-
'p(insertion)': average_insertion_frequency,
304-
'p(deletion)': average_deletion_frequency,
305-
'overall average mut rate': avg_mut_rate,
306-
'total variants processed': total_var,
307-
'homozygous probability': homozygous_frequency
308-
}
309-
310-
for k in sorted(trinuc_mut_prob):
311-
trinuc_output_data[f'p({k} mutates)'] = trinuc_mut_prob[k]
312-
313-
for k in sorted(trinuc_trans_probs):
314-
trinuc_output_data[f'p({k[0]} --> {k[1]} | {k[0]} mutates)'] = trinuc_trans_probs[k]
315-
316-
for k in sorted(deletion_counts):
317-
trinuc_output_data[f'p(del length = {abs(k)} | deletion occurs)'] = deletion_frequency[k]
318-
319-
for k in sorted(insertion_counts):
320-
trinuc_output_data[f'p(insert length = {abs(k)} | insertion occurs)'] = insertion_freqency[k]
321-
322-
for k in sorted(snp_trans_freq):
323-
trinuc_output_data[f'p({k[0]} --> {k[1]} | SNP occurs)'] = snp_trans_freq[k]
324-
325-
trinuc_output_path = Path(output)
326-
trinuc_output_path = trinuc_output_path.with_suffix('')
327-
trinuc_output_path = trinuc_output_path.with_suffix('.trinuc.pickle.gz')
328-
_LOG.info(f'Saving trinucleotide counts to: {trinuc_output_path}')
329-
330-
with open_output(trinuc_output_path, 'w+') as trinuc_outfile:
331-
332-
pickle.dump(trinuc_output_data, trinuc_outfile)
333-
334-
# Human-readable content of file below
335-
trinuc_outfile.write('\n')
336-
337-
for key, value in trinuc_output_data.items():
338-
trinuc_outfile.write(f'{key}: {value}\n')
339-
340304
_LOG.info(f'p(snp) = {average_snp_freq}')
341305
_LOG.info(f'p(insertion) = {average_insertion_frequency}')
342306
_LOG.info(f'p(deletion) = {average_deletion_frequency}')
@@ -405,6 +369,8 @@ def compute_mut_runner(reference,
405369
if outcounts:
406370
validate_input_path(outcounts)
407371
outcounts = Path(outcounts)
372+
elif save_trinuc:
373+
outcounts = Path(output + '.trinuc.pickle.gz')
408374

409375
print('Processing reference...')
410376
reference_index = SeqIO.index(reference, 'fasta')
@@ -477,8 +443,18 @@ def compute_mut_runner(reference,
477443
output = Path(output + '.pickle.gz')
478444
validate_output_path(output, overwrite=overwrite_output)
479445

480-
runner(reference_index, vcf_to_process, vcf_columns, outcounts, show_trinuc, save_trinuc,
481-
output, bed, human_sample, skip_common)
446+
runner(
447+
reference_index,
448+
vcf_to_process,
449+
vcf_columns,
450+
outcounts,
451+
show_trinuc,
452+
save_trinuc,
453+
output,
454+
bed,
455+
human_sample,
456+
skip_common
457+
)
482458

483459
if os.path.exists('temp.vcf'):
484460
os.remove('temp.vcf')

neat/gen_mut_model/utils.py

+10-8
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
import json
66
import sys
7+
import pickle
8+
import gzip
79

810
import numpy as np
911

@@ -165,14 +167,16 @@ def cluster_list(list_to_cluster, delta):
165167
def count_trinucleotides(reference_index,
166168
bed,
167169
trinuc_counts,
168-
matching_chroms):
170+
matching_chroms,
171+
save_trinuc_file):
169172
"""
170173
Counts the frequency of the various trinucleotide combinations in the dataset
171174
172175
:param dict reference_index: The index of the fasta, from SeqIO
173176
:param Path bed: Full path to bed file, if using
174177
:param Path trinuc_counts: Full path to existing trinculeotide counts file, if input, or the output path
175178
:param list matching_chroms: List of matching chromosomes
179+
:param save_trinuc_file: Boolean determines whether to save trinucleotide counts file.
176180
:return dict, int: A dictionary of trinculeotides and counts, the number of bases spanned
177181
"""
178182
# Data format: TRINUC: COUNT (e.g., "AAA": 12), where COUNT is the number of times trinuc was observed
@@ -183,11 +187,11 @@ def count_trinucleotides(reference_index,
183187
track_len = 0
184188

185189
trinuc_counts_exists = False
186-
save_trinuc_file = False
187190
if trinuc_counts:
188191
if trinuc_counts.is_file():
192+
_LOG.info("Trinucleotide counts file exists, skipping save to avoid overwriting data.")
189193
trinuc_counts_exists = True
190-
save_trinuc_file = True
194+
save_trinuc_file = False
191195

192196
if bed:
193197
_LOG.info("Counting trinucleotide combinations in bed regions")
@@ -207,7 +211,6 @@ def count_trinucleotides(reference_index,
207211
trinuc_ref_count = count_trinuc(trinuc, trinuc_ref_count)
208212

209213
# Solution to attribute error (needs to be checked)
210-
# TODO remove ref_name from this dict
211214
elif not trinuc_counts_exists:
212215
_LOG.info("Counting trinucleotide combinations in reference.")
213216
for ref_name in matching_chroms:
@@ -220,13 +223,12 @@ def count_trinucleotides(reference_index,
220223
with open_output(trinuc_counts, 'w') as countfile:
221224
_LOG.info('Saving trinuc counts to file...')
222225
# Convert all values to writable formats
223-
trinuc_ref_count = {str(x): int(y) for x, y in trinuc_ref_count.items()}
224-
countfile.write(json.dumps(trinuc_ref_count))
226+
pickle.dump(trinuc_ref_count, countfile)
225227

226228
else:
227229
_LOG.info(f'Loading file: {trinuc_counts}.')
228-
with open_input(trinuc_counts) as counts:
229-
trinuc_ref_count = json.load(counts)
230+
with gzip.open(trinuc_counts, 'rb') as counts:
231+
trinuc_ref_count = pickle.load(counts)
230232
if save_trinuc_file:
231233
_LOG.warning('Existing trinucelotide file will not be changed.')
232234

0 commit comments

Comments
 (0)