annotate 0.6.1/bin/get_top_unique_mash_hit_genomes.py @ 11:749faef1caa9

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