kkonganti@17: #!/usr/bin/env python3 kkonganti@17: kkonganti@17: # Kranti Konganti kkonganti@17: kkonganti@17: import argparse kkonganti@17: import glob kkonganti@17: import inspect kkonganti@17: import logging kkonganti@17: import os kkonganti@17: import pickle kkonganti@17: import pprint kkonganti@17: import re kkonganti@17: import subprocess kkonganti@17: from collections import defaultdict kkonganti@17: kkonganti@17: kkonganti@17: # Multiple inheritence for pretty printing of help text. kkonganti@17: class MultiArgFormatClasses(argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter): kkonganti@17: pass kkonganti@17: kkonganti@17: kkonganti@17: # Main kkonganti@17: def main() -> None: kkonganti@17: """ kkonganti@17: This script works only in the context of a Nextflow workflow. kkonganti@17: It takes: kkonganti@17: 1. A pickle file containing a dictionary object where genome accession kkonganti@17: is the key and the computed serotype is the value. kkonganti@17: OR kkonganti@17: 1. It takes a pickle file containing a nested dictionary, where genome accession kkonganti@17: is the key and the metadata is a dictionary associated with that key. kkonganti@17: 2. A file with `mash screen` results. kkonganti@17: 3. A directory containing genomes' FASTA in gzipped format where the kkonganti@17: FASTA file contains 2 lines: one FASTA header followed by kkonganti@17: genome Sequence. kkonganti@17: and then generates a concatenated FASTA file of top N unique `mash screen` kkonganti@17: genome hits as requested. kkonganti@17: kkonganti@17: In addition: kkonganti@17: 1. User can skip `mash screen` hits that originate from the supplied kkonganti@17: bio project accessions. kkonganti@17: For -skip option to work, ncbi-datasets should be available in $PATH. kkonganti@17: """ kkonganti@17: kkonganti@17: # Set logging. kkonganti@17: logging.basicConfig( kkonganti@17: format="\n" + "=" * 55 + "\n%(asctime)s - %(levelname)s\n" + "=" * 55 + "\n%(message)s\n\n", kkonganti@17: level=logging.DEBUG, kkonganti@17: ) kkonganti@17: kkonganti@17: # Debug print. kkonganti@17: ppp = pprint.PrettyPrinter(width=55) kkonganti@17: prog_name = os.path.basename(inspect.stack()[0].filename) kkonganti@17: kkonganti@17: parser = argparse.ArgumentParser( kkonganti@17: prog=prog_name, description=main.__doc__, formatter_class=MultiArgFormatClasses kkonganti@17: ) kkonganti@17: kkonganti@17: parser.add_argument( kkonganti@17: "-s", kkonganti@17: dest="sero_snp_metadata", kkonganti@17: default=False, kkonganti@17: required=False, kkonganti@17: help="Absolute UNIX path to metadata text file with the field separator, | " kkonganti@17: + "\nand 5 fields: serotype|asm_lvl|asm_url|snp_cluster_id" kkonganti@17: + "\nEx: serotype=Derby,antigen_formula=4:f,g:-|Scaffold|402440|ftp://...\n|PDS000096654.2\n" kkonganti@17: + "Mentioning this option will create a pickle file for the\nprovided metadata and exits.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-fs", kkonganti@17: dest="force_write_pick", kkonganti@17: action="store_true", kkonganti@17: required=False, kkonganti@17: help="By default, when -s flag is on, the pickle file named *.ACC2SERO.pickle\n" kkonganti@17: + "is written to CWD. If the file exists, the program will not overwrite\n" kkonganti@17: + "and exit. Use -fs option to overwrite.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-m", kkonganti@17: dest="mash_screen_res", kkonganti@17: default=False, kkonganti@17: required=False, kkonganti@17: help="Absolute UNIX path to `mash screen` results file.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-ms", kkonganti@17: dest="mash_screen_res_suffix", kkonganti@17: default=".screened", kkonganti@17: required=False, kkonganti@17: help="Suffix of the `mash screen` result file.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-ps", kkonganti@17: dest="pickled_sero", kkonganti@17: default=False, kkonganti@17: required=False, kkonganti@17: help="Absolute UNIX Path to serialized metadata object in a pickle file.\n" kkonganti@17: + "You can create the pickle file of the metadata using -s option.\n" kkonganti@17: + "Required if -m is on.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-gd", kkonganti@17: dest="genomes_dir", kkonganti@17: default=False, kkonganti@17: required=False, kkonganti@17: help="Absolute UNIX path to a directory containing\n" kkonganti@17: + "gzipped genome FASTA files.\n" kkonganti@17: + "Required if -m is on.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-gds", kkonganti@17: dest="genomes_dir_suffix", kkonganti@17: default="_scaffolded_genomic.fna.gz", kkonganti@17: required=False, kkonganti@17: help="Genome FASTA file suffix to search for\nin the directory mentioned using\n-gd.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-n", kkonganti@17: dest="num_uniq_hits", kkonganti@17: default=10, kkonganti@17: required=False, kkonganti@17: help="This many number of serotype genomes' accessions are returned.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-skip", kkonganti@17: dest="skip_accs", kkonganti@17: default=str(""), kkonganti@17: required=False, kkonganti@17: help="Skip all hits which belong to the following bioproject accession(s).\n" kkonganti@17: + "A comma separated list of more than one bioproject.", kkonganti@17: ) kkonganti@17: parser.add_argument( kkonganti@17: "-op", kkonganti@17: dest="out_prefix", kkonganti@17: default="MASH_SCREEN", kkonganti@17: required=False, kkonganti@17: help="Set the output file prefix for .fna.gz and .txt files.", kkonganti@17: ) kkonganti@17: # required = parser.add_argument_group('required arguments') kkonganti@17: kkonganti@17: args = parser.parse_args() kkonganti@17: num_uniq_hits = int(args.num_uniq_hits) kkonganti@17: mash_screen_res = args.mash_screen_res kkonganti@17: mash_screen_res_suffix = args.mash_screen_res_suffix kkonganti@17: pickle_sero = args.sero_snp_metadata kkonganti@17: pickled_sero = args.pickled_sero kkonganti@17: f_write_pick = args.force_write_pick kkonganti@17: genomes_dir = args.genomes_dir kkonganti@17: genomes_dir_suffix = args.genomes_dir_suffix kkonganti@17: out_prefix = args.out_prefix kkonganti@17: skip_accs = args.skip_accs kkonganti@17: skip_accs_list = list() kkonganti@17: skip_check = re.compile(r"PRJNA\d+(?:\,PRJNA\d+){0,1}") kkonganti@17: req_metadata = { kkonganti@17: "mlst_sequence_type": "ST", kkonganti@17: "epi_type": "ET", kkonganti@17: "host": "HO", kkonganti@17: "host_disease": "HD", kkonganti@17: "isolation_source": "IS", kkonganti@17: "outbreak": "OU", kkonganti@17: "source_type": "SOT", kkonganti@17: "strain": "GS", kkonganti@17: } kkonganti@17: target_acc_key = "target_acc" kkonganti@17: ncbi_path_heading = "NCBI Pathogen Isolates Browser" kkonganti@17: ncbi_path_uri = "https://www.ncbi.nlm.nih.gov/pathogens/isolates/#" kkonganti@17: mash_genomes_gz = os.path.join( kkonganti@17: os.getcwd(), out_prefix + "_TOP_" + str(num_uniq_hits) + "_UNIQUE_HITS.fna.gz" kkonganti@17: ) kkonganti@17: mash_uniq_hits_txt = os.path.join( kkonganti@17: os.getcwd(), re.sub(".fna.gz", ".txt", os.path.basename(mash_genomes_gz)) kkonganti@17: ) kkonganti@17: mash_uniq_accs_txt = os.path.join( kkonganti@17: os.getcwd(), re.sub(".fna.gz", "_ACCS.txt", os.path.basename(mash_genomes_gz)) kkonganti@17: ) kkonganti@17: mash_popup_info_txt = os.path.join( kkonganti@17: os.getcwd(), re.sub(".fna.gz", "_POPUP.txt", os.path.basename(mash_genomes_gz)) kkonganti@17: ) kkonganti@17: kkonganti@17: if mash_screen_res and os.path.exists(mash_genomes_gz): kkonganti@17: logging.error( kkonganti@17: "A concatenated genome FASTA file,\n" kkonganti@17: + f"{os.path.basename(mash_genomes_gz)} already exists in:\n" kkonganti@17: + f"{os.getcwd()}\n" kkonganti@17: + "Please remove or move it as we will not " kkonganti@17: + "overwrite it." kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: kkonganti@17: if os.path.exists(mash_uniq_hits_txt) and os.path.getsize(mash_uniq_hits_txt) > 0: kkonganti@17: os.remove(mash_uniq_hits_txt) kkonganti@17: kkonganti@17: if mash_screen_res and (not genomes_dir or not pickled_sero): kkonganti@17: logging.error("When -m is on, -ps and -gd are also required.") kkonganti@17: exit(1) kkonganti@17: kkonganti@17: if skip_accs and not skip_check.match(skip_accs): kkonganti@17: logging.error( kkonganti@17: "Supplied bio project accessions are not valid!\n" kkonganti@17: + "Valid options:\n\t-skip PRJNA766315\n\t-skip PRJNA766315,PRJNA675435" kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: elif skip_check.match(skip_accs): kkonganti@17: datasets_cmd = "datasets summary genome accession --as-json-lines --report ids_only".split() kkonganti@17: datasets_cmd.append(skip_accs) kkonganti@17: dataformat_cmd = "dataformat tsv genome --fields accession --elide-header".split() kkonganti@17: try: kkonganti@17: accs_query = subprocess.run(datasets_cmd, capture_output=True, check=True) kkonganti@17: try: kkonganti@17: skip_accs_list = ( kkonganti@17: subprocess.check_output(dataformat_cmd, input=accs_query.stdout) kkonganti@17: .decode("utf-8") kkonganti@17: .split("\n") kkonganti@17: ) kkonganti@17: except subprocess.CalledProcessError as e: kkonganti@17: logging.error(f"Query failed\n\t{dataformat_cmd.join(' ')}\nError:\n\t{e}") kkonganti@17: exit(1) kkonganti@17: except subprocess.CalledProcessError as e: kkonganti@17: logging.error(f"Query failed\n\t{datasets_cmd.join(' ')}\nError:\n\t{e}") kkonganti@17: exit(1) kkonganti@17: kkonganti@17: if len(skip_accs_list) > 0: kkonganti@17: filter_these_hits = list(filter(bool, skip_accs_list)) kkonganti@17: else: kkonganti@17: filter_these_hits = list() kkonganti@17: kkonganti@17: if genomes_dir: kkonganti@17: if not os.path.isdir(genomes_dir): kkonganti@17: logging.error("UNIX path\n" + f"{genomes_dir}\n" + "does not exist!") kkonganti@17: exit(1) kkonganti@17: if len(glob.glob(os.path.join(genomes_dir, "*" + genomes_dir_suffix))) <= 0: kkonganti@17: logging.error( kkonganti@17: "Genomes directory" kkonganti@17: + f"{genomes_dir}" kkonganti@17: + "\ndoes not seem to have any\n" kkonganti@17: + f"files ending with suffix: {genomes_dir_suffix}" kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: kkonganti@17: if pickle_sero and os.path.exists(pickle_sero) and os.path.getsize(pickle_sero) > 0: kkonganti@17: acc2serotype = defaultdict() kkonganti@17: init_pickled_sero = os.path.join(os.getcwd(), out_prefix + ".ACC2SERO.pickle") kkonganti@17: kkonganti@17: if ( kkonganti@17: os.path.exists(init_pickled_sero) kkonganti@17: and os.path.getsize(init_pickled_sero) kkonganti@17: and not f_write_pick kkonganti@17: ): kkonganti@17: logging.error( kkonganti@17: f"File {os.path.basename(init_pickled_sero)} already exists in\n{os.getcwd()}\n" kkonganti@17: + "Use -fs to force overwrite it." kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: kkonganti@17: with open(pickle_sero, "r") as sero_snp_meta: kkonganti@17: for line in sero_snp_meta: kkonganti@17: cols = line.strip().split("|") kkonganti@17: url_cols = cols[3].split("/") kkonganti@17: kkonganti@17: if not 4 <= len(cols) <= 5: kkonganti@17: logging.error( kkonganti@17: f"The metadata file {pickle_sero} is malformed.\n" kkonganti@17: + f"Expected 4-5 columns. Got {len(cols)} columns.\n" kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: kkonganti@17: if not len(url_cols) > 5: kkonganti@17: acc = url_cols[3] kkonganti@17: else: kkonganti@17: acc = url_cols[9] kkonganti@17: kkonganti@17: if not re.match(r"^GC[AF]\_\d+\.\d+$", acc): kkonganti@17: logging.error( kkonganti@17: f"Did not find accession in either field number 4\n" kkonganti@17: + "or field number 10 of column 4." kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: kkonganti@17: acc2serotype[acc] = cols[0] kkonganti@17: kkonganti@17: with open(init_pickled_sero, "wb") as write_pickled_sero: kkonganti@17: pickle.dump(file=write_pickled_sero, obj=acc2serotype) kkonganti@17: kkonganti@17: logging.info( kkonganti@17: f"Created the pickle file for\n{os.path.basename(pickle_sero)}.\n" kkonganti@17: + "This was the only requested function." kkonganti@17: ) kkonganti@17: sero_snp_meta.close() kkonganti@17: write_pickled_sero.close() kkonganti@17: exit(0) kkonganti@17: elif pickle_sero and not (os.path.exists(pickle_sero) and os.path.getsize(pickle_sero) > 0): kkonganti@17: logging.error( kkonganti@17: "Requested to create pickle from metadata, but\n" kkonganti@17: + f"the file, {os.path.basename(pickle_sero)} is empty or\ndoes not exist!" kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: kkonganti@17: if mash_screen_res and os.path.exists(mash_screen_res): kkonganti@17: if os.path.getsize(mash_screen_res) > 0: kkonganti@17: seen_uniq_hits = 0 kkonganti@17: unpickled_acc2serotype = pickle.load(file=open(pickled_sero, "rb")) kkonganti@17: kkonganti@17: with open(mash_screen_res, "r") as msh_res: kkonganti@17: mash_hits = defaultdict() kkonganti@17: seen_mash_sero = defaultdict() kkonganti@17: kkonganti@17: for line in msh_res: kkonganti@17: cols = line.strip().split("\t") kkonganti@17: kkonganti@17: if len(cols) < 5: kkonganti@17: logging.error( kkonganti@17: f"The file {os.path.basename(mash_screen_res)} seems to\n" kkonganti@17: + "be malformed. It contains less than required 5-6 columns." kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: kkonganti@17: mash_hit_acc = re.sub( kkonganti@17: genomes_dir_suffix, kkonganti@17: "", kkonganti@17: str((re.search(r"GC[AF].*?" + genomes_dir_suffix, cols[4])).group()), kkonganti@17: ) kkonganti@17: kkonganti@17: if mash_hit_acc: kkonganti@17: mash_hits.setdefault(cols[0], []).append(mash_hit_acc) kkonganti@17: else: kkonganti@17: logging.error( kkonganti@17: "Did not find an assembly accession in column\n" kkonganti@17: + f"number 5. Found {cols[4]} instead. Cannot proceed!" kkonganti@17: ) kkonganti@17: exit(1) kkonganti@17: msh_res.close() kkonganti@17: elif os.path.getsize(mash_screen_res) == 0: kkonganti@17: failed_sample_name = os.path.basename(mash_screen_res).rstrip(mash_screen_res_suffix) kkonganti@17: with open( kkonganti@17: os.path.join(os.getcwd(), "_".join([out_prefix, "FAILED.txt"])), "w" kkonganti@17: ) as failed_sample_fh: kkonganti@17: failed_sample_fh.write(f"{failed_sample_name}\n") kkonganti@17: failed_sample_fh.close() kkonganti@17: exit(0) kkonganti@17: kkonganti@17: # ppp.pprint(mash_hits) kkonganti@17: msh_out_txt = open(mash_uniq_hits_txt, "w") kkonganti@17: wrote_header_pop = False kkonganti@17: wrote_header_acc = False kkonganti@17: kkonganti@17: with open(mash_genomes_gz, "wb") as msh_out_gz: kkonganti@17: for _, (ident, acc_list) in enumerate(sorted(mash_hits.items(), reverse=True)): kkonganti@17: for acc in acc_list: kkonganti@17: if len(filter_these_hits) > 0 and acc in filter_these_hits: kkonganti@17: continue kkonganti@17: if seen_uniq_hits >= num_uniq_hits: kkonganti@17: break kkonganti@17: if isinstance(unpickled_acc2serotype[acc], dict): kkonganti@17: if target_acc_key in unpickled_acc2serotype[acc].keys(): kkonganti@17: if not wrote_header_pop: kkonganti@17: mash_out_pop_txt = open(mash_popup_info_txt, "w") kkonganti@17: mash_out_pop_txt.write("POPUP_INFO\nSEPARATOR COMMA\nDATA\n") kkonganti@17: wrote_header_pop = True kkonganti@17: kkonganti@17: pdt = "".join(unpickled_acc2serotype[acc][target_acc_key]) kkonganti@17: kkonganti@17: popup_line = ",".join( kkonganti@17: [ kkonganti@17: acc, kkonganti@17: ncbi_path_heading, kkonganti@17: f'{pdt}', kkonganti@17: ] kkonganti@17: ) kkonganti@17: mash_out_pop_txt.write(popup_line + "\n") kkonganti@17: kkonganti@17: if all( kkonganti@17: k in unpickled_acc2serotype[acc].keys() for k in req_metadata.keys() kkonganti@17: ): kkonganti@17: if not wrote_header_acc: kkonganti@17: msh_out_accs_txt = open(mash_uniq_accs_txt, "w") kkonganti@17: msh_out_txt.write("METADATA\nSEPARATOR COMMA\nFIELD_LABELS,") kkonganti@17: msh_out_txt.write( kkonganti@17: f"{','.join([str(key).upper() for key in req_metadata.keys()])}\nDATA\n" kkonganti@17: ) kkonganti@17: wrote_header_acc = True kkonganti@17: kkonganti@17: metadata_line = ",".join( kkonganti@17: [ kkonganti@17: re.sub( kkonganti@17: ",", kkonganti@17: "", kkonganti@17: "|".join(unpickled_acc2serotype[acc][m]), kkonganti@17: ) kkonganti@17: for m in req_metadata.keys() kkonganti@17: ], kkonganti@17: ) kkonganti@17: kkonganti@17: msh_out_txt.write(f"{acc.strip()},{metadata_line}\n") kkonganti@17: msh_out_accs_txt.write( kkonganti@17: f"{os.path.join(genomes_dir, acc + genomes_dir_suffix)}\n" kkonganti@17: ) kkonganti@17: seen_mash_sero[acc] = 1 kkonganti@17: seen_uniq_hits += 1 kkonganti@17: elif not isinstance(unpickled_acc2serotype[acc], dict): kkonganti@17: if unpickled_acc2serotype[acc] not in seen_mash_sero.keys(): kkonganti@17: seen_mash_sero[unpickled_acc2serotype[acc]] = 1 kkonganti@17: seen_uniq_hits += 1 kkonganti@17: # print(acc.strip() + '\t' + ident + '\t' + unpickled_acc2serotype[acc], file=sys.stdout) kkonganti@17: msh_out_txt.write( kkonganti@17: f"{acc.strip()}\t{unpickled_acc2serotype[acc]}\t{ident}\n" kkonganti@17: ) kkonganti@17: with open( kkonganti@17: os.path.join(genomes_dir, acc + genomes_dir_suffix), kkonganti@17: "rb", kkonganti@17: ) as msh_in_gz: kkonganti@17: msh_out_gz.writelines(msh_in_gz.readlines()) kkonganti@17: msh_in_gz.close() kkonganti@17: msh_out_gz.close() kkonganti@17: msh_out_txt.close() kkonganti@17: kkonganti@17: if "msh_out_accs_txt" in locals().keys() and not msh_out_accs_txt.closed: kkonganti@17: msh_out_accs_txt.close() kkonganti@17: if "mash_out_pop_txt" in locals().keys() and not mash_out_pop_txt.closed: kkonganti@17: mash_out_pop_txt.close() kkonganti@17: kkonganti@17: logging.info( kkonganti@17: f"File {os.path.basename(mash_genomes_gz)}\n" kkonganti@17: + f"written in:\n{os.getcwd()}\nDone! Bye!" kkonganti@17: ) kkonganti@17: exit(0) kkonganti@17: kkonganti@17: kkonganti@17: if __name__ == "__main__": kkonganti@17: main()