comparison 0.5.0/bin/get_top_unique_mash_hit_genomes.py @ 1:365849f031fd

"planemo upload"
author kkonganti
date Mon, 05 Jun 2023 18:48:51 -0400
parents
children
comparison
equal deleted inserted replaced
0:a4b1ee4b68b1 1:365849f031fd
1 #!/usr/bin/env python3
2
3 # Kranti Konganti
4
5 import os
6 import glob
7 import pickle
8 import argparse
9 import inspect
10 import logging
11 import re
12 import pprint
13 from collections import defaultdict
14
15 # Multiple inheritence for pretty printing of help text.
16 class MultiArgFormatClasses(argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):
17 pass
18
19
20 # Main
21 def main() -> None:
22 """
23 This script works only in the context of `bettercallsal` Nextflow workflow.
24 It takes:
25 1. A pickle file containing a dictionary object where genome accession
26 is the key and the computed serotype is the value.
27 2. A file with `mash screen` results run against the Salmonella SNP
28 Cluster genomes' sketch.
29 3. A directory containing genomes' FASTA in gzipped format where the
30 FASTA file contains 2 lines: one FASTA header followed by
31 genome Sequence.
32 and then generates a concatenated FASTA file of top N unique `mash screen`
33 genome hits as requested.
34 """
35
36 # Set logging.
37 logging.basicConfig(
38 format="\n" + "=" * 55 + "\n%(asctime)s - %(levelname)s\n" + "=" * 55 + "\n%(message)s\n\n",
39 level=logging.DEBUG,
40 )
41
42 # Debug print.
43 ppp = pprint.PrettyPrinter(width=55)
44 prog_name = os.path.basename(inspect.stack()[0].filename)
45
46 parser = argparse.ArgumentParser(
47 prog=prog_name, description=main.__doc__, formatter_class=MultiArgFormatClasses
48 )
49
50 parser.add_argument(
51 "-s",
52 dest="sero_snp_metadata",
53 default=False,
54 required=False,
55 help="Absolute UNIX path to metadata text file with the field separator, | "
56 + "\nand 5 fields: serotype|asm_lvl|asm_url|snp_cluster_id"
57 + "\nEx: serotype=Derby,antigen_formula=4:f,g:-|Scaffold|402440|ftp://...\n|PDS000096654.2\n"
58 + "Mentioning this option will create a pickle file for the\nprovided metadata and exits.",
59 )
60 parser.add_argument(
61 "-fs",
62 dest="force_write_pick",
63 action="store_true",
64 required=False,
65 help="By default, when -s flag is on, the pickle file named *.ACC2SERO.pickle\n"
66 + "is written to CWD. If the file exists, the program will not overwrite\n"
67 + "and exit. Use -fs option to overwrite.",
68 )
69 parser.add_argument(
70 "-m",
71 dest="mash_screen_res",
72 default=False,
73 required=False,
74 help="Absolute UNIX path to `mash screen` results file.",
75 )
76 parser.add_argument(
77 "-ms",
78 dest="mash_screen_res_suffix",
79 default=".screened",
80 required=False,
81 help="Suffix of the `mash screen` result file.",
82 )
83 parser.add_argument(
84 "-ps",
85 dest="pickled_sero",
86 default=False,
87 required=False,
88 help="Absolute UNIX Path to serialized metadata object in a pickle file.\n"
89 + "You can create the pickle file of the metadata using -s option.\n"
90 + "Required if -m is on.",
91 )
92 parser.add_argument(
93 "-gd",
94 dest="genomes_dir",
95 default=False,
96 required=False,
97 help="Absolute UNIX path to a directory containing\n"
98 + "gzipped genome FASTA files.\n"
99 + "Required if -m is on.",
100 )
101 parser.add_argument(
102 "-gds",
103 dest="genomes_dir_suffix",
104 default="_scaffolded_genomic.fna.gz",
105 required=False,
106 help="Genome FASTA file suffix to search for\nin the directory mentioned using\n-gd.",
107 )
108 parser.add_argument(
109 "-n",
110 dest="num_uniq_hits",
111 default=10,
112 help="This many number of serotype genomes' accessions are " + "\nreturned.",
113 )
114 parser.add_argument(
115 "-op",
116 dest="out_prefix",
117 default="MASH_SCREEN",
118 help="Set the output file prefix for .fna.gz and .txt files.",
119 )
120 # required = parser.add_argument_group('required arguments')
121
122 args = parser.parse_args()
123 num_uniq_hits = int(args.num_uniq_hits)
124 mash_screen_res = args.mash_screen_res
125 mash_screen_res_suffix = args.mash_screen_res_suffix
126 pickle_sero = args.sero_snp_metadata
127 pickled_sero = args.pickled_sero
128 f_write_pick = args.force_write_pick
129 genomes_dir = args.genomes_dir
130 genomes_dir_suffix = args.genomes_dir_suffix
131 out_prefix = args.out_prefix
132 mash_genomes_gz = os.path.join(
133 os.getcwd(), out_prefix + "_TOP_" + str(num_uniq_hits) + "_UNIQUE_HITS.fna.gz"
134 )
135 mash_uniq_hits_txt = os.path.join(
136 os.getcwd(), re.sub(".fna.gz", ".txt", os.path.basename(mash_genomes_gz))
137 )
138
139 if mash_screen_res and os.path.exists(mash_genomes_gz):
140 logging.error(
141 "A concatenated genome FASTA file,\n"
142 + f"{os.path.basename(mash_genomes_gz)} already exists in:\n"
143 + f"{os.getcwd()}\n"
144 + "Please remove or move it as we will not "
145 + "overwrite it."
146 )
147 exit(1)
148
149 if os.path.exists(mash_uniq_hits_txt) and os.path.getsize(mash_uniq_hits_txt) > 0:
150 os.remove(mash_uniq_hits_txt)
151
152 if mash_screen_res and (not genomes_dir or not pickled_sero):
153 logging.error("When -m is on, -ps and -gd are also required.")
154 exit(1)
155
156 if genomes_dir:
157 if not os.path.isdir(genomes_dir):
158 logging.error("UNIX path\n" + f"{genomes_dir}\n" + "does not exist!")
159 exit(1)
160 if len(glob.glob(os.path.join(genomes_dir, "*" + genomes_dir_suffix))) <= 0:
161 logging.error(
162 "Genomes directory"
163 + f"{genomes_dir}"
164 + "\ndoes not seem to have any\n"
165 + f"files ending with suffix: {genomes_dir_suffix}"
166 )
167 exit(1)
168
169 if pickle_sero and os.path.exists(pickle_sero) and os.path.getsize(pickle_sero) > 0:
170 acc2serotype = defaultdict()
171 init_pickled_sero = os.path.join(os.getcwd(), out_prefix + ".ACC2SERO.pickle")
172
173 if (
174 os.path.exists(init_pickled_sero)
175 and os.path.getsize(init_pickled_sero)
176 and not f_write_pick
177 ):
178 logging.error(
179 f"File {os.path.basename(init_pickled_sero)} already exists in\n{os.getcwd()}\n"
180 + "Use -fs to force overwrite it."
181 )
182 exit(1)
183
184 with open(pickle_sero, "r") as sero_snp_meta:
185 for line in sero_snp_meta:
186 cols = line.strip().split("|")
187 url_cols = cols[3].split("/")
188
189 if not 4 <= len(cols) <= 5:
190 logging.error(
191 f"The metadata file {pickle_sero} is malformed.\n"
192 + f"Expected 4-5 columns. Got {len(cols)} columns.\n"
193 )
194 exit(1)
195
196 if not len(url_cols) > 5:
197 acc = url_cols[3]
198 else:
199 acc = url_cols[9]
200
201 if not re.match(r"^GC[AF]\_\d+\.\d+$", acc):
202 logging.error(
203 f"Did not find accession in either field number 4\n"
204 + "or field number 10 of column 4."
205 )
206 exit(1)
207
208 acc2serotype[acc] = cols[0]
209
210 with open(init_pickled_sero, "wb") as write_pickled_sero:
211 pickle.dump(file=write_pickled_sero, obj=acc2serotype)
212
213 logging.info(
214 f"Created the pickle file for\n{os.path.basename(pickle_sero)}.\n"
215 + "This was the only requested function."
216 )
217 sero_snp_meta.close()
218 write_pickled_sero.close()
219 exit(0)
220 elif pickle_sero and not (os.path.exists(pickle_sero) and os.path.getsize(pickle_sero) > 0):
221
222 logging.error(
223 "Requested to create pickle from metadata, but\n"
224 + f"the file, {os.path.basename(pickle_sero)} is empty or\ndoes not exist!"
225 )
226 exit(1)
227
228 if mash_screen_res and os.path.exists(mash_screen_res):
229 if os.path.getsize(mash_screen_res) > 0:
230
231 seen_uniq_hits = 0
232 unpickled_acc2serotype = pickle.load(file=open(pickled_sero, "rb"))
233
234 with open(mash_screen_res, "r") as msh_res:
235 mash_hits = defaultdict()
236 seen_mash_sero = defaultdict()
237
238 for line in msh_res:
239 cols = line.strip().split("\t")
240
241 if len(cols) < 5:
242 logging.error(
243 f"The file {os.path.basename(mash_screen_res)} seems to\n"
244 + "be malformed. It contains less than required 5-6 columns."
245 )
246 exit(1)
247
248 mash_hit_acc = re.sub(
249 genomes_dir_suffix,
250 "",
251 str((re.search(r"GC[AF].*?" + genomes_dir_suffix, cols[4])).group()),
252 )
253
254 if mash_hit_acc:
255 mash_hits.setdefault(cols[0], []).append(mash_hit_acc)
256 else:
257 logging.error(
258 "Did not find an assembly accession in column\n"
259 + f"number 5. Found {cols[4]} instead. Cannot proceed!"
260 )
261 exit(1)
262 msh_res.close()
263 elif os.path.getsize(mash_screen_res) == 0:
264 failed_sample_name = os.path.basename(mash_screen_res).rstrip(mash_screen_res_suffix)
265 with open(
266 os.path.join(os.getcwd(), "_".join([out_prefix, "FAILED.txt"])), "w"
267 ) as failed_sample_fh:
268 failed_sample_fh.write(f"{failed_sample_name}\n")
269 failed_sample_fh.close()
270 exit(0)
271
272 # ppp.pprint(mash_hits)
273 msh_out_txt = open(mash_uniq_hits_txt, "w")
274 with open(mash_genomes_gz, "wb") as msh_out_gz:
275 for _, (ident, acc_list) in enumerate(sorted(mash_hits.items(), reverse=True)):
276 for acc in acc_list:
277 if seen_uniq_hits >= num_uniq_hits:
278 break
279 if unpickled_acc2serotype[acc] not in seen_mash_sero.keys():
280 seen_mash_sero[unpickled_acc2serotype[acc]] = 1
281 seen_uniq_hits += 1
282 # print(acc.strip() + '\t' + ident + '\t' + unpickled_acc2serotype[acc], file=sys.stdout)
283 msh_out_txt.write(
284 f"{acc.strip()}\t{unpickled_acc2serotype[acc]}\t{ident}\n"
285 )
286 with open(
287 os.path.join(genomes_dir, acc + genomes_dir_suffix), "rb"
288 ) as msh_in_gz:
289 msh_out_gz.writelines(msh_in_gz.readlines())
290 msh_in_gz.close()
291 msh_out_gz.close()
292 msh_out_txt.close()
293 logging.info(
294 f"File {os.path.basename(mash_genomes_gz)}\n"
295 + f"written in:\n{os.getcwd()}\nDone! Bye!"
296 )
297 exit(0)
298
299
300 if __name__ == "__main__":
301 main()