kkonganti@11: #!/usr/bin/env python3 kkonganti@11: kkonganti@11: # Kranti Konganti kkonganti@11: kkonganti@11: import os kkonganti@11: import glob kkonganti@11: import pickle kkonganti@11: import argparse kkonganti@11: import inspect kkonganti@11: import logging kkonganti@11: import re kkonganti@11: import pprint kkonganti@11: from collections import defaultdict kkonganti@11: kkonganti@11: # Multiple inheritence for pretty printing of help text. kkonganti@11: class MultiArgFormatClasses(argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter): kkonganti@11: pass kkonganti@11: kkonganti@11: kkonganti@11: # Main kkonganti@11: def main() -> None: kkonganti@11: """ kkonganti@11: This script works only in the context of `bettercallsal` Nextflow workflow. kkonganti@11: It takes: kkonganti@11: 1. A pickle file containing a dictionary object where genome accession kkonganti@11: is the key and the computed serotype is the value. kkonganti@11: 2. A file with `mash screen` results run against the Salmonella SNP kkonganti@11: Cluster genomes' sketch. kkonganti@11: 3. A directory containing genomes' FASTA in gzipped format where the kkonganti@11: FASTA file contains 2 lines: one FASTA header followed by kkonganti@11: genome Sequence. kkonganti@11: and then generates a concatenated FASTA file of top N unique `mash screen` kkonganti@11: genome hits as requested. kkonganti@11: """ kkonganti@11: kkonganti@11: # Set logging. kkonganti@11: logging.basicConfig( kkonganti@11: format="\n" + "=" * 55 + "\n%(asctime)s - %(levelname)s\n" + "=" * 55 + "\n%(message)s\n\n", kkonganti@11: level=logging.DEBUG, kkonganti@11: ) kkonganti@11: kkonganti@11: # Debug print. kkonganti@11: ppp = pprint.PrettyPrinter(width=55) kkonganti@11: prog_name = os.path.basename(inspect.stack()[0].filename) kkonganti@11: kkonganti@11: parser = argparse.ArgumentParser( kkonganti@11: prog=prog_name, description=main.__doc__, formatter_class=MultiArgFormatClasses kkonganti@11: ) kkonganti@11: kkonganti@11: parser.add_argument( kkonganti@11: "-s", kkonganti@11: dest="sero_snp_metadata", kkonganti@11: default=False, kkonganti@11: required=False, kkonganti@11: help="Absolute UNIX path to metadata text file with the field separator, | " kkonganti@11: + "\nand 5 fields: serotype|asm_lvl|asm_url|snp_cluster_id" kkonganti@11: + "\nEx: serotype=Derby,antigen_formula=4:f,g:-|Scaffold|402440|ftp://...\n|PDS000096654.2\n" kkonganti@11: + "Mentioning this option will create a pickle file for the\nprovided metadata and exits.", kkonganti@11: ) kkonganti@11: parser.add_argument( kkonganti@11: "-fs", kkonganti@11: dest="force_write_pick", kkonganti@11: action="store_true", kkonganti@11: required=False, kkonganti@11: help="By default, when -s flag is on, the pickle file named *.ACC2SERO.pickle\n" kkonganti@11: + "is written to CWD. If the file exists, the program will not overwrite\n" kkonganti@11: + "and exit. Use -fs option to overwrite.", kkonganti@11: ) kkonganti@11: parser.add_argument( kkonganti@11: "-m", kkonganti@11: dest="mash_screen_res", kkonganti@11: default=False, kkonganti@11: required=False, kkonganti@11: help="Absolute UNIX path to `mash screen` results file.", kkonganti@11: ) kkonganti@11: parser.add_argument( kkonganti@11: "-ms", kkonganti@11: dest="mash_screen_res_suffix", kkonganti@11: default=".screened", kkonganti@11: required=False, kkonganti@11: help="Suffix of the `mash screen` result file.", kkonganti@11: ) kkonganti@11: parser.add_argument( kkonganti@11: "-ps", kkonganti@11: dest="pickled_sero", kkonganti@11: default=False, kkonganti@11: required=False, kkonganti@11: help="Absolute UNIX Path to serialized metadata object in a pickle file.\n" kkonganti@11: + "You can create the pickle file of the metadata using -s option.\n" kkonganti@11: + "Required if -m is on.", kkonganti@11: ) kkonganti@11: parser.add_argument( kkonganti@11: "-gd", kkonganti@11: dest="genomes_dir", kkonganti@11: default=False, kkonganti@11: required=False, kkonganti@11: help="Absolute UNIX path to a directory containing\n" kkonganti@11: + "gzipped genome FASTA files.\n" kkonganti@11: + "Required if -m is on.", kkonganti@11: ) kkonganti@11: parser.add_argument( kkonganti@11: "-gds", kkonganti@11: dest="genomes_dir_suffix", kkonganti@11: default="_scaffolded_genomic.fna.gz", kkonganti@11: required=False, kkonganti@11: help="Genome FASTA file suffix to search for\nin the directory mentioned using\n-gd.", kkonganti@11: ) kkonganti@11: parser.add_argument( kkonganti@11: "-n", kkonganti@11: dest="num_uniq_hits", kkonganti@11: default=10, kkonganti@11: help="This many number of serotype genomes' accessions are " + "\nreturned.", kkonganti@11: ) kkonganti@11: parser.add_argument( kkonganti@11: "-op", kkonganti@11: dest="out_prefix", kkonganti@11: default="MASH_SCREEN", kkonganti@11: help="Set the output file prefix for .fna.gz and .txt files.", kkonganti@11: ) kkonganti@11: # required = parser.add_argument_group('required arguments') kkonganti@11: kkonganti@11: args = parser.parse_args() kkonganti@11: num_uniq_hits = int(args.num_uniq_hits) kkonganti@11: mash_screen_res = args.mash_screen_res kkonganti@11: mash_screen_res_suffix = args.mash_screen_res_suffix kkonganti@11: pickle_sero = args.sero_snp_metadata kkonganti@11: pickled_sero = args.pickled_sero kkonganti@11: f_write_pick = args.force_write_pick kkonganti@11: genomes_dir = args.genomes_dir kkonganti@11: genomes_dir_suffix = args.genomes_dir_suffix kkonganti@11: out_prefix = args.out_prefix kkonganti@11: mash_genomes_gz = os.path.join( kkonganti@11: os.getcwd(), out_prefix + "_TOP_" + str(num_uniq_hits) + "_UNIQUE_HITS.fna.gz" kkonganti@11: ) kkonganti@11: mash_uniq_hits_txt = os.path.join( kkonganti@11: os.getcwd(), re.sub(".fna.gz", ".txt", os.path.basename(mash_genomes_gz)) kkonganti@11: ) kkonganti@11: kkonganti@11: if mash_screen_res and os.path.exists(mash_genomes_gz): kkonganti@11: logging.error( kkonganti@11: "A concatenated genome FASTA file,\n" kkonganti@11: + f"{os.path.basename(mash_genomes_gz)} already exists in:\n" kkonganti@11: + f"{os.getcwd()}\n" kkonganti@11: + "Please remove or move it as we will not " kkonganti@11: + "overwrite it." kkonganti@11: ) kkonganti@11: exit(1) kkonganti@11: kkonganti@11: if os.path.exists(mash_uniq_hits_txt) and os.path.getsize(mash_uniq_hits_txt) > 0: kkonganti@11: os.remove(mash_uniq_hits_txt) kkonganti@11: kkonganti@11: if mash_screen_res and (not genomes_dir or not pickled_sero): kkonganti@11: logging.error("When -m is on, -ps and -gd are also required.") kkonganti@11: exit(1) kkonganti@11: kkonganti@11: if genomes_dir: kkonganti@11: if not os.path.isdir(genomes_dir): kkonganti@11: logging.error("UNIX path\n" + f"{genomes_dir}\n" + "does not exist!") kkonganti@11: exit(1) kkonganti@11: if len(glob.glob(os.path.join(genomes_dir, "*" + genomes_dir_suffix))) <= 0: kkonganti@11: logging.error( kkonganti@11: "Genomes directory" kkonganti@11: + f"{genomes_dir}" kkonganti@11: + "\ndoes not seem to have any\n" kkonganti@11: + f"files ending with suffix: {genomes_dir_suffix}" kkonganti@11: ) kkonganti@11: exit(1) kkonganti@11: kkonganti@11: if pickle_sero and os.path.exists(pickle_sero) and os.path.getsize(pickle_sero) > 0: kkonganti@11: acc2serotype = defaultdict() kkonganti@11: init_pickled_sero = os.path.join(os.getcwd(), out_prefix + ".ACC2SERO.pickle") kkonganti@11: kkonganti@11: if ( kkonganti@11: os.path.exists(init_pickled_sero) kkonganti@11: and os.path.getsize(init_pickled_sero) kkonganti@11: and not f_write_pick kkonganti@11: ): kkonganti@11: logging.error( kkonganti@11: f"File {os.path.basename(init_pickled_sero)} already exists in\n{os.getcwd()}\n" kkonganti@11: + "Use -fs to force overwrite it." kkonganti@11: ) kkonganti@11: exit(1) kkonganti@11: kkonganti@11: with open(pickle_sero, "r") as sero_snp_meta: kkonganti@11: for line in sero_snp_meta: kkonganti@11: cols = line.strip().split("|") kkonganti@11: url_cols = cols[3].split("/") kkonganti@11: kkonganti@11: if not 4 <= len(cols) <= 5: kkonganti@11: logging.error( kkonganti@11: f"The metadata file {pickle_sero} is malformed.\n" kkonganti@11: + f"Expected 4-5 columns. Got {len(cols)} columns.\n" kkonganti@11: ) kkonganti@11: exit(1) kkonganti@11: kkonganti@11: if not len(url_cols) > 5: kkonganti@11: acc = url_cols[3] kkonganti@11: else: kkonganti@11: acc = url_cols[9] kkonganti@11: kkonganti@11: if not re.match(r"^GC[AF]\_\d+\.\d+$", acc): kkonganti@11: logging.error( kkonganti@11: f"Did not find accession in either field number 4\n" kkonganti@11: + "or field number 10 of column 4." kkonganti@11: ) kkonganti@11: exit(1) kkonganti@11: kkonganti@11: acc2serotype[acc] = cols[0] kkonganti@11: kkonganti@11: with open(init_pickled_sero, "wb") as write_pickled_sero: kkonganti@11: pickle.dump(file=write_pickled_sero, obj=acc2serotype) kkonganti@11: kkonganti@11: logging.info( kkonganti@11: f"Created the pickle file for\n{os.path.basename(pickle_sero)}.\n" kkonganti@11: + "This was the only requested function." kkonganti@11: ) kkonganti@11: sero_snp_meta.close() kkonganti@11: write_pickled_sero.close() kkonganti@11: exit(0) kkonganti@11: elif pickle_sero and not (os.path.exists(pickle_sero) and os.path.getsize(pickle_sero) > 0): kkonganti@11: kkonganti@11: logging.error( kkonganti@11: "Requested to create pickle from metadata, but\n" kkonganti@11: + f"the file, {os.path.basename(pickle_sero)} is empty or\ndoes not exist!" kkonganti@11: ) kkonganti@11: exit(1) kkonganti@11: kkonganti@11: if mash_screen_res and os.path.exists(mash_screen_res): kkonganti@11: if os.path.getsize(mash_screen_res) > 0: kkonganti@11: kkonganti@11: seen_uniq_hits = 0 kkonganti@11: unpickled_acc2serotype = pickle.load(file=open(pickled_sero, "rb")) kkonganti@11: kkonganti@11: with open(mash_screen_res, "r") as msh_res: kkonganti@11: mash_hits = defaultdict() kkonganti@11: seen_mash_sero = defaultdict() kkonganti@11: kkonganti@11: for line in msh_res: kkonganti@11: cols = line.strip().split("\t") kkonganti@11: kkonganti@11: if len(cols) < 5: kkonganti@11: logging.error( kkonganti@11: f"The file {os.path.basename(mash_screen_res)} seems to\n" kkonganti@11: + "be malformed. It contains less than required 5-6 columns." kkonganti@11: ) kkonganti@11: exit(1) kkonganti@11: kkonganti@11: mash_hit_acc = re.sub( kkonganti@11: genomes_dir_suffix, kkonganti@11: "", kkonganti@11: str((re.search(r"GC[AF].*?" + genomes_dir_suffix, cols[4])).group()), kkonganti@11: ) kkonganti@11: kkonganti@11: if mash_hit_acc: kkonganti@11: mash_hits.setdefault(cols[0], []).append(mash_hit_acc) kkonganti@11: else: kkonganti@11: logging.error( kkonganti@11: "Did not find an assembly accession in column\n" kkonganti@11: + f"number 5. Found {cols[4]} instead. Cannot proceed!" kkonganti@11: ) kkonganti@11: exit(1) kkonganti@11: msh_res.close() kkonganti@11: elif os.path.getsize(mash_screen_res) == 0: kkonganti@11: failed_sample_name = os.path.basename(mash_screen_res).rstrip(mash_screen_res_suffix) kkonganti@11: with open( kkonganti@11: os.path.join(os.getcwd(), "_".join([out_prefix, "FAILED.txt"])), "w" kkonganti@11: ) as failed_sample_fh: kkonganti@11: failed_sample_fh.write(f"{failed_sample_name}\n") kkonganti@11: failed_sample_fh.close() kkonganti@11: exit(0) kkonganti@11: kkonganti@11: # ppp.pprint(mash_hits) kkonganti@11: msh_out_txt = open(mash_uniq_hits_txt, "w") kkonganti@11: with open(mash_genomes_gz, "wb") as msh_out_gz: kkonganti@11: for _, (ident, acc_list) in enumerate(sorted(mash_hits.items(), reverse=True)): kkonganti@11: for acc in acc_list: kkonganti@11: if seen_uniq_hits >= num_uniq_hits: kkonganti@11: break kkonganti@11: if unpickled_acc2serotype[acc] not in seen_mash_sero.keys(): kkonganti@11: seen_mash_sero[unpickled_acc2serotype[acc]] = 1 kkonganti@11: seen_uniq_hits += 1 kkonganti@11: # print(acc.strip() + '\t' + ident + '\t' + unpickled_acc2serotype[acc], file=sys.stdout) kkonganti@11: msh_out_txt.write( kkonganti@11: f"{acc.strip()}\t{unpickled_acc2serotype[acc]}\t{ident}\n" kkonganti@11: ) kkonganti@11: with open( kkonganti@11: os.path.join(genomes_dir, acc + genomes_dir_suffix), "rb" kkonganti@11: ) as msh_in_gz: kkonganti@11: msh_out_gz.writelines(msh_in_gz.readlines()) kkonganti@11: msh_in_gz.close() kkonganti@11: msh_out_gz.close() kkonganti@11: msh_out_txt.close() kkonganti@11: logging.info( kkonganti@11: f"File {os.path.basename(mash_genomes_gz)}\n" kkonganti@11: + f"written in:\n{os.getcwd()}\nDone! Bye!" kkonganti@11: ) kkonganti@11: exit(0) kkonganti@11: kkonganti@11: kkonganti@11: if __name__ == "__main__": kkonganti@11: main()