annotate vsnp_add_zero_coverage.py @ 1:eaf4c304fd22 draft

Uploaded
author greg
date Tue, 21 Apr 2020 09:51:00 -0400
parents 3cb0bf7e1b2d
children 01312f8a6ca9
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
0
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
1 #!/usr/bin/env python
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
2
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
3 import argparse
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
4 import multiprocessing
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
5 import os
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
6 import pandas
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
7 import pysam
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
8 import queue
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
9 import re
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
10 import shutil
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
11 from numpy import mean
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
12 from Bio import SeqIO
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
13
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
14 INPUT_BAM_DIR = 'input_bam_dir'
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
15 INPUT_VCF_DIR = 'input_vcf_dir'
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
16 OUTPUT_VCF_DIR = 'output_vcf_dir'
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
17 OUTPUT_METRICS_DIR = 'output_metrics_dir'
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
18
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
19
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
20 def get_base_file_name(file_path):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
21 base_file_name = os.path.basename(file_path)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
22 if base_file_name.find(".") > 0:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
23 # Eliminate the extension.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
24 return os.path.splitext(base_file_name)[0]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
25 elif base_file_name.find("_") > 0:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
26 # The dot extension was likely changed to
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
27 # the " character.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
28 items = base_file_name.split("_")
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
29 return "_".join(items[0:-1])
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
30 else:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
31 return base_file_name
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
32
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
33
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
34 def get_coverage_and_snp_count(task_queue, reference, output_metrics, output_vcf, timeout):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
35 while True:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
36 try:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
37 tup = task_queue.get(block=True, timeout=timeout)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
38 except queue.Empty:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
39 break
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
40 bam_file, vcf_file = tup
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
41 # Create a coverage dictionary.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
42 coverage_dict = {}
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
43 coverage_list = pysam.depth(bam_file, split_lines=True)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
44 for line in coverage_list:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
45 chrom, position, depth = line.split('\t')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
46 coverage_dict["%s-%s" % (chrom, position)] = depth
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
47 # Convert it to a data frame.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
48 coverage_df = pandas.DataFrame.from_dict(coverage_dict, orient='index', columns=["depth"])
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
49 # Create a zero coverage dictionary.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
50 zero_dict = {}
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
51 for record in SeqIO.parse(reference, "fasta"):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
52 chrom = record.id
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
53 total_len = len(record.seq)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
54 for pos in list(range(1, total_len + 1)):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
55 zero_dict["%s-%s" % (str(chrom), str(pos))] = 0
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
56 # Convert it to a data frame with depth_x
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
57 # and depth_y columns - index is NaN.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
58 zero_df = pandas.DataFrame.from_dict(zero_dict, orient='index', columns=["depth"])
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
59 coverage_df = zero_df.merge(coverage_df, left_index=True, right_index=True, how='outer')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
60 # depth_x "0" column no longer needed.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
61 coverage_df = coverage_df.drop(columns=['depth_x'])
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
62 coverage_df = coverage_df.rename(columns={'depth_y': 'depth'})
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
63 # Covert the NaN to 0 coverage and get some metrics.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
64 coverage_df = coverage_df.fillna(0)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
65 coverage_df['depth'] = coverage_df['depth'].apply(int)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
66 total_length = len(coverage_df)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
67 average_coverage = coverage_df['depth'].mean()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
68 zero_df = coverage_df[coverage_df['depth'] == 0]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
69 total_zero_coverage = len(zero_df)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
70 total_coverage = total_length - total_zero_coverage
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
71 genome_coverage = "{:.2%}".format(total_coverage / total_length)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
72 # Process the associated VCF input.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
73 column_names = ["CHROM", "POS", "ID", "REF", "ALT", "QUAL", "FILTER", "INFO", "FORMAT", "Sample"]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
74 vcf_df = pandas.read_csv(vcf_file, sep='\t', header=None, names=column_names, comment='#')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
75 good_snp_count = len(vcf_df[(vcf_df['ALT'].str.len() == 1) & (vcf_df['REF'].str.len() == 1) & (vcf_df['QUAL'] > 150)])
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
76 base_file_name = get_base_file_name(vcf_file)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
77 if total_zero_coverage > 0:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
78 header_file = "%s_header.csv" % base_file_name
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
79 with open(header_file, 'w') as outfile:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
80 with open(vcf_file) as infile:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
81 for line in infile:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
82 if re.search('^#', line):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
83 outfile.write("%s" % line)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
84 vcf_df_snp = vcf_df[vcf_df['REF'].str.len() == 1]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
85 vcf_df_snp = vcf_df_snp[vcf_df_snp['ALT'].str.len() == 1]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
86 vcf_df_snp['ABS_VALUE'] = vcf_df_snp['CHROM'].map(str) + "-" + vcf_df_snp['POS'].map(str)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
87 vcf_df_snp = vcf_df_snp.set_index('ABS_VALUE')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
88 cat_df = pandas.concat([vcf_df_snp, zero_df], axis=1, sort=False)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
89 cat_df = cat_df.drop(columns=['CHROM', 'POS', 'depth'])
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
90 cat_df[['ID', 'ALT', 'QUAL', 'FILTER', 'INFO']] = cat_df[['ID', 'ALT', 'QUAL', 'FILTER', 'INFO']].fillna('.')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
91 cat_df['REF'] = cat_df['REF'].fillna('N')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
92 cat_df['FORMAT'] = cat_df['FORMAT'].fillna('GT')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
93 cat_df['Sample'] = cat_df['Sample'].fillna('./.')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
94 cat_df['temp'] = cat_df.index.str.rsplit('-', n=1)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
95 cat_df[['CHROM', 'POS']] = pandas.DataFrame(cat_df.temp.values.tolist(), index=cat_df.index)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
96 cat_df = cat_df[['CHROM', 'POS', 'ID', 'REF', 'ALT', 'QUAL', 'FILTER', 'INFO', 'FORMAT', 'Sample']]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
97 cat_df['POS'] = cat_df['POS'].astype(int)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
98 cat_df = cat_df.sort_values(['CHROM', 'POS'])
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
99 body_file = "%s_body.csv" % base_file_name
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
100 cat_df.to_csv(body_file, sep='\t', header=False, index=False)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
101 if output_vcf is None:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
102 output_vcf_file = os.path.join(OUTPUT_VCF_DIR, "%s.vcf" % base_file_name)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
103 else:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
104 output_vcf_file = output_vcf
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
105 with open(output_vcf_file, "w") as outfile:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
106 for cf in [header_file, body_file]:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
107 with open(cf, "r") as infile:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
108 for line in infile:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
109 outfile.write("%s" % line)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
110 else:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
111 if output_vcf is None:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
112 output_vcf_file = os.path.join(OUTPUT_VCF_DIR, "%s.vcf" % base_file_name)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
113 else:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
114 output_vcf_file = output_vcf
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
115 shutil.copyfile(vcf_file, output_vcf_file)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
116 bam_metrics = [base_file_name, "", "%4f" % average_coverage, genome_coverage]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
117 vcf_metrics = [base_file_name, str(good_snp_count), "", ""]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
118 if output_metrics is None:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
119 output_metrics_file = os.path.join(OUTPUT_METRICS_DIR, "%s.tabular" % base_file_name)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
120 else:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
121 output_metrics_file = output_metrics
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
122 metrics_columns = ["File", "Number of Good SNPs", "Average Coverage", "Genome Coverage"]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
123 with open(output_metrics_file, "w") as fh:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
124 fh.write("# %s\n" % "\t".join(metrics_columns))
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
125 fh.write("%s\n" % "\t".join(bam_metrics))
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
126 fh.write("%s\n" % "\t".join(vcf_metrics))
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
127 task_queue.task_done()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
128
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
129
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
130 def set_num_cpus(num_files, processes):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
131 num_cpus = int(multiprocessing.cpu_count())
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
132 if num_files < num_cpus and num_files < processes:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
133 return num_files
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
134 if num_cpus < processes:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
135 half_cpus = int(num_cpus / 2)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
136 if num_files < half_cpus:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
137 return num_files
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
138 return half_cpus
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
139 return processes
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
140
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
141
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
142 if __name__ == '__main__':
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
143 parser = argparse.ArgumentParser()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
144
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
145 parser.add_argument('--output_metrics', action='store', dest='output_metrics', required=False, default=None, help='Output metrics text file')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
146 parser.add_argument('--output_vcf', action='store', dest='output_vcf', required=False, default=None, help='Output VCF file')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
147 parser.add_argument('--reference', action='store', dest='reference', help='Reference dataset')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
148 parser.add_argument('--processes', action='store', dest='processes', type=int, help='User-selected number of processes to use for job splitting')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
149
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
150 args = parser.parse_args()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
151
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
152 # The assumption here is that the list of files
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
153 # in both INPUT_BAM_DIR and INPUT_VCF_DIR are
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
154 # equal in number and named such that they are
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
155 # properly matched if the directories contain
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
156 # more than 1 file (i.e., hopefully the bam file
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
157 # names and vcf file names will be something like
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
158 # Mbovis-01D6_* so they can be # sorted and properly
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
159 # associated with each other).
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
160 bam_files = []
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
161 for file_name in sorted(os.listdir(INPUT_BAM_DIR)):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
162 file_path = os.path.abspath(os.path.join(INPUT_BAM_DIR, file_name))
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
163 bam_files.append(file_path)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
164 vcf_files = []
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
165 for file_name in sorted(os.listdir(INPUT_VCF_DIR)):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
166 file_path = os.path.abspath(os.path.join(INPUT_VCF_DIR, file_name))
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
167 vcf_files.append(file_path)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
168
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
169 multiprocessing.set_start_method('spawn')
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
170 queue1 = multiprocessing.JoinableQueue()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
171 num_files = len(bam_files)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
172 cpus = set_num_cpus(num_files, args.processes)
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
173 # Set a timeout for get()s in the queue.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
174 timeout = 0.05
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
175
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
176 # Add each associated bam and vcf file pair to the queue.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
177 for i, bam_file in enumerate(bam_files):
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
178 vcf_file = vcf_files[i]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
179 queue1.put((bam_file, vcf_file))
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
180
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
181 # Complete the get_coverage_and_snp_count task.
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
182 processes = [multiprocessing.Process(target=get_coverage_and_snp_count, args=(queue1, args.reference, args.output_metrics, args.output_vcf, timeout, )) for _ in range(cpus)]
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
183 for p in processes:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
184 p.start()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
185 for p in processes:
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
186 p.join()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
187 queue1.join()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
188
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
189 if queue1.empty():
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
190 queue1.close()
3cb0bf7e1b2d Uploaded
greg
parents:
diff changeset
191 queue1.join_thread()