From b498f9ea914965e5574f3b4ee174773817c5698a Mon Sep 17 00:00:00 2001 From: Dennis Schmitz <48991783+DennisSchmitz@users.noreply.github.com> Date: Tue, 13 Feb 2024 14:38:39 +0100 Subject: [PATCH] initial commit cleaned up the private repo, committed to fresh public repo. Original public repo, versions <2.0, can be found here: https://github.com/DennisSchmitz/Jovian_archive --- Jovian/Jovian.py | 393 ++++++ Jovian/__init__.py | 6 + Jovian/functions.py | 200 +++ Jovian/runconfigs.py | 221 ++++ Jovian/samplesheet.py | 29 + Jovian/update.py | 91 ++ Jovian/workflow/Snakefile | 1104 +++++++++++++++++ Jovian/workflow/directories.py | 49 + .../envs/ancillary_files/Jovian_report.ipynb | 726 +++++++++++ .../envs/ancillary_files/acknowledgements.md | 44 + .../workflow/envs/ancillary_files/authors.md | 15 + .../envs/ancillary_files/default-site.conf | 47 + .../workflow/envs/ancillary_files/edit.json | 16 + .../envs/ancillary_files/notebook.json | 31 + .../envs/ancillary_files/overrides.css | 23 + .../workflow/envs/ancillary_files/tree.json | 5 + Jovian/workflow/envs/assembly.def | 19 + Jovian/workflow/envs/assembly.yaml | 12 + Jovian/workflow/envs/data_wrangling.def | 19 + Jovian/workflow/envs/data_wrangling.yaml | 12 + Jovian/workflow/envs/heatmaps.def | 19 + Jovian/workflow/envs/heatmaps.yaml | 13 + Jovian/workflow/envs/jovian_report.def | 66 + Jovian/workflow/envs/jovian_report.yaml | 22 + Jovian/workflow/envs/krona.def | 19 + Jovian/workflow/envs/krona.yaml | 12 + Jovian/workflow/envs/mgkit_lca.def | 19 + Jovian/workflow/envs/mgkit_lca.yaml | 12 + Jovian/workflow/envs/qc_and_clean.def | 19 + Jovian/workflow/envs/qc_and_clean.yaml | 24 + .../workflow/envs/scaffold_classification.def | 19 + .../envs/scaffold_classification.yaml | 9 + Jovian/workflow/envs/sequence_analysis.def | 19 + Jovian/workflow/envs/sequence_analysis.yaml | 21 + Jovian/workflow/files/Jovian_logo.svg | 43 + Jovian/workflow/files/html/1_header.html | 70 ++ .../files/html/3_tab_explanation.html | 9 + Jovian/workflow/files/html/5_js_begin.html | 10 + Jovian/workflow/files/html/7_js_end.html | 76 ++ Jovian/workflow/files/launch_report.sh | 40 + Jovian/workflow/files/multiqc_config.yaml | 20 + Jovian/workflow/files/nexteraPE_adapters.fa | 12 + .../scripts/average_logEvalue_no_lca.py | 61 + .../workflow/scripts/concat_filtered_vcf.py | 83 ++ .../scripts/concatenate_mapped_read_counts.py | 131 ++ Jovian/workflow/scripts/count_mapped_reads.sh | 32 + Jovian/workflow/scripts/draw_heatmaps.py | 910 ++++++++++++++ Jovian/workflow/scripts/fqc.sh | 47 + .../workflow/scripts/html/igvjs_write_divs.sh | 14 + .../html/igvjs_write_flex_js_middle.sh | 71 ++ .../workflow/scripts/html/igvjs_write_tabs.sh | 12 + Jovian/workflow/scripts/krona_magnitudes.py | 43 + Jovian/workflow/scripts/merge_data.py | 204 +++ Jovian/workflow/scripts/quantify_profiles.py | 906 ++++++++++++++ .../workflow/scripts/slurm-cluster-status.py | 71 ++ .../typingtool_EV_XML_to_csv_parser.py | 106 ++ .../typingtool_Flavi_XML_to_csv_parser.py | 94 ++ .../typingtool_HAV_XML_to_csv_parser.py | 87 ++ .../typingtool_HEV_XML_to_csv_parser.py | 88 ++ .../typingtool_NoV_XML_to_csv_parser.py | 116 ++ .../typingtool_PV_XML_to_csv_parser.py | 83 ++ .../typingtool_RVA_XML_to_csv_parser.py | 83 ++ Jovian/workflow/scripts/virus_typing.sh | 277 +++++ LICENSE | 661 ++++++++++ README.md | 303 +++++ env.yaml | 16 + mamba-env.yml | 16 + setup.py | 71 ++ 68 files changed, 8221 insertions(+) create mode 100644 Jovian/Jovian.py create mode 100644 Jovian/__init__.py create mode 100644 Jovian/functions.py create mode 100644 Jovian/runconfigs.py create mode 100644 Jovian/samplesheet.py create mode 100644 Jovian/update.py create mode 100644 Jovian/workflow/Snakefile create mode 100644 Jovian/workflow/directories.py create mode 100644 Jovian/workflow/envs/ancillary_files/Jovian_report.ipynb create mode 100644 Jovian/workflow/envs/ancillary_files/acknowledgements.md create mode 100644 Jovian/workflow/envs/ancillary_files/authors.md create mode 100644 Jovian/workflow/envs/ancillary_files/default-site.conf create mode 100644 Jovian/workflow/envs/ancillary_files/edit.json create mode 100644 Jovian/workflow/envs/ancillary_files/notebook.json create mode 100644 Jovian/workflow/envs/ancillary_files/overrides.css create mode 100644 Jovian/workflow/envs/ancillary_files/tree.json create mode 100644 Jovian/workflow/envs/assembly.def create mode 100644 Jovian/workflow/envs/assembly.yaml create mode 100644 Jovian/workflow/envs/data_wrangling.def create mode 100644 Jovian/workflow/envs/data_wrangling.yaml create mode 100644 Jovian/workflow/envs/heatmaps.def create mode 100644 Jovian/workflow/envs/heatmaps.yaml create mode 100644 Jovian/workflow/envs/jovian_report.def create mode 100644 Jovian/workflow/envs/jovian_report.yaml create mode 100644 Jovian/workflow/envs/krona.def create mode 100644 Jovian/workflow/envs/krona.yaml create mode 100644 Jovian/workflow/envs/mgkit_lca.def create mode 100644 Jovian/workflow/envs/mgkit_lca.yaml create mode 100644 Jovian/workflow/envs/qc_and_clean.def create mode 100644 Jovian/workflow/envs/qc_and_clean.yaml create mode 100644 Jovian/workflow/envs/scaffold_classification.def create mode 100644 Jovian/workflow/envs/scaffold_classification.yaml create mode 100644 Jovian/workflow/envs/sequence_analysis.def create mode 100644 Jovian/workflow/envs/sequence_analysis.yaml create mode 100644 Jovian/workflow/files/Jovian_logo.svg create mode 100644 Jovian/workflow/files/html/1_header.html create mode 100644 Jovian/workflow/files/html/3_tab_explanation.html create mode 100644 Jovian/workflow/files/html/5_js_begin.html create mode 100644 Jovian/workflow/files/html/7_js_end.html create mode 100644 Jovian/workflow/files/launch_report.sh create mode 100644 Jovian/workflow/files/multiqc_config.yaml create mode 100644 Jovian/workflow/files/nexteraPE_adapters.fa create mode 100644 Jovian/workflow/scripts/average_logEvalue_no_lca.py create mode 100644 Jovian/workflow/scripts/concat_filtered_vcf.py create mode 100644 Jovian/workflow/scripts/concatenate_mapped_read_counts.py create mode 100644 Jovian/workflow/scripts/count_mapped_reads.sh create mode 100644 Jovian/workflow/scripts/draw_heatmaps.py create mode 100644 Jovian/workflow/scripts/fqc.sh create mode 100644 Jovian/workflow/scripts/html/igvjs_write_divs.sh create mode 100644 Jovian/workflow/scripts/html/igvjs_write_flex_js_middle.sh create mode 100644 Jovian/workflow/scripts/html/igvjs_write_tabs.sh create mode 100644 Jovian/workflow/scripts/krona_magnitudes.py create mode 100644 Jovian/workflow/scripts/merge_data.py create mode 100644 Jovian/workflow/scripts/quantify_profiles.py create mode 100644 Jovian/workflow/scripts/slurm-cluster-status.py create mode 100644 Jovian/workflow/scripts/typingtool_EV_XML_to_csv_parser.py create mode 100644 Jovian/workflow/scripts/typingtool_Flavi_XML_to_csv_parser.py create mode 100644 Jovian/workflow/scripts/typingtool_HAV_XML_to_csv_parser.py create mode 100644 Jovian/workflow/scripts/typingtool_HEV_XML_to_csv_parser.py create mode 100644 Jovian/workflow/scripts/typingtool_NoV_XML_to_csv_parser.py create mode 100644 Jovian/workflow/scripts/typingtool_PV_XML_to_csv_parser.py create mode 100644 Jovian/workflow/scripts/typingtool_RVA_XML_to_csv_parser.py create mode 100644 Jovian/workflow/scripts/virus_typing.sh create mode 100644 LICENSE create mode 100644 README.md create mode 100644 env.yaml create mode 100644 mamba-env.yml create mode 100644 setup.py diff --git a/Jovian/Jovian.py b/Jovian/Jovian.py new file mode 100644 index 0000000..593bd1b --- /dev/null +++ b/Jovian/Jovian.py @@ -0,0 +1,393 @@ +""" +Starting point of the Jovian metagenomic pipeline and wrapper +Authors: + Dennis Schmitz, Florian Zwagemaker, Sam Nooij, Robert Verhagen, + Karim Hajji, Jeroen Cremer, Thierry Janssens, Mark Kroon, Erwin + van Wieringen, Harry Vennema, Miranda de Graaf, Annelies Kroneman, + Jeroen Laros, Marion Koopmans +Organization: + Rijksinstituut voor Volksgezondheid en Milieu (RIVM) + Dutch Public Health institute (https://www.rivm.nl/en) + Erasmus Medical Center (EMC) Rotterdam (https://www.erasmusmc.nl/en) +Departments: + RIVM Virology, RIVM Bioinformatics, EMC Viroscience +Date and license: + 2018 - present, AGPL3 (https://www.gnu.org/licenses/agpl-3.0.en.html) +Homepage containing documentation, examples and changelog: + https://github.com/DennisSchmitz/jovian +Funding: + This project/research has received funding from the European Union's + Horizon 2020 research and innovation programme under grant agreement + No. 643476. +Automation: + iRODS automatically executes this workflow for the "vir-ngs" project +""" + +import argparse +import multiprocessing +import os +import pathlib +import sys + +import snakemake +import yaml + +from Jovian import __home_env_configuration__, __package_name__, __version__ +from Jovian.functions import MyHelpFormatter, color +from Jovian.runconfigs import WriteConfigs +from Jovian.samplesheet import WriteSampleSheet +from Jovian.update import update + +yaml.warnings({"YAMLLoadWarning": False}) + + +def get_args(givenargs): + """ + Parse the command line arguments + """ + + def dir_path(arginput): + if os.path.isdir(arginput): + return arginput + print(f'"{arginput}" is not a directory. Exiting...') + sys.exit(1) + + def currentpath(): + return os.getcwd() + + arg = argparse.ArgumentParser( + prog=__package_name__, + usage="%(prog)s [required arguments] [optional arguments]", + description="%(prog)s: a metagenomic analysis workflow for public health and clinics with interactive reports in your web-browser\n\n" + + "NB default database paths are hardcoded for RIVM users, otherwise, specify your own database paths using the optional arguments.\n" + + "On subsequent invocations of %(prog)s, the database paths will be read from the file located at: " + + __home_env_configuration__ + + " and you will not have to provide them again.\n" + + "Similarly, the default RIVM queue is provided as a default value for the '--queuename' flag, but you can override this value if you want to use a different queue.\n", + formatter_class=MyHelpFormatter, + add_help=False, + ) + + required_args = arg.add_argument_group("Required arguments") + optional_args = arg.add_argument_group("Optional arguments") + + required_args.add_argument( + "--input", + "-i", + type=dir_path, + metavar="DIR", + help="The input directory containing the raw fastq(.gz) files", + required=True, + ) + + required_args.add_argument( + "--output", + "-o", + metavar="DIR", + type=str, + default=currentpath(), + help="Output directory", + required=True, + ) + + optional_args.add_argument( + "--reset-db-paths", + action="store_true", + help="Reset the database paths to the default values", + ) + + optional_args.add_argument( + "--background", + type=str, + metavar="File", + help="Override the default human genome background path", + required=False, + ) + + optional_args.add_argument( + "--blast-db", + type=str, + metavar="Path", + help="Override the default BLAST NT database path", + required=False, + ) + + optional_args.add_argument( + "--blast-taxdb", + type=str, + metavar="Path", + help="Override the default BLAST taxonomy database path", + required=False, + ) + + optional_args.add_argument( + "--mgkit-db", + type=str, + metavar="Path", + help="Override the default MGKit database path", + required=False, + ) + + optional_args.add_argument( + "--krona-db", + type=str, + metavar="Path", + help="Override the default Krona database path", + required=False, + ) + + optional_args.add_argument( + "--virus-host-db", + type=str, + metavar="File", + help="Override the default virus-host database path (https://www.genome.jp/virushostdb/)", + required=False, + ) + + optional_args.add_argument( + "--new-taxdump-db", + type=str, + metavar="Path", + help="Override the default new taxdump database path", + required=False, + ) + + optional_args.add_argument( + "--version", + "-v", + version=__version__, + action="version", + help="Show %(prog)s version and exit", + ) + + optional_args.add_argument( + "--help", + "-h", + action="help", + default=argparse.SUPPRESS, + help="Show this help message and exit", + ) + + optional_args.add_argument("--skip-updates", action="store_true", help="Skip the update check") + + optional_args.add_argument( + "--local", + action="store_true", + help="Use %(prog)s locally instead of in a grid-computing configuration", + ) + + optional_args.add_argument( + "--slurm", + action="store_true", + help="Use SLURM instead of the default DRMAA for grid execution (default: DRMAA)", + ) + + optional_args.add_argument( + "--queuename", + default="bio", + type=str, + metavar="NAME", + help="Name of the queue to use for grid execution (default: bio)", + ) + + optional_args.add_argument( + "--conda", + action="store_true", + help="Use conda environments instead of the default singularity images (default: False)", + ) + + optional_args.add_argument( + "--dryrun", + action="store_true", + help="Run the %(prog)s workflow without actually doing anything to confirm that the workflow will run as expected", + ) + + optional_args.add_argument( + "--threads", + default=min(multiprocessing.cpu_count(), 128), + type=int, + metavar="N", + help=f"Number of local threads that are available to use.\nDefault is the number of available threads in your system ({min(multiprocessing.cpu_count(), 128)})", + ) + + optional_args.add_argument( + "--minphredscore", + default=20, + type=int, + metavar="N", + help="Minimum phred score to be used for QC trimming (default: 20)", + ) + + optional_args.add_argument( + "--minreadlength", + default=50, + type=int, + metavar="N", + help="Minimum read length to used for QC trimming (default: 50)", + ) + + optional_args.add_argument( + "--mincontiglength", + default=250, + type=int, + metavar="N", + help="Minimum contig length to be analysed and included in the final output (default: 250)", + ) + + if len(givenargs) < 1: + print(f"{arg.prog} was called but no arguments were given, please try again \n\tUse '{arg.prog} -h' to see the help document") + sys.exit(1) + else: + flags = arg.parse_args(givenargs) + return flags + + +def CheckInputFiles(indir): + """ + Check if the input files are valid fastq files + """ + allowedextensions = [".fastq", ".fq", ".fastq.gz", ".fq.gz"] + foundfiles = [] + + for filenames in os.listdir(indir): + extensions = "".join(pathlib.Path(filenames).suffixes) + foundfiles.append(extensions) + + return any((i in allowedextensions for i in foundfiles)) + + +def main(): + """ + Jovian starting point + """ + + flags = get_args(sys.argv[1:]) + + if flags.reset_db_paths: + os.remove(__home_env_configuration__) + sys.exit(f'Removed "{__home_env_configuration__}", database paths are now reset. Exiting...') + + if not flags.skip_updates: + update(sys.argv) + + inpath = os.path.abspath(flags.input) + outpath = os.path.abspath(flags.output) + exec_folder = os.path.abspath(os.path.dirname(__file__)) + + Snakefile = os.path.join(exec_folder, "workflow", "Snakefile") + + if CheckInputFiles(inpath) is False: + print( + f""" +{color.RED + color.BOLD}"{inpath}" does not contain any valid FastQ files.{color.END} +Please check the input directory and try again. Exiting... + """ + ) + sys.exit(1) + else: + print( + f""" +{color.GREEN}Valid input files were found in the input directory{color.END} ('{inpath}') + """ + ) + if not os.path.exists(outpath): + os.makedirs(outpath) + + if os.getcwd() != outpath: + os.chdir(outpath) + workdir = outpath + + samplesheet = WriteSampleSheet(inpath) + + paramfile, _conffile, _paramdict, confdict = WriteConfigs( + samplesheet, + flags.threads, + flags.queuename, + os.getcwd(), + flags.local, + flags.minphredscore, + flags.minreadlength, + flags.mincontiglength, + flags.conda, + flags.background, + flags.blast_db, + flags.blast_taxdb, + flags.mgkit_db, + flags.krona_db, + flags.virus_host_db, + flags.new_taxdump_db, + flags.dryrun, + inpath, + ) + + # Snakemake command and params for "local" execution + if flags.local is True: + status = snakemake.snakemake( + Snakefile, + workdir=workdir, + conda_frontend="conda", # TODO had to change frontend from `mamba` to `conda`, for some reason the installation of `Sequence_analysis.yaml` is incompatible with the `mamba` frontend... Works fine in `singularity` though... + cores=confdict["cores"], + use_conda=confdict["use-conda"], + use_singularity=confdict["use-singularity"], + singularity_args=confdict["singularity-args"], + jobname=confdict["jobname"], + latency_wait=confdict["latency-wait"], + dryrun=confdict["dryrun"], + printshellcmds=confdict["printshellcmds"], + printreason=confdict["printreason"], + configfiles=[paramfile], + restart_times=3, + ) + # Snakemake command and params for "grid" execution + if flags.local is False and flags.slurm is False: + status = snakemake.snakemake( + Snakefile, + workdir=workdir, + conda_frontend="conda", # TODO had to change frontend from `mamba` to `conda`, for some reason the installation of `Sequence_analysis.yaml` is incompatible with the `mamba` frontend... Works fine in `singularity` though... + cores=confdict["cores"], + nodes=confdict["cores"], + use_conda=confdict["use-conda"], + use_singularity=confdict["use-singularity"], + singularity_args=confdict["singularity-args"], + jobname=confdict["jobname"], + latency_wait=confdict["latency-wait"], + drmaa=confdict["drmaa"], + drmaa_log_dir=confdict["drmaa-log-dir"], + dryrun=confdict["dryrun"], + printshellcmds=confdict["printshellcmds"], + printreason=confdict["printreason"], + configfiles=[paramfile], + restart_times=3, + ) + + # Snakemake command and params for "grid" execution but using SLURM instead of DRMAA + if flags.local is False and flags.slurm is True: + status = snakemake.snakemake( + Snakefile, + workdir=workdir, + conda_frontend="conda", # TODO had to change frontend from `mamba` to `conda`, for some reason the installation of `Sequence_analysis.yaml` is incompatible with the `mamba` frontend... Works fine in `singularity` though... + cores=confdict["cores"], + nodes=confdict["cores"], + use_conda=confdict["use-conda"], + use_singularity=confdict["use-singularity"], + singularity_args=confdict["singularity-args"], + jobname=confdict["jobname"], + latency_wait=confdict["latency-wait"], + cluster=confdict["cluster"], + cluster_status=confdict["cluster-status"], + dryrun=confdict["dryrun"], + printshellcmds=confdict["printshellcmds"], + printreason=confdict["printreason"], + configfiles=[paramfile], + restart_times=3, + ) + + # Snakemake command for making the snakemake report only + if confdict["dryrun"] is False and status is True: + snakemake.snakemake( + Snakefile, + workdir=workdir, + report="results/snakemake_report.html", + configfiles=[paramfile], + quiet=True, + ) diff --git a/Jovian/__init__.py b/Jovian/__init__.py new file mode 100644 index 0000000..dc1e52b --- /dev/null +++ b/Jovian/__init__.py @@ -0,0 +1,6 @@ +import os + +__version__ = "0.1.0" +__package_name__ = "Jovian" +__package_dir__ = os.path.dirname(os.path.abspath(__file__)) +__home_env_configuration__ = os.path.join(os.path.expanduser("~"), ".jovian_env.yaml") diff --git a/Jovian/functions.py b/Jovian/functions.py new file mode 100644 index 0000000..735a003 --- /dev/null +++ b/Jovian/functions.py @@ -0,0 +1,200 @@ +# pylint: disable=C0103.C0301 + +""" +Basic functions for various uses throughout Jovian +""" + +import argparse +import glob +import os +import readline +import shutil + +from Jovian import __package_dir__ + + +class MyHelpFormatter(argparse.RawTextHelpFormatter): + """ + This is a custom formatter class for argparse. It allows for some custom formatting, + in particular for the help texts with multiple options (like bridging mode and verbosity level). + http://stackoverflow.com/questions/3853722 + """ + + def __init__(self, prog): + terminal_width = shutil.get_terminal_size().columns + os.environ["COLUMNS"] = str(terminal_width) + max_help_position = min(max(24, terminal_width // 2), 80) + super().__init__(prog, max_help_position=max_help_position) + + def _get_help_string(self, action): + help_text = action.help + if action.default != argparse.SUPPRESS and "default" not in help_text.lower() and action.default is not None: + help_text += f" (default: {str(action.default)})" + return help_text + + +class color: + """ + define basic colors to use in the terminal + """ + + PURPLE = "\033[95m" + CYAN = "\033[96m" + DARKCYAN = "\033[36m" + BLUE = "\033[94m" + GREEN = "\033[92m" + YELLOW = "\033[93m" + RED = "\033[91m" + BOLD = "\033[1m" + UNDERLINE = "\033[4m" + END = "\033[0m" + + +# tabCompleter Class taken from https://gist.github.com/iamatypeofwalrus/5637895 +## this was intended for the raw_input() function of python. But that one is deprecated now +## this also seems to work for the new input() functions however so muy bueno +#! use the gnureadline module instead of readline module +##! the 'normal' readline module causes a bug with memory pointers +##! --> https://stackoverflow.com/questions/43013060/python-3-6-1-crashed-after-i-installed-readline-module +class tabCompleter: + """ + A tab completer that can either complete from + the filesystem or from a list. + + Partially taken from: + http://stackoverflow.com/questions/5637124/tab-completion-in-pythons-raw-input + """ + + def pathCompleter(self, text, state): + """ + This is the tab completer for systems paths. + Only tested on *nix systems + """ + line = readline.get_line_buffer().split() + + # replace ~ with the user's home dir. See https://docs.python.org/2/library/os.path.html + if "~" in text: + text = os.path.expanduser("~") + + # autocomplete directories with having a trailing slash + if os.path.isdir(text): + text += "/" + + return list(glob.glob(f"{text}*"))[state] + + def createListCompleter(self, ll): + """ + This is a closure that creates a method that autocompletes from + the given list. + + Since the autocomplete function can't be given a list to complete from + a closure is used to create the listCompleter function with a list to complete + from. + """ + + def listCompleter(text, state): + line = readline.get_line_buffer() + + if not line: + return [f"{c} " for c in ll][state] + + return [f"{c} " for c in ll if c.startswith(line)][state] + + self.listCompleter = listCompleter + + +def get_max_local_mem(): + mem = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") + return int(round(mem / (1024.0**2) - 2000, -3)) + + +class DefaultConfig: + """ + This class is the wrapper class for the default config dictionary + """ + + config = { + "local": { + "cores": 12, + "latency-wait": 60, + "use-conda": False, + "use-singularity": True, + "singularity-args": "", + "dryrun": False, + "printshellcmds": False, # ? For debugging only + "printreason": False, # ? For debugging only + "jobname": "Jovian_{name}.{jobid}", + }, + "grid": { + "cores": 300, + "latency-wait": 60, + "use-conda": False, + "use-singularity": True, + "singularity-args": "", + "dryrun": False, + "printshellcmds": False, # ? For debugging only + "printreason": False, # ? For debugging only + "jobname": "Jovian_{name}.{jobid}", + "drmaa": ' -q PLACEHOLDER -n {threads} -R "span[hosts=1]" -M {resources.mem_mb}', # ? PLACEHOLDER will be replaced by queuename supplied in CLI; default = "bio" + "drmaa-log-dir": "logs/drmaa", + "cluster": "sbatch -p PLACEHOLDER --parsable -N1 -n1 -c{threads} --mem={resources.mem_mb} -D . -o logs/SLURM/Jovian_{name}-{jobid}.out -e logs/SLURM/Jovian_{name}-{jobid}.err", # ? PLACEHOLDER will be replaced by queuename supplied in CLI; default = "bio" + "cluster-status": f"{__package_dir__}/workflow/scripts/slurm-cluster-status.py", + }, + } + params = { + "sample_sheet": "samplesheet.yaml", + "threads": { + "Alignments": 12, + "Filter": 6, + "Assemble": 14, + "MultiQC": 1, + "align_to_scaffolds_RmDup_FragLength": 4, + "SNP_calling": 12, + "ORF_analysis": 1, + "Contig_metrics": 1, + "GC_content": 1, + "Scaffold_classification": 12, + "mgkit_lca": 1, + "data_wrangling": 1, + "krona": 1, + }, + "computing_execution": "grid", + "use_singularity_or_conda": "use_singularity", + "max_local_mem": get_max_local_mem(), + "QC": { + "min_phred_score": 20, # ? this is overwritten by the value supplied in the wrapper CLI + "window_size": 5, + "min_read_length": 50, # ? this is overwritten by the value supplied in the wrapper CLI + }, + "Assembly": { + "min_contig_len": 250, # ? this is overwritten by the value supplied in the wrapper CLI + "kmersizes": "21,33,55,77", + }, + "db": { # ? These are set either by the defaults listed below or the user-specified path, see WriteConfigs() + "background": "", + "blast_nt": "", + "blast_taxdb": "", + "mgkit_db": "", + "krona_db": "", + "virus_host_db": "", + "new_taxdump_db": "", + }, + "db_defaults_local": { + "background": "/mnt/db/Jov2/HuGo_GRCh38_NoDecoy_NoEBV/genome.fa", + "blast_nt": "/mnt/db/Jov2/NT_database/nt", + "blast_taxdb": "/mnt/db/Jov2/taxdb/", + "mgkit_db": "/mnt/db/Jov2/mgkit_db/", + "krona_db": "/mnt/db/Jov2/krona_db/", + "virus_host_db": "/mnt/db/Jov2/virus_host_db/virushostdb.tsv", + "new_taxdump_db": "/mnt/db/Jov2/new_taxdump/", + }, + "db_defaults_grid": { + "background": "/data/BioGrid/schmitzd/20220428_databases_jov2/HuGo_GRCh38_NoDecoy_NoEBV/genome.fa", + "blast_nt": "/data/BioGrid/schmitzd/20220428_databases_jov2/NT_database/nt", + "blast_taxdb": "/data/BioGrid/schmitzd/20220428_databases_jov2/taxdb/", + "mgkit_db": "/data/BioGrid/schmitzd/20220428_databases_jov2/mgkit_db/", + "krona_db": "/data/BioGrid/schmitzd/20220428_databases_jov2/krona_db/", + "virus_host_db": "/data/BioGrid/schmitzd/20220428_databases_jov2/virus_host_db/virushostdb.tsv", + "new_taxdump_db": "/data/BioGrid/schmitzd/20220428_databases_jov2/new_taxdump/", + }, + } diff --git a/Jovian/runconfigs.py b/Jovian/runconfigs.py new file mode 100644 index 0000000..fb886a2 --- /dev/null +++ b/Jovian/runconfigs.py @@ -0,0 +1,221 @@ +""" +Construct and write configuration files for Jovian. +""" + +import multiprocessing +import os +import sys + +import yaml + +from Jovian import __home_env_configuration__ + +from .functions import DefaultConfig + + +def set_cores(cores: int) -> int: + """ + Set the maximum (viable) number of cores to max - 2, allotting two threads for overhead + """ + max_available = multiprocessing.cpu_count() + return max_available - 2 if cores >= max_available else cores + + +def user_supplied_db_paths(background, blast_nt, blast_taxdb, mgkit_db, krona_db, virus_host_db, new_taxdump_db) -> None: + """ + If user-supplied database paths are given, set them in DefaultConfig.params["db"]KEY + + Inputs of this function are the database paths as provided to the wrapper by the user. + """ + #! When adding/removing database flags/path also update check_validity_db_paths() + if background is not None: + DefaultConfig.params["db"]["background"] = background + if blast_nt is not None: + DefaultConfig.params["db"]["blast_nt"] = blast_nt + if blast_taxdb is not None: + DefaultConfig.params["db"]["blast_taxdb"] = blast_taxdb + if mgkit_db is not None: + DefaultConfig.params["db"]["mgkit_db"] = mgkit_db + if krona_db is not None: + DefaultConfig.params["db"]["krona_db"] = krona_db + if virus_host_db is not None: + DefaultConfig.params["db"]["virus_host_db"] = virus_host_db + if new_taxdump_db is not None: + DefaultConfig.params["db"]["new_taxdump_db"] = new_taxdump_db + + +def write_user_supplied_db_paths_to_home_dir_env() -> None: + """ + DefaultConfig.params["db"] is non-empty if the user supplied database paths, so, store non-empty + values permanently in a hidden configuration YAML file in the user's HOME so they do not have to + supply it each time they run the wrapper. + """ + db_paths = {key: value for key, value in DefaultConfig.params["db"].items() if value} + with open(__home_env_configuration__, "w", encoding="utf-8") as yaml_file: + yaml.dump(db_paths, yaml_file, default_flow_style=False) + + +def set_db_paths(local: bool) -> None: + """ + If no user-supplied database paths are given (user_supplied_db_paths()) nor have they have been + stored in the config file in the user's home-dir (write_user_supplied_db_paths_to_home_dir_env()), + set default paths for local or grid-computation from DefaultConfig.params["db_defaults_local"] + and DefaultConfig.params["db_defaults_grid"], respectively. NB defaults are configured for usage + with default RIVM paths. + + local = boolean, was `--local` flag invoked or not, i.e. local or grid execution + """ + if os.path.exists(__home_env_configuration__): + with open(__home_env_configuration__, "r", encoding="utf-8") as yaml_file: + previously_stored_db_paths = yaml.safe_load(yaml_file) + + # ? If db-paths were previously stored, update the DefaultConfig.params["db"] dictionary with these paths, then they are not overwritten with the RIVMs default paths downstream since they are not empty + if previously_stored_db_paths and isinstance(previously_stored_db_paths, dict): + for key, value in previously_stored_db_paths.items(): + if key in DefaultConfig.params["db"]: + DefaultConfig.params["db"][key] = value + + for key in DefaultConfig.params["db"].keys(): + if not DefaultConfig.params["db"][key]: + if local: # ? Set local compute default paths if empty, i.e. no user-supplied path + DefaultConfig.params["db"][key] = DefaultConfig.params["db_defaults_local"][key] + else: # ? Set grid compute default paths if empty, i.e. no user-supplied path + DefaultConfig.params["db"][key] = DefaultConfig.params["db_defaults_grid"][key] + + +def check_validity_db_paths() -> None: + """ + Check if all the database root folders exist and/or files exist. Exit if not true. + """ + #! When adding/removing database flags/path also update user_supplied_db_paths() + try: + for filename in [DefaultConfig.params["db"]["background"], DefaultConfig.params["db"]["virus_host_db"]]: + if not os.path.exists(filename): + raise FileNotFoundError(filename) + for filepath in [ + DefaultConfig.params["db"]["blast_nt"], + DefaultConfig.params["db"]["blast_taxdb"], + DefaultConfig.params["db"]["krona_db"], + DefaultConfig.params["db"]["new_taxdump_db"], + DefaultConfig.params["db"]["mgkit_db"], + ]: + if not os.path.exists(os.path.dirname(filepath)): + raise FileNotFoundError(filepath) + except FileNotFoundError as error_message: + sys.exit(f"This file or folder is not available or accessible: {error_message}\nExiting...") + + +def WriteConfigs( + samplesheet, + cores, + queuename, + cwd, + local, + minphredscore, + minreadlength, + mincontiglength, + conda, + background, + blast_nt, + blast_taxdb, + mgkit_db, + krona_db, + virus_host_db, + new_taxdump_db, + dryrun, + inpath, +): + """ + Write the config files needed for proper functionality. Includes + database paths, singularity binds, --local mode core-counts, etc. + are all set here. + """ + + def use_conda(configuration: dict, parameter: dict) -> None: + "Use conda instead of Singularity; not recommended, only for debug purposes" + configuration["use-conda"] = True + configuration["use-singularity"] = False + parameter["use_singularity_or_conda"] = "use_conda" + + def update_queuename(configuration: dict, queuename: str) -> None: + "Update the queuename in the configuration file with the user-supplied queuename" + + def update_queuename(key: str) -> None: + value = configuration[key] + value = value.replace("PLACEHOLDER", queuename) + configuration[key] = value + + update_queuename("drmaa") + update_queuename("cluster") + + def set_no_threads_local_mode(configuration: dict, parameter: dict) -> None: + "Update the threads used per rule based on system specs. NB this is only needed for --local mode" + configuration["cores"] = set_cores(cores) + parameter["computing_execution"] = "local" + + def setup_singularity_mountpoints() -> str: + "Setup the singularity mount-points and returns this as a _single_ big string used to update config file" + # ? Bind the necessary folders to the singularity containers. Including Jovian's scripts/ and files/ folders, but also the input directory and reference basepath supplied by the user through the wrapper. + # ? Line below makes an anchor, below this location you"ll find ./workflow/scripts/ and ./workflow/files/ as installed by pip. Anchor to: `**/conda/envs/[PACKAGE_NAME]/lib/python3.7/site-packages/[PACKAGE_NAME]/` + exec_folder = os.path.abspath(os.path.dirname(__file__)) + scripts_folder = os.path.join(exec_folder, "workflow/", "scripts/") + files_folder = os.path.join(exec_folder, "workflow/", "files/") + + # ! This is a single big string split over multiple lines, not a list + singularity_mount_points = ( + f"--bind {scripts_folder}:/Jovian/scripts --bind {files_folder}:/Jovian/files --bind {inpath}:{inpath} " + f"--bind {os.path.dirname(DefaultConfig.params['db']['background'])}:{os.path.dirname(DefaultConfig.params['db']['background'])} " + f"--bind {os.path.dirname(DefaultConfig.params['db']['blast_nt'])}:{os.path.dirname(DefaultConfig.params['db']['blast_nt'])} " + f"--bind {os.path.dirname(DefaultConfig.params['db']['blast_taxdb'])}:{os.path.dirname(DefaultConfig.params['db']['blast_taxdb'])} " + f"--bind {os.path.dirname(DefaultConfig.params['db']['mgkit_db'])}:{os.path.dirname(DefaultConfig.params['db']['mgkit_db'])} " + f"--bind {os.path.dirname(DefaultConfig.params['db']['krona_db'])}:{os.path.dirname(DefaultConfig.params['db']['krona_db'])} " + f"--bind {os.path.dirname(DefaultConfig.params['db']['virus_host_db'])}:{os.path.dirname(DefaultConfig.params['db']['virus_host_db'])} " + f"--bind {os.path.dirname(DefaultConfig.params['db']['new_taxdump_db'])}:{os.path.dirname(DefaultConfig.params['db']['new_taxdump_db'])}" + ) + return singularity_mount_points + + # ? Make folder to store config and param files + if not os.path.exists(f"{cwd}/config"): + os.makedirs(f"{cwd}/config") + + # ! Below, update the parameters. I.e. values that are used by the Snakefile/rules itself + parameter_dict = DefaultConfig.params # ? Load default params, will be updated downstream + parameter_dict["QC"]["min_phred_score"] = minphredscore # ? Based on user supplied value + parameter_dict["QC"]["min_read_length"] = minreadlength # ? Based on user supplied value + parameter_dict["Assembly"]["min_contig_len"] = mincontiglength # ? Based on user supplied value + # ? set proper database paths, if none are given by the user, set default paths based on grid or local compute mode + user_supplied_db_paths(background, blast_nt, blast_taxdb, mgkit_db, krona_db, virus_host_db, new_taxdump_db) + write_user_supplied_db_paths_to_home_dir_env() + set_db_paths(local) + check_validity_db_paths() + + # ! Below, update the configurations. I.e. values that are used by the Snakemake engine/wrapper itself + singularity_mount_points = setup_singularity_mountpoints() # ? setup singularity mountpoints based on installation location of this package + + # ! Load the configs specific to either local execution or grid execution + if local is True: + configuration_dict = DefaultConfig.config["local"] + # ? The ` --bind /run/shm:/run/shm` addition is to make the Py multiprocessing of `lofreq` work, it requires write permissions to /run/shm. See similar issue here https://github.com/nipreps/fmriprep/issues/780 + DefaultConfig.config["local"]["singularity-args"] = f"{singularity_mount_points} --bind /run/shm:/run/shm" + set_no_threads_local_mode(configuration_dict, parameter_dict) + else: # ! I.e. it will run in "grid" mode + configuration_dict = DefaultConfig.config["grid"] + update_queuename(configuration_dict, queuename) + DefaultConfig.config["grid"]["singularity-args"] = singularity_mount_points + + # ! Configure configuration values that are independent on whether it's local or grid + parameter_dict["sample_sheet"] = samplesheet # ? Load sample_sheet + if dryrun is True: + configuration_dict["dryrun"] = True + if conda is True: + use_conda(configuration_dict, parameter_dict) + + # ! Write final config and params yaml files for audit-trail + parameter_file_path = f"{cwd}/config/params.yaml" + configuration_file_path = f"{cwd}/config/config.yaml" + with open(parameter_file_path, "w", encoding="utf-8") as outfile: + yaml.dump(parameter_dict, outfile, default_flow_style=False) + with open(configuration_file_path, "w", encoding="utf-8") as outfile: + yaml.dump(configuration_dict, outfile, default_flow_style=False) + + return parameter_file_path, configuration_file_path, parameter_dict, configuration_dict diff --git a/Jovian/samplesheet.py b/Jovian/samplesheet.py new file mode 100644 index 0000000..f3b5d32 --- /dev/null +++ b/Jovian/samplesheet.py @@ -0,0 +1,29 @@ +""" +Write the samplesheets +""" + +import os +import re + +import yaml + + +def illumina_sheet(inputdir, sheet): + illuminapattern = re.compile(r"(.*)(_|\.)R?(1|2)(?:_.*\.|\..*\.|\.)f(ast)?q(\.gz)?") + samples = {} + for dirname, subdir, filename in os.walk(inputdir): + for files in filename: + fullpath = os.path.join(dirname, files) + match = illuminapattern.fullmatch(files) + if match: + sample = samples.setdefault(match.group(1), {}) + sample["R{}".format(match.group(3))] = str(fullpath) + with open(sheet, "w") as samplesheet: + yaml.dump(samples, samplesheet, default_flow_style=False) + samplesheet.close() + + +def WriteSampleSheet(inputdir): + illumina_sheet(inputdir, "samplesheet.yaml") + samplesheet = os.getcwd() + "/samplesheet.yaml" + return samplesheet diff --git a/Jovian/update.py b/Jovian/update.py new file mode 100644 index 0000000..32d51a2 --- /dev/null +++ b/Jovian/update.py @@ -0,0 +1,91 @@ +import json +import readline +import subprocess +import sys +from distutils.version import LooseVersion +from urllib import request + +from Jovian import __version__ + +from .functions import color, tabCompleter + + +def AskPrompts(intro, prompt, options, fixedchoices=False): + if fixedchoices is True: + completer = tabCompleter() + completer.createListCompleter(options) + + readline.set_completer_delims("\t") + readline.parse_and_bind("tab: complete") + readline.set_completer(completer.listCompleter) + + subprocess.call("/bin/clear", shell=False) + print(intro) + while "the answer is invalid": + if fixedchoices is True: + reply = input(prompt).lower().strip() + if reply in options: + return reply + if reply == "quit": + print("Quitting...") + sys.exit(-1) + else: + print("The given answer was invalid. Please choose one of the available options\n") + if fixedchoices is False: + reply = input(prompt).strip() + if reply == "quit": + sys.exit(-1) + else: + return reply + + +def update(sysargs): + + try: + latest_release = request.urlopen("https://api.github.com/repos/DennisSchmitz/jovian/releases/latest") + except Exception as e: + sys.stderr.write("Unable to connect to GitHub API\n" f"{e}") + return + + latest_release = json.loads(latest_release.read().decode("utf-8")) + + latest_release_tag = latest_release["tag_name"] + latest_release_tag_tidied = LooseVersion(latest_release["tag_name"].lstrip("v").strip()) + + localversion = LooseVersion(__version__) + + if localversion < latest_release_tag_tidied: + if ( + AskPrompts( + f""" +There's a new version of Jovian available. +Current version: {color.RED + color.BOLD}{'v' + __version__}{color.END} +Latest version: {color.GREEN + color.BOLD}{latest_release_tag}{color.END}\n""", + f"""Do you want to update? [yes/no] """, + ["yes", "no"], + fixedchoices=True, + ) + == "yes" + ): + subprocess.run( + [ + sys.executable, + "-m", + "pip", + "install", + "--upgrade", + f"git+https://github.com/DennisSchmitz/jovian@{latest_release_tag}", + ], + check=True, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + print(f"Jovian updated to {color.YELLOW + color.BOLD}{latest_release_tag}{color.END}") + + subprocess.run(sysargs) + sys.exit(0) + print(f"Skipping update to version {latest_release_tag}") + print(f"Continuing...") + return + return diff --git a/Jovian/workflow/Snakefile b/Jovian/workflow/Snakefile new file mode 100644 index 0000000..73a798b --- /dev/null +++ b/Jovian/workflow/Snakefile @@ -0,0 +1,1104 @@ +""" +Starting point of the Jovian metagenomic pipeline and wrapper +Authors: + Dennis Schmitz, Florian Zwagemaker, Sam Nooij, Robert Verhagen, + Karim Hajji, Jeroen Cremer, Thierry Janssens, Mark Kroon, Erwin + van Wieringen, Harry Vennema, Miranda de Graaf, Annelies Kroneman, + Jeroen Laros, Marion Koopmans +Organization: + Rijksinstituut voor Volksgezondheid en Milieu (RIVM) + Dutch Public Health institute (https://www.rivm.nl/en) + Erasmus Medical Center (EMC) Rotterdam (https://www.erasmusmc.nl/en) +Departments: + RIVM Virology, RIVM Bioinformatics, EMC Viroscience +Date and license: + 2018 - present, AGPL3 (https://www.gnu.org/licenses/agpl-3.0.en.html) +Homepage containing documentation, examples and changelog: + https://github.com/DennisSchmitz/jovian +Funding: + This project/research has received funding from the European Union's + Horizon 2020 research and innovation programme under grant agreement + No. 643476. +Automation: + iRODS automatically executes this workflow for the "vir-ngs" project +""" + +import pprint +import yaml +import os +import sys +import json +from directories import * +import snakemake + +snakemake.utils.min_version("6.0") + +yaml.warnings({'YAMLLoadWarning': False}) +shell.executable('/bin/bash') + +SAMPLES = {} + +with open("samplesheet.yaml") as sheetfile: + SAMPLES = yaml.safe_load(sheetfile) + +def low_memory_job(wildcards, threads, attempt): + if config['computing_execution'] == 'local': + return min(attempt * threads * 1 * 1000, config['max_local_mem']) + return attempt * threads * 1 * 1000 + +def medium_memory_job(wildcards, threads, attempt): + if config['computing_execution'] == 'local': + return min(attempt * threads * 2 * 1000, config['max_local_mem']) + return attempt * threads * 2 * 1000 + +def high_memory_job(wildcards, threads, attempt): + if config['computing_execution'] == 'local': + return min(attempt * threads * 4 * 1000, config['max_local_mem']) + return attempt * threads * 4 * 1000 + +def very_high_memory_job(wildcards, threads, attempt): + if config['computing_execution'] == 'local': + return min(attempt * threads * 4 * 1.75 * 1000, config['max_local_mem']) + return attempt * threads * 4 * 1.75 * 1000 + + +# low_runtime_min = 60 # ? Schudeler sends jobs <= 1h runtime to the 6 additional nodes +# high_runtime_min = 3000 # ? Little over two days + + +localrules: + all, + Copy_scaffolds, + concat_files, + concat_filtered_SNPs, + HTML_IGVjs_variable_parts, + HTML_IGVjs_final + + +rule all: + input: + f"{res}multiqc.html", + expand("{p}{sample}_scaffolds.fasta", p = f"{res+scf}", sample = SAMPLES), + expand("{p}{sample}_{ext}", p = f"{datadir + asm + filt}", sample = SAMPLES, + ext = ["sorted.bam", "sorted.bam.bai", "sorted_MarkDup-metrics.txt", "insert_size_metrics.txt", "insert_size_histogram.pdf"]), + expand("{p}{sample}_{ext}", p = f"{datadir + asm + filt}", sample = SAMPLES, + ext = [f"scaffolds_filtered-ge{config['Assembly']['min_contig_len']}.fasta.fai", "scaffolds_raw.vcf", + "scaffolds_AF5pct-filt.vcf", "scaffolds_AF5pct-filt.vcf.gz", "scaffolds_AF5pct-filt.vcf.gz.tbi"]), + expand("{p}{sample}_{ext}", p = f"{datadir + asm + filt}", sample = SAMPLES, + ext = ["ORF_AA.fa", "ORF_NT.fa", "annotation.gff", "annotation.gff.gz", "annotation.gff.gz.tbi", "contig_ORF_count_list.txt"]), + expand("{p}{sample}_{ext}", p = f"{datadir + asm + filt}", sample = SAMPLES, + ext = ["MinLenFiltSummary.stats", "perMinLenFiltScaffold.stats", "perORFcoverage.stats"]), + expand("{p}{sample}_GC.bedgraph", p = f"{datadir + asm + filt}", sample = SAMPLES), + f"{res}" + "igv.html", + expand("{p}{sample}.blastn", p = f"{datadir + scf_classified}", sample = SAMPLES), + expand("{p}{sample}{ext}", p = f"{datadir + scf_classified}", sample = SAMPLES, + ext = ["_lca_raw.gff", "_lca_tax.gff", "_lca_taxfilt.gff", "_lca_filt.gff", "_nolca_filt.gff", ".taxtab", ".taxMagtab"]), + f"{res}" + "krona.html", + expand("{p}Mapped_read_counts-{sample}.tsv", p = f"{res + cnt}", sample = SAMPLES), + f"{res + cnt}" + "Mapped_read_counts.tsv", + expand("{p}all_{ext}.tsv", p = f"{res}", ext = ["taxClassified", "taxUnclassified", "virusHost", "filtered_SNPs", "noLCA"]), + expand("{p}{file}", p = f"{res}", file = ["profile_read_counts.csv", "profile_read_percentages.csv", "Sample_composition_graph.html", "Superkingdoms_quantities_per_sample.csv"]), + expand("{p}{file}", p = f"{res}", file = ["Taxonomic_rank_statistics.tsv", "Virus_rank_statistics.tsv", "Phage_rank_statistics.tsv", "Bacteria_rank_statistics.tsv"]), + expand("{p}{file}", p = f"{res + hmap}", file = ["Superkingdoms_heatmap.html", "Virus_heatmap.html", "Phage_heatmap.html", "Bacteria_heatmap.html"]) + + +onstart: + try: + print("Checking if all specified files are accessible...") + for filename in [ + config['db']['background'], + config['db']['virus_host_db'] + ]: + if not os.path.exists(filename): + raise FileNotFoundError(filename) + for filepath in [ + config['db']['blast_nt'], + config['db']['blast_taxdb'], + config['db']['krona_db'], + config['db']['new_taxdump_db'], + config['db']['mgkit_db'] + ]: + if not os.path.exists(os.path.dirname(filepath)): + raise FileNotFoundError(filepath) + except FileNotFoundError as e: + print("This file is not available or accessible: %s" % e) + sys.exit(1) + else: + print("\tAll specified files are present!") + shell(""" + mkdir -p results + echo -e "\nLogging pipeline settings..." + echo -e "\tGenerating methodological hash (fingerprint)..." + echo -e "This is the link to the code used for this analysis:\thttps://github.com/DennisSchmitz/jovian/tree/$(git log -n 1 --pretty=format:"%H")" > results/log_git.txt + echo -e "This code with unique fingerprint $(git log -n1 --pretty=format:"%H") was committed by $(git log -n1 --pretty=format:"%an <%ae>") at $(git log -n1 --pretty=format:"%ad")" >> results/log_git.txt + echo -e "\tGenerating full software list of current Conda environment..." + conda list > results/log_conda.txt + echo -e "\tGenerating used databases log..." + echo -e "==> User-specified background reference (default: Homo Sapiens NCBI GRch38 NO DECOY genome): <==\n$(ls -lah {config[db][background]}*)\n" > results/log_db.txt + echo -e "\n==> NCBI BLAST database: <==\n$(ls -lah {config[db][blast_nt]}*)\n" >> results/log_db.txt + echo -e "\n==> NCBI taxonomy database: <==\n$(ls -lah {config[db][blast_taxdb]}*)\n" >> results/log_db.txt + echo -e "\n==> Virus-Host Interaction Database: <==\n$(ls -lah {config[db][virus_host_db]}*)\n" >> results/log_db.txt + echo -e "\n==> Krona Taxonomy Database: <==\n$(ls -lah {config[db][krona_db]}*)\n" >> results/log_db.txt + echo -e "\n==> NCBI new_taxdump Database: <==\n$(ls -lah {config[db][new_taxdump_db]}*)\n" >> results/log_db.txt + echo -e "\n==> mgkit database: <==\n$(ls -lah {config[db][mgkit_db]}*)\n" >> results/log_db.txt + + echo -e "\tGenerating config file log..." + rm -f results/log_config.txt + for file in config/*.yaml + do + echo -e "\n==> Contents of file \"${{file}}\": <==" >> results/log_config.txt + cat ${{file}} >> results/log_config.txt + echo -e "\n\n" >> results/log_config.txt + done + + echo -e "\tCopying samplesheet.yaml to results/ folder." #? To easily mount it in singularity since the results folder is mounted anyway + cp samplesheet.yaml results/samplesheet.yaml + """) + + +rule QC_raw: + input: lambda wildcards: SAMPLES[wildcards.sample][wildcards.read] + output: + html = f"{datadir + qc_pre}" + "{sample}_{read}_fastqc.html", + zip = f"{datadir + qc_pre}" + "{sample}_{read}_fastqc.zip" + conda: + f"{conda_envs}qc_and_clean.yaml" + container: + "library://ds_bioinformatics/jovian/qc_and_clean:2.0.0" + log: + f"{logdir}" + "QC_raw_{sample}_{read}.log" + benchmark: + f"{logdir + bench}" + "QC_raw_{sample}_{read}.txt" + threads: config['threads']['Filter'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + output_dir = f"{datadir + qc_pre}", + script = "/Jovian/scripts/fqc.sh" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/fqc.sh"), + shell: + """ +bash {params.script} {input} {params.output_dir} {output.html} {output.zip} {log} {threads} + """ + + +rule QC_filter: + input: lambda wildcards: (SAMPLES[wildcards.sample][i] for i in ("R1", "R2")) + output: + r1 = f"{datadir + cln + qcfilt}" + "{sample}_pR1.fq", + r2 = f"{datadir + cln + qcfilt}" + "{sample}_pR2.fq", + r1_unpaired = f"{datadir + cln + qcfilt}" + "{sample}_uR1.fq", + r2_unpaired = f"{datadir + cln + qcfilt}" + "{sample}_uR2.fq" + conda: + f"{conda_envs}qc_and_clean.yaml" + container: + "library://ds_bioinformatics/jovian/qc_and_clean:2.0.0" + log: + f"{logdir}" + "QC_filter_{sample}.log" + benchmark: + f"{logdir + bench}" + "QC_filter_{sample}.txt" + threads: config['threads']['Filter'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + adapter_removal_config = "ILLUMINACLIP:/Jovian/files/nexteraPE_adapters.fa:2:30:10:8:true" if config['use_singularity_or_conda'] == "use_singularity" else "ILLUMINACLIP:" + srcdir("files/nexteraPE_adapters.fa") + ":2:30:10:8:true", + quality_trimming_config = f"SLIDINGWINDOW:{config['QC']['window_size']}:{config['QC']['min_phred_score']}", + minimum_length_config = f"MINLEN:{config['QC']['min_read_length']}" + shell: + """ +trimmomatic PE -threads {threads} {input[0]:q} {input[1]:q} {output.r1} {output.r1_unpaired} {output.r2} {output.r2_unpaired} \ +{params.adapter_removal_config} {params.quality_trimming_config} {params.minimum_length_config} > {log} 2>&1 +touch -r {output.r1} {output.r1_unpaired} +touch -r {output.r2} {output.r2_unpaired} + """ + + +rule QC_clean: + input: + f"{datadir + cln + qcfilt}" + "{sample}_{read}.fq" #? don't use the `rules.QC_filter.output` syntax since you need the {sample} and {read} capturegroups to have a properly functioning DAG + output: + html = f"{datadir + qc_post}" + "{sample}_{read}_fastqc.html", + zip = f"{datadir + qc_post}" + "{sample}_{read}_fastqc.zip" + conda: + f"{conda_envs}qc_and_clean.yaml" + container: + "library://ds_bioinformatics/jovian/qc_and_clean:2.0.0" + log: + f"{logdir}" + "QC_clean_{sample}_{read}.log" + benchmark: + f"{logdir + bench}" + "QC_clean_{sample}_{read}.txt" + threads: config['threads']['Filter'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + output_dir = f"{datadir + qc_post}" + shell: + """ +if [ -s "{input}" ]; then + fastqc -t {threads} --quiet --outdir {params.output_dir} {input} > {log} 2>&1 +else + touch {output.html} + touch {output.zip} + echo "touched things because input was empty" > {log} 2>&1 +fi + """ + + +rule Remove_BG_p1: + input: + bg = config['db']['background'], + r1 = rules.QC_filter.output.r1, + r2 = rules.QC_filter.output.r2, + r1_unpaired = rules.QC_filter.output.r1_unpaired, + r2_unpaired = rules.QC_filter.output.r2_unpaired + output: + bam = f"{datadir + cln + aln}" + "{sample}_raw-alignment.bam", + bai = f"{datadir + cln + aln}" + "{sample}_raw-alignment.bam.bai" + conda: + f"{conda_envs}qc_and_clean.yaml" + container: + "library://ds_bioinformatics/jovian/qc_and_clean:2.0.0" + log: + f"{logdir}" + "Remove_BG_p1_{sample}.log" + benchmark: + f"{logdir + bench}" + "Remove_BG_p1_{sample}.txt" + threads: config['threads']['Alignments'] + resources: + mem_mb = high_memory_job, + # runtime_min = low_runtime_min + params: + aln_type = '--local' + shell: + """ +bowtie2 --time --threads {threads} {params.aln_type} -x {input.bg} -1 {input.r1} -2 {input.r2} -U {input.r1_unpaired} -U {input.r2_unpaired} 2> {log} |\ +samtools view -@ {threads} -uS - 2>> {log} |\ +samtools sort -@ {threads} - -o {output.bam} >> {log} 2>&1 +samtools index -@ {threads} {output.bam} >> {log} 2>&1 + """ + + +rule Remove_BG_p2: + input: + bam = rules.Remove_BG_p1.output.bam, + bai = rules.Remove_BG_p1.output.bai + output: + r1 = f"{datadir + cln + filt}" + "{sample}_pR1.fq", + r2 = f"{datadir + cln + filt}" + "{sample}_pR2.fq", + conda: + f"{conda_envs}qc_and_clean.yaml" + container: + "library://ds_bioinformatics/jovian/qc_and_clean:2.0.0" + log: + f"{logdir}" + "Remove_BG_p2_{sample}.log" + benchmark: + f"{logdir + bench}" + "Remove_BG_p2_{sample}.txt" + threads: config['threads']['Filter'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + shell: + """ +samtools view -@ {threads} -b -f 1 -f 8 {input.bam} 2> {log} |\ +samtools sort -@ {threads} -n - 2>> {log} |\ +bedtools bamtofastq -i - -fq {output.r1} -fq2 {output.r2} >> {log} 2>&1 + """ + + +rule Remove_BG_p3: + input: + bam = rules.Remove_BG_p1.output.bam, + bai = rules.Remove_BG_p1.output.bai + output: + tbam = temp(f"{datadir + cln + aln}" + "{sample}_temp_unpaired.bam"), + un = f"{datadir + cln + filt}" + "{sample}_unpaired.fq", + conda: + f"{conda_envs}qc_and_clean.yaml" + container: + "library://ds_bioinformatics/jovian/qc_and_clean:2.0.0" + log: + f"{logdir}" + "Remove_BG_p3_{sample}.log" + benchmark: + f"{logdir + bench}" + "Remove_BG_p3_{sample}.txt" + threads: config['threads']['Filter'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + shell: + """ +samtools view -@ {threads} -b -F 1 -f 4 {input.bam} 2> {log} |\ +samtools sort -@ {threads} -n -o {output.tbam} 2>> {log} +bedtools bamtofastq -i {output.tbam} -fq {output.un} >> {log} 2>&1 + """ + + +rule Assemble: + input: + r1 = rules.Remove_BG_p2.output.r1, + r2 = rules.Remove_BG_p2.output.r2, + un = rules.Remove_BG_p3.output.un + output: + scaffolds = f"{datadir + asm + raw}" + "{sample}/scaffolds.fasta", + scaff_filt = f"{datadir + asm + filt}" + "{sample}" + f"_scaffolds_filtered-ge{config['Assembly']['min_contig_len']}.fasta", + conda: + f"{conda_envs}assembly.yaml" + container: + "library://ds_bioinformatics/jovian/assembly:2.0.0" + log: + f"{logdir}" + "Assemble_{sample}.log" + benchmark: + f"{logdir + bench}" + "Assemble_{sample}.txt" + threads: config['threads']['Assemble'] + resources: + mem_mb = very_high_memory_job, + # runtime_min = high_runtime_min + params: + min_contig_len = config['Assembly']['min_contig_len'], + kmersizes = config['Assembly']['kmersizes'], + outdir = f"{datadir + asm + raw}" + "{sample}/" + shell: + """ +spades.py --only-assembler --meta -1 {input.r1} -2 {input.r2} -s {input.un} -t {threads} -m $(({resources.mem_mb} / 1000)) -k {params.kmersizes} -o {params.outdir} > {log} 2>&1 +seqtk seq {output.scaffolds} 2>> {log} |\ +gawk -F "_" '/^>/ {{if ($4 >= {params.min_contig_len}) {{print $0; getline; print $0}};}}' 2>> {log} 1> {output.scaff_filt} + """ + + +rule align_to_scaffolds_RmDup_FragLength: + input: + fasta = rules.Assemble.output.scaff_filt, + R1 = rules.Remove_BG_p2.output.r1, + R2 = rules.Remove_BG_p2.output.r2 + output: + bam = f"{datadir + asm + filt}" + "{sample}_sorted.bam", + bam_bai = f"{datadir + asm + filt}" + "{sample}_sorted.bam.bai", + dup_metrics = f"{datadir + asm + filt}" + "{sample}_sorted_MarkDup-metrics.txt", + frag_metrics = f"{datadir + asm + filt}" + "{sample}_insert_size_metrics.txt", + frag_pdf = f"{datadir + asm + filt}" + "{sample}_insert_size_histogram.pdf" + conda: + f"{conda_envs}sequence_analysis.yaml" + container: + "library://ds_bioinformatics/jovian/sequence_analysis:2.0.0" + log: + f"{logdir}" + "align_to_scaffolds_RmDup_FragLength_{sample}.log" + benchmark: + f"{logdir + bench}" + "align_to_scaffolds_RmDup_FragLength_{sample}.txt" + threads: config['threads']['align_to_scaffolds_RmDup_FragLength'] + resources: + mem_mb = high_memory_job, + # runtime_min = low_runtime_min + params: + remove_dups = "", #? To turn this on, e.g. for metagenomics data replace it with a "-r" [NB, without quotes]. To turn this off, e.g. for amplicon experiments such as ARTIC, replace this with "" #! The `-r` will HARD remove the duplicates instead of only marking them, N.B. this is REQUIRED for the downstream bbtools' pileup.sh to work --> it ignores the DUP marker and counts the reads in its coverage metrics. Thus giving a false sense of confidence. + markdup_mode = "t", + max_read_length = "300" #? This is the default value and also the max read length of Illumina in-house sequencing. + shell: + """ +bwa index {input.fasta} > {log} 2>&1 +bwa mem -t {threads} {input.fasta} {input.R1} {input.R2} 2>> {log} |\ +samtools view -@ {threads} -uS - 2>> {log} |\ +samtools collate -@ {threads} -O - 2>> {log} |\ +samtools fixmate -@ {threads} -m - - 2>> {log} |\ +samtools sort -@ {threads} - -o - 2>> {log} |\ +samtools markdup -@ {threads} -l {params.max_read_length} -m {params.markdup_mode} {params.remove_dups} -f {output.dup_metrics} - {output.bam} >> {log} 2>&1 +samtools index -@ {threads} {output.bam} >> {log} 2>&1 + +picard -Dpicard.useLegacyParser=false CollectInsertSizeMetrics -I {output.bam} -O {output.frag_metrics} -H {output.frag_pdf} >> {log} 2>&1 + """ + + +rule SNP_calling: + input: + fasta = rules.Assemble.output.scaff_filt, + bam = rules.align_to_scaffolds_RmDup_FragLength.output.bam, + bam_bai = rules.align_to_scaffolds_RmDup_FragLength.output.bam_bai + output: + fasta_fai = f"{datadir + asm + filt}" + "{sample}" + f"_scaffolds_filtered-ge{config['Assembly']['min_contig_len']}.fasta.fai", + unfilt_vcf = f"{datadir + asm + filt}" + "{sample}" + f"_scaffolds_raw.vcf", + filt_vcf = f"{datadir + asm + filt}" + "{sample}" + f"_scaffolds_AF5pct-filt.vcf", + zipped_filt_vcf = f"{datadir + asm + filt}" + "{sample}" + f"_scaffolds_AF5pct-filt.vcf.gz", + zipped_filt_vcf_index = f"{datadir + asm + filt}" + "{sample}" + f"_scaffolds_AF5pct-filt.vcf.gz.tbi" + conda: + f"{conda_envs}sequence_analysis.yaml" + container: + "library://ds_bioinformatics/jovian/sequence_analysis:2.0.0" + log: + f"{logdir}" + "SNP_calling_{sample}.log" + benchmark: + f"{logdir + bench}" + "SNP_calling_{sample}.txt" + threads: config['threads']['SNP_calling'] + resources: + mem_mb = high_memory_job, + # runtime_min = high_runtime_min # ? rarely it takes >1h to run this rule + params: + max_cov = 20000, #? Maximum coverage used for SNP calling. + min_AF = 0.05 #? This is the minimum allelle frequency (=AF) for which a SNP is reported, default is 5%. + shell: + """ +samtools faidx -o {output.fasta_fai} {input.fasta} > {log} 2>&1 +lofreq call-parallel -d {params.max_cov} --no-default-filter --pp-threads {threads} -f {input.fasta} -o {output.unfilt_vcf} {input.bam} >> {log} 2>&1 +lofreq filter -a {params.min_AF} -i {output.unfilt_vcf} -o {output.filt_vcf} >> {log} 2>&1 +bgzip -c {output.filt_vcf} 2>> {log} 1> {output.zipped_filt_vcf} +tabix -p vcf {output.zipped_filt_vcf} >> {log} 2>&1 + """ + + +rule ORF_analysis: + input: + rules.Assemble.output.scaff_filt + output: + ORF_AA_fasta = f"{datadir + asm + filt}" + "{sample}_ORF_AA.fa", + ORF_NT_fasta = f"{datadir + asm + filt}" + "{sample}_ORF_NT.fa", + ORF_annotation_gff = f"{datadir + asm + filt}" + "{sample}_annotation.gff", + zipped_gff3 = f"{datadir + asm + filt}" + "{sample}_annotation.gff.gz", + index_zipped_gff3 = f"{datadir + asm + filt}" + "{sample}_annotation.gff.gz.tbi", + contig_ORF_count_list = f"{datadir + asm + filt}" + "{sample}_contig_ORF_count_list.txt" + conda: + f"{conda_envs}sequence_analysis.yaml" + container: + "library://ds_bioinformatics/jovian/sequence_analysis:2.0.0" + log: + f"{logdir}" + "ORF_analysis_{sample}.log" + benchmark: + f"{logdir + bench}" + "ORF_analysis_{sample}.txt" + threads: config['threads']['ORF_analysis'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + procedure = "meta", + output_format = "gff" + shell: + """ +prodigal -q -i {input} -a {output.ORF_AA_fasta} -d {output.ORF_NT_fasta} -o {output.ORF_annotation_gff} -p {params.procedure} -f {params.output_format} > {log} 2>&1 +bgzip -c {output.ORF_annotation_gff} 2>> {log} 1> {output.zipped_gff3} +tabix -p gff {output.zipped_gff3} >> {log} 2>&1 +egrep "^>" {output.ORF_NT_fasta} | sed 's/_/ /6' | tr -d ">" | cut -f 1 -d " " | uniq -c > {output.contig_ORF_count_list} + """ + + +rule Contig_metrics: + input: + bam = rules.align_to_scaffolds_RmDup_FragLength.output.bam, + fasta = rules.Assemble.output.scaff_filt, + ORF_NT_fasta = rules.ORF_analysis.output.ORF_NT_fasta + output: + summary = f"{datadir + asm + filt}" + "{sample}_MinLenFiltSummary.stats", + perScaffold = f"{datadir + asm + filt}" + "{sample}_perMinLenFiltScaffold.stats", + perORFcoverage = f"{datadir + asm + filt}" + "{sample}_perORFcoverage.stats" + conda: + f"{conda_envs}sequence_analysis.yaml" + container: + "library://ds_bioinformatics/jovian/sequence_analysis:2.0.0" + log: + f"{logdir}" + "Contig_metrics_{sample}.log" + benchmark: + f"{logdir + bench}" + "Contig_metrics_{sample}.txt" + threads: config['threads']['Contig_metrics'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + shell: #! bbtools' pileup.sh counts every read, even those marked as duplicate upstream. Hence, for accurate counts, make sure the `remove_dups` param in rule `align_to_scaffolds_RmDup_FragLength` is set to `-r`. + """ +pileup.sh in={input.bam} ref={input.fasta} fastaorf={input.ORF_NT_fasta} outorf={output.perORFcoverage} out={output.perScaffold} secondary=f samstreamer=t 2> {output.summary} 1> {log} + """ + + +rule GC_content: + input: + fasta = rules.Assemble.output.scaff_filt, + fasta_fai = rules.SNP_calling.output.fasta_fai + output: + fasta_sizes = f"{datadir + asm + filt}" + "{sample}" + f"_scaffolds_filtered-ge{config['Assembly']['min_contig_len']}.fasta.sizes", + bed_windows = f"{datadir + asm + filt}" + "{sample}.windows", + GC_bed = f"{datadir + asm + filt}" + "{sample}_GC.bedgraph" + conda: + f"{conda_envs}sequence_analysis.yaml" + container: + "library://ds_bioinformatics/jovian/sequence_analysis:2.0.0" + log: + f"{logdir}" + "GC_content_{sample}.log" + benchmark: + f"{logdir + bench}" + "GC_content_{sample}.txt" + threads: config['threads']['GC_content'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + window_size = 50 + shell: + """ +cut -f 1,2 {input.fasta_fai} 2> {log} 1> {output.fasta_sizes} +bedtools makewindows -g {output.fasta_sizes} -w {params.window_size} 2>> {log} 1> {output.bed_windows} +bedtools nuc -fi {input.fasta} -bed {output.bed_windows} 2>> {log} | cut -f 1-3,5 2>>{log} 1> {output.GC_bed} + """ + + +rule HTML_IGVjs_variable_parts: + input: + fasta = rules.Assemble.output.scaff_filt, + ref_GC_bedgraph = rules.GC_content.output.GC_bed, + ref_zipped_ORF_gff = rules.ORF_analysis.output.zipped_gff3, + basepath_zipped_SNP_vcf = rules.SNP_calling.output.zipped_filt_vcf, + basepath_sorted_bam = rules.align_to_scaffolds_RmDup_FragLength.output.bam + output: + tab_output = f"{datadir + html}" + "2_tab_{sample}", + div_output = f"{datadir + html}" + "4_html_divs_{sample}", + js_flex_output = f"{datadir + html}" + "6_js_flex_{sample}" + conda: + f"{conda_envs}data_wrangling.yaml" + container: + "library://ds_bioinformatics/jovian/data_wrangling:2.0.0" + log: + f"{logdir}" + "HTML_IGVjs_variable_parts_{sample}.log" + benchmark: + f"{logdir + bench}" + "HTML_IGVjs_variable_parts_{sample}.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + script_html_path = "/Jovian/scripts/html/" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/html/"), + nginx_ip = "http://127.0.0.1", + nginx_port = "8079" + shell: + """ +bash {params.script_html_path}igvjs_write_tabs.sh {wildcards.sample} {output.tab_output} > {log} 2>&1 +bash {params.script_html_path}igvjs_write_divs.sh {wildcards.sample} {output.div_output} >> {log} 2>&1 +bash {params.script_html_path}igvjs_write_flex_js_middle.sh {wildcards.sample} {output.js_flex_output} {input.fasta} {input.ref_GC_bedgraph} {input.ref_zipped_ORF_gff} {input.basepath_zipped_SNP_vcf} {input.basepath_sorted_bam} {params.nginx_ip} {params.nginx_port} >> {log} 2>&1 + """ + + +rule HTML_IGVjs_final: + input: + expand("{p}{chunk_name}_{sample}", p = f"{datadir + html}", chunk_name = ["2_tab", "4_html_divs", "6_js_flex"], sample = SAMPLES) + output: + f"{res}" + "igv.html" + conda: + f"{conda_envs}data_wrangling.yaml" + container: + "library://ds_bioinformatics/jovian/data_wrangling:2.0.0" + log: + f"{logdir}" + "HTML_IGVjs_final.log" + benchmark: + f"{logdir + bench}" + "HTML_IGVjs_final.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + tab_basename = f"{datadir + html}" + "2_tab_", + div_basename = f"{datadir + html}" + "4_html_divs_", + js_flex_basename = f"{datadir + html}" + "6_js_flex_", + files_path = "/Jovian/files/html/" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("files/html/"), + shell: + """ +cat {params.files_path}1_header.html > {output} 2> {log} +cat {params.tab_basename}* >> {output} 2>> {log} +cat {params.files_path}3_tab_explanation.html >> {output} 2>> {log} +cat {params.div_basename}* >> {output} 2>> {log} +cat {params.files_path}5_js_begin.html >> {output} 2>> {log} +cat {params.js_flex_basename}* >> {output} 2>> {log} +cat {params.files_path}7_js_end.html >> {output} 2>> {log} + """ + + +rule Scaffold_classification: + input: + rules.Assemble.output.scaff_filt + output: + f"{datadir + scf_classified}" + "{sample}.blastn" + conda: + f"{conda_envs}scaffold_classification.yaml" + container: + "library://ds_bioinformatics/jovian/scaffold_classification:2.0.0" + log: + f"{logdir}" + "Scaffold_classification_{sample}.log" + benchmark: + f"{logdir + bench}" + "Scaffold_classification_{sample}.txt" + threads: config['threads']['Scaffold_classification'] + resources: + mem_mb = very_high_memory_job, + # runtime_min = high_runtime_min + params: + nt_db_path = config['db']['blast_nt'], + taxdb_db_path = config['db']['blast_taxdb'], + outfmt = "6 std qseqid sseqid staxids sscinames stitle", + evalue = "0.05", #? E-value threshold for saving hits + qcov_hsp_perc = "50", #? Minimum length percentage of the query (i.e. scaffold) to be covered by the hsp, i.e. hits with less than this value will not be reported. + max_target_seqs = "250", + max_hsps = "1" + shell: + """ +export BLASTDB="{params.taxdb_db_path}" +blastn -task megablast -outfmt "{params.outfmt}" -query {input} -evalue {params.evalue} -qcov_hsp_perc {params.qcov_hsp_perc} -max_target_seqs {params.max_target_seqs} -max_hsps {params.max_hsps} -db {params.nt_db_path} -num_threads {threads} -out {output} > {log} 2>&1 + """ + + +#? Reformat blast tsv output to gff +#? Remove all construct/synthetic entries (because the filtering based on their specific taxid, as perform in rule `taxfilter_gff`, is not adequate) +#? Remove any entry with a lower bitscore than the user specified bitscore_threshold (i.e. filter short alignments since every match is a +2 bitscore) +rule make_gff: + input: + rules.Scaffold_classification.output + output: + f"{datadir + scf_classified}" + "{sample}_lca_raw.gff" #? This is a temp file, removed in the onSuccess//onError clause. + conda: + f"{conda_envs}mgkit_lca.yaml" + container: + "library://ds_bioinformatics/jovian/mgkit_lca:2.0.0" + log: + f"{logdir}" + "make_gff_{sample}.log" + benchmark: + f"{logdir + bench}" + "make_gff_{sample}.txt" + threads: config['threads']['mgkit_lca'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + bitscore_threshold = "100", + filt_keywords = "/construct\|synthetic/Id" + shell: #? sed does a case-insensitive search and in-place deletion of any record containing the filt_keywords + """ +sed -i "{params.filt_keywords}" {input} +blast2gff blastdb -v -b {params.bitscore_threshold} -n {input} {output} > {log} 2>&1 + """ + + +#? Reformat gff, augment accession id of the blasthit with the taxid +rule addtaxa_gff: + input: + rules.make_gff.output + output: + f"{datadir + scf_classified}" + "{sample}_lca_tax.gff" + conda: + f"{conda_envs}mgkit_lca.yaml" + container: + "library://ds_bioinformatics/jovian/mgkit_lca:2.0.0" + log: + f"{logdir}" + "addtaxa_gff_{sample}.log" + benchmark: + f"{logdir + bench}" + "addtaxa_gff_{sample}.txt" + threads: config['threads']['mgkit_lca'] + resources: + mem_mb = high_memory_job, + # runtime_min = low_runtime_min + params: + mgkit_tax_db = config['db']['mgkit_db'] + shell: + """ +add-gff-info addtaxa -v -t {params.mgkit_tax_db}nucl_gb.accession2taxid_sliced.tsv -e {input} {output} > {log} 2>&1 + """ + + +#? Filter taxid 81077 (https://www.ncbi.nlm.nih.gov/taxonomy/?term=81077 --> artificial sequences) and 12908 (https://www.ncbi.nlm.nih.gov/taxonomy/?term=12908 --> unclassified sequences) +rule taxfilter_gff: + input: + rules.addtaxa_gff.output + output: + f"{datadir + scf_classified}" + "{sample}_lca_taxfilt.gff" + conda: + f"{conda_envs}mgkit_lca.yaml" + container: + "library://ds_bioinformatics/jovian/mgkit_lca:2.0.0" + log: + f"{logdir}" + "taxfilter_gff_{sample}.log" + benchmark: + f"{logdir + bench}" + "taxfilter_gff_{sample}.txt" + threads: config['threads']['mgkit_lca'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + mgkit_tax_db = config['db']['mgkit_db'] + shell: + """ +taxon-utils filter -v -e 81077 -e 12908 -t {params.mgkit_tax_db}taxonomy.pickle {input} {output} > {log} 2>&1 + """ + + +#? Filter gff on the user-specified bitscore-quantile settings. +#? Filters on bitscore, it sorts assignments high to low and takes only the 3% highest number of records for LCA. (.97 param and 'ge' = greater or equal than params: NB it's an order-based analysis not a value-based one) +rule qfilter_gff: + input: + rules.taxfilter_gff.output + output: + f"{datadir + scf_classified}" + "{sample}_lca_filt.gff" + conda: + f"{conda_envs}mgkit_lca.yaml" + container: + "library://ds_bioinformatics/jovian/mgkit_lca:2.0.0" + log: + f"{logdir}" + "qfilter_gff_{sample}.log" + benchmark: + f"{logdir + bench}" + "qfilter_gff_{sample}.txt" + threads: config['threads']['mgkit_lca'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + quantile_threshold = ".97" + shell: + """ +filter-gff sequence -v -t -a bitscore -f quantile -l {params.quantile_threshold} -c ge {input} {output} > {log} 2>&1 + """ + + +#? Perform the LCA analysis. +##? in `taxon-utils lca` the `-n {output.no_lca}` flag is important because these are reported in the visualisation report for manual inspection. +##? in `taxon-utils lca` the `-b {params.bitscore_threshold} ` is redundant because this is already done in the first rule, still, leaving it in for clarity. +##? the `sed` rule creates a header for the output file +##? touch the {output.no_lca} if it hasn't been generated yet, otherwise you get an error downstream +##? NB mgkit log10 transforms evalues, i.e. these are not the default evalues as reported by BLAST. +##? `bin/average_logevalue_no_lca.py` adds a `taxid=1` and `evalue=1` for all entries without an LCA result (i.e. taxid=1, which is "Root") and also averages the e-values of the LCA constituents alongside setting av. log10 transformed evalues of 0 to -450 due to undeflow. +##? `bin/krona_magnitudes.py` adds magnitude information for the Krona plot (same as default Krona method). +rule lca_mgkit: + input: + filtgff = rules.qfilter_gff.output, + stats = rules.Contig_metrics.output.perScaffold + output: + no_lca = f"{datadir + scf_classified}" + "{sample}_nolca_filt.gff", + taxtab = f"{datadir + scf_classified}" + "{sample}.taxtab", + taxMagtab = f"{datadir + scf_classified}" + "{sample}.taxMagtab" + conda: + f"{conda_envs}mgkit_lca.yaml" + container: + "library://ds_bioinformatics/jovian/mgkit_lca:2.0.0" + log: + f"{logdir}" + "lca_mgkit_{sample}.log" + benchmark: + f"{logdir + bench}" + "lca_mgkit_{sample}.txt" + threads: config['threads']['mgkit_lca'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + mgkit_tax_db = config['db']['mgkit_db'], + bitscore_threshold = "100", + script_path = "/Jovian/scripts/" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/"), + shell: + """ +taxon-utils lca -v -b {params.bitscore_threshold} -s -p -n {output.no_lca} -t {params.mgkit_tax_db}taxonomy.pickle {input.filtgff} {output.taxtab} > {log} 2>&1; +sed -i '1i #queryID\ttaxID' {output.taxtab} >> {log} 2>&1; +if [[ ! -e {output.no_lca} ]]; then + touch {output.no_lca} +fi +python {params.script_path}average_logEvalue_no_lca.py {output.taxtab} {output.no_lca} {input.filtgff} {output.taxtab} >> {log} 2>&1; +python {params.script_path}krona_magnitudes.py {output.taxtab} {input.stats} {output.taxMagtab} >> {log} 2>&1 + """ + + +rule Krona: + input: + sorted(expand(rules.lca_mgkit.output.taxMagtab, sample = set(SAMPLES))) + output: + f"{res}" + "krona.html" + conda: + f"{conda_envs}krona.yaml" + container: + "library://ds_bioinformatics/jovian/krona:2.0.0" + log: + f"{logdir}" + "krona.log" + benchmark: + f"{logdir + bench}" + "krona.txt" + threads: config['threads']['krona'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + krona_db_path = config['db']['krona_db'] + shell: + """ +ktImportTaxonomy {input} -tax {params.krona_db_path} -i -k -m 4 -o {output} > {log} 2>&1 + """ + + +rule count_mapped_reads: + input: + rules.align_to_scaffolds_RmDup_FragLength.output.bam + output: + f"{res + cnt}" + "Mapped_read_counts-{sample}.tsv" + conda: + f"{conda_envs}sequence_analysis.yaml" + container: + "library://ds_bioinformatics/jovian/sequence_analysis:2.0.0" + log: + f"{logdir}" + "count_mapped_reads-{sample}.log" + benchmark: + f"{logdir + bench}" + "count_mapped_reads-{sample}.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + script = "/Jovian/scripts/count_mapped_reads.sh" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/count_mapped_reads.sh") + shell: + """ +bash {params.script} {input} > {output} 2> {log} + """ + + +rule concatenate_read_counts: + input: + expand(rules.count_mapped_reads.output, sample = SAMPLES) + output: + f"{res + cnt}" + "Mapped_read_counts.tsv" + conda: + f"{conda_envs}data_wrangling.yaml" + container: + "library://ds_bioinformatics/jovian/data_wrangling:2.0.0" + log: + f"{logdir}" + "concatenate_read_counts.log" + benchmark: + f"{logdir + bench}" + "concatenate_read_counts.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + script = "/Jovian/scripts/concatenate_mapped_read_counts.py" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/concatenate_mapped_read_counts.py") + shell: + """ +python {params.script} -i {input} -o {output} > {log} 2>&1 + """ + + +rule merge_all_metrics_into_single_tsv: + input: + bbtoolsFile = rules.Contig_metrics.output.perScaffold, + kronaFile = rules.lca_mgkit.output.taxtab, + minLenFiltScaffolds = rules.Assemble.output.scaff_filt, + scaffoldORFcounts = rules.ORF_analysis.output.contig_ORF_count_list, + virusHostDB = config['db']['virus_host_db'], + new_taxdump_rankedlineage = f"{config['db']['new_taxdump_db']}" + "rankedlineage.dmp.delim", + new_taxdump_host = f"{config['db']['new_taxdump_db']}" + "host.dmp.delim" + output: + taxClassifiedTable = f"{datadir + tbl}" + "{sample}_taxClassified.tsv", + taxUnclassifiedTable = f"{datadir + tbl}" + "{sample}_taxUnclassified.tsv", + virusHostTable = f"{datadir + tbl}" + "{sample}_virusHost.tsv", + conda: + f"{conda_envs}data_wrangling.yaml" + container: + "library://ds_bioinformatics/jovian/data_wrangling:2.0.0" + log: + f"{logdir}" + "merge_all_metrics_into_single_tsv_{sample}.log" + benchmark: + f"{logdir + bench}" + "merge_all_metrics_into_single_tsv_{sample}.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + script = "/Jovian/scripts/merge_data.py" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/merge_data.py") + shell: + """ +python {params.script} {wildcards.sample} {input.bbtoolsFile} {input.kronaFile} {input.minLenFiltScaffolds} {input.scaffoldORFcounts} {input.virusHostDB} {input.new_taxdump_rankedlineage} {input.new_taxdump_host} {output.taxClassifiedTable} {output.taxUnclassifiedTable} {output.virusHostTable} > {log} 2>&1 + """ + + +rule concat_files: + input: + expand(rules.merge_all_metrics_into_single_tsv.output, sample = SAMPLES, extension = ["taxClassified.tsv", "taxUnclassified.tsv", "virusHost.tsv"]), + expand(rules.lca_mgkit.output.no_lca, sample = SAMPLES) + output: + taxClassified = f"{res}" + "all_taxClassified.tsv", + taxUnclassified = f"{res}" + "all_taxUnclassified.tsv", + virusHost = f"{res}" + "all_virusHost.tsv", + noLCA = f"{res}" + "all_noLCA.tsv" + conda: + f"{conda_envs}data_wrangling.yaml" + container: + "library://ds_bioinformatics/jovian/data_wrangling:2.0.0" + log: + f"{logdir}" + "concat_files.log" + benchmark: + f"{logdir + bench}" + "concat_files.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + search_folder = f"{datadir + tbl}", + classified_glob = "*_taxClassified.tsv", + unclassified_glob = "*_taxUnclassified.tsv", + virusHost_glob = "*_virusHost.tsv", + search_folder_noLCA = f"{datadir + scf_classified}", + noLCA_glob = "*_nolca_filt.gff" + shell: + """ +find {params.search_folder} -type f -name "{params.classified_glob}" -exec gawk 'NR==1 || FNR!=1' {{}} + | (read header; echo "$header"; sort -t$'\t' -k 1,1 -k 15,15nr) 2> {log} 1> {output.taxClassified} +find {params.search_folder} -type f -name "{params.unclassified_glob}" -exec gawk 'NR==1 || FNR!=1' {{}} + | (read header; echo "$header"; sort -t$'\t' -k 1,1 -k 4,4nr) 2>> {log} 1> {output.taxUnclassified} +find {params.search_folder} -type f -name "{params.virusHost_glob}" -exec gawk 'NR==1 || FNR!=1' {{}} + | (read header; echo "$header"; sort -t$'\t' -k 1,1 -k 2,2) 2>> {log} 1> {output.virusHost} + +find {params.search_folder_noLCA} -type f -name "{params.noLCA_glob}" -exec gawk 'BEGIN {{OFS="\t"; print "Sample_name", "Scaffold_name", "Constituent_taxIDs", "Constituent_tax_names"}} {{split(FILENAME, list_A, "_nolca_filt.gff"); split(list_A[1], list_B, "{params.search_folder_noLCA}"); print list_B[2], $0}}' {{}} + 2>> {log} 1> {output.noLCA} + """ #? Last one-liner: search all files with {params.noLCA_glob}, print a header, extract samplename by removing the extension ("_nolca_filt.gff") and then removing the root-path (stored in {params.search_folder_noLCA}), then print samplename in first column and the normal output after that, concat them for all samples in analysis. + + +rule concat_filtered_SNPs: + input: + expand(rules.SNP_calling.output.filt_vcf, sample = SAMPLES) + output: + final = f"{res}" + "all_filtered_SNPs.tsv", + temp = temp(f"{res}" + "all_filtered_SNPs.temp") + conda: + f"{conda_envs}data_wrangling.yaml" + container: + "library://ds_bioinformatics/jovian/data_wrangling:2.0.0" + log: + f"{logdir}" + "concat_filtered_SNPs.log" + benchmark: + f"{logdir + bench}" + "concat_filtered_SNPs.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + params: + vcf_folder_glob = f"{datadir + asm + filt}/\*-filt.vcf", + script = "/Jovian/scripts/concat_filtered_vcf.py" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/concat_filtered_vcf.py") + shell: + """ +python {params.script} {params.vcf_folder_glob} {output.temp} > {log} 2>&1 +cat {output.temp} | (read header; echo "$header"; sort -t$'\t' -k1,1 -k2,2 -k3,3n) 1> {output.final} 2>> {log} + """ + + +rule MultiQC: + input: + expand(rules.QC_raw.output.zip, sample = SAMPLES, read = ['R1', 'R2']), + expand(rules.QC_clean.output.zip, sample = SAMPLES, read = ['pR1', 'pR2', 'uR1', 'uR2']), + expand(rules.align_to_scaffolds_RmDup_FragLength.output.frag_metrics, sample = SAMPLES), + expand(rules.Remove_BG_p1.log, sample = SAMPLES), + expand(rules.QC_filter.log, sample = SAMPLES) + output: + f"{res}multiqc.html", + expand("{p}multiqc_{program}.txt", p = f"{res+mqc_data}", program = ['fastqc', 'trimmomatic', 'bowtie2']), + conda: + f"{conda_envs}qc_and_clean.yaml" + container: + "library://ds_bioinformatics/jovian/qc_and_clean:2.0.0" + log: + f"{logdir}" + "MultiQC.log" + benchmark: + f"{logdir + bench}" + "MultiQC.txt" + threads: config['threads']['MultiQC'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + conf = "/Jovian/files/multiqc_config.yaml" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("files/multiqc_config.yaml"), + outdir = f"{res}" + shell: + """ +multiqc --force --config {params.conf} -o {params.outdir} -n multiqc.html {input} > {log} 2>&1 + """ + + +rule quantify_output: + input: + classified = rules.concat_files.output.taxClassified, + unclassified = rules.concat_files.output.taxUnclassified, + mapped_reads = rules.concatenate_read_counts.output, + fastqc = f"{res + mqc_data}multiqc_fastqc.txt", + trimmomatic = f"{res + mqc_data}multiqc_trimmomatic.txt", + hugo = expand("{p}{sample}_{suffix}.fq", p = f"{datadir + cln + filt}", sample = set(SAMPLES), suffix = ["pR1", "pR2", "unpaired"]) + output: + read_count = f"{res}profile_read_counts.csv", + percentages = f"{res}profile_read_percentages.csv", + graph = f"{res}Sample_composition_graph.html" + conda: + f"{conda_envs}heatmaps.yaml" + container: + "library://ds_bioinformatics/jovian/heatmaps:2.0.0" + log: + f"{logdir}" + "quantify_output.log" + benchmark: + f"{logdir + bench}" + "quantify_output.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + script = "/Jovian/scripts/quantify_profiles.py" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/quantify_profiles.py") + shell: + """ +python {params.script} -f {input.fastqc} -t {input.trimmomatic} -hg {input.hugo} -c {input.classified} -u {input.unclassified} -m {input.mapped_reads} -co {output.read_count} -p {output.percentages} -g {output.graph} -cpu {threads} -l {log} + """ + + +rule draw_heatmaps: + input: + classified = rules.concat_files.output.taxClassified, + numbers = f"{res + mqc_data}multiqc_trimmomatic.txt" + output: + super_quantities = f"{res}Superkingdoms_quantities_per_sample.csv", + super = f"{res + hmap}Superkingdoms_heatmap.html", + virus = f"{res + hmap}Virus_heatmap.html", + phage = f"{res + hmap}Phage_heatmap.html", + bact = f"{res + hmap}Bacteria_heatmap.html", + stats = f"{res}Taxonomic_rank_statistics.tsv", + vir_stats = f"{res}Virus_rank_statistics.tsv", + phage_stats = f"{res}Phage_rank_statistics.tsv", + bact_stats = f"{res}Bacteria_rank_statistics.tsv" + conda: + f"{conda_envs}heatmaps.yaml" + container: + "library://ds_bioinformatics/jovian/heatmaps:2.0.0" + log: + f"{logdir}" + "draw_heatmaps.log" + benchmark: + f"{logdir + bench}" + "draw_heatmaps.txt" + threads: config['threads']['data_wrangling'] + resources: + mem_mb = medium_memory_job, + # runtime_min = low_runtime_min + params: + script = "/Jovian/scripts/draw_heatmaps.py" if config['use_singularity_or_conda'] == "use_singularity" else srcdir("scripts/draw_heatmaps.py") + shell: + """ +python {params.script} -c {input.classified} -n {input.numbers} -sq {output.super_quantities} -st {output.stats} -vs {output.vir_stats} -ps {output.phage_stats} -bs {output.bact_stats} -s {output.super} -v {output.virus} -p {output.phage} -b {output.bact} > {log} 2>&1 + """ + + +rule Copy_scaffolds: + input: rules.Assemble.output.scaff_filt + output: f"{res+scf}" + "{sample}_scaffolds.fasta" + threads: 1 + resources: + mem_mb = low_memory_job, + # runtime_min = low_runtime_min + shell: + """ +cp {input} {output} + """ + + +vt_script_path = srcdir("scripts/virus_typing.sh") #? you can add a `--force` flag to the script to force it to overwrite previous results +launch_report_script = srcdir("files/launch_report.sh") #? should be launched via iRODS, but leaving this for --local users and/or debugging +onsuccess: + shell(""" + echo -e "\nStarting virus typing, this may take a while...\n" + bash {vt_script_path} all + + echo -e "Virus typing finished." + + echo -e "Generating HTML index of log files..." + tree -hD --dirsfirst -H "../logs" -L 2 -T "Logs overview" --noreport --charset utf-8 -P "*" -o {res}logfiles_index.html {logdir} + + echo -e "Copying \`launch_report.sh\` script to output folder." + cp {launch_report_script} ./ + echo -e "\tLaunch the Jovian-report via command \`bash launch_report.sh ./\` from the user-specified output directory.\n\tNB, this requires singularity to be installed on your system." + + echo -e "Jovian is finished with processing all the files in the given input directory." + + echo -e "Shutting down..." + """) + return True + + +onerror: + print(""" + An error occurred and Jovian had to shut down. + Please check the the input and logfiles for any abnormalities and try again. + """) + return False diff --git a/Jovian/workflow/directories.py b/Jovian/workflow/directories.py new file mode 100644 index 0000000..b880557 --- /dev/null +++ b/Jovian/workflow/directories.py @@ -0,0 +1,49 @@ +logdir = "logs/" +bench = "benchmark/" + +conda_envs = "envs/" + +res = "results/" + +datadir = "data/" +cln = "cleaned_fastq/" +qcfilt = "QC_filter/" +scf_classified = "scaffolds_classified/" + +asm = "assembly/" +scf = "scaffolds/" + +html = "html/" +json = "json/" + +qc_pre = "FastQC_pretrim/" +qc_post = "FastQC_posttrim/" + +aln = "alignment/" +bf = "bam-files/" +vf = "vcf-files/" +features = "features/" +ann = "annotations/" +muts = "mutations/" + +seqs = "sequences/" +amino = "aminoacids/" +com = "combined/" +indiv = "individual/" + +tbl = "tables/" + +hmap = "heatmaps/" +cnt = "counts/" +mqc_data = "multiqc_data/" +fls = "files/" + +raw = "raw/" +filt = "filt/" + +cons = "consensus/" +covs = "coverages/" +insr = "inserts/" +boc = "BoC/" +chunks = "html_chunks/" +trims = "trimmed/" diff --git a/Jovian/workflow/envs/ancillary_files/Jovian_report.ipynb b/Jovian/workflow/envs/ancillary_files/Jovian_report.ipynb new file mode 100644 index 0000000..511c406 --- /dev/null +++ b/Jovian/workflow/envs/ancillary_files/Jovian_report.ipynb @@ -0,0 +1,726 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "# Jovian analysis report\n", + "___" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Please visualize the report by pressing `Cell` in the toolbar and then selecting `Run All`. This can take a couple of minutes (depending on the size of your dataset).** \n", + "
\n", + "*N.B. The sum total of reads in this report will not add up to the sum total number of reads that were supplied as input. This is because, 1) human reads are removed, 2) PCR-duplicates might be removed depending on the chosen configuration, by default, PCR-duplicates are not removed.* \n", + "
" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "deleteable": false, + "init_cell": true, + "scrolled": false + }, + "outputs": [], + "source": [ + "%%html\n", + " + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Jovian/workflow/files/html/1_header.html b/Jovian/workflow/files/html/1_header.html new file mode 100644 index 0000000..f049056 --- /dev/null +++ b/Jovian/workflow/files/html/1_header.html @@ -0,0 +1,70 @@ + + + + + + + + + + + + igv.js + + + + + + + + + + +

Alignments from a BAM file

+ + + +
+ +
diff --git a/Jovian/workflow/files/html/5_js_begin.html b/Jovian/workflow/files/html/5_js_begin.html new file mode 100644 index 0000000..1e6dfe3 --- /dev/null +++ b/Jovian/workflow/files/html/5_js_begin.html @@ -0,0 +1,10 @@ + + + + + diff --git a/Jovian/workflow/files/launch_report.sh b/Jovian/workflow/files/launch_report.sh new file mode 100644 index 0000000..414e598 --- /dev/null +++ b/Jovian/workflow/files/launch_report.sh @@ -0,0 +1,40 @@ +#!/bin/bash +#set -vx # For debugging only + +BASE_OUTPUT_FOLDER="$1" +VERSION="2.0.0" + +if [ -z "$BASE_OUTPUT_FOLDER" ] + then + echo "Base output folder not provided, please provide the base output folder generated by Jovian as an argument to this script. By default: \`bash launch_report.sh ./\`" + exit 1 +fi + +if [ ! -d "$BASE_OUTPUT_FOLDER" ] + then + echo "This is not a directory, please provide the base output folder generated by Jovian" + exit 1 +fi + +if ! command -v singularity &> /dev/null + then + echo "Singularity could not be found. The visualisation report relies on this program, please install it on your system or ask a system-admin to do this for you. See: https://docs.sylabs.io/guides/3.0/user-guide/installation.html . Exiting." + exit 1 +fi + +set -euo pipefail + +cd "${BASE_OUTPUT_FOLDER}" + +if [ ! -f "jovian_report_${VERSION}.sif" ] + then + echo "Downloading singularity container, this may take a while." + singularity pull library://ds_bioinformatics/jovian/jovian_report:${VERSION} +fi + +mkdir -p ./.nginx/tmp/nginx ./.nginx/run/ ./.nginx/log/ + +singularity run --bind ./:/opt/.jupyter/migrated \ +--bind ./.nginx/log:/opt/conda/var/log/nginx/ --bind ./.nginx/run:/opt/conda/var/run/ --bind ./.nginx/tmp:/opt/conda/var/tmp/ \ +--bind ./results/:/opt/Jovian/results/ --bind ./data/:/opt/Jovian/data/ --bind ./logs/:/opt/Jovian/logs/ \ +jovian_report_${VERSION}.sif diff --git a/Jovian/workflow/files/multiqc_config.yaml b/Jovian/workflow/files/multiqc_config.yaml new file mode 100644 index 0000000..a99a576 --- /dev/null +++ b/Jovian/workflow/files/multiqc_config.yaml @@ -0,0 +1,20 @@ +# Source: https://github.com/ewels/MultiQC/blob/master/multiqc_config_example.yaml +# Date: 20181026 + +# Title to use for the report. +title: Jovian quality control metrics + +# How to plot graphs. Different templates can override these settings, but +# the default template can use interactive plots (Javascript using HighCharts) +# or flat plots (images, using MatPlotLib). With interactive plots, the report +# can prevent automatically rendering all graphs if there are lots of samples +# to prevent the browser being locked up when the report opens. +plots_force_flat: False # Try to use only flat image graphs +plots_force_interactive: False # Try to use only interactive javascript graphs +plots_flat_numseries: 250 # If neither of the above, use flat if > this number of datasets +num_datasets_plot_limit: 50 # If interactive, don't plot on load if > this number of datasets +max_table_rows: 1500 # Swap tables for a beeswarm plot above this + +extra_fn_clean_trim: # MultiQC also imports the log of HuGo alignment, this log file has the rule name in it, this needs to be removed, this can be done as follows... Source: https://multiqc.info/docs/#sample-name-cleaning + - "Remove_BG_p1_" + - "_sorted" diff --git a/Jovian/workflow/files/nexteraPE_adapters.fa b/Jovian/workflow/files/nexteraPE_adapters.fa new file mode 100644 index 0000000..a986757 --- /dev/null +++ b/Jovian/workflow/files/nexteraPE_adapters.fa @@ -0,0 +1,12 @@ +>PrefixNX/1 +AGATGTGTATAAGAGACAG +>PrefixNX/2 +AGATGTGTATAAGAGACAG +>Trans1 +TCGTCGGCAGCGTCAGATGTGTATAAGAGACAG +>Trans1_rc +CTGTCTCTTATACACATCTGACGCTGCCGACGA +>Trans2 +GTCTCGTGGGCTCGGAGATGTGTATAAGAGACAG +>Trans2_rc +CTGTCTCTTATACACATCTCCGAGCCCACGAGAC \ No newline at end of file diff --git a/Jovian/workflow/scripts/average_logEvalue_no_lca.py b/Jovian/workflow/scripts/average_logEvalue_no_lca.py new file mode 100644 index 0000000..6397a88 --- /dev/null +++ b/Jovian/workflow/scripts/average_logEvalue_no_lca.py @@ -0,0 +1,61 @@ +""" +Thierry Janssens, 28JUN2019 +Add root results for LCA and average the evalues from the filtered gff file (mgkit) to the taxtab file. +Usage: + average_logevalue.py + is the file generated by mgkit taxon-utils lca (made tmp()). + is the file generated by mgkit-utils lca (made(tmp()) + is the file generated by mgkit filter-gff. + is the input taxtab amended with a column with an average log evalue for every LCA (contig). +""" + +import os.path +import re +import pandas as pd +import numpy as np +from sys import argv + +SCRIPT, INPUTTAX, INPUTNOLCA, INPUTGFF, OUTPUTFILE = argv + +df_tax = pd.read_csv(INPUTTAX, sep="\t", header = 0) + +if os.path.getsize(INPUTNOLCA) > 0: + df_nolca = pd.read_csv(INPUTNOLCA, sep="\t", header=None) + series_nolca = df_nolca[df_nolca.columns[0]] + series_nolca = series_nolca.unique() + frame = {"#queryID": series_nolca, "taxID": 1, "Avg. log e-value": 1} + df_nolca = pd.DataFrame(frame) +else: + df_nolca = pd.DataFrame() + +df_gff = pd.read_csv(INPUTGFF, sep="\t", header = None) + +#? Drop everything but the 1st column (scaffold_name) and the last column (8th column; key-value pairs output by mgkit) +df_gff.drop(df_gff.columns[1:8], axis=1, inplace=True) + +#? Regex for literal `evalue=\"` but don't include it in the results (i.e. "(?<=" syntax; positive lookbehind), grab the value reported there (i.e. the actual evalue; NB, it can be zero), match a literal '\";' but dont include it in the results (i.e. "(?=" syntax; positive lookahead) +#? Basically, it removes all the key-value pairs and it keeps only the actual evalue-value without it's key +df_gff.iloc[:, 1] = df_gff.iloc[:, 1].str.extract( + r"((?<=evalue=\").*?(?=\";))", expand=True +) +df_gff.columns = ["contig", "evalue"] #? set column names +df_gff["evalue"] = pd.to_numeric(df_gff["evalue"]) #? as numeric instead of object dtype + +#? Get average of all evalues per scaffold: lower taxonomische levels are averaged on and reported at the LCA-determined level. NB, many scaffolds get a 0; this is due to underflow, i.e. the number is so small it cannot be stored anymore and it might as well be 0. +df_mean_evalues = df_gff.groupby(["contig"]).mean() +#? Convert it to a log10 value, since this is the metric that MGkit uses, i.e. it does not use the default evalue as provided by BLAST but a log10 converted evalue instead. +df_log_mean_evalues = np.log10(df_mean_evalues) +df_log_mean_evalues.columns = ["Avg. log e-value"] +df_log_mean_evalues = df_log_mean_evalues.replace(-np.inf, -450) #? see comment above +df_log_mean_evalues = df_log_mean_evalues.round(decimals=1) + +#? Merge tables, add records without an LCA (i.e. LCA with taxID = 1, which is 'Root') and generate outputfile +df_tax_logevalues = pd.merge( + left=df_tax, + right=df_log_mean_evalues, + how="left", + left_on="#queryID", + right_index=True, +) +df_tax_logevalues = df_tax_logevalues.append(df_nolca, sort=False) +df_tax_logevalues.to_csv(OUTPUTFILE, index=False, sep="\t") \ No newline at end of file diff --git a/Jovian/workflow/scripts/concat_filtered_vcf.py b/Jovian/workflow/scripts/concat_filtered_vcf.py new file mode 100644 index 0000000..df15b46 --- /dev/null +++ b/Jovian/workflow/scripts/concat_filtered_vcf.py @@ -0,0 +1,83 @@ +"""Concatenate the filtered vcf files. +Usage: + concat_filtered_vcf.py + is a "glob" of vcf files, e.g. `data/scaffolds_filtered/*_filtered.vcf`. + is the output tsv (tab seperated values). +Example: + concat_filtered_vcf.py data/scaffolds_filtered/*_filtered.vcf results/all_filtered_SNPs.tsv +""" + +import pandas as pd +import glob +import os +from sys import argv + +SCRIPT, VCF_FOLDER_GLOB, OUTPUT_FILE = argv + +samples_list_MergedData = glob.glob(VCF_FOLDER_GLOB) + +column_names_list = [ + "Contig_name", + "Position", + "Identifier", + "Reference_base", + "Alternative_base", + "Quality", + "Filter_status", + "Info", + "Sample_name", +] + +MergedData_df = pd.concat( + [ + pd.read_csv( + f, sep="\t", comment="#", header=None, names=column_names_list + ).assign(Sample_name=os.path.basename(f)) + for f in samples_list_MergedData + ] +) + +cols = list(MergedData_df.columns.values) +cols.pop(cols.index("Sample_name")) +MergedData_df = MergedData_df[["Sample_name"] + cols] + +MergedData_df[ + ["Total_depth_of_coverage", "Allele_frequency", "Strand_bias", "DP4"] +] = MergedData_df["Info"].str.split(";", expand=True) +MergedData_df["Total_depth_of_coverage"] = ( + MergedData_df["Total_depth_of_coverage"].str.split("=").str[-1] +) +MergedData_df["Allele_frequency"] = ( + MergedData_df["Allele_frequency"].str.split("=").str[-1] +) +MergedData_df["Strand_bias"] = MergedData_df["Strand_bias"].str.split("=").str[-1] +MergedData_df["DP4"] = MergedData_df["DP4"].str.split("=").str[-1] +MergedData_df[ + [ + "DoC_forward_ref_allele", + "DoC_reverse_ref_allele", + "DoC_forward_non-ref_allele", + "DoC_reverse_non-ref_allele", + ] +] = MergedData_df["DP4"].str.split(",", expand=True) +MergedData_df.drop("Info", 1, inplace=True) +MergedData_df.drop("DP4", 1, inplace=True) +MergedData_df["Total_depth_of_coverage"] = MergedData_df[ + "Total_depth_of_coverage" +].astype("int") +MergedData_df["Allele_frequency"] = MergedData_df["Allele_frequency"].astype("float") +MergedData_df["Strand_bias"] = MergedData_df["Strand_bias"].astype("int") +MergedData_df["DoC_forward_ref_allele"] = MergedData_df[ + "DoC_forward_ref_allele" +].astype("int") +MergedData_df["DoC_reverse_ref_allele"] = MergedData_df[ + "DoC_reverse_ref_allele" +].astype("int") +MergedData_df["DoC_forward_non-ref_allele"] = MergedData_df[ + "DoC_forward_non-ref_allele" +].astype("int") +MergedData_df["DoC_reverse_non-ref_allele"] = MergedData_df[ + "DoC_reverse_non-ref_allele" +].astype("int") + +MergedData_df.to_csv(OUTPUT_FILE, index=False, sep="\t") \ No newline at end of file diff --git a/Jovian/workflow/scripts/concatenate_mapped_read_counts.py b/Jovian/workflow/scripts/concatenate_mapped_read_counts.py new file mode 100644 index 0000000..34352b0 --- /dev/null +++ b/Jovian/workflow/scripts/concatenate_mapped_read_counts.py @@ -0,0 +1,131 @@ +""" +Author: Sam Nooij +Date: 8 November 2019 +Concatenate mapped read counts per sample into an overall +read count table. Also checks for duplicated scaffold +names. +Requires input files with a file name that ends with: +-{sample}.tsv +where {sample} is the name of the sample. +Example use: +$ python3 concatenate_mapped_read_counts.py mapped_read_counts-1.tsv mapped_read_counts-2.tsv mapped_read_counts-3.tsv mapped_read_counts.tsv +""" + +# IMPORT required libraries-------------------------------- +import pandas as pd +import argparse +import os + +# Define FUNCTIONS----------------------------------------- + + +def parse_arguments(): + """ + Parse the arguments from the command line, i.e.: + -i/--input = list of input files (tab-separated tables) + -o/--output = output file (tab-separated table) + -h/--help = show help + """ + parser = argparse.ArgumentParser( + prog="concatenate mapped read counts", + description="Concatenate mapped read count tables", + usage="concatenate_mapped_read_counts.py -i [input] -o [output]" + " [-h / --help]", + add_help=False, + ) + + required = parser.add_argument_group("Required arguments") + + required.add_argument( + "-i", + "--input", + dest="input", + metavar="", + required=True, + type=str, + nargs="+", + help="List of input files (counts per sample).", + ) + + required.add_argument( + "-o", + "--output", + dest="output", + metavar="", + required=True, + type=str, + help="Output file name (and directory).", + ) + + (args, extra_args) = parser.parse_known_args() + + return args + + +def main(): + """ + Main execution of the script + """ + # 1. Parse and show arguments + arguments = parse_arguments() + + message = ( + "\n" + "These are the arguments you have provided:\n" + " INPUT:\n" + "{0},\n" + " OUTPUT:\n" + "{1}\n".format(arguments.input, arguments.output) + ) + + print(message) + + # 2. Read input files and make into one dataframe + concat_df = pd.DataFrame() + + for file in arguments.input: + if file.count("-") > 1: + # If there are multiple dashes in the file name, the + # sample name contains one or more dashes. + sample = os.path.splitext("-".join(file.split("-")[1:]))[0] + # So sample should include all parts separated by dashes. + else: + # Otherwise, the sample name has no dashes and splitting + # the filename in two will work. + sample = os.path.splitext(file.split("-")[-1])[0] + df = pd.read_csv(file, sep="\t") + df["Sample_name"] = sample + + concat_df = pd.concat([concat_df, df]) + + # 3. Check for duplicated scaffold names + if len(concat_df["scaffold_name"]) > len(set(concat_df["scaffold_name"])): + # If the whole list is longer than the deduplicated 'set', + # there must be a duplicate in the list. + print("Warning, duplicated scaffold name suspected!") + print("Total number of scaffolds: %i" % len(concat_df["scaffold_name"])) + print( + "Number of unique scaffold names: %i" % len(set(concat_df["scaffold_name"])) + ) + print("-------------------------------------") + duplicates = concat_df[concat_df.duplicated(["scaffold_name"], keep=False)] + print("These are the duplicates:\n\n", duplicates) + print( + "\nAs contig names are unique _per sample_, " + "you should also filter by *Sample_name* to " + "separate scaffolds and count correctly." + ) + print("(This is done automatically with " "'quantify_output.py')") + + else: + # Otherwise, there should be no duplicates and everything + # is fine. + print("No duplicate scaffold names found. Proceed normally.") + + # 4. Write table to a tsv file + concat_df.to_csv(arguments.output, sep="\t", index=False) + + +# EXECUTE script-------------------------------------------- +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Jovian/workflow/scripts/count_mapped_reads.sh b/Jovian/workflow/scripts/count_mapped_reads.sh new file mode 100644 index 0000000..f66a2f3 --- /dev/null +++ b/Jovian/workflow/scripts/count_mapped_reads.sh @@ -0,0 +1,32 @@ +# Script to count reads mapped to scaffolds, +# counting ONLY PRIMARY alignments and +# NO SUPPLEMENTARY alignments. + +# Returns counts as a table with two columns: +# 'scaffold_name' and 'mapped_reads' +# (for merging with all_taxClassified.tsv and +# all_taxUnclassified.tsv in bin/quantify_output.py). + +# Requires an input file as command-line argument. +# Recommended to redirect output to a (tsv) file. +# Example: +# $ bash count_mapped_reads.sh data/mapped_reads.bam > results/mapped_read_counts.tsv + +INPUT_FILE=$1 + +#Write a header line +printf "mapped_reads\tscaffold_name\n" + +#Append read counts and scaffold names +samtools view -F 4 -F 256 -F 2048 $INPUT_FILE | cut -f 3 | sort | uniq -c | sed $"s/NODE_/\tNODE_/g" + +#Pipe explained: +# 1. use samtools to parse the bam file (samtools view) +# 1.1 exclude unmapped reads (-F 4) +# 1.2 exclude 'not primary alignments' (-F 256) +# 1.3 exclude supplementary alignments (-F 2048) +# (mates may be extracted separately by using the flag -F 8/-f 8 +# to exclude or include reads for which the mate is unmapped) +# 2. cut only the scaffold names from the sam file output (cut) +# 3. count the number of occurrences of each scaffold name (sort | uniq -c) +# 4. insert a tab to make a tab-separated table (sed) \ No newline at end of file diff --git a/Jovian/workflow/scripts/draw_heatmaps.py b/Jovian/workflow/scripts/draw_heatmaps.py new file mode 100644 index 0000000..6f050a3 --- /dev/null +++ b/Jovian/workflow/scripts/draw_heatmaps.py @@ -0,0 +1,910 @@ +""" +# Create a heatmap of taxa in all analysed samples, quantified by the number of reads per sample + +Date: 13 Nov 2018 +Author: Sam Nooij + +Input: Identified taxa, number of reads (or read pairs) per taxon, total number of reads per sample + +Output: Heatmap of taxa in different samples from the same run, quantified by their read numbers to look at the differences between samples + + - 14 Nov 2018 update: changed notebook into regular Python script that is run by the Snakefile + - 30 Apr 2019 update: start complete rework to make the script snakemake-independent and fix bugs + - 10 Sep 2019 update: restore superkingdom heatmap to former version that leaves out empty values, + and draw heatmaps in single files using tabs for taxonomic ranks + +Required Python packages: + - Pandas + - Bokeh +""" + +# IMPORT required libraries-------------------------------- +import argparse +import re +import numpy as np +import pandas as pd +from bokeh.plotting import figure, output_file, save +from bokeh.models import HoverTool, ColumnDataSource +from bokeh.models.widgets import Tabs, Panel + + +# Set global VARIABLES------------------------------------- +RANKS = ["superkingdom", "phylum", "class", "order", "family", "genus", "species"] + +PHAGE_FAMILY_LIST = [ + "Myoviridae", + "Siphoviridae", + "Podoviridae", + "Lipothrixviridae", + "Rudiviridae", + "Ampullaviridae", + "Bicaudaviridae", + "Clavaviridae", + "Corticoviridae", + "Cystoviridae", + "Fuselloviridae", + "Globuloviridae", + "Guttaviridae", + "Inoviridae", + "Leviviridae", + "Microviridae", + "Plasmaviridae", + "Tectiviridae", +] + + +# Define FUNCTIONS----------------------------------------- +def parse_arguments(): + """ + Parse the arguments from the command line, i.e.: + -c/--classified = table with taxonomic classifications + -n/--numbers = file with (MultiQC, Trimmomatic's) read numbers + -s/--super = output file for superkingdoms heatmap + -v/--virus = output file for virus heatmap + -p/--phage = output file for phage heatmap + -b/--bact = output file for bacteria heatmap + -sq/--super-quantities = output file for superkingdom quantities + -st/--stats = output file with taxonomic rank statistics + -vs/--vir-stats = ouput file for viral statistis + -ps/--phage-stats = output file for phage statistics + -bs/--bact-stats = output file for bacterial statistics + -col/--colour = heatmap colour + -h/--help = show help + """ + parser = argparse.ArgumentParser( + prog="draw heatmaps", + description="Draw heatmaps for the Jovian taxonomic output", + usage="draw_heatmaps.py -c -n -s -v -p -b -sq -st -vs -ps -bs -col" + " [-h / --help]", + add_help=False, + ) + + required = parser.add_argument_group("Required arguments") + + required.add_argument( + "-c", + "--classified", + dest="classified", + metavar="", + required=True, + type=str, + help="Table with taxonomic classifications.", + ) + + required.add_argument( + "-n", + "--numbers", + dest="numbers", + metavar="", + required=True, + type=str, + help="Multiqc Trimmomatic file with read numbers", + ) + + required.add_argument( + "-sq", + "--super-quantities", + dest="super_quantities", + metavar="", + required=True, + type=str, + help="Table with superkingdom quantities per sample", + ) + + required.add_argument( + "-st", + "--stats", + dest="stats", + metavar="", + required=True, + type=str, + help="Table with taxonomic rank statistics", + ) + + required.add_argument( + "-vs", + "--vir-stats", + dest="vir_stats", + metavar="", + required=True, + type=str, + help="Table with virual taxonomic rank statistics", + ) + + required.add_argument( + "-ps", + "--phage-stats", + dest="phage_stats", + metavar="", + required=True, + type=str, + help="Table with phage taxonomic rank statistics", + ) + + required.add_argument( + "-bs", + "--bact-stats", + dest="bact_stats", + metavar="", + required=True, + type=str, + help="Table with bacterial taxonomic rank statistics", + ) + + required.add_argument( + "-s", + "--super", + dest="super", + metavar="", + required=True, + type=str, + help="File name for superkingdoms heatmap", + ) + + required.add_argument( + "-v", + "--virus", + dest="virus", + metavar="", + required=True, + type=str, + help="Virus heatmap file name", + ) + + required.add_argument( + "-p", + "--phage", + dest="phage", + metavar="", + required=True, + type=str, + help="Phage heatmap file name", + ) + + required.add_argument( + "-b", + "--bact", + dest="bact", + metavar="", + required=True, + type=str, + help="Bacterium heatmap file", + ) + + optional = parser.add_argument_group("Optional arguments") + + optional.add_argument( + "-col", + "--colour", + dest="colour", + metavar="", + required=False, + type=str, + nargs="+", + default=["#000000"], + help="Colour of the heatmap tiles", + ) + + optional.add_argument( + "-h", "--help", action="help", help="Show this message and exit." + ) + + (args, extra_args) = parser.parse_known_args() + + return args + + +def read_numbers(infile): + """ + Input: Tabular text file (.tsv) with number of reads/read pairs per sample + Output: Pandas Dataframe with sample names and numbers in columns + """ + # Read the number of read pairs per read set/sample + numbers_df = pd.read_csv(infile, delimiter="\t") + numbers_df = numbers_df[["Sample", "input_read_pairs"]] + numbers_df = numbers_df.rename(columns={"input_read_pairs": "read_pairs"}) + + regex = re.compile(r"(.*)(_|\.)R?[12][_.]?") + numbers_df["Sample"] = numbers_df.Sample.apply( + lambda x: re.search(regex, x).group(1) + ) # On every value in column named "Sample" perform regex capture as to only get the sample name (text before the "_R?[12][_.]?"). + + return numbers_df + + +def read_classifications(infile): + """ + Input: Tabulers text file (.tsv) with output from PZN analysis: + classifications for scaffolds and quantitative information of mapped-back reads, + for _all samples analysed in the same run_ + Output: Pandas Dataframe with the information of the classified scaffolds + """ + # Initialise the dataframe with taxonomic classifications + # and numbers of reads mapped to the scaffolds (i.e. + # the result/output of the pipeline). + classifications_df = pd.read_csv(infile, delimiter="\t") + + # Check column names for debugging: + # print(classifications_df.columns) + + # Select only relevant columns: + classifications_df = classifications_df[ + [ + "Sample_name", + "scaffold_name", + "taxID", + "tax_name", + "superkingdom", + "kingdom", + "phylum", + "class", + "order", + "family", + "genus", + "species", + "Plus_reads", + "Minus_reads", + "Avg_fold", + "Length", + "Nr_ORFs", + ] + ] + + # Calculate the number of read pairs matched to each scaffold + # by averaging the plus and minus reads. + # N.B. This is an imperfect approximation. + classifications_df["reads"] = round( + (classifications_df.Plus_reads + classifications_df.Minus_reads) / 2 + ) + + return classifications_df + + +def filter_taxa(df, taxon, rank): + """ + Filter taxa of interest of a certain rank from + a dataframe. + (taxon may be a single taxon as string, or a list of taxa) + """ + if isinstance(taxon, str): + # If a string is provided, continue as intended + subset_df = df[df[rank] == taxon] + elif isinstance(taxon, list) and len(taxon) == 1: + # If a single-entry list is provided, use taxon as string + taxon = taxon[0] + subset_df = df[df[rank] == taxon] + else: + # If a list is provided, filter all given taxa + taxa_list = taxon + subset_df = df[df[rank].isin(taxa_list)] + + return subset_df + + +def remove_taxa(df, taxon, rank): + """ + Negative filter of taxa of a certain rank from + a dataframe: remove them and keep the rest. + (taxon may be a single taxon as string, or a list of taxa) + """ + if isinstance(taxon, str): + # If a string is provided, continue as intended + subset_df = df[~df[rank] == taxon] + elif isinstance(taxon, list) and len(taxon) == 1: + # If a single-entry list is provided, use taxon as string + taxon = taxon[0] + subset_df = df[~df[rank] == taxon] + else: + # If a list is provided, filter all given taxa + taxa_list = taxon + subset_df = df[~df[rank].isin(taxa_list)] + + return subset_df + + +def report_taxonomic_statistics(df, outfile): + """ + Input: dataframe with classifications of scaffolds, a name for an output file (txt) + Output: a list of statistics in a text file, like: + superkingdom 4 + phylum 50 + class 99 + order 220 + family 373 + genus 649 + species 337 + """ + header = "taxonomic_level\tnumber_found\n" + with open(outfile, "w") as f: + f.write(header) + # Count how many taxa have been reported + for t in [ + "superkingdom", + "phylum", + "class", + "order", + "family", + "genus", + "species", + ]: + f.write("%s\t%i\n" % (t, df[t].nunique())) + + print("File %s has been created!" % outfile) + + return None + + +def draw_heatmaps(df, outfile, title, taxonomic_rank, colour): + """ + Draw heatmaps for the given input dataframe, to + the specified file with the given title. + """ + # If the sample contains only superkingdom information, use that: + if taxonomic_rank == "superkingdom": + # create source info + # and set hovertool tooltip parameters + samples = df["Sample_name"].astype(str) + assigned = df["superkingdom"].astype(str) + reads = df["reads"].astype(float) + percent_of_total = df["Percentage"].astype(float) + + colors = len(reads) * colour # multiply to make an equally long list + + max_load = max(percent_of_total) + alphas = [min(x / float(max_load), 0.9) + 0.1 for x in percent_of_total] + + source = ColumnDataSource( + data=dict( + samples=samples, + assigned=assigned, + reads=reads, + percent_of_total=percent_of_total, + colors=colors, + alphas=alphas, + ) + ) + + y_value = (assigned, "assigned") + + # Otherwise, create the usual heatmap input info for each + # (relevant) taxonomic rank down to species. + else: + # Remove 'unclassified' taxa: NaN in dataframe + df = df[df[taxonomic_rank].notnull()] + + # Check if the dataframe is empty + if df.empty: + # If so, warn the user and exit + return (None, False) + + else: + # If it is not empty, continue normally + if ( + max(pd.DataFrame(df.groupby(["Sample_name", taxonomic_rank]).size())[0]) + > 3 + ): + # if there are taxa with more than 3 contigs *in one sample* + # the hover info boxes will be too many, so + # aggregate statistics per taxon + + aggregated = True + + new_df = pd.DataFrame( + df.groupby(["Sample_name", taxonomic_rank]).size() + ).reset_index() + new_df = new_df.rename(columns={0: "Number_of_contigs"}) + + min_df = pd.DataFrame( + df.groupby(["Sample_name", taxonomic_rank]).min() + ).reset_index() + max_df = pd.DataFrame( + df.groupby(["Sample_name", taxonomic_rank]).max() + ).reset_index() + sum_df = pd.DataFrame( + df.groupby(["Sample_name", taxonomic_rank]).sum() + ).reset_index() + avg_df = pd.DataFrame( + df.groupby(["Sample_name", taxonomic_rank]).mean() + ).reset_index() + + for column in [ + "Plus_reads", + "Minus_reads", + "Avg_fold", + "Length", + "Percentage", + "Nr_ORFs", + ]: + min_df = min_df.rename(columns={column: "MIN_%s" % column}) + max_df = max_df.rename(columns={column: "MAX_%s" % column}) + sum_df = sum_df.rename(columns={column: "SUM_%s" % column}) + avg_df = avg_df.rename(columns={column: "AVG_%s" % column}) + + new_df["MIN_%s" % column] = min_df["MIN_%s" % column] + new_df["MAX_%s" % column] = max_df["MAX_%s" % column] + new_df["SUM_%s" % column] = sum_df["SUM_%s" % column] + new_df["AVG_%s" % column] = avg_df["AVG_%s" % column] + + for stat in ["MIN", "MAX", "SUM", "AVG"]: + new_df["%s_reads" % stat] = ( + new_df["%s_Minus_reads" % stat] + new_df["%s_Plus_reads" % stat] + ) + + new_df["tax_name"] = min_df["tax_name"] + new_df["taxon"] = min_df[taxonomic_rank] + new_df["total_reads"] = df["read_pairs"] + + new_df = new_df.fillna(0) + + samples = new_df["Sample_name"].astype(str) + nr_contigs = new_df["Number_of_contigs"].astype(int) + assigned = new_df["tax_name"].astype(str) + taxonomy = new_df["taxon"].astype(str) + min_reads = new_df["MIN_reads"].astype(int) + max_reads = new_df["MAX_reads"].astype(int) + sum_reads = new_df["SUM_reads"].astype(int) + avg_reads = new_df["AVG_reads"].astype(int) + total_reads = new_df["total_reads"].astype(int) + min_percentage = new_df["MIN_Percentage"].astype(float) + max_percentage = new_df["MAX_Percentage"].astype(float) + sum_percentage = new_df["SUM_Percentage"].astype(float) + avg_percentage = new_df["AVG_Percentage"].astype(float) + min_coverage = new_df["MIN_Avg_fold"].astype(int) + max_coverage = new_df["MAX_Avg_fold"].astype(int) + sum_coverage = new_df["SUM_Avg_fold"].astype(int) + avg_coverage = new_df["AVG_Avg_fold"].astype(int) + min_length = new_df["MIN_Length"].astype(int) + max_length = new_df["MAX_Length"].astype(int) + sum_length = new_df["SUM_Length"].astype(int) + avg_length = new_df["AVG_Length"].astype(int) + min_nr_orfs = new_df["MIN_Nr_ORFs"].astype(int) + max_nr_orfs = new_df["MAX_Nr_ORFs"].astype(int) + sum_nr_orfs = new_df["SUM_Nr_ORFs"].astype(int) + avg_nr_orfs = new_df["AVG_Nr_ORFs"].astype(int) + + colors = len(samples) * colour + + max_load = max(avg_percentage) + alphas = [min(x / float(max_load), 0.9) + 0.1 for x in avg_percentage] + # scale darkness to the average percentage of reads + + source = ColumnDataSource( + data=dict( + samples=samples, + nr_contigs=nr_contigs, + assigned=assigned, + taxonomy=taxonomy, + min_reads=min_reads, + max_reads=max_reads, + sum_reads=sum_reads, + avg_reads=avg_reads, + total_reads=total_reads, + min_percentage=min_percentage, + max_percentage=max_percentage, + sum_percentage=sum_percentage, + avg_percentage=avg_percentage, + min_coverage=min_coverage, + max_coverage=max_coverage, + sum_coverage=sum_coverage, + avg_coverage=avg_coverage, + min_length=min_length, + max_length=max_length, + sum_length=sum_length, + avg_length=avg_length, + min_nr_orfs=min_nr_orfs, + max_nr_orfs=max_nr_orfs, + sum_nr_orfs=sum_nr_orfs, + avg_nr_orfs=avg_nr_orfs, + colors=colors, + alphas=alphas, + ) + ) + + else: + # no taxon has too many contigs assigned per sample, + # so create a plot for everything + + aggregated = False + + df.fillna(0, inplace=True) + + samples = df["Sample_name"].astype(str) + scaffolds = df["scaffold_name"].astype(str) + assigned = df["tax_name"].astype(str) + taxonomy = df[taxonomic_rank].astype(str) + reads = df["reads"].astype(int) + total_reads = df["read_pairs"].astype(int) + percent_of_total = df["Percentage"].astype(float) + coverage = df["Avg_fold"].astype(int) + contig_length = df["Length"].astype(int) + nr_orfs = df["Nr_ORFs"].astype(int) + + colors = len(reads) * colour # multiply to make an equally long list + + max_load = max(percent_of_total) + alphas = [min(x / float(max_load), 0.9) + 0.1 for x in percent_of_total] + + source = ColumnDataSource( + data=dict( + samples=samples, + scaffolds=scaffolds, + assigned=assigned, + taxonomy=taxonomy, + reads=reads, + total_reads=total_reads, + percent_of_total=percent_of_total, + coverage=coverage, + contig_length=contig_length, + nr_orfs=nr_orfs, + colors=colors, + alphas=alphas, + ) + ) + + y_value = (taxonomy, "taxonomy") + + TOOLS = "hover, save, pan, box_zoom, wheel_zoom, reset" + + p = figure( + title=title, + # If desired, the sample can be displayed as "Run x, sample y" + # -> uncomment the next line + # x_range = [ "Run %s, sample %s" % (x.split('_')[0], x.split('_')[1]) for x in list(sorted(set(samples))) ], + x_range=list(sorted(set(df["Sample_name"]))), + y_range=list( + reversed(sorted(set(y_value[0]))) + ), # reverse to order 'from top to bottom' + x_axis_location="above", + toolbar_location="right", + tools=TOOLS, + ) + + # Edit the size of the heatmap when there are many samples and/or taxa + if len(set(samples)) > 20: + p.plot_width = int(len(set(samples)) * 25) + else: + pass + # Adjust heatmap sizes depending on the number of + # taxa observed (not applicable for superkingdom heatmap) + if taxonomic_rank != "superkingdom": + if len(set(taxonomy)) > 100: + p.plot_height = int(p.plot_height * 3) + p.plot_width = int(p.plot_width * 1.5) + elif len(set(taxonomy)) > 50: + p.plot_height = int(p.plot_height * 2) + p.plot_width = int(p.plot_width * 1.2) + elif len(set(taxonomy)) > 25: + p.plot_height = int(p.plot_height * 1.2) + else: + pass + + # And set tooltip depending on superkingdoms + + if aggregated: + # An aggregated format requires a different hover tooltip + p.select_one(HoverTool).tooltips = [ + ("Sample", "@samples"), + ("Taxon", "@assigned"), + ("Number of scaffolds", "@nr_contigs"), + # ('-----', ""), # If you like a separator in the tooltip + ( + "Number of reads total (min, avg, max)", + "@sum_reads (@min_reads, @avg_reads, @max_reads)", + ), + ( + "Scaffold length total (min, avg, max)", + "@sum_length (@min_length, @avg_length, @max_length)", + ), + ( + "Number of ORFs total (min, avg, max)", + "@sum_nr_orfs (@min_nr_orfs, @avg_nr_orfs, @max_nr_orfs)", + ), + ( + "Depth of coverage total (min, avg, max)", + "@sum_coverage (@min_coverage, @avg_coverage*, @max_coverage)", + ), + ("*", "darkness scaled to this number"), + ] + else: + p.select_one(HoverTool).tooltips = [ + ("Sample", "@samples"), + ("Scaffold", "@scaffolds"), + ("Taxon", "@assigned"), + ("Number of reads", "@reads (@percent_of_total % of sample total)"), + ("Scaffold length", "@contig_length"), + ("Number of ORFs", "@nr_orfs"), + ("Average Depth of Coverage", "@coverage"), + ] + else: + p.select_one(HoverTool).tooltips = [ + ("Sample", "@samples"), + ("Taxon", "@assigned"), + ("Number of reads", "@reads"), + ("Percentage of total", "@percent_of_total %"), + ] + + p.grid.grid_line_color = None + p.axis.axis_line_color = None + p.axis.major_tick_line_color = None + if len(set(assigned)) > 15: + p.axis.major_label_text_font_size = "10pt" + else: + p.axis.major_label_text_font_size = "12pt" + p.axis.major_label_standoff = 0 + p.xaxis.major_label_orientation = np.pi / 4 + p.title.text_color = colour[0] + p.title.text_font_size = "16pt" + p.title.align = "right" + + p.rect( + "samples", + y_value[1], + 1, + 1, + source=source, + color="colors", + alpha="alphas", + line_color=None, + ) + + panel = Panel(child=p, title=title.split()[1].title()) + # the .title() methods capitalises a string + + if taxonomic_rank == "superkingdom": + # The superkingdom heatmap still requires a single output file + output_file(outfile, title=title) + save(p) + print("The heatmap %s has been created and written to: %s" % (title, outfile)) + return None + else: + return (panel, True) + + +def main(): + """ + Main execution of the script + """ + # 1. Parse and show arguments + arguments = parse_arguments() + + message = ( + "\n" + "These are the arguments you have provided:\n" + " INPUT:\n" + "classified = {0},\n" + "numbers = {1}\n" + " OUTPUT:\n" + "super = {2}\n" + "virus = {3}\n" + "phage = {4}\n" + "bact = {5}\n" + "super_quantities = {6}\n" + "stats = {7}\n" + "vir_stats = {8}\n" + "phage_stats = {9}\n" + "bact_stats = {10}\n" + " OPTIONAL PARAMETERS:\n" + "colour = {11}\n".format( + arguments.classified, + arguments.numbers, + arguments.super, + arguments.virus, + arguments.phage, + arguments.bact, + arguments.super_quantities, + arguments.stats, + arguments.vir_stats, + arguments.phage_stats, + arguments.bact_stats, + arguments.colour, + ) + ) + + print(message) + + # 2. Read input files and make dataframes + numbers_df = read_numbers(arguments.numbers) + classifications_df = read_classifications(arguments.classified) + + merged_df = classifications_df.merge( + numbers_df, left_on="Sample_name", right_on="Sample" + ) + merged_df["Percentage"] = merged_df.reads / merged_df.read_pairs * 100 + + # 3. Create chunks of information required for the heatmaps + # 3.1. Aggregate superkingdom-rank information + # Count the percentages of Archaea, Bacteria, Eukaryota and Viruses per sample: + superkingdom_sums = pd.DataFrame( + merged_df.groupby(["Sample_name", "superkingdom"]).sum()[ + ["reads", "Percentage"] + ] + ) + superkingdom_sums.reset_index( + inplace=True + ) # to use MultiIndex "Sample_name" and "superkingdom" as columns + + superkingdom_sums.to_csv(arguments.super_quantities, index=False) + print("File %s has been created!" % arguments.super_quantities) + + # 3.2. Filter viruses from the table + virus_df = filter_taxa(df=merged_df, taxon="Viruses", rank="superkingdom") + # Remove the phages from the virus df to make less cluttered heatmaps + virus_df = remove_taxa(df=virus_df, taxon=PHAGE_FAMILY_LIST, rank="family") + + # 3.3. Filter phages + phage_df = filter_taxa(df=merged_df, taxon=PHAGE_FAMILY_LIST, rank="family") + + # 3.4. Filter bacteria + bacterium_df = filter_taxa(df=merged_df, taxon="Bacteria", rank="superkingdom") + + # 4. Write taxonomic rank statistics to a file, for each chunk + # 4.1. All taxa + report_taxonomic_statistics(df=merged_df, outfile=arguments.stats) + # 4.2. Viruses + report_taxonomic_statistics(df=virus_df, outfile=arguments.vir_stats) + # 4.3. Phages + report_taxonomic_statistics(df=phage_df, outfile=arguments.phage_stats) + # 4.4. Bacteria + report_taxonomic_statistics(df=bacterium_df, outfile=arguments.bact_stats) + + # 5. Draw heatmaps for each chunk + # 5.1. All taxa: superkingdoms + draw_heatmaps( + df=superkingdom_sums, + outfile=arguments.super, + title="Superkingdoms heatmap", + taxonomic_rank="superkingdom", + colour=arguments.colour, + ) + + # 5.2. Viruses + virus_tabs = [] + for rank in RANKS[3:]: + # Create heatmaps for each rank below 'class' + (content, panel) = draw_heatmaps( + df=virus_df, + outfile=None, + title="Virus %s heatmap" % rank, + taxonomic_rank=rank, + colour=arguments.colour, + ) + # Check if there was data to make a panel + if panel: + virus_tabs.append(content) + + # if there was no data, print a warning and do not add nonsense panel + else: + print("No data for the current virus rank! (%s)" % rank) + print( + "\n---\nThere are no contigs for the given %s. No virus %s heatmap can be made.\n---\n" + % (rank, rank) + ) + + if len(virus_tabs) > 1: + # multiple tabs: create figure with tabs + output_file(arguments.virus, title="Virus heatmap") + tabs = Tabs(tabs=virus_tabs) + save(tabs) + print("The Virus heatmap has been created and written to: %s" % arguments.virus) + elif len(virus_tabs) == 1: + # single tab: create regular figure + output_file(arguments.virus, title="Virus heatmap") + save(virus_tabs[0]) + else: + # no tabs: warn user that no heatmap can be made + print( + "\n---\nThere are no contigs for Viruses in this sample! No virus heatmap is made.\n---\n" + ) + with open(arguments.virus, "w") as outfile: + outfile.write("No virus contigs found in the current dataset.") + + # 5.3. Phages + phage_tabs = [] + for rank in RANKS[3:]: + # Create heatmaps for each rank below 'class' + (content, panel) = draw_heatmaps( + df=phage_df, + outfile=None, + title="Phage %s heatmap" % rank, + taxonomic_rank=rank, + colour=arguments.colour, + ) + + # Check if there was data to make a panel + if panel: + phage_tabs.append(content) + + # if there was no data, print a warning and do not add nonsense panel + else: + print("No data for the current phage rank! (%s)" % rank) + print( + "\n---\nThere are no contigs for the given %s. No phage %s heatmap can be made.\n---\n" + % (rank, rank) + ) + + if len(phage_tabs) > 1: + # multiple tabs: create figure with tabs + output_file(arguments.phage, title="Phage heatmap") + tabs = Tabs(tabs=phage_tabs) + save(tabs) + print("The Phage heatmap has been created and written to: %s" % arguments.phage) + elif len(phage_tabs) == 1: + # single tab: create regular figure + output_file(arguments.phage, title="Phage heatmap") + save(phage_tabs[0]) + else: + # no tabs: warn user that no heatmap can be made + print( + "\n---\nThere are no contigs for phages in this sample! No phage heatmap is made.\n---\n" + ) + with open(arguments.phage, "w") as outfile: + outfile.write("No phage contigs found in the current dataset.") + + # 5.4. Bacteria + bacterium_tabs = [] + for rank in RANKS[1:]: + # Create heatmaps for each rank below 'superkingdom' + (content, panel) = draw_heatmaps( + df=bacterium_df, + outfile=None, + title="Bacterium %s heatmap" % rank, + taxonomic_rank=rank, + colour=arguments.colour, + ) + + # Check if there was data to make a panel + if panel: + bacterium_tabs.append(content) + + # if there was no data, print a warning and do not add nonsense panel + else: + print("No data for the current bacteria rank! (%s)" % rank) + print( + "\n---\nThere are no contigs for the given %s. No bacteria %s heatmap can be made.\n---\n" + % (rank, rank) + ) + + if len(bacterium_tabs) > 1: + # multiple tabs: create figure with tabs + output_file(arguments.bact, title="Bacteria heatmap") + tabs = Tabs(tabs=bacterium_tabs) + save(tabs) + print( + "The Bacteria heatmap has been created and written to: %s" % arguments.bact + ) + elif len(bacterium_tabs) == 1: + # single tab: create regular figure + output_file(arguments.bact, title="Bacteria heatmap") + save(bacterium_tabs[0]) + else: + # no tabs: warn user that no heatmap can be made + print( + "\n---\nThere are no contigs for bacteria in this sample! No bacteria heatmap is made.\n---\n" + ) + with open(arguments.bact, "w") as outfile: + outfile.write("No bacterial contigs found in the current dataset.") + + +# EXECUTE script-------------------------------------------- +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Jovian/workflow/scripts/fqc.sh b/Jovian/workflow/scripts/fqc.sh new file mode 100644 index 0000000..63cacf6 --- /dev/null +++ b/Jovian/workflow/scripts/fqc.sh @@ -0,0 +1,47 @@ +##################################################################################################################### +### This is a wrapper for fastqc used in the snakefile. ### +### Usage: bin/fastqc_wrapper.sh {input} {params.output_dir} {output.html} {output.zip} {log} ### +### Reason: Fastqc implicitly generates output files based on the input file name. Therefore, if these are ### +### not the same, this output is moved to the explicitly Snakefile defined output location. ### +### I had to put this simple bash code into a script because of the Snakemake-bash strict settings, see: ### +### https://snakemake.readthedocs.io/en/stable/project_info/faq.html#my-shell-command-fails-with-with-errors-about-an-unbound-variable-what-s-wrong +##################################################################################################################### + +# Import the positional arguments (specified in the Snakefile) +INPUT_FILE="$1" +OUTPUT_DIR="$2" +DESIRED_OUTPUT_HTML="$3" +DESIRED_OUTPUT_ZIP="$4" +LOG="$5" +THREADS="$6" + +# Generate sample basename (i.e. remove everything before the last '/' and then remove everything after the '.') +EXTENSION1=".gz" +EXTENSION2=".fastq" +EXTENSION3=".fq" + + +SAMPLE_TEMP="${INPUT_FILE##*/}" +TEMP1=${SAMPLE_TEMP//$EXTENSION1/} +TEMP2=${TEMP1//$EXTENSION2/} +TEMP3=${TEMP2//$EXTENSION3/} + +SAMPLE_NAME="${TEMP3}" + +# These are the output files that fastqc implicitly generates (based on the input file basename) +REAL_OUTPUT_HTML="${OUTPUT_DIR}${SAMPLE_NAME}_fastqc.html" +REAL_OUTPUT_ZIP="${OUTPUT_DIR}${SAMPLE_NAME}_fastqc.zip" + +# Run fastqc +fastqc -t ${THREADS} --quiet --outdir ${OUTPUT_DIR} ${INPUT_FILE} > ${LOG} 2>&1 + +# If the implicit output file are not equal to the explicitly defined output in the Snakefile, rename them to the explicitly defined output name. +if [ "$DESIRED_OUTPUT_HTML" != "$REAL_OUTPUT_HTML" ] +then + mv $REAL_OUTPUT_HTML $DESIRED_OUTPUT_HTML +fi + +if [ "$DESIRED_OUTPUT_ZIP" != "$REAL_OUTPUT_ZIP" ] +then + mv $REAL_OUTPUT_ZIP $DESIRED_OUTPUT_ZIP +fi \ No newline at end of file diff --git a/Jovian/workflow/scripts/html/igvjs_write_divs.sh b/Jovian/workflow/scripts/html/igvjs_write_divs.sh new file mode 100644 index 0000000..6184a53 --- /dev/null +++ b/Jovian/workflow/scripts/html/igvjs_write_divs.sh @@ -0,0 +1,14 @@ +# shellcheck shell=bash +# This script (part 2) this script writes the various div elements for the samples +# this script should be called for every sample individually. + +INPUT="$1" +OUTPUT_HTML="$2" + +SAMPLE="sample_${INPUT//-/_}" + +cat << EOF >> ${OUTPUT_HTML} +
+
+
+EOF diff --git a/Jovian/workflow/scripts/html/igvjs_write_flex_js_middle.sh b/Jovian/workflow/scripts/html/igvjs_write_flex_js_middle.sh new file mode 100644 index 0000000..d9ca4d7 --- /dev/null +++ b/Jovian/workflow/scripts/html/igvjs_write_flex_js_middle.sh @@ -0,0 +1,71 @@ +# shellcheck shell=bash +# This script (part 3) this script writes the flexible part of the required JavaScript +# this script should be called for every sample. + +INPUT="$1" +OUTPUT_HTML="$2" +INPUT_REF_FASTA="$3" +INPUT_REF_GC_BEDGRAPH="$4" +INPUT_REF_ZIPPED_ORF_GFF="$5" +INPUT_ZIPPED_SNP_VCF="$6" +INPUT_SORTED_BAM="$7" +NGINX_IP="$8" +NGINX_PORT="$9" + + +SAMPLE="sample_${INPUT//-/_}" + +cat << EOF >> ${OUTPUT_HTML} + ${SAMPLE} = document.getElementById("${SAMPLE}"); + options = + { + reference: + { + id: "${INPUT}", + fastaURL: "${NGINX_IP}:${NGINX_PORT}/${INPUT_REF_FASTA}", + wholeGenomeView: false, + tracks: [ + { + type: "wig", + name: "GC contents", + format: "bedGraph", + url: "${NGINX_IP}:${NGINX_PORT}/${INPUT_REF_GC_BEDGRAPH}", + min: "0", + max: "1", + order: Number.MAX_VALUE + }, + { + name:"SNPs", + type:"variant", + format:"vcf", + url: "${NGINX_IP}:${NGINX_PORT}/${INPUT_ZIPPED_SNP_VCF}", + indexURL: "${NGINX_IP}:${NGINX_PORT}/${INPUT_ZIPPED_SNP_VCF}.tbi", + displayMode: "SQUISHED", + order: 2 + }, + { + type: "alignment", + format: "bam", + colorBy: "strand", + url: "${NGINX_IP}:${NGINX_PORT}/${INPUT_SORTED_BAM}", + indexURL: "${NGINX_IP}:${NGINX_PORT}/${INPUT_SORTED_BAM}.bai", + indexed: "true", + name: "Alignment", + showSoftClips: false, + viewAsPairs: true, + order: 3 + }, + { + type: "annotation", + name: "ORF predictions", + format: "gff3", + url: "${NGINX_IP}:${NGINX_PORT}/${INPUT_REF_ZIPPED_ORF_GFF}", + indexURL: "${NGINX_IP}:${NGINX_PORT}/${INPUT_REF_ZIPPED_ORF_GFF}.tbi", + displayMode: "EXPANDED", + order: 1 + } + ] + }, + }; + igv.createBrowser(${SAMPLE}, options); +EOF diff --git a/Jovian/workflow/scripts/html/igvjs_write_tabs.sh b/Jovian/workflow/scripts/html/igvjs_write_tabs.sh new file mode 100644 index 0000000..e8c1807 --- /dev/null +++ b/Jovian/workflow/scripts/html/igvjs_write_tabs.sh @@ -0,0 +1,12 @@ +# shellcheck shell=bash +# This script (part 1) writes the various tabs for the IGVJS html. +# This script should be called for every individual sample + +INPUT="$1" +OUTPUT_HTML="$2" + +SAMPLE="sample_${INPUT//-/_}" + +cat << EOF >> ${OUTPUT_HTML} +
  • ${SAMPLE}
  • +EOF diff --git a/Jovian/workflow/scripts/krona_magnitudes.py b/Jovian/workflow/scripts/krona_magnitudes.py new file mode 100644 index 0000000..a934b8b --- /dev/null +++ b/Jovian/workflow/scripts/krona_magnitudes.py @@ -0,0 +1,43 @@ +""" +Thierry Janssens 01 July 2019 +Add contigs withou blastn hits and magnitude information to the Krona chart. +Usage: + krona_magnitudes.py + is the file generated by `ktClassifyBLAST` or by the mgkit function taxonutils lca. + is the file generated by `BBtools pileup.sh` script. + is output taxMagtab; `ktImportTaxonomy` will use this to generate +a Krona chart where the size of the pie-parts are scaled to the number of +aligned reads. +Example: + krona_magnitudes.py data/taxonomic_classification/[sample_name].taxtab ata/taxonomic_classification/[sample_name].blastn data/scaffolds_filtered/[sample_name]_perMinLenFiltScaffold.stats data/taxonomic_classification/[sample_name].taxMagtab +""" + +import pandas as pd +import numpy as np +import sys +from sys import argv + + +SCRIPT, INPUTTAX, INPUTSTATS, OUTPUTFILE = argv + +df_tax = pd.read_csv(INPUTTAX, sep="\t") +fields = ["#ID", "Plus_reads", "Minus_reads"] + +df_stats = pd.read_csv(INPUTSTATS, sep="\t", usecols=fields) +df_statsID = df_stats["#ID"] +df_statsID.rename("#queryID", inplace=True) +df_nohits = pd.DataFrame(df_statsID[~df_statsID.isin(df_tax[df_tax.columns[0]])]) + +df_nohits.insert(loc=1, column="taxID", value=0) +df_nohits.insert(2, "Avg. log e-value", "1") +df_tax = pd.concat([df_tax, df_nohits], join_axes=[df_tax.columns]) + + +df_stats["Nr_of_reads"] = df_stats["Plus_reads"].add(df_stats["Minus_reads"]) +df_stats.drop(["Plus_reads", "Minus_reads"], axis=1, inplace=True) + +merged_tax_readCount = pd.merge( + df_tax, df_stats, how="left", left_on="#queryID", right_on="#ID" +).drop("#ID", axis=1) + +merged_tax_readCount.to_csv(OUTPUTFILE, index=False, sep="\t") \ No newline at end of file diff --git a/Jovian/workflow/scripts/merge_data.py b/Jovian/workflow/scripts/merge_data.py new file mode 100644 index 0000000..83c7d56 --- /dev/null +++ b/Jovian/workflow/scripts/merge_data.py @@ -0,0 +1,204 @@ +"""For each scaffold, merge the following data: +scaffold metrics, taxonomic classification after LCA, +virus host and disease information. +Usage: + merge_data.py + is how you want to call this sample (in plain text). + is the BBtools generated scaffold metrics file. + is the taxtab file generated by Krona after +the LCA analysis. + is the input scaffold fasta file. + is the input per scaffold ORF count list. + is the location on your filesystem where the +virus-host database can be found (Mihara et al. 2016). + is the location on your filesystem +where the NCBI "new_taxdump" file called "rankedlineage" can be found. + is the location on your filesystem +where the NCBI "new_taxdump" file called "host" can be found. + is the output file containing +the scaffolds with taxonomic classification data, i.e. +"classified" scaffolds. + is the output file containing +the scaffolds without taxonomic classification data, i.e. +"unclassified" scaffolds. + is the output file containing the host +and disease information generated by cross-referencing the +virus-host database (Mihara et al. 2016) and NCBI "host" database. +Example: + python bin/merge_data.py [sample_name] \ + data/scaffolds_filtered/[sample_name]_perMinLenFiltScaffold.stats \ + data/taxonomic_classification/[sample_name].taxtab \ + data/scaffolds_filtered/[sample_name]_scaffolds_ge500nt.fasta \ + data/scaffolds_filtered/[sample_name]_contig_ORF_count_list.txt \ + [path_to_virushost_DB] \ + [path_to_NCBI_newTaxdump_rankedlineage] \ + [path_to_NCBI_newTaxdump_host] \ + data/tables/[sample_name]_taxClassified.tsv \ + data/tables/[sample_name]_taxUnclassified.tsv \ + data/tables/[sample_name]_virusHost.tsv +""" + +import pandas as pd +from sys import argv +from Bio import SeqIO + +( + SCRIPT, + SAMPLENAME, + INPUTBBTOOLS, + INPUTKRONA, + INPUTSCAFFOLDS, + CONTIG_ORF_COUNT_LIST, + VIRUSHOSTDB, + PATH_TAXDUMP_RANKEDLINEAGE, + PATH_TAXDUMP_HOST, + OUTPUTFILE_CLASSIFIED_SCAFFOLDS_TAX_TABLE, + OUTPUTFILE_UNCLASSIFIED_SCAFFOLDS_TAX_TABLE, + OUTPUTFILE_VIRAL_SCAFFOLDS_HOSTS_TABLE, +) = argv + +# Import scaffold statistics to df +perScaffoldStats = pd.read_csv(INPUTBBTOOLS, sep="\t", header=0) +# Import Krona LCA results to df and replace spaces with underscores +kronaTaxLCA = pd.read_csv(INPUTKRONA, sep="\t", header=0) +kronaTaxLCA.columns = kronaTaxLCA.columns.str.replace("\s+", "_") +# Import virus-host DB and replace spaces with underscores +virusHostDB = pd.read_csv(VIRUSHOSTDB, sep="\t", header=0) +virusHostDB.columns = virusHostDB.columns.str.replace("\s+", "_") +# Import assembled scaffold fasta +scaffolds_dict = {"scaffold_name": [], "scaffold_seq": []} +for seq_record in SeqIO.parse(INPUTSCAFFOLDS, "fasta"): + scaffolds_dict["scaffold_name"].append(seq_record.id) + scaffolds_dict["scaffold_seq"].append(str(seq_record.seq)) +scaffoldsFasta = pd.DataFrame.from_dict(scaffolds_dict) +# Import new_taxdump rankedlineage +colnames_rankedlineage = [ + "tax_id", + "tax_name", + "species", + "genus", + "family", + "order", + "class", + "phylum", + "kingdom", + "superkingdom", +] +taxdump_rankedlineage = pd.read_csv( + PATH_TAXDUMP_RANKEDLINEAGE, + sep="|", + header=None, + names=colnames_rankedlineage, + low_memory=False, +) +# Import new_taxdump host +colnames_host = ["tax_id", "potential_hosts"] +taxdump_host = pd.read_csv( + PATH_TAXDUMP_HOST, sep="|", header=None, names=colnames_host, low_memory=False +) +# Import per scaffold ORF counts +colnames_scaffold_orf_count_list = ["Nr_ORFs", "scaffold_name"] +contig_orf_count_list = pd.read_csv( + CONTIG_ORF_COUNT_LIST, + sep="\s+", + header=None, + names=colnames_scaffold_orf_count_list, + low_memory=False, +) + + +# Merge Krona LCA with scaffold metrics +df1 = pd.merge( + perScaffoldStats, kronaTaxLCA, how="left", left_on="#ID", right_on="#queryID" +).drop("#queryID", axis=1) +# Merge above df with rankedlineage +df2 = pd.merge( + df1, taxdump_rankedlineage, how="left", left_on="taxID", right_on="tax_id" +).drop("tax_id", axis=1) +# Merge above df with ORF counts +df3 = pd.merge( + df2, contig_orf_count_list, how="left", left_on="#ID", right_on="scaffold_name" +).drop("scaffold_name", axis=1) +# Merge above df with fasta +df4 = pd.merge( + df3, scaffoldsFasta, how="left", left_on="#ID", right_on="scaffold_name" +).drop("#ID", axis=1) + +# Add sample name as first column, then reorder df as desired, then replace any spaces with underscores +df4["Sample_name"] = SAMPLENAME +colnames = [ + "Sample_name", + "scaffold_name", + "taxID", + "tax_name", + "Avg._log_e-value", + "species", + "genus", + "family", + "order", + "class", + "phylum", + "kingdom", + "superkingdom", + "Avg_fold", + "Length", + "Ref_GC", + "Nr_ORFs", + "Covered_percent", + "Covered_bases", + "Plus_reads", + "Minus_reads", + "Read_GC", + "Median_fold", + "Std_Dev", + "scaffold_seq", +] +df4 = df4.reindex(columns=colnames) + +# Slice into classified scaffolds, print to file. A selections is made that captures anything where taxID is not "1", i.e. anything that LCA doesn't assign to 'Root' and where the taxID not empty, which are records where BLAST could not identify any hits to even perform LCA on. +taxClassified = df4.loc[(df4["taxID"] != 1 ) & (df4["taxID"].notnull())] +taxClassified.to_csv(OUTPUTFILE_CLASSIFIED_SCAFFOLDS_TAX_TABLE, index=False, sep="\t") +# Slice into unclassified scaffolds, print to file. Vice versa as above. `Root` LCA assignment usually happens for bacterial seqs with integrated prophages. +taxUnclassified = df4.loc[(df4["taxID"] == 1 ) | (df4["taxID"].isnull())].drop( + [ + "taxID", + "tax_name", + "Avg._log_e-value", + "species", + "genus", + "family", + "order", + "class", + "phylum", + "kingdom", + "superkingdom", + ], + axis=1, +) +taxUnclassified.to_csv( + OUTPUTFILE_UNCLASSIFIED_SCAFFOLDS_TAX_TABLE, index=False, sep="\t" +) +# Slice into virus scaffolds with added host/disease information, print to file +virus_taxa_with_NCBIhosts = ( + pd.merge( + taxClassified.loc[taxClassified["superkingdom"] == "Viruses"].iloc[ + :, [0, 1, 2] + ], + taxdump_host, + how="left", + left_on="taxID", + right_on="tax_id", + ) + .drop("tax_id", axis=1) + .rename(columns={"potential_hosts": "NCBI_potential_hosts"}) +) +virusHost_table_raw = pd.merge( + virus_taxa_with_NCBIhosts, + virusHostDB, + how="left", + left_on="taxID", + right_on="virus_tax_id", +).drop("virus_tax_id", axis=1) +virusHost_table_raw.to_csv( + OUTPUTFILE_VIRAL_SCAFFOLDS_HOSTS_TABLE, index=False, sep="\t" +) \ No newline at end of file diff --git a/Jovian/workflow/scripts/quantify_profiles.py b/Jovian/workflow/scripts/quantify_profiles.py new file mode 100644 index 0000000..75ce34b --- /dev/null +++ b/Jovian/workflow/scripts/quantify_profiles.py @@ -0,0 +1,906 @@ +""" +Author: Sam Nooij +Date: 4 December 2018 +-- 21 May 2019 update: start complete rework to make the script snakemake-independent and fix bugs + N.B. For now, the number of threads is still passed by snakemake! + It can optionally be provided as command-line argument. +-- 19 Sep 2019 update: count mapped reads with separate script (with samtools view) + merge these reads to all_tax[Un]classified.tsv for correct quantifications +Script that gathers numbers from the PZN analysis, i.e.: + - number of reads per sample (raw) + - number of reads removed by trimmomatic + - number of human reads identified by Bowtie2 (and removed) + - number of reads mapped to scaffolds that have been classified as: + - Archaea + - Bacteria + - Eukaryota + - Viruses + - number of reads that map to unclassified scaffolds ("dark matter") +(If there is a gap between these groups and the total number of raw reads, + these were unable to assemble into contigs > 500 nt.) + +These 7 numbers are collected for each sample and written to a table (.csv file) +and a stacked bargraph is made to visualise these data. +Input: + Requires output files from FastQC, Trimmomatic, Bowtie, and the PZN taxonomic report: + - results/multiqc_data/multiqc_fastqc.txt + - results/multiqc_data/multiqc_trimmomatic.txt + - data/HuGo_removal/*.fq + - results/all_taxClassified.tsv + - results/all_taxUnclassified.tsv + +Output: + Creates two tables (number of reads and percentages), and stacked bar charts: + - results/read_counts.csv + - results/profile_percentages.csv + - results/Sample_composition_graph.html +""" + +### Import required libraries ------------------------------------ +import argparse +import datetime +import os +import sys +import re +import pandas as pd +from bokeh.core.properties import value +from bokeh.io import save, output_file +from bokeh.plotting import figure +from bokeh.models.widgets import Tabs, Panel +from bokeh.models import ColumnDataSource +import concurrent.futures + +### Define global variables -------------------------------------- +FASTQ_COUNT_WARINING_MESSAGE = """ +Now counting the number of lines in the fastq files from which +reads have been discarded that were mapped to the human genome +by Bowtie2 to determine the number of non-human reads. +This may take a while... +""" + +COLOURS = [ + "#FFDBE5", + "#7A4900", + "#0000A6", + "#63FFAC", + "#B79762", + "#004D43", + "#8FB0FF", + "#997D87", +] +# Colour scheme with distinct colours thanks to Tatarize +# (https://godsnotwheregodsnot.blogspot.com/2013/11/kmeans-color-quantization-seeding.html) +# And Alexey Popkov (https://graphicdesign.stackexchange.com/revisions/3815/8) + +### Create functions that do all the work ------------------------ +def parse_arguments(): + """ + Parse the arguments from the command line, i.e.: + -f/--fastqc = file with (multiqc) fastqc output + -t/--trimmomatic = file with (multiqc) trimmomatic output + -hg/--hugo = fastq files of extracted human reads + -c/--classified = table with taxonomic classifications + -u/--unclassified = table with unclassified contigs + -m/--mapped_reads = table with number of mapped reads + -co/--counts = output file (table) with counts + -pg/--percentages = output file (table) with percentages + -cpu/--cpu-cores = number of cores (threads) to use + -col/--colours = colours to use in figure/barchart (8 colours) + -h/--help = show help + """ + parser = argparse.ArgumentParser( + prog="draw heatmaps", + description="Draw heatamps for the Jovian taxonomic output", + usage="quantify_profiles.py -f -t -hg -c -u" " [-h / --help]", + add_help=False, + ) + + required = parser.add_argument_group("Required arguments") + + required.add_argument( + "-f", + "--fastqc", + dest="fastqc", + metavar="", + required=True, + type=str, + help="MultiQC-FastQC output file", + ) + + required.add_argument( + "-t", + "--trimmomatic", + dest="trimmomatic", + metavar="", + required=True, + type=str, + help="MultiQC-Trimmomatic output file", + ) + + required.add_argument( + "-hg", + "--hugo", + dest="hugo", + metavar="", + required=True, + type=str, + nargs="+", + help="Fastq files of extracted human reads", + ) + + required.add_argument( + "-c", + "--classified", + dest="classified", + metavar="", + required=True, + type=str, + help="Table with taxonomic classifications", + ) + + required.add_argument( + "-u", + "--unclassified", + dest="unclassified", + metavar="", + required=True, + type=str, + help="Table with unclassified contigs", + ) + + required.add_argument( + "-m", + "--mapped-reads", + dest="mapped_reads", + metavar="", + required=True, + type=str, + help="Table with mapped read counts", + ) + + required.add_argument( + "-co", + "--counts", + dest="counts", + metavar="", + required=True, + type=str, + help="Table of read counts", + ) + + required.add_argument( + "-p", + "--percentages", + dest="percentages", + metavar="", + required=True, + type=str, + help="Table of read counts as percentages", + ) + + required.add_argument( + "-g", + "--graph", + dest="graph", + metavar="", + required=True, + type=str, + help="Graph of sample compositions", + ) + + optional = parser.add_argument_group("Optional arguments") + + optional.add_argument( + "-l", + "--log", + dest="log", + metavar="", + required=False, + default=False, + type=str, + help="Log file to write warnings to", + ) + + optional.add_argument( + "-cpu", + "--cpu-cores", + dest="cores", + metavar="", + required=False, + type=int, + default=4, + help="Number of threads to read fastq files", + ) + + optional.add_argument( + "-col", + "--colours", + dest="colours", + metavar="", + required=False, + type=str, + nargs="+", + default=[ + "#FFDBE5", + "#7A4900", + "#0000A6", + "#63FFAC", + "#B79762", + "#004D43", + "#8FB0FF", + "#997D87", + ], + help="Colours (8) of the barchart (stacks)", + ) + # Colour scheme with distinct colours thanks to Tatarize + # (https://godsnotwheregodsnot.blogspot.com/2013/11/kmeans-color-quantization-seeding.html) + # And Alexey Popkov (https://graphicdesign.stackexchange.com/revisions/3815/8) + + optional.add_argument( + "-h", "--help", action="help", help="Show this message and exit." + ) + + (args, extra_args) = parser.parse_known_args() + + return args + + +def count_sequences_in_fastq(infile): + """ + Input: fastq file + Output: line number / 4 (number of sequences) + """ + with open(infile, "r") as f: + for i, l in enumerate(f): + pass + try: + lines = i + 1 + return lines / 4 + except UnboundLocalError: # happens when file is empty, there is no 'i' + return 0 + + +def progress(count, total, status=""): + """ + Copyright (c) Vladimir Ignatev (MIT Licence) + https://gist.github.com/vladignatyev/06860ec2040cb497f0f3 + """ + bar_len = 60 + filled_len = int(round(bar_len * count / float(total))) + + percents = round(100.0 * count / float(total), 1) + bar = "=" * filled_len + "-" * (bar_len - filled_len) + + sys.stdout.write( + "[%s] %s%s - %s [ %i / %i ]\r" % (bar, percents, "%", status, count, total) + ) + # Adapted above line to also show how many files are counted - Sam + sys.stdout.flush() # As suggested by Rom Ruben (see: http://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console/27871113#comment50529068_27871113) + + +def count_non_human_reads(file_list, threads): + """ + Input: list of fastq files after human read filtering + Output: counts of non-human reads per sample (as pandas dataframe) + + For each sample, count the reads that did not map to the human genome: + - forward read/mate + - reverse read/mate + - unpaired read + (all summed) + """ + print(FASTQ_COUNT_WARINING_MESSAGE) + + files_read = 0 # keep track of how many files have been read + read_counts = {} + + with concurrent.futures.ProcessPoolExecutor(max_workers=threads) as executor: + for file, reads in zip( + file_list, executor.map(count_sequences_in_fastq, file_list) + ): + if "_pR1.fq" in file: + sample = file[: file.index("_pR1.fq")].split("/")[-1] + elif "_pR2.fq" in file: + sample = file[: file.index("_pR2.fq")].split("/")[-1] + elif "_unpaired.fq" in file: + sample = file[: file.index("_unpaired.fq")].split("/")[-1] + else: + print( + "A fastq file with has been provided for non-human read counting that does not match the expected suffix patterns (i.e. '_pR1.fq', '\_pR2.fq', or '_unpaired.fq'." + ) + break # stop if there is a file with an unexpected name + + if sample in read_counts: + read_counts[sample] += reads + else: + read_counts[sample] = reads + + files_read += 1 + # Show the progress of counting files on the terminal: + progress(files_read, len(file_list), status="Reading files") + + read_df = pd.DataFrame( + { + "Sample": [n for n in read_counts.keys()], + "Non-human_reads": [n for n in read_counts.values()], + } + ) + + read_df["Non-human_reads"] = read_df["Non-human_reads"].astype(int) + + print("Done counting!") + + return read_df + + +def sum_superkingdoms(classified_file, mapped_reads_file): + """ + Input: + taxonomic classifications and quantifications as + generated by Jovian (i.e. results/all_taxClassified.tsv) + Output: + dataframe with the number of reads assigned to each + superkindgom per sample, also taking into account reads + that were not assigned a superkingdom ("not classified") + """ + clas_df = pd.read_csv(classified_file, delimiter="\t") + + counts_df = pd.read_csv(mapped_reads_file, delimiter="\t") + clas_df = pd.merge( + clas_df, counts_df, how="left", on=["scaffold_name", "Sample_name"] + ) + # If a scaffold has no reads mapping to it, set to 0: + clas_df.fillna({"mapped_reads": 0}, inplace=True) + + # N.B. Take into account reads that were not assigned a superkingdom + # and are therefore actually still unclassified! + clas_df.fillna("not classified", inplace=True) + + # Count the reads assigned to Archaea, Bacteria, Eukaryota and Viruses per sample: + superkingdom_sums = pd.DataFrame( + clas_df.groupby(["Sample_name", "superkingdom"]).sum()[["mapped_reads"]] + ) + + # Check all samples and superkingdoms to find out for which superkingdoms there is no data + samples_superkingdoms_dict = {} + for i in superkingdom_sums.index: + if i[0] not in samples_superkingdoms_dict.keys(): + # If the sample name is not yet in the dictionary, add it with the corresponding superkingdom + samples_superkingdoms_dict[i[0]] = [i[1]] + else: + # If the sample is there already, add the current superkingdom + samples_superkingdoms_dict[i[0]].append(i[1]) + + # Make a dataframe for the missing data + newdata = pd.DataFrame(index=superkingdom_sums.index, columns=[]) + + for key, value in samples_superkingdoms_dict.items(): + for superkingdom in [ + "Archaea", + "Bacteria", + "Eukaryota", + "Viruses", + "not classified", + ]: + if superkingdom not in value: + newdata.loc[(key, superkingdom), "mapped_reads"] = 0 + else: + pass + + # Concatenate the missing data into the dataframe + new_df = pd.concat([superkingdom_sums, newdata], sort=False) + new_df.reset_index(inplace=True) + new_df = new_df.sort_values(by=["Sample_name", "superkingdom"]) + new_df = new_df.dropna() + new_df.reset_index(inplace=True, drop=True) + + # And make these into a proper dataframe: + final_df = pd.DataFrame( + new_df.pivot(index="Sample_name", columns="superkingdom", values="mapped_reads") + ) + final_df.reset_index(inplace=True) + + return final_df + + +def sum_unclassified(unclassified_file, mapped_reads_file): + """ + Input: + table of scaffolds that were not classified by PZN + (results/all_taxUnclassified.tsv) + Output: + dataframe with the number of reads assigned to + unclassified scaffolds per sample + """ + unclas_df = pd.read_csv(unclassified_file, delimiter="\t") + + counts_df = pd.read_csv(mapped_reads_file, delimiter="\t") + unclas_df = pd.merge( + unclas_df, counts_df, how="left", on=["scaffold_name", "Sample_name"] + ) + + # Summarise the reads per sample: + unclas_sums = pd.DataFrame(unclas_df.groupby("Sample_name").sum()[["mapped_reads"]]) + unclas_sums.reset_index(inplace=True) + + return unclas_sums + + +def validate_numbers(df, log=False): + """ + Validates if the numbers add up to a number lower than the total + number of raw reads. (I.e. low-quality + human + other taxa + + unclassified <= total sequences.) Reports a warning when the sum + of these groups is too high. + Input: + Dataframe with all numbers of reads - profile of: + - total/raw reads + - low-quality reads + - human reads + - reads mapped to classified contigs: + - Archaea + - Bacteria + - Eukaryota + - Viruses + Output: + None if the numbers are within expected margins, + Warning when the numbers are clearly wrong. + """ + if log: + with open(log, "a") as logfile: + logfile.write("---\n\nNow checking if numbers add up properly...\n") + else: + print("Now checking if the numbers add up properly...") + + errors = [] + for i in range(len(df)): + sample = df.loc[i, "Sample"] + total = df.loc[i, "Total_reads"] + reads_sum = ( + df.loc[i, "Low-quality"] + + df.loc[i, "Human"] + + df.loc[i, "Archaea"] + + df.loc[i, "Bacteria"] + + df.loc[i, "Eukaryota"] + + df.loc[i, "Viruses"] + + df.loc[i, "Unclassified"] + ) + + if not total >= reads_sum: + if log: + with open(log, "a") as logfile: + logfile.write( + "Warning! Sample %s has a bad reads sum: %i > total (%i)\n" + % (df.loc[i, "Sample"], reads_sum, total) + ) + else: + print( + "Warning! Sample %s has a bad reads sum: %i > total (%i)" + % (df.loc[i, "Sample"], reads_sum, total) + ) + errors.append(df.loc[i, "Sample"]) + else: + pass + + if log: + with open(log, "a") as logfile: + if len(errors) == 0: + logfile.write("All numbers okay: no sums are higher than the total!\n") + else: + logfile.write( + "%i errors have been found, these are from samples: %s\n" + % (len(errors), errors) + ) + else: + if len(errors) == 0: + print("All numbers okay: no sums are higher than the total!\n") + else: + print( + "%i errors have been found, these are from samples: %s" + % (len(errors), errors) + ) + + return None + + +def draw_stacked_bars(df, perc, sample="", parts=[], outfile="", colours=COLOURS): + """ + Takes a file of quantified read annotations by a pipeline (e.g. PZN) + and draws a stacked bar chart using Bokeh, creating an interactive + HTML file. + + Input: + - A Pandas dataframe with all the required data + - The column name of Sample IDs (as string) + - The column names for the numbers ("parts", as list) + - The title of the figure (as string) + - The name of the output file (as string) + - The colours to be used for the bars (as list of strings - hexcodes) + Output: + - Interactive (Bokeh) stacked bar chart that visualises + the composition of each sample in your experiment + """ + # Set a comfortable length depending on the number of samples to show: + if len(df[sample]) > 40: + width = len(df[sample]) * 20 + # Have the graph grow horizontally to accomodate large numbers of samples + elif len(df[sample]) > 25: + width = len(df[sample]) * 33 + else: + # With a minimum of 800 to display the legend + width = 800 + + nr_fig = figure( + x_range=df[sample], + plot_height=800, + plot_width=width, + title="Composition of samples (read-based)", + toolbar_location=None, + tools="hover, pan", + tooltips="@%s $name: @$name" % sample, + ) + + nr_fig.vbar_stack( + parts, + x=sample, + width=0.9, + color=colours, + source=df, + legend=[value(x) for x in parts], + ) + + nr_fig.y_range.start = 0 + nr_fig.x_range.range_padding = 0.1 + nr_fig.xgrid.grid_line_color = None + nr_fig.axis.minor_tick_line_color = None + nr_fig.outline_line_color = None + nr_fig.legend.location = "top_left" + nr_fig.legend.orientation = "horizontal" + nr_fig.xaxis.major_label_orientation = 1 + + nr_panel = Panel(child=nr_fig, title="Absolute number of reads") + + perc_fig = figure( + x_range=perc[sample], + plot_height=800, + plot_width=width, + title="Composition of samples (percentages)", + toolbar_location=None, + tools="hover, pan", + tooltips="@%s $name: @$name" % sample, + ) + + perc_fig.vbar_stack( + parts, + x=sample, + width=0.9, + color=colours, + source=perc, + legend=[value(x) for x in parts], + ) + + perc_fig.y_range.start = 0 + perc_fig.x_range.range_padding = 0.1 + perc_fig.xgrid.grid_line_color = None + perc_fig.axis.minor_tick_line_color = None + perc_fig.outline_line_color = None + perc_fig.legend.location = "top_left" + perc_fig.legend.orientation = "horizontal" + perc_fig.xaxis.major_label_orientation = 1 + + perc_panel = Panel(child=perc_fig, title="Percentage of reads") + + tabs = Tabs(tabs=[nr_panel, perc_panel]) + + output_file(outfile) + save(tabs) + + return None + + +def main(): + """ + The main functionality of this script: + reads files, merges them together in a table, + save them as csv files and create graphs. + + Input: + files as defined at the top (lines 26-30) + Output: + defined at the top (lines 34-37) + """ + # 1. Parse and show arguments + arguments = parse_arguments() + + message = ( + "\n" + "These are the arguments you have provided:\n" + " INPUT:\n" + "fastqc = {0},\n" + "trimmomatic = {1}\n" + "hugo = {2}\n" + "classified = {3}\n" + "unclassified: {4}\n" + "mapped_reads: {5}\n" + " OUTPUT:\n" + "counts = {6}\n" + "percentages = {7}\n" + "graph = {8}\n" + " OPTIONAL:\n" + "log = {9}\n" + "cores = {10}\n" + "colours = {11}".format( + arguments.fastqc, + arguments.trimmomatic, + arguments.hugo, + arguments.classified, + arguments.unclassified, + arguments.mapped_reads, + arguments.counts, + arguments.percentages, + arguments.graph, + arguments.log, + arguments.cores, + arguments.colours, + ) + ) + + if arguments.log: + if os.path.exists(arguments.log) and os.path.getsize(arguments.log) > 0: + # File already exists and has been written to + header = "\n---\n[{0}] Please find below the log of the current execution.".format( + datetime.datetime.now() + ) + else: + header = "[{0}] Please find below the log of the current execution.".format( + datetime.datetime.now() + ) + with open(arguments.log, "a") as logfile: + logfile.write("{0}\n---\n".format(header)) + logfile.write("{0}\n".format(message)) + else: + print(message) + + threads = arguments.cores + + if arguments.log: + with open(arguments.log, "a") as logfile: + try: + threads = snakemake.threads + logfile.write( + "Variable 'threads' overwritten by snakemake = %i\n" + % snakemake.threads + ) + except: + logfile.write("Cores not provided by snakemake,\n") + logfile.write("trying to read them from the -cpu argument...\n") + + if not isinstance(threads, int) or not threads in range(1, 32): + threads = 4 + else: + pass + + logfile.write( + "Continuing with %i threads for reading fastq files.\n" % threads + ) + else: + try: + threads = snakemake.threads + print( + "\nVariable 'threads' overwritten by snakemake = %i" % snakemake.threads + ) + except: + print("\nCores not provided by snakemake,") + print("trying to read them from the -cpu argument...") + + if not isinstance(threads, int) or not threads in range(1, 32): + threads = 4 + else: + pass + + print("Continuing with %i threads for reading fastq files." % threads) + + # 2. Total (raw) read numbers/sample + read_nrs = pd.read_csv(arguments.fastqc, delimiter="\t")[ + ["Sample", "Total Sequences"] + ] + # Note1: FastQC reports numbers of reads of pre- and post-QC fastq files, + # I only want to have the pre-QC numbers now: + pattern = re.compile( + r".*(_|\.)R?1([_.].*$|$)" + ) # A regex meaning: get anything up to "_R?1" and then either "_R?1[_.].*$" or "_R?1$". + pre_qc = [col for col in read_nrs.Sample if bool(re.search(pattern, col))] + read_nrs = read_nrs[read_nrs.Sample.isin(pre_qc)] + read_nrs.Sample = read_nrs.Sample.str.replace( + r"(_|\.)R?1([_.].*$|$)", "" + ) # remove the "_R1" or "_1" suffix and anything that may be after it. N.B. a simple `.*`` doesn't work because otherwise it will greedily remove everything after the first occurrence of "_R1" e.g. "Sample_bla_bla_R138_ACGGT_R1" becomes "Sample_bla_bla" + + # Note2: I now only have the number of forward reads. To add reverse, + # multiply this number by 2: + read_nrs["Total Sequences"] = (read_nrs["Total Sequences"] * 2).astype(int) + read_nrs.reset_index(drop=True, inplace=True) + + # Debug: + # print(read_nrs.head()) + + # 3. low-quality reads/sample (by Trimmomatic): + lowq_nrs = pd.read_csv(arguments.trimmomatic, delimiter="\t")[ + ["Sample", "forward_only_surviving", "reverse_only_surviving", "dropped"] + ] + lowq_nrs.Sample = lowq_nrs.Sample.str.replace( + r"(_|\.)R?1([_.].*$|$)", "" + ) # remove the "_R1" or "_1" suffix and anything that may be after it. N.B. a simple `.*`` doesn't work because otherwise it will greedily remove everything after the first occurrence of "_R1" e.g. "Sample_bla_bla_R138_ACGGT_R1" becomes "Sample_bla_bla" + # Note: trimmomatic drops read pairs ("dropped") and for some pairs + # only one mate is of sufficiently high quality ("forward/reverse + # only surviving"). The number of low-quality reads is calculated + # by multiplying the dropped pairs by 2 and adding the forward + # and reverse only mates: + lowq_nrs["dropped_reads"] = ( + lowq_nrs["dropped"] * 2 + + lowq_nrs["forward_only_surviving"] + + lowq_nrs["reverse_only_surviving"] + ).astype(int) + lowq_nrs.reset_index(drop=True, inplace=True) + + # Debug: + # print(lowq_nrs.head()) + + # 4. human reads/sample (Bowtie2 to human genome) + human_nrs = count_non_human_reads(file_list=arguments.hugo, threads=threads) + # Note: MultiQC does not have complete data for the Bowtie2 + # alignments. Instead I count the number of lines in each + # of the fastq files that proceed to assembly. (Forward, + # reverse and unpaired reads that did not map to the human + # genome). This process may take a while! + + # Sort the dataframe by Sample ID to make it match the other dataframes + human_nrs.sort_values(by=["Sample"], inplace=True) + human_nrs.reset_index(inplace=True, drop=True) + + # Debug: + # print(human_nrs.head()) + + # 5. Reads classified by mapping to scaffolds/sample + ## (Minimap reads to scaffolds > 500 nt long from SPAdes, + ## that have been classified with Megablast to BLAST nt database + ## and the LCA algorithm from Krona (see PZN methods).) + classified_nrs = sum_superkingdoms(arguments.classified, arguments.mapped_reads) + + # Debug: + # print(classified_nrs.head()) + + # 6. Reads mapped to unclassified scaffolds/sample: + ## (Minimap reads to scaffolds that Megablast could not + ## assign.) + unclassified_nrs = sum_unclassified(arguments.unclassified, arguments.mapped_reads) + + # Debug: + # print(unclassified_nrs.head()) + + # 7. Merge all these data into one dataframe: + dfs = [read_nrs, lowq_nrs, human_nrs, classified_nrs, unclassified_nrs] + + nrs_df = pd.concat(dfs, axis=1, join="outer") + + # Calculate the human reads by subtracting low-quality + # and non-human reads from the total number of reads: + nrs_df["Human"] = nrs_df["Total Sequences"] - ( + nrs_df["dropped_reads"] + nrs_df["Non-human_reads"] + ) + # Calculate the unclassified reads by summing the numbers + # from the 'unclassified contigs table' and those from + # the 'classified contigs table' that wern not assigned + # a superkingdom: + nrs_df["Unclassified"] = nrs_df.mapped_reads + nrs_df["not classified"] + + # And keep only the relevant columns, + # in a logical order: + nrs_df = nrs_df[ + [ + "Sample", + "Total Sequences", + "dropped_reads", + "Human", + "Archaea", + "Bacteria", + "Eukaryota", + "Viruses", + "Unclassified", + ] + ] + nrs_df = nrs_df.iloc[ + :, ~nrs_df.columns.duplicated() + ] # remove duplicate columns, thanks https://stackoverflow.com/a/35798262 ! + # and with proper names: + nrs_df.rename( + columns={"Total Sequences": "Total_reads", "dropped_reads": "Low-quality"}, + inplace=True, + ) + # Replace NaN by 0: + nrs_df.fillna(value=0, inplace=True) + + # And calculate the number of remaining reads + # (i.e. high-quality reads that were not assembled + # into scaffolds >= 500 nt and could thus not be + # classified). + nrs_df["Remaining"] = nrs_df["Total_reads"] - ( + nrs_df["Low-quality"] + + nrs_df["Human"] + + nrs_df["Archaea"] + + nrs_df["Bacteria"] + + nrs_df["Eukaryota"] + + nrs_df["Viruses"] + + nrs_df["Unclassified"] + ) + + # Integers with decimals are silly, remove them: + nrs_df = nrs_df.apply(pd.to_numeric, downcast="integer", errors="ignore") + + # Debug: + # print(nrs_df.head(20)) + + validate_numbers(df=nrs_df, log=arguments.log) + + # 8. Write the numbers dataframe to a file: + nrs_df.to_csv(arguments.counts, index=False) + if arguments.log: + with open(arguments.log, "a") as logfile: + logfile.write("---\n\nWrote read-based table to:\t %s\n" % arguments.counts) + else: + print("Wrote read-based table to:\t %s" % arguments.counts) + + # 9. Create a dataframe with percentages: + perc_df = pd.DataFrame() + + for header in nrs_df.columns: + if header == "Sample": + # Copy the Sample column + perc_df[header] = nrs_df[header] + elif header == "Total_reads": + # Skip the Total_reads column (no need with percentages) + pass + else: + # Create a percentage column for all other values + perc_df[header] = nrs_df[header] / nrs_df["Total_reads"] * 100 + + perc_df.to_csv(arguments.percentages, index=False) + + if arguments.log: + with open(arguments.log, "a") as logfile: + logfile.write("Wrote percentages table to:\t %s\n" % arguments.percentages) + else: + print("Wrote percentages table to:\t %s" % arguments.percentages) + + # 10. Create a stacked bar chart to visualise annotated reads per sample: + draw_stacked_bars( + df=nrs_df, + perc=perc_df, + sample="Sample", + parts=[ + "Low-quality", + "Human", + "Archaea", + "Bacteria", + "Eukaryota", + "Viruses", + "Unclassified", + "Remaining", + ], + outfile=arguments.graph, + ) + + if arguments.log: + with open(arguments.log, "a") as logfile: + logfile.write( + "Created a read-based stacked bar chart in:\t %s\n" % arguments.graph + ) + else: + print("Created a read-based stacked bar chart in:\t %s" % arguments.graph) + + return None + + +### Run the script ----------------------------------------------- + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/Jovian/workflow/scripts/slurm-cluster-status.py b/Jovian/workflow/scripts/slurm-cluster-status.py new file mode 100644 index 0000000..a97b273 --- /dev/null +++ b/Jovian/workflow/scripts/slurm-cluster-status.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# ! Original source: https://github.com/LUMC/slurm-cluster-status downloaded 2023-09-06 +# ! Original Author: Redmar van den Berg (LUMC) +# ! License: BSD-3-Clause License +# ! Reason: interoperability with LUMC's slurm cluster + +import argparse +import subprocess + +STATE_MAP = { + "BOOT_FAIL": "failed", + "CANCELLED": "failed", + "COMPLETED": "success", + "CONFIGURING": "running", + "COMPLETING": "running", + "DEADLINE": "failed", + "FAILED": "failed", + "NODE_FAIL": "failed", + "OUT_OF_MEMORY": "failed", + "PENDING": "running", + "PREEMPTED": "failed", + "RUNNING": "running", + "RESIZING": "running", + "SUSPENDED": "running", + "TIMEOUT": "failed", + "UNKNOWN": "running" +} + + +def fetch_status(batch_id): + """fetch the status for the batch id""" + sacct_args = ["sacct", "-j", batch_id, "-o", "State", "--parsable2", + "--noheader"] + + try: + output = subprocess.check_output(sacct_args).decode("utf-8").strip() + except Exception: + # If sacct fails for whatever reason, assume its temporary and return 'running' + output = 'UNKNOWN' + + # Sometimes, sacct returns nothing, in which case we assume it is temporary + # and return 'running' + if not output: + output = 'UNKNOWN' + + # The first output is the state of the overall job + # See + # https://stackoverflow.com/questions/52447602/slurm-sacct-shows-batch-and-extern-job-names + # for details + job_status = output.split("\n")[0] + + # If the job was cancelled manually, it will say by who, e.g "CANCELLED by 12345" + # We only care that it was cancelled + if job_status.startswith("CANCELLED by"): + job_status = "CANCELLED" + + # Otherwise, return the status + try: + return STATE_MAP[job_status] + except KeyError: + raise NotImplementedError(f"Encountered unknown status '{job_status}' " + f"when parsing output:\n'{output}'") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("batch_id", type=str) + args = parser.parse_args() + + status = fetch_status(args.batch_id) + print(status) \ No newline at end of file diff --git a/Jovian/workflow/scripts/typingtool_EV_XML_to_csv_parser.py b/Jovian/workflow/scripts/typingtool_EV_XML_to_csv_parser.py new file mode 100644 index 0000000..81eadd7 --- /dev/null +++ b/Jovian/workflow/scripts/typingtool_EV_XML_to_csv_parser.py @@ -0,0 +1,106 @@ +"""Parser for the XML output of the enterovirus (EV) typing tool (TT). +Usage: + typingtool_EV_XML_to_csv_parser.py + is how you want to call this sample (in plain text). + is the input XML file that you got from the EV TT. + is the output csv file. +Example: + typingtool_EV_XML_to_csv_parser.py [sample_name] \ + data/virus_typing_tables/[sample_name]_EV.xml \ + data/virus_typing_tables/[sample_name]_EV.csv +""" + +import csv +import xml.etree.cElementTree as et +from collections import OrderedDict +from sys import argv + +SCRIPT, SAMPLE_NAME, INPUT_XML, OUTPUT_CSV = argv + +parsedXML = et.parse(INPUT_XML) + +csv_data = [] + +input_fields = ["result", "start", "end", "nucleotides", "conclusion"] + +output_fields = [ + "Sample_name", + "Query_name", + "start", + "length", + "end", + "blast_concluded-name", + "blast_absolute-similarity", + "blast_refseq", + "blast_reverse-complement", + "type", + "type_support", + "VP1_type", + "VP1_type_support", + "VP1_subgenogroup", + "VP1_subgenogroup_support", +] + +for elem in parsedXML.findall(".//sequence"): + inner_dict = OrderedDict({k: None for k in output_fields}) + + inner_dict["Sample_name"] = SAMPLE_NAME + + inner_dict["Query_name"] = elem.attrib["name"] + inner_dict["length"] = elem.attrib["length"] + + for item in elem.findall(".//*"): + if item.tag in input_fields: + if item.tag == "nucleotides": + inner_dict["nucleotides"] = item.text.strip() + elif item.tag == "result": + tmp_result_id = item.attrib.get("id") + if tmp_result_id == "blast": + inner_dict["blast_concluded-name"] = item.find( + ".//concluded-name" + ).text + inner_dict["blast_absolute-similarity"] = item.find( + ".//absolute-similarity" + ).text + try: + inner_dict["blast_refseq"] = item.find(".//refseq").text + except: + inner_dict["blast_refseq"] = item.find(".//refseq") + inner_dict["blast_reverse-complement"] = item.find( + ".//reverse-compliment" + ).text + elif item.tag == "conclusion": + tmp_conclusion_type = item.attrib.get("type") + tmp_conclusion_id = item.attrib.get("id") + tmp_conclusion_region = item.attrib.get("region") + if ( + tmp_conclusion_type == "simple" + and tmp_conclusion_id == "type" + and tmp_conclusion_region is None + ): + inner_dict["type"] = item.find(".//name").text + inner_dict["type_support"] = item.find(".//support").text + elif ( + tmp_conclusion_type == "simple" + and tmp_conclusion_id == "type" + and tmp_conclusion_region == "VP1" + ): + inner_dict["VP1_type"] = item.find(".//name").text + inner_dict["VP1_type_support"] = item.find(".//support").text + elif ( + tmp_conclusion_type == "simple" + and tmp_conclusion_id == "subtype" + and tmp_conclusion_region == "VP1" + ): + inner_dict["VP1_subgenogroup"] = item.find(".//name").text + inner_dict["VP1_subgenogroup_support"] = item.find( + ".//support" + ).text + else: + inner_dict[item.tag] = item.text + csv_data.append(inner_dict) + +with open(OUTPUT_CSV, "w", newline="") as f: + w = csv.DictWriter(f, csv_data[0].keys()) + w.writeheader() + w.writerows(csv_data) diff --git a/Jovian/workflow/scripts/typingtool_Flavi_XML_to_csv_parser.py b/Jovian/workflow/scripts/typingtool_Flavi_XML_to_csv_parser.py new file mode 100644 index 0000000..db274c5 --- /dev/null +++ b/Jovian/workflow/scripts/typingtool_Flavi_XML_to_csv_parser.py @@ -0,0 +1,94 @@ +"""Parser for the XML output of the flaviviridae (Flavi) typing tool (TT). +Usage: + typingtool_Flavi_XML_to_csv_parser.py + is how you want to call this sample (in plain text). + is the input XML file that you got from the Flavi TT. + is the output csv file. +Example: + typingtool_Flavi_XML_to_csv_parser.py [sample_name] \ + data/virus_typing_tables/[sample_name]_Flavi.xml \ + data/virus_typing_tables/[sample_name]_Flavi.csv +""" + +import csv +import xml.etree.cElementTree as et +from collections import OrderedDict +from sys import argv + +SCRIPT, SAMPLE_NAME, INPUT_XML, OUTPUT_CSV = argv + +parsedXML = et.parse(INPUT_XML) + +csv_data = [] + +input_fields = ["result", "start", "end", "nucleotides", "conclusion"] + +output_fields = [ + "Sample_name", + "Query_name", + "start", + "length", + "end", + "blast_concluded-name", + "blast_absolute-similarity", + "blast_refseq", + "blast_reverse-complement", + "cluster_type", + "cluster_support", + "region1_subcluster_type", + "region1_subcluster_support", + "nucleotides", +] + +for elem in parsedXML.findall(".//sequence"): + inner_dict = OrderedDict({k: None for k in output_fields}) + + inner_dict["Sample_name"] = SAMPLE_NAME + + inner_dict["Query_name"] = elem.attrib["name"] + inner_dict["length"] = elem.attrib["length"] + + for item in elem.findall(".//*"): + if item.tag in input_fields: + if item.tag == "nucleotides": + inner_dict["nucleotides"] = item.text.strip() + elif item.tag == "result": + tmp_result_id = item.attrib.get("id") + if tmp_result_id == "blast": + inner_dict["blast_concluded-name"] = item.find( + ".//concluded-name" + ).text + inner_dict["blast_absolute-similarity"] = item.find( + ".//absolute-similarity" + ).text + try: + inner_dict["blast_refseq"] = item.find(".//refseq").text + except: + inner_dict["blast_refseq"] = item.find(".//refseq") + inner_dict["blast_reverse-complement"] = item.find( + ".//reverse-compliment" + ).text + elif item.tag == "conclusion": + tmp_conclusion_type = item.attrib.get("type") + tmp_conclusion_id = item.attrib.get("id") + tmp_conclusion_region = item.attrib.get("region") + if tmp_conclusion_type == "simple" and tmp_conclusion_id == "type": + inner_dict["cluster_type"] = item.find(".//name").text + inner_dict["cluster_support"] = item.find(".//support").text + elif ( + tmp_conclusion_type == "simple" + and tmp_conclusion_id == "subtype" + and tmp_conclusion_region == "region1" + ): + inner_dict["region1_subcluster_type"] = item.find(".//name").text + inner_dict["region1_subcluster_support"] = item.find( + ".//support" + ).text + else: + inner_dict[item.tag] = item.text + csv_data.append(inner_dict) + +with open(OUTPUT_CSV, "w", newline="") as f: + w = csv.DictWriter(f, csv_data[0].keys()) + w.writeheader() + w.writerows(csv_data) diff --git a/Jovian/workflow/scripts/typingtool_HAV_XML_to_csv_parser.py b/Jovian/workflow/scripts/typingtool_HAV_XML_to_csv_parser.py new file mode 100644 index 0000000..1b5c057 --- /dev/null +++ b/Jovian/workflow/scripts/typingtool_HAV_XML_to_csv_parser.py @@ -0,0 +1,87 @@ +"""Parser for the XML output of the norovirus (HAV) typing tool (TT). +Usage: + typingtool_HAV_XML_to_csv_parser.py + is how you want to call this sample (in plain text). + is the input XML file that you got from the HAV TT. + is the output csv file. +Example: + typingtool_HAV_XML_to_csv_parser.py [sample_name] \ + data/virus_typing_tables/[sample_name]_HAV.xml \ + data/virus_typing_tables/[sample_name]_HAV.csv +""" + +import csv +import xml.etree.cElementTree as et +from collections import OrderedDict +from sys import argv + +SCRIPT, SAMPLE_NAME, INPUT_XML, OUTPUT_CSV = argv + +parsedXML = et.parse(INPUT_XML) + +csv_data = [] + +input_fields = ["result", "start", "end", "nucleotides", "conclusion"] + +output_fields = [ + "Sample_name", + "Query_name", + "start", + "length", + "end", + "blast_concluded-name", + "blast_absolute-similarity", + "blast_refseq", + "blast_reverse-complement", + "type", + "type_support", + "subtype", + "subtype_support", + "nucleotides", +] + +for elem in parsedXML.findall(".//sequence"): + inner_dict = OrderedDict({k: None for k in output_fields}) + + inner_dict["Sample_name"] = SAMPLE_NAME + + inner_dict["Query_name"] = elem.attrib["name"] + inner_dict["length"] = elem.attrib["length"] + + for item in elem.findall(".//*"): + if item.tag in input_fields: + if item.tag == "nucleotides": + inner_dict["nucleotides"] = item.text.strip() + elif item.tag == "result": + tmp_result_id = item.attrib.get("id") + if tmp_result_id == "blast": + inner_dict["blast_concluded-name"] = item.find( + ".//concluded-name" + ).text + inner_dict["blast_absolute-similarity"] = item.find( + ".//absolute-similarity" + ).text + try: + inner_dict["blast_refseq"] = item.find(".//refseq").text + except: + inner_dict["blast_refseq"] = item.find(".//refseq") + inner_dict["blast_reverse-complement"] = item.find( + ".//reverse-compliment" + ).text + elif item.tag == "conclusion": + tmp_conclusion_type = item.attrib.get("type") + tmp_conclusion_id = item.attrib.get("id") + if tmp_conclusion_type == "simple" and tmp_conclusion_id == "type": + inner_dict["type"] = item.find(".//name").text + inner_dict["type_support"] = item.find(".//support").text + elif tmp_conclusion_type == "simple" and tmp_conclusion_id == "subtype": + inner_dict["subtype"] = item.find(".//name").text + inner_dict["subtype_support"] = item.find(".//support").text + else: + inner_dict[item.tag] = item.text + csv_data.append(inner_dict) + +with open(OUTPUT_CSV, "w", newline="") as f: + w = csv.DictWriter(f, csv_data[0].keys()) + w.writeheader() + w.writerows(csv_data) diff --git a/Jovian/workflow/scripts/typingtool_HEV_XML_to_csv_parser.py b/Jovian/workflow/scripts/typingtool_HEV_XML_to_csv_parser.py new file mode 100644 index 0000000..9e99978 --- /dev/null +++ b/Jovian/workflow/scripts/typingtool_HEV_XML_to_csv_parser.py @@ -0,0 +1,88 @@ +"""Parser for the XML output of the hepatitis E (HEV) typing tool (TT). +Usage: + typingtool_HEV_XML_to_csv_parser.py + is how you want to call this sample (in plain text). + is the input XML file that you got from the HEV TT. + is the output csv file. +Example: + typingtool_HEV_XML_to_csv_parser.py [sample_name] \ + data/virus_typing_tables/[sample_name]_HEV.xml \ + data/virus_typing_tables/[sample_name]_HEV.csv +""" + +import csv +import xml.etree.cElementTree as et +from collections import OrderedDict +from sys import argv + +SCRIPT, SAMPLE_NAME, INPUT_XML, OUTPUT_CSV = argv + +parsedXML = et.parse(INPUT_XML) + +csv_data = [] + +input_fields = ["result", "start", "end", "nucleotides", "conclusion"] + +output_fields = [ + "Sample_name", + "Query_name", + "start", + "length", + "end", + "blast_concluded-name", + "blast_absolute-similarity", + "blast_refseq", + "blast_reverse-complement", + "type", + "type_support", + "subtype", + "subtype_support", + "nucleotides", +] + +for elem in parsedXML.findall(".//sequence"): + inner_dict = OrderedDict({k: None for k in output_fields}) + + inner_dict["Sample_name"] = SAMPLE_NAME + + inner_dict["Query_name"] = elem.attrib["name"] + inner_dict["length"] = elem.attrib["length"] + + for item in elem.findall(".//*"): + if item.tag in input_fields: + if item.tag == "nucleotides": + inner_dict["nucleotides"] = item.text.strip() + elif item.tag == "result": + tmp_result_id = item.attrib.get("id") + if tmp_result_id == "blast": + inner_dict["blast_concluded-name"] = item.find( + ".//concluded-name" + ).text + inner_dict["blast_absolute-similarity"] = item.find( + ".//absolute-similarity" + ).text + try: + inner_dict["blast_refseq"] = item.find(".//refseq").text + except: + inner_dict["blast_refseq"] = item.find(".//refseq") + inner_dict["blast_reverse-complement"] = item.find( + ".//reverse-compliment" + ).text + elif item.tag == "conclusion": + tmp_conclusion_type = item.attrib.get("type") + tmp_conclusion_id = item.attrib.get("id") + tmp_conclusion_region = item.attrib.get("region") + if tmp_conclusion_type == "simple" and tmp_conclusion_id == "type": + inner_dict["type"] = item.find(".//name").text + inner_dict["type_support"] = item.find(".//support").text + elif tmp_conclusion_type == "simple" and tmp_conclusion_id == "subtype": + inner_dict["subtype"] = item.find(".//name").text + inner_dict["subtype_support"] = item.find(".//support").text + else: + inner_dict[item.tag] = item.text + csv_data.append(inner_dict) + +with open(OUTPUT_CSV, "w", newline="") as f: + w = csv.DictWriter(f, csv_data[0].keys()) + w.writeheader() + w.writerows(csv_data) diff --git a/Jovian/workflow/scripts/typingtool_NoV_XML_to_csv_parser.py b/Jovian/workflow/scripts/typingtool_NoV_XML_to_csv_parser.py new file mode 100644 index 0000000..1490c1d --- /dev/null +++ b/Jovian/workflow/scripts/typingtool_NoV_XML_to_csv_parser.py @@ -0,0 +1,116 @@ +"""Parser for the XML output of the norovirus (NoV) typing tool (TT). +Usage: + typingtool_NoV_XML_to_csv_parser.py + is how you want to call this sample (in plain text). + is the input XML file that you got from the NoV TT. + is the output csv file. +Example: + typingtool_NoV_XML_to_csv_parser.py [sample_name] \ + data/virus_typing_tables/[sample_name]_NoV.xml \ + data/virus_typing_tables/[sample_name]_NoV.csv +""" + +import csv +import xml.etree.cElementTree as et +from collections import OrderedDict +from sys import argv + +SCRIPT, SAMPLE_NAME, INPUT_XML, OUTPUT_CSV = argv + +parsedXML = et.parse(INPUT_XML) + +csv_data = [] + +input_fields = ["result", "start", "end", "nucleotides", "conclusion"] + +output_fields = [ + "Sample_name", + "Query_name", + "start", + "length", + "end", + "blast_concluded-name", + "blast_absolute-similarity", + "blast_refseq", + "blast_reverse-complement", + "polymerase_type", + "polymerase_type_support", + "polymerase_subtype", + "polymerase_subtype_support", + "capsid_type", + "capsid_type_support", + "capsid_subtype", + "capsid_subtype_support", + "nucleotides", +] + +for elem in parsedXML.findall(".//sequence"): + inner_dict = OrderedDict({k: None for k in output_fields}) + + inner_dict["Sample_name"] = SAMPLE_NAME + + inner_dict["Query_name"] = elem.attrib["name"] + inner_dict["length"] = elem.attrib["length"] + + for item in elem.findall(".//*"): + if item.tag in input_fields: + if item.tag == "nucleotides": + inner_dict["nucleotides"] = item.text.strip() + elif item.tag == "result": + tmp_result_id = item.attrib.get("id") + if tmp_result_id == "blast": + inner_dict["blast_concluded-name"] = item.find( + ".//concluded-name" + ).text + inner_dict["blast_absolute-similarity"] = item.find( + ".//absolute-similarity" + ).text + try: + inner_dict["blast_refseq"] = item.find(".//refseq").text + except: + inner_dict["blast_refseq"] = item.find(".//refseq") + inner_dict["blast_reverse-complement"] = item.find( + ".//reverse-compliment" + ).text + elif item.tag == "conclusion": + tmp_conclusion_type = item.attrib.get("type") + tmp_conclusion_id = item.attrib.get("id") + tmp_conclusion_region = item.attrib.get("region") + if ( + tmp_conclusion_type == "simple" + and tmp_conclusion_id == "type" + and tmp_conclusion_region == "region1" + ): + inner_dict["polymerase_type"] = item.find(".//name").text + inner_dict["polymerase_type_support"] = item.find(".//support").text + elif ( + tmp_conclusion_type == "simple" + and tmp_conclusion_id == "subtype" + and tmp_conclusion_region == "region1" + ): + inner_dict["polymerase_subtype"] = item.find(".//name").text + inner_dict["polymerase_subtype_support"] = item.find( + ".//support" + ).text + elif ( + tmp_conclusion_type == "simple" + and tmp_conclusion_id == "type" + and tmp_conclusion_region == "region2" + ): + inner_dict["capsid_type"] = item.find(".//name").text + inner_dict["capsid_type_support"] = item.find(".//support").text + elif ( + tmp_conclusion_type == "simple" + and tmp_conclusion_id == "subtype" + and tmp_conclusion_region == "region2" + ): + inner_dict["capsid_subtype"] = item.find(".//name").text + inner_dict["capsid_subtype_support"] = item.find(".//support").text + else: + inner_dict[item.tag] = item.text + csv_data.append(inner_dict) + +with open(OUTPUT_CSV, "w", newline="") as f: + w = csv.DictWriter(f, csv_data[0].keys()) + w.writeheader() + w.writerows(csv_data) diff --git a/Jovian/workflow/scripts/typingtool_PV_XML_to_csv_parser.py b/Jovian/workflow/scripts/typingtool_PV_XML_to_csv_parser.py new file mode 100644 index 0000000..126e686 --- /dev/null +++ b/Jovian/workflow/scripts/typingtool_PV_XML_to_csv_parser.py @@ -0,0 +1,83 @@ +"""Parser for the XML output of the papillomaviridae (PV) typing tool (TT). +Usage: + typingtool_PV_XML_to_csv_parser.py + is how you want to call this sample (in plain text). + is the input XML file that you got from the PV TT. + is the output csv file. +Example: + typingtool_PV_XML_to_csv_parser.py [sample_name] \ + data/virus_typing_tables/[sample_name]_PV.xml \ + data/virus_typing_tables/[sample_name]_PV.csv +""" + +import csv +import xml.etree.cElementTree as et +from collections import OrderedDict +from sys import argv + +SCRIPT, SAMPLE_NAME, INPUT_XML, OUTPUT_CSV = argv + +parsedXML = et.parse(INPUT_XML) + +csv_data = [] + +input_fields = ["result", "start", "end", "nucleotides", "conclusion"] + +output_fields = [ + "Sample_name", + "Query_name", + "start", + "length", + "end", + "blast_concluded-name", + "blast_absolute-similarity", + "blast_refseq", + "blast_reverse-complement", + "cluster_result", + "cluster_support", + "nucleotides", +] + +for elem in parsedXML.findall(".//sequence"): + inner_dict = OrderedDict({k: None for k in output_fields}) + + inner_dict["Sample_name"] = SAMPLE_NAME + + inner_dict["Query_name"] = elem.attrib["name"] + inner_dict["length"] = elem.attrib["length"] + + for item in elem.findall(".//*"): + if item.tag in input_fields: + if item.tag == "nucleotides": + inner_dict["nucleotides"] = item.text.strip() + elif item.tag == "result": + tmp_result_id = item.attrib.get("id") + if tmp_result_id == "blast": + inner_dict["blast_concluded-name"] = item.find( + ".//concluded-name" + ).text + inner_dict["blast_absolute-similarity"] = item.find( + ".//absolute-similarity" + ).text + try: + inner_dict["blast_refseq"] = item.find(".//refseq").text + except: + inner_dict["blast_refseq"] = item.find(".//refseq") + inner_dict["blast_reverse-complement"] = item.find( + ".//reverse-compliment" + ).text + elif item.tag == "conclusion": + tmp_conclusion_type = item.attrib.get("type") + tmp_conclusion_id = item.attrib.get("id") + tmp_conclusion_region = item.attrib.get("region") + if tmp_conclusion_type == "simple" and tmp_conclusion_id == "type": + inner_dict["cluster_result"] = item.find(".//name").text + inner_dict["cluster_support"] = item.find(".//support").text + else: + inner_dict[item.tag] = item.text + csv_data.append(inner_dict) + +with open(OUTPUT_CSV, "w", newline="") as f: + w = csv.DictWriter(f, csv_data[0].keys()) + w.writeheader() + w.writerows(csv_data) diff --git a/Jovian/workflow/scripts/typingtool_RVA_XML_to_csv_parser.py b/Jovian/workflow/scripts/typingtool_RVA_XML_to_csv_parser.py new file mode 100644 index 0000000..88a8864 --- /dev/null +++ b/Jovian/workflow/scripts/typingtool_RVA_XML_to_csv_parser.py @@ -0,0 +1,83 @@ +"""Parser for the XML output of the rotavirus A (RVA) typing tool (TT). +Usage: + typingtool_RVA_XML_to_csv_parser.py + is how you want to call this sample (in plain text). + is the input XML file that you got from the RVA TT. + is the output csv file. +Example: + typingtool_RVA_XML_to_csv_parser.py [sample_name] \ + data/virus_typing_tables/[sample_name]_RVA.xml \ + data/virus_typing_tables/[sample_name]_RVA.csv +""" + +import csv +import xml.etree.cElementTree as et +from collections import OrderedDict +from sys import argv + +SCRIPT, SAMPLE_NAME, INPUT_XML, OUTPUT_CSV = argv + +parsedXML = et.parse(INPUT_XML) + +csv_data = [] + +input_fields = ["result", "start", "end", "nucleotides", "conclusion"] + +output_fields = [ + "Sample_name", + "Query_name", + "start", + "length", + "end", + "blast_concluded-name", + "blast_absolute-similarity", + "blast_refseq", + "blast_reverse-complement", + "cluster_type", + "cluster_type_support", + "nucleotides", +] + +for elem in parsedXML.findall(".//sequence"): + inner_dict = OrderedDict({k: None for k in output_fields}) + + inner_dict["Sample_name"] = SAMPLE_NAME + + inner_dict["Query_name"] = elem.attrib["name"] + inner_dict["length"] = elem.attrib["length"] + + for item in elem.findall(".//*"): + if item.tag in input_fields: + if item.tag == "nucleotides": + inner_dict["nucleotides"] = item.text.strip() + elif item.tag == "result": + tmp_result_id = item.attrib.get("id") + if tmp_result_id == "blast": + inner_dict["blast_concluded-name"] = item.find( + ".//concluded-name" + ).text + inner_dict["blast_absolute-similarity"] = item.find( + ".//absolute-similarity" + ).text + try: + inner_dict["blast_refseq"] = item.find(".//refseq").text + except: + inner_dict["blast_refseq"] = item.find(".//refseq") + inner_dict["blast_reverse-complement"] = item.find( + ".//reverse-compliment" + ).text + elif item.tag == "conclusion": + tmp_conclusion_type = item.attrib.get("type") + tmp_conclusion_id = item.attrib.get("id") + tmp_conclusion_region = item.attrib.get("region") + if tmp_conclusion_type == "simple" and tmp_conclusion_id == "type": + inner_dict["cluster_type"] = item.find(".//name").text + inner_dict["cluster_type_support"] = item.find(".//support").text + else: + inner_dict[item.tag] = item.text + csv_data.append(inner_dict) + +with open(OUTPUT_CSV, "w", newline="") as f: + w = csv.DictWriter(f, csv_data[0].keys()) + w.writeheader() + w.writerows(csv_data) diff --git a/Jovian/workflow/scripts/virus_typing.sh b/Jovian/workflow/scripts/virus_typing.sh new file mode 100644 index 0000000..da9fc90 --- /dev/null +++ b/Jovian/workflow/scripts/virus_typing.sh @@ -0,0 +1,277 @@ + +##################################################################################################################### +### This script interacts with the public web-based virus typingtools hosted by the RIVM: ### +### Norovirus: https://www.rivm.nl/mpf/[typingservice|typingtool]/norovirus/ ### +### Enterovirus: https://www.rivm.nl/mpf/[typingservice|typingtool]/enterovirus/ ### +### Hepatitis A: https://www.rivm.nl/mpf/[typingservice|typingtool]/hav/ ### +### Hepatitis E: https://www.rivm.nl/mpf/[typingservice|typingtool]/hev/ ### +### Rotavirus: https://www.rivm.nl/mpf/[typingservice|typingtool]/rotavirusa/ ### +### Papillomavirus: https://www.rivm.nl/mpf/[typingservice|typingtool]/papillomavirus/ ### +### Flavivirus: https://www.rivm.nl/mpf/[typingservice|typingtool]/flavivirus/ ### +### ### +### Usage: bin/virus_typing.sh {NoV|EV|HAV|HEV|RVA|PV|Flavi} (--force) ### +### --force Will redo and force-overwrite previously generated results. ### +### --help Will print the help message and exit. ### +##################################################################################################################### + +# Setup +INPUT_FOLDER="data/tables/" # Default Jovian output directory ("data/tables/") +INPUT_FILES="${INPUT_FOLDER}*_taxClassified.tsv" # Combine the INPUT_FOLDER with the default output file suffix ("*_taxClassified.tsv") into a file glob +OUTPUT_FOLDER="data/virus_typing_tables/" +PYTHON_SITE_PACKAGE_FOLDER=$(python3 -c "import sysconfig; print(sysconfig.get_path('purelib'))") # Get the python site-packages folder where Jovian is installed +mkdir -p ${OUTPUT_FOLDER} + +WHICH_TT=${1,,} # The ${var,,} syntax converts it all to lowercase, this makes it easier to regex/match the keywords later and makes the keywords case-insensitive. + +usage_msg() { + cat < so the check if a virus keyword was given with the --force keyword +elif [ ! -z "${1}" -a ! -z "${2}" -a $# -eq 2 ]; then + validate_input_tt_keyword "${WHICH_TT}" + #! If $2 equal the literal --force + if [ "${2}" == "--force" ]; then + FORCE_FLAG="TRUE" + else + echo -e "\nUnknown parameter '"${2}"' given. Did you mean '"--force"'?" + exit 1 + fi +#! If $1 is not empty, and number of arguments is equal to 1 --> so the check if only a virus keyword was given without --force keyword +elif [ ! -z "${1}" -a $# -eq 1 ]; then + validate_input_tt_keyword "${WHICH_TT}" +else + echo -e "Invalid input parameters, please use one of these parameters:\n" + usage_msg + exit 1 +fi + +################################################################################# +### Virus typing ##### +################################################################################# + +extract_fasta() { + local input="${1}" + local output="${2}" + local capture_name="${3}" + local capture_field="${4}" + # Extract the scaffold name and sequence of a certain taxonomic rank from the complete Jovian taxonomic output and write it as a fasta + gawk -F "\t" -v name="${capture_name}" -v field="${capture_field}" '$field == name {print ">" $2 "\n" $25}' < ${input} > ${output} +} +submit_query_fasta() { + local input="${1}" + local output="${2}" + local url="${3}" + # Send the extracted taxonomic slice fasta to the specified public typing tool and wait for the XML results + curl -s --data-urlencode fasta-sequence@${input} ${url} > ${output} +} +typingtool() { + local file_path="${1}" + local basename="${2}" + local which_tt="${3}" + local sample_name=${basename/_taxClassified.tsv/} # Base sample name without path and suffixes + local srcdir="${PYTHON_SITE_PACKAGE_FOLDER}/Jovian/workflow/" + + # Set proper variables depending on chosen typingtool + if [ "${which_tt}" == "nov" ]; then + local tt_url="https://www.rivm.nl/mpf/typingservice/norovirus/" + local parser_py="${srcdir}scripts/typingtool_NoV_XML_to_csv_parser.py" + local query_fasta=${OUTPUT_FOLDER}${basename/_taxClassified.tsv/_nov.fa} + local extract_name="Caliciviridae" # Family + local extract_field="8" # Family + local nothing_found_message="Sample:\t${sample_name}\tNo scaffolds with family == Caliciviridae found." + elif [ "${which_tt}" == "ev" ]; then + local tt_url="https://www.rivm.nl/mpf/typingservice/enterovirus/" + local parser_py="${srcdir}scripts/typingtool_EV_XML_to_csv_parser.py" + local query_fasta=${OUTPUT_FOLDER}${basename/_taxClassified.tsv/_ev.fa} + local extract_name="Picornaviridae" # Family + local extract_field="8" # Family + local nothing_found_message="Sample:\t${sample_name}\tNo scaffolds with family == Picornaviridae found." + elif [ "${which_tt}" == "hav" ]; then + local tt_url="https://www.rivm.nl/mpf/typingservice/hav/" + local parser_py="${srcdir}scripts/typingtool_HAV_XML_to_csv_parser.py" + local query_fasta=${OUTPUT_FOLDER}${basename/_taxClassified.tsv/_hav.fa} + local extract_name="Hepatovirus" # Genus + local extract_field="7" # Genus + local nothing_found_message="Sample:\t${sample_name}\tNo scaffolds with genus == Hepatovirus found." + elif [ "${which_tt}" == "hev" ]; then + local tt_url="https://www.rivm.nl/mpf/typingservice/hev/" + local parser_py="${srcdir}scripts/typingtool_HEV_XML_to_csv_parser.py" + local query_fasta=${OUTPUT_FOLDER}${basename/_taxClassified.tsv/_hev.fa} + local extract_name="Orthohepevirus" # Genus + local extract_field="7" # Genus + local nothing_found_message="Sample:\t${sample_name}\tNo scaffolds with genus == Orthohepevirus found." + elif [ "${which_tt}" == "rva" ]; then + local tt_url="https://www.rivm.nl/mpf/typingservice/rotavirusa/" + local parser_py="${srcdir}scripts/typingtool_RVA_XML_to_csv_parser.py" + local query_fasta=${OUTPUT_FOLDER}${basename/_taxClassified.tsv/_rva.fa} + local extract_name="Rotavirus" # Genus + local extract_field="7" # Genus + local nothing_found_message="Sample:\t${sample_name}\tNo scaffolds with genus == Rotavirus found." + elif [ "${which_tt}" == "pv" ]; then + local tt_url="https://www.rivm.nl/mpf/typingservice/papillomavirus/" + local parser_py="${srcdir}scripts/typingtool_PV_XML_to_csv_parser.py" + local query_fasta=${OUTPUT_FOLDER}${basename/_taxClassified.tsv/_pv.fa} + local extract_name="Papillomaviridae" # Family + local extract_field="8" # Family + local nothing_found_message="Sample:\t${sample_name}\tNo scaffolds with family == Papillomaviridae found." + elif [ "${which_tt}" == "flavi" ]; then + local tt_url="https://www.rivm.nl/mpf/typingservice/flavivirus/" + local parser_py="${srcdir}scripts/typingtool_Flavi_XML_to_csv_parser.py" + local query_fasta=${OUTPUT_FOLDER}${basename/_taxClassified.tsv/_flavi.fa} + local extract_name="Flaviviridae" # Family + local extract_field="8" # Family + local nothing_found_message="Sample:\t${sample_name}\tNo scaffolds with family == Flaviviridae found." + else + echo -e "Unknown typingtool specified." + wrong_tt_keyword_err_msg "${1}" + exit 1 + fi + + local tt_xml=${query_fasta/.fa/.xml} + local tt_csv=${tt_xml/.xml/.csv} + + #! If tt_csv doesn't exist, OR, FORCE_FLAG is NOT empty (i.e. force overwrite previously generated output) + #TODO this will need to be changed if we remove the tt_csv output in the snakemake script (remove temp chunk/onsuccess) + if [ ! -e "${tt_csv}" ] || [ ! -z "${FORCE_FLAG}" ]; then + # Extract taxonomic slice fasta, send to TT, parse the results XML into csv + extract_fasta "${file_path}" "${query_fasta}" "${extract_name}" "${extract_field}" + if [ -s "${query_fasta}" ] + then + echo -e "Sample:\t${sample_name}\tScaffolds compatible with the ${which_tt} tool found, sent to typingtool service, waiting for results... This may take a while..." + submit_query_fasta "${query_fasta}" "${tt_xml}" "${tt_url}" + + # Sadly, the current version of the typingtool service has some issues, resulting in errors because it can't handle the request. + ### One of two things can happen; you get a terse xml output that states "502 Proxy Error" or you get a verbose html output that states "Error reading from remote server". Hence, the double grep OR statement... + if grep -q -e "502 Proxy Error" -e "Error reading from remote server" ${tt_xml}; then + echo -e "Sample:\t${sample_name}\tQuery cannot currently be handled by typingtool... Please try again later, for further information, see: https://github.com/DennisSchmitz/Jovian/issues/51" + else + # If error code is not found; parse the XML + python ${parser_py} "${sample_name}" "${tt_xml}" "${tt_csv}" + fi + else + echo -e "${nothing_found_message}" + fi + #! If tt_csv is not empty (i.e. it exists and has content), AND, FORCE_FLAG is empty (i.e. don't force overwrite previously generated output) + elif [ -s "${tt_csv}" ] && [ -z "${FORCE_FLAG}" ]; then + echo -e "Sample:\t${sample_name}\tScaffolds compatible with the ${which_tt} tool were already found and analyzed in earlier analysis. Skipping..." + else + echo -e "${nothing_found_message}" + fi +} + +# Perform all typingtool functions for each input file specified in the glob below, based on the INPUT_FILES variable +echo -e "\nStarting with ${WHICH_TT} typingtool analysis.\nN.B. depending on the size of your dataset, and the load of the virus typingtool webservice, this might take some time...\n" +for FILE in ${INPUT_FILES} +do + BASENAME=${FILE##*/} # Filename without path but WITH suffixes + if [ "${WHICH_TT}" == "all" ]; then + for TT in "nov" "ev" "hav" "hev" "rva" "pv" "flavi"; do + typingtool "${FILE}" "${BASENAME}" "${TT}" + done + else + typingtool "${FILE}" "${BASENAME}" "${WHICH_TT}" + fi +done + +################################################################################# +### Concatenate all indivual files together into one big file ##### +################################################################################# + +if [ "$(ls -A data/virus_typing_tables)" ]; then + mkdir -p results/typingtools +fi + +if [ "${WHICH_TT}" == "all" ]; then + for TT in "nov" "ev" "hav" "hev" "rva" "pv" "flavi"; do + if [ -n "$( find data/virus_typing_tables/ -maxdepth 1 -name "*_${TT}.csv" -print -quit )" ]; then + # If any files were created in the first place; concat individual outputs into one combined output, the awk magic is to not repeat headers + gawk 'FNR==1 && NR!=1 { next; } { print }' data/virus_typing_tables/*_${TT}.csv > results/typingtools/all_${TT}-TT.csv + fi + done +elif [ -n "$( find data/virus_typing_tables/ -maxdepth 1 -name "*_${WHICH_TT}.csv" -print -quit )" ]; then + # If any files were created in the first place; concat individual outputs into one combined output, the awk magic is to not repeat headers + gawk 'FNR==1 && NR!=1 { next; } { print }' data/virus_typing_tables/*_${WHICH_TT}.csv > results/typingtools/all_${WHICH_TT}-TT.csv +fi + +################################################################################# +### Cleanup ##### +################################################################################# +find data/virus_typing_tables/ -type f -empty -delete +#TODO After updates, not sure if a cleanup is really needed. If it is, better to include it in the for concatenation chunk above. +#TODO rm -f data/virus_typing_tables/*_${WHICH_TT}.fa # Commented this out for debugging purposes, should be activated in v.1.0 (but please first see other #TODO above) +#TODO rm -f data/virus_typing_tables/*_${WHICH_TT}.xml # Commented this out for debugging purposes, should be activated in v.1.0 (but please first see other #TODO above) +echo -e "\nFinished" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b37643a --- /dev/null +++ b/README.md @@ -0,0 +1,303 @@ + +# Jovian - Accessible viral metagenomics for public health and clinical domains + +

    + Jovian logo +

    + +

    + + GitHub release version button + + + GNU license button for AGPL3.0 + +
    + + Snakemake version button + + + Python version button + +

    + +

    + View an interactive demo report: +
    + + MyBinder Jovian example button + +

    + + +## Table of contents +- [Introduction](#introduction) +- [Usage](#usage) + - [Input](#input) + - [Output](#output) + - [Command-line parameters](#command-line-parameters) + - [Examples](#examples) +- [Visualizing results](#visualizing-results) +- [Installation instructions](#installation-instructions) + - [Prerequisites](#prerequisites) + - [Download](#download) + - [Installation](#installation) + - [Databases](#databases) +- [Citation](#citation) +- [Funding](#funding) + + +## Introduction + +Jovian is a pipeline for assembling metagenomics/viromics samples from raw paired-end Illumina FastQ data and intended for batch-wise data analysis, e.g. analyzing an entire sequencing run in one workflow. It performs quality control and data cleanup, removal of human host data to facilitate GDPR-compliance, and assembly of cleaned reads into bigger scaffolds with a focus on full viral genomes. All scaffolds are taxonomically annotated and certain viral families, genera and species are genotyped to the (sub)species and/or cluster level. Any taxonomically ambiguous scaffolds that cannot be resolved by the lowest common ancestor analysis (LCA) are reported for manual inspection. + +It is designed to run on High-Performance Computing (HPC) infrastructures, but can also run locally on a standalone (Linux) computer if needed. It depends on `conda` and `singularity` (explained [here](#installation)) and on [these databases](#databases). Jovian's usage of `singularity` is to facilitate [mobility of compute](https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0177459). + +A distinguishing feature is its ability to generate an interactive report to empower end-users to perform their own analyses. An example is shown [here](https://mybinder.org/v2/gh/DennisSchmitz/Jovian_mybinder_passthrough/HEAD). This report contains an overview of generated scaffolds and their taxonomic assignment, allows interactive assessment of the scaffolds and SNPs identified therein, alongside rich and interactive visualizations including QC reports, Krona-chart, taxonomic heatmaps and interactive spreadsheet to investigate the dataset. Additionally, logging, audit-trail and acknowledgements are reported. + +--- + +## Usage + +___On first use___, the paths to the required databases need to be specified (as explained [here](#databases)): + +```bash +jovian \ + --background {/path/to/background/genome.fa} \ + --blast-db {/path/to/NT_database/nt} \ + --blast-taxdb {/path/to/NCBI/taxdb/} \ + --mgkit-db {/path/to/mgkit_db/} \ + --krona-db {/path/to/krona_db/} \ + --virus-host-db {/path/to/virus_host_db/virushostdb.tsv} \ + --new-taxdump-db {/path/to/new_taxdump/} \ + --input {/path/to/input-directory} \ + --output {/path/to/desired-output} +``` + +These database paths are saved in `~/.jovian_env.yaml` so that they do not need to be supplied for future analyses. Thus, you can start a subsequent analysis with just the [input](#input) and [output](#output) directories: + +```bash +jovian \ + --input {/path/to/input-directory} \ + --output {/path/to/desired-output} +``` + +Other command-line parameters can be found [here](#command-line-parameters) alongside these [examples](#examples). After the analysis finishes, this can be visualized as described [here](#visualizing-results). + +NB, by default Jovian is intended to be used on a grid-computing infrastructure, e.g. a High-Performance Computing (HPC) cluster with a default queue-name called `bio` and through the `DRMAA` abstraction layer. If you want to run it on a single computer (i.e. locally), use it on a `SLURM` system, or, change the queue-name, please see the examples [here](#examples). + +### Input + +Jovian takes as input a folder containing either uncompressed or gzipped Illumina paired-end fastq files with the extensions `.fastq`, `.fq`, `.fastq.gz` or `.fq.gz`. In order to correctly infer paired-end relationship between the R1 and R2 file the filenames must follow this regular expression `(.*)(_|\.)R?(1|2)(?:_.*\.|\..*\.|\.)f(ast)?q(\.gz)?`; essentially samples must have an identical basename that contains `_R[1|2]`, `.R[1|2]`, `_[1|2]` or `.[1|2]`. + +### Output + +Many output files are generated in the specified output folder via [--output](#command-line-parameters), intended to be visualized as explained [here](#visualizing-results). In light of [FAIR](https://www.go-fair.org/fair-principles/) data, and in case you want to parse these files yourself, the table below explains the intent and formatting of these output files. + +| Foldername | Filename | Format | Brief content description | +| -------------------------- | ------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| root*/ | launch_report.sh | bash script (US-ASCII) | Script required to visualize the data as described [here](#visualizing-results) | +| root*/results | all_filtered_SNPs.tsv | Tab separated flatfile (US-ASCII) | Conversion of VCF** metrics to text containing a summary of all identified minority variants, per sample and scaffold | +| root*/results | all_noLCA.tsv | Tab separated flatfile (US-ASCII) | Scaffolds for which Lowest Common Ancestor Analysis taxonomic assignment was unsuccessful due to incongruent taxon assignment*** | +| root*/results | all_taxClassified.tsv | Tab separated flatfile (US-ASCII) | Scaffolds with full taxonomic assignment alongside `BLAST` E-Value and alignment metrics | +| root*/results | all_taxUnclassified.tsv | Tab separated flatfile (US-ASCII) | Scaffolds that could not be taxonomically assigned alongside alignment metrics | +| root*/results | all_virusHost.tsv | Tab separated flatfile (US-ASCII) | Scaffolds assigned with host-metadata from NCBI and Mihara et al., 2016 | +| root*/results | [Bacteria\|Phage\|Taxonomic\|Virus]_rank_statistics.tsv | Tab separated flatfile (US-ASCII) | No. of unique taxonomic assignments from Superkingdom to species for Bacterial, Phage and Virus assigned scaffolds | +| root*/results | igv.html | HTML file (US-ASCII) | `Integrative Genome Viewer` (IGVjs, Robinson et al., 2023) index.html tuned for usage as described [here](#visualizing-results) | +| root*/results | krona.html | HTML file (US-ASCII) | `Krona` chart (Ondov et al., 2011) depicting metagenomic content | +| root*/results | log_conda.txt | Text file (US-ASCII) | Logging of the master conda environment where the workflow runs in, part of the audit trail | +| root*/results | log_config.txt | Text file (US-ASCII) | Logging of the workflow parameters, part of the audit trail | +| root*/results | log_db.txt | Text file (US-ASCII) | Logging of the database paths, part of the audit trail | +| root*/results | log_git.txt | Text file (US-ASCII) | Git hash and github repo link, part of the audit trail | +| root*/results | logfiles_index.html | HTML file (US-ASCII) | Collation of the logfiles generated by the workflow, part of the audit trail | +| root*/results | multiqc.html | HTML file (US-ASCII) | `MultiQC` report (Ewels et al., 2016) depicting quality control metrics | +| root*/results | profile_read_counts.tsv | Tab separated flatfile (US-ASCII) | Read-counts underlying the Sample_composition_graph.html file listed below | +| root*/results | profile_read_percentages.tsv | Tab separated flatfile (US-ASCII) | Read-counts, as percentage, underlying the Sample_composition_graph.html file listed below | +| root*/results | Sample_composition_graph.html | HTML file (US-ASCII) | HTML barchart showing the stratified sample composition | +| root*/results | samplesheet.yaml | YAML file (US-ASCII) | List of processed samples containing the paths to the input files, part of the audit trail | +| root*/results | snakemake_report.html | HTML file (US-ASCII) | `Snakemake` (Köster et al., 2012) logs, part of the audit-trail | +| root*/results | Superkingdoms_quantities_per_sample.csv | Comma separated flatfile (US-ASCII) | Intermediate file for the profile_read files listed above | +| root*/results/counts | Mapped_read_counts.tsv | Tab separated flatfile (US-ASCII) | Intermediate file with mapped reads per scaffold for the all_tax*.tsv files listed above | +| root*/results/counts | Mapped_read_counts-[Sample_name].tsv | Tab separated flatfile (US-ASCII) | Intermediate file with mapped reads per scaffold for the all_tax*.tsv files listed above | +| root*/results/heatmaps | [Bacteria\|Phage\|Superkingdom\|Virus]_heatmap.html | HTML file (US-ASCII) | Heatmaps for different taxonomic strata's down to species level assignment | +| root*/results/multiqc_data | _several files_ | Text file (US-ASCII) | Files required for proper functionality of multiqc.html as listed above | +| root*/results/scaffolds | [Sample_name]_scaffolds.fasta | FASTA file (US-ASCII) | Scaffolds as assembled by `metaSPAdes` (Nurk et al., 2017) filtered by minimum length as described [here](#command-line-parameters) | +| root*/results/typingtools | all_[nov\|ev\|hav\|hev\|rva\|pv\|flavi]-TT.csv | Comma separated flatfile (US-ASCII) | Genotyping results from various typingtools as listed in [publication](#citation) | +| root*/configs/ | config.yaml & params.yaml | YAML file (US-ASCII) | Intermediate configuration and parameter files which are collated in log_config.txt listed above | +| root*/data/ | _several folders with subfiles_ | _various_ | Intermediate files, not intended for direct use but kept for audit and debugging purposes | +| root*/logs/ | _several folders with subfiles_ | Text files (US-ASCII) | Log-files of all the disparate algorithms used by `Jovian` which are collated in logfiles_index.html as listed above | +| root*/.snakemake/ | _several folders with subfiles_ | _various_ | Only for internal use by `Snakemake`, not intended for direct use | + +\* this represents the "root" folder, i.e. the name your supplied to the `--output` flag as listed [here](#command-line-parameters). +\** [Variant Call Format (VCF) explained](https://gatk.broadinstitute.org/hc/en-us/articles/360035531692-VCF-Variant-Call-Format). +\*** Generally this is caused by scaffolds that can be assigned as both a bacterium or as a phage, e.g. temperate phages. + +### Command-line parameters + +```text +usage: Jovian [required arguments] [optional arguments] + +Jovian: a metagenomic analysis workflow for public health and clinics with interactive reports in your web-browser + +NB default database paths are hardcoded for RIVM users, otherwise, specify your own database paths using the optional arguments. +On subsequent invocations of Jovian, the database paths will be read from the file located at: /home/schmitzd/.jovian_env.yaml and you will not have to provide them again. +Similarly, the default RIVM queue is provided as a default value for the '--queuename' flag, but you can override this value if you want to use a different queue. + +Required arguments: + --input DIR, -i DIR The input directory containing the raw fastq(.gz) files + --output DIR, -o DIR Output directory (default: /some/path) + +Optional arguments: + --reset-db-paths Reset the database paths to the default values + --background File Override the default human genome background path + --blast-db Path Override the default BLAST NT database path + --blast-taxdb Path Override the default BLAST taxonomy database path + --mgkit-db Path Override the default MGKit database path + --krona-db Path Override the default Krona database path + --virus-host-db File Override the default virus-host database path (https://www.genome.jp/virushostdb/) + --new-taxdump-db Path Override the default new taxdump database path + --version, -v Show Jovian version and exit + --help, -h Show this help message and exit + --skip-updates Skip the update check (default: False) + --local Use Jovian locally instead of in a grid-computing configuration (default: False) + --slurm Use SLURM instead of the default DRMAA for grid execution (default: DRMAA) + --queuename NAME Name of the queue to use for grid execution (default: bio) + --conda Use conda environments instead of the default singularity images (default: False) + --dryrun Run the Jovian workflow without actually doing anything to confirm that the workflow will run as expected (default: False) + --threads N Number of local threads that are available to use. + Default is the number of available threads in your system (20) + --minphredscore N Minimum phred score to be used for QC trimming (default: 20) + --minreadlength N Minimum read length to used for QC trimming (default: 50) + --mincontiglength N Minimum contig length to be analysed and included in the final output (default: 250) +``` + +### Examples + +If you want to run Jovian through a certain queue-name, use the `--queuename` flag with your own queue-name as specified below. Likewise, if you are using `SLURM`, provide the `--slurm` flag. + +```bash +jovian \ + --input {/path/to/input-directory} \ + --output {/path/to/desired-output} \ + --queuename {your_queue_name} \ + --slurm # only if you are using a SLURM job scheduler +``` + +If you want to invoke it on a single computer/laptop you can invoke the `--local` flag like: + +```bash +jovian \ + --local \ + --input {/path/to/input-directory} \ + --output {/path/to/desired-output} +``` + +Similarly, you can toggle to build the environments via `conda` but for proper functionality please use the default mode that uses `singularity` containers. + +```bash +jovian \ + --conda \ + --input {/path/to/input-directory} \ + --output {/path/to/desired-output} +``` + +## Visualizing results + +When the pipeline has finished an analysis successfully, you can visualize the data via an interactive rapport as follows: +___NB keep this process running for as long as you want to visualize and inspect the data___ + +```bash +cd {/path/to/desired-output} +bash launch_report.sh ./ +``` + +Subsequently, open the reported link in your browser and... + +1. Click 'Jovian_report.ipynb' + 1. When presented with popups click 'Trust'. +2. Via the toolbar, press the `Cell` and then the `Run all` button and wait for all data to be loaded. If you do not see the interactive spreadsheets, e.g. the "Classified scaffolds" section is empty, that means that you need to click the `Run all` button! + 1. This is a known bug, pull-requests are very welcome! + +## Installation instructions + +`Jovian` depends on the prerequisites described [here](#prerequisites) and can be [downloaded](#download) and [installed](#installation) afterwards. After the installation, required databases can be downloaded as described [here](#databases). + +The workflow will update itself to the latest version automatically. This makes it easier for everyone to use the latest available version without having to manually check the GitHub releases. If you wish to run Jovian without the updater checking for a new release, then add the `--skip-updates` flag to your command. in this case you wil ___not___ be notified if there is a new release available. + +### Prerequisites + +1. Before you download and install Jovian, please make sure [Conda](https://docs.conda.io/projects/conda/en/latest/index.html) is installed on your system and functioning properly! Otherwise, install it via [these instuctions](https://docs.conda.io/projects/conda/en/latest/user-guide/install/linux.html). Conda is required to build the "main" environment and contains all required dependencies. +2. Jovian is intended for usage with `singularity`, that is the only way we can properly validate functionality of the code and it helps reduce maintenance. As such, please make sure [Singularity](https://sylabs.io/singularity/), and its dependency [Go](https://go.dev/) are installed properly. Otherwise, install it via [these instructions](https://docs.sylabs.io/guides/3.1/user-guide/installation.html). Singularity is used to build all sub-units of the pipeline. + +### Download + +Use the following command to download the latest release of Jovian and move to the newly downloaded `jovian/` directory: + +```bash +git clone https://github.com/DennisSchmitz/jovian; cd jovian +``` + +### Installation + +First, make sure you are in the root folder of the Jovian repo. If you followed the instructions above, this is the case. + +01. Install the proper dependencies using `conda create --name Jovian -c conda-forge mamba python=3.9 -y; conda activate Jovian; mamba env update -f mamba-env.yml; conda deactivate` +02. Build the Python package via `conda activate Jovian; pip install .` +03. `Jovian` uses `singularity` by default, this must be installed on your computer or on your HPC by your system-admin. Alternatively, use the `--conda` flag to use `conda`, but only the `singularity` option is validated and supported. +04. Follow the steps described in the [databases](#databases) section. +05. Jovian is now installed! You can verify the installation by running `Jovian -h` or `Jovian -v` which should return the help-document or installed version respectively. You can start Jovian from anywhere on your system as long as the Jovian conda-environment is active. If this environment isn't active you can activate it with `conda activate Jovian`. + +### Databases + +Several databases are required before you can use `Jovian` for metagenomics analyses. These are listed below. Please note, these steps requires `Singularity` to be installed as described in the [installation](#installation) section. + +**NB, for people from the RIVM working on the in-house grid-computer, the following steps have already been performed for you.** + +1. Download the `krona` db. NB this step temporarily requires a large amount of storage space, takes some time to complete and might require you to retry it a couple of times. + 1. `mkdir /to/desired/db/location/krona_db/; cd /to/desired/db/location/krona_db/` + 2. `singularity pull --arch amd64 library://ds_bioinformatics/jovian/krona:2.0.0` + 3. `singularity exec --bind "${PWD}" krona_2.0.0.sif bash /opt/conda/opt/krona/updateTaxonomy.sh ./` + 4. `singularity exec --bind "${PWD}" krona_2.0.0.sif bash /opt/conda/opt/krona/updateAccessions.sh ./` + 5. `rm krona_2.0.0.sif` +2. Download the NCBI `nt` and `taxdb` databases. NB update time-stamp accordingly, list available time-stamps with `aws s3 ls --no-sign-request s3://ncbi-blast-databases/`. Importantly, use the same time-stamps for both `nt` and `taxdb`. + 1. NB this requires `awscli` to be installed. + 2. `mkdir /to/desired/db/location/nt/; cd /to/desired/db/location/nt/` + 3. `aws s3 sync --no-sign-request s3://ncbi-blast-databases/[enter_timestamp_here]/ . --exclude "*" --include "nt.*"` + 4. `aws s3 sync --no-sign-request s3://ncbi-blast-databases/[enter_timestamp_here]/ . --exclude "*" --include "taxdb*"` +3. Download the `mgkit` database: + 1. `mkdir /to/desired/db/location/mgkit/; cd /to/desired/db/location/mgkit/` + 2. `singularity pull --arch amd64 library://ds_bioinformatics/jovian/mgkit_lca:2.0.0` + 3. `singularity exec --bind "${PWD}" mgkit_lca_2.0.0.sif download-taxonomy.sh` + 4. `rm taxdump.tar.gz` + 5. `wget -O nucl_gb.accession2taxid.gz ftp://ftp.ncbi.nlm.nih.gov/pub/taxonomy/accession2taxid/nucl_gb.accession2taxid.gz; wget -O nucl_gb.accession2taxid.gz.md5 https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/accession2taxid/nucl_gb.accession2taxid.gz.md5; md5sum -c nucl_gb.accession2taxid.gz.md5` + 6. `gunzip -c nucl_gb.accession2taxid.gz | cut -f2,3 > nucl_gb.accession2taxid_sliced.tsv; rm nucl_gb.accession2taxid.gz*` + 7. `rm mgkit_lca_2.0.0.sif` +4. Download the `virus_host_db`: + 1. `mkdir /to/desired/db/location/virus_host_db/; cd /to/desired/db/location/virus_host_db/` + 2. `wget -O virushostdb.tsv ftp://ftp.genome.jp/pub/db/virushostdb/virushostdb.tsv` +5. Download the NCBI `new_taxdump` database: + 1. `mkdir /to/desired/db/location/new_taxdump/; cd /to/desired/db/location/new_taxdump/` + 2. `wget -O new_taxdump.tar.gz https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/new_taxdump/new_taxdump.tar.gz; wget -O new_taxdump.tar.gz.md5 https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/new_taxdump/new_taxdump.tar.gz.md5` + 3. `if md5sum -c new_taxdump.tar.gz.md5; then tar -xzf new_taxdump.tar.gz; for file in *.dmp; do gawk '{gsub("\t",""); if(substr($0,length($0),length($0))=="|") print substr($0,0,length($0)-1); else print $0}' < ${file} > ${file}.delim; done; else echo "The md5sum does not match new_taxdump.tar.gz! Please try downloading again."; fi` +6. Download the HuGo reference via: + 1. NB this requires `awscli` to be installed. + 2. `mkdir /to/desired/db/location/HuGo/; cd /to/desired/db/location/HuGo/` + 3. `aws s3 --no-sign-request --region eu-west-1 sync s3://ngi-igenomes/igenomes/Homo_sapiens/NCBI/GRCh38/Sequence/WholeGenomeFasta/ ./ --exclude "*" --include "genome.fa*` + 4. `gawk '{print >out}; />chrEBV/{out="EBV.fa"}' out=temp.fa genome.fa; head -n -1 temp.fa > nonEBV.fa; rm EBV.fa temp.fa; mv nonEBV.fa genome.fa` Remove the EBV fasta record in this genome. + 5. `singularity pull --arch amd64 library://ds_bioinformatics/jovian/qc_and_clean:2.0.0` + 6. `singularity exec --bind "${PWD}" qc_and_clean_2.0.0.sif bowtie2-build --threads 8 genome.fa genome.fa` + 7. `rm qc_and_clean:2.0.0` + +## Citation + +Please cite this paper as follows: + +```text +#TODO update after publication +``` + +## Funding + +This study was financed under European Union’s Horizon H2020 grants COMPARE and VEO (grant no. 643476 and 874735) and the NWO Stevin prize (Koopmans). + +__Layout of this README was made using [BioSchemas' Computational Workflow schema](https://bioschemas.org/types/ComputationalWorkflow/1.0-RELEASE) as a guideline__ diff --git a/env.yaml b/env.yaml new file mode 100644 index 0000000..a09b076 --- /dev/null +++ b/env.yaml @@ -0,0 +1,16 @@ +name: Jovian +channels: + - bioconda + - conda-forge + - intel + - nodefaults +dependencies: + - python=3.9 + - conda=4.12 + - mamba + - drmaa==0.7.9 + - snakemake==7.18.2 + - biopython==1.79 + - pyyaml==6.0 + - pip + - tree==2.1.1 diff --git a/mamba-env.yml b/mamba-env.yml new file mode 100644 index 0000000..9436bdf --- /dev/null +++ b/mamba-env.yml @@ -0,0 +1,16 @@ +channels: + - bioconda + - conda-forge + - intel + - nodefaults +dependencies: + - python=3.9 + - conda=4.12 + - mamba + - drmaa==0.7.9 + - snakemake==7.18.2 + - tabulate==0.8.10 + - biopython==1.79 + - pyyaml==6.0 + - pip + - tree==2.1.1 diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..6c5b751 --- /dev/null +++ b/setup.py @@ -0,0 +1,71 @@ +import sys + +from packaging import version as vv +from setuptools import find_packages, setup + +from Jovian import __package_name__, __version__ + +if sys.version_info.major != 3 or sys.version_info.minor < 6: + print("Jovian requires Python 3.6 or higher") + sys.exit(1) + +try: + import conda +except SystemError: + sys.exit( + """ +Error: conda could not be accessed. +Please make sure conda is installed and functioning properly before installing Jovian +""" + ) + + +try: + import snakemake +except SystemError: + sys.exit( + """ +Error: snakemake could not be accessed. +Please make sure snakemake is installed and functioning properly before installing Jovian +""" + ) + + +if vv.parse(snakemake.__version__) < vv.parse("6.0"): + sys.exit( + f""" +The installed SnakeMake version is older than the minimally required version: + +Installed SnakeMake version: {snakemake.__version__} +Required SnakeMake version: 6.0 or later + +Please update SnakeMake to a supported version and try again +""" + ) + +# TODO this isn't used. +with open("README.md", "r") as fh: + long_description = fh.read() + + +setup( + name=__package_name__, + author="Dennis Schmitz", + author_email="DennisSchmitz@users.noreply.github.com", + url="https://github.com/DennisSchmitz/jovian", + license="AGPLv3", + version=__version__, + packages=find_packages(), + scripts=["Jovian/workflow/Snakefile", "Jovian/workflow/directories.py"], + package_data={"Jovian": ["workflow/envs/*", "workflow/scripts/*", "workflow/scripts/html/*", "workflow/files/*", "workflow/files/html/*"]}, + install_requires=["drmaa==0.7.9", "pyyaml==6.0", "biopython==1.79"], + entry_points={ + "console_scripts": [ + "jovian = Jovian.Jovian:main", + "Jovian = Jovian.Jovian:main", + ] + }, + keywords=[], + include_package_data=True, + zip_safe=False, +)