Mercurial > repos > fubar > egapx_runner
changeset 0:d9c5c5b87fec draft
planemo upload for repository https://github.com/ncbi/egapx commit 8173d01b08d9a91c9ec5f6cb50af346edc8020c4
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LICENSE Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,88 @@ +CONTENTS + + Public Domain Notice + Exceptions (for bundled 3rd-party code) + Copyright F.A.Q. + + + +================================================================================ + PUBLIC DOMAIN NOTICE + National Center for Biotechnology Information + +This software was created as part of the author(s) official duties as a United +States Government employee(s), is a "United States Government Work" and is not +subject to copyright in the United States (17 USC 105). The National Library of +Medicine (NLM) and the U.S. Government have not placed any restriction on its +use or reproduction. + +The NLM disclaims all warranties, express or implied, including warranties of +performance, merchantability, or fitness for any particular purpose. + +Please cite NLM in any work or product based on this material. + +EGAPx makes use of various third-party tools which carry their own licenses. + +The list of third-party tools and their licenses are provided here: +================================================================================ +EXCEPTIONS (in all cases excluding NCBI-written makefiles): + + +Location: img/gp/third-party/STAR +Authors: Alexander Dobin +License: MIT License + [https://github.com/alexdobin/STAR/blob/master/LICENSE] + +Location: img/gp/third-party/samtools +Authors: Genome Research Ltd. +License: The MIT/Expat License + [https://github.com/samtools/samtools/blob/develop/LICENSE] + +Location: img/gp/third-party/miniprot +Authors: Dana-Farber Cancer Institute +License: MIT License + [https://github.com/lh3/miniprot/blob/master/LICENSE.txt] + +Location: img/gp/third-party/diamond +Authors: Benjamin Buchfink +License: GNU GENERAL PUBLIC LICENSE + [https://github.com/bbuchfink/diamond/blob/master/LICENSE] + +Location: img/gp/third-party/seqkit +Authors: Wei Shen +License: MIT License + [https://github.com/shenwei356/seqkit/blob/master/LICENSE] + +================================================================================ + +Copyright F.A.Q. + + +-------------------------------------------------------------- +Q. Our product makes use of the NCBI source code, and we did changes + and additions to that version of the NCBI code to better fit it to + our needs. Can we copyright the code, and how? + +A. You can copyright only the *changes* or the *additions* you made to the + NCBI source code. You should identify unambiguously those sections of + the code that were modified, e.g. by commenting any changes you made + in the code you distribute. Therefore, your license has to make clear + to users that your product is a combination of code that is public domain + within the U.S. (but may be subject to copyright by the U.S. in foreign + countries) and code that has been created or modified by you. + + +-------------------------------------------------------------- +Q. Can we (re)license all or part of the NCBI source code? + +A. No, you cannot license or relicense the source code written by NCBI + since you cannot claim any copyright in the software that was developed + at NCBI as a 'government work' and consequently is in the public domain + within the U.S. + + +-------------------------------------------------------------- +Q. What if these copyright guidelines are not clear enough or are not + applicable to my particular case? + +A. Contact us. Send your questions to 'toolbox@ncbi.nlm.nih.gov'.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/PRIVACY.md Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,6 @@ +# Privacy + +## Privacy Statement +We do not currently collect EGAPx usage data. + +Additional privacy and security policy information can be found on the [NLM Web Policies](https://www.nlm.nih.gov/web_policies.html) page.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/README.md Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,377 @@ +# Eukaryotic Genome Annotation Pipeline - External (EGAPx) + +EGAPx is the publicly accessible version of the updated NCBI [Eukaryotic Genome Annotation Pipeline](https://www.ncbi.nlm.nih.gov/genome/annotation_euk/process/). + +EGAPx takes an assembly fasta file, a taxid of the organism, and RNA-seq data. Based on the taxid, EGAPx will pick protein sets and HMM models. The pipeline runs `miniprot` to align protein sequences, and `STAR` to align RNA-seq to the assembly. Protein alignments and RNA-seq read alignments are then passed to `Gnomon` for gene prediction. In the first step of `Gnomon`, the short alignments are chained together into putative gene models. In the second step, these predictions are further supplemented by _ab-initio_ predictions based on HMM models. The final annotation for the input assembly is produced as a `gff` file. + +We currently have protein datasets posted that are suitable for most vertebrates and arthropods: + - Chordata - Mammalia, Sauropsida, Actinopterygii (ray-finned fishes) + - Insecta - Hymenoptera, Diptera, Lepidoptera, Coleoptera, Hemiptera + - Arthropoda - Arachnida, other Arthropoda + +We will be adding datasets for plants and other invertebrates in the next couple of months. Fungi, protists and nematodes are currently out-of-scope for EGAPx pending additional refinements. + +We currently have protein datasets posted for most vertebrates (mammals, sauropsids, ray-finned fishes) and arthropods. We will be adding datasets for more arthropods, vertebrates and plants in the next couple of months. Fungi, protists and nematodes are currently out-of-scope for EGAPx pending additional refinements. + +**Warning:** +The current version is an alpha release with limited features and organism scope to collect initial feedback on execution. Outputs are not yet complete and not intended for production use. Please open a GitHub [Issue](https://github.com/ncbi/egapx/issues) if you encounter any problems with EGAPx. You can also write to cgr@nlm.nih.gov to give us your feedback or if you have any questions. + + +**Security Notice:** +EGAPx has dependencies in and outside of its execution path that include several thousand files from the [NCBI C++ toolkit](https://www.ncbi.nlm.nih.gov/toolkit), and more than a million total lines of code. Static Application Security Testing has shown a small number of verified buffer overrun security vulnerabilities. Users should consult with their organizational security team on risk and if there is concern, consider mitigating options like running via VM or cloud instance. + +**License:** +See the EGAPx license [here](https://github.com/ncbi/egapx/blob/main/LICENSE). + + + +## Prerequisites + +- Docker or Singularity +- AWS batch, UGE cluster, or a r6a.4xlarge machine (32 CPUs, 256GB RAM) +- Nextflow v.23.10.1 +- Python v.3.9+ + +Notes: +- General configuration for AWS Batch is described in the Nextflow documentation at https://www.nextflow.io/docs/latest/aws.html +- See Nextflow installation at https://www.nextflow.io/docs/latest/getstarted.html + +## The workflow files + +- Clone the EGAPx repo: + ``` + git clone https://github.com/ncbi/egapx.git + cd egapx + ``` + +## Input data format + +Input to EGAPx is in the form of a YAML file. + +- The following are the _required_ key-value pairs for the input file: + + ``` + genome: path to assembled genome in FASTA format + taxid: NCBI Taxonomy identifier of the target organism + reads: RNA-seq data + ``` + You can obtain taxid from the [NCBI Taxonomy page](https://www.ncbi.nlm.nih.gov/taxonomy). + + + - RNA-seq data can be supplied in any one of the following ways: + + ``` + reads: [ array of paths to reads FASTA or FASTQ files] + reads: [ array of SRA run IDs ] + reads: [SRA Study ID] + reads: SRA query for reads + ``` + - If you are using your local reads, then the FASTA/FASTQ files should be provided in the following format: + ``` + reads: + - path_to_Sample1_R1.gz + - path_to_Sample1_R2.gz + - path_to_Sample2_R1.gz + - path_to_Sample2_R2.gz + ``` + + - If you provide an SRA Study ID, all the SRA run ID's belonging to that Study ID will be included in the EGAPx run. + +- The following are the _optional_ key-value pairs for the input file: + + - A protein set. A taxid-based protein set will be chosen if no protein set is provided. + ``` + proteins: path to proteins data in FASTA format. + ``` + + - HMM file used in Gnomon training. A taxid-based HMM will be chosen if no HMM file is provided. + ``` + hmm: path to HMM file + ``` + + + +## Input example + +- A test example YAML file `./examples/input_D_farinae_small.yaml` is included in the `egapx` folder. Here, the RNA-seq data is provided as paths to the reads FASTA files. These FASTA files are a sampling of the reads from the complete SRA read files to expedite testing. + + + ``` + genome: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/020/809/275/GCF_020809275.1_ASM2080927v1/GCF_020809275.1_ASM2080927v1_genomic.fna.gz + taxid: 6954 + reads: + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/data/Dermatophagoides_farinae_small/SRR8506572.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/data/Dermatophagoides_farinae_small/SRR8506572.2 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/data/Dermatophagoides_farinae_small/SRR9005248.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/data/Dermatophagoides_farinae_small/SRR9005248.2 + ``` + +- To specify an array of NCBI SRA datasets: + ``` + reads: + - SRR8506572 + - SRR9005248 + ``` + +- To specify an SRA entrez query: + ``` + reads: 'txid6954[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession] AND (SRR8506572[Accession] OR SRR9005248[Accession] )' + ``` + + **Note:** Both the above examples will have more RNA-seq data than the `input_D_farinae_small.yaml` example. To make sure the entrez query does not produce a large number of SRA runs, please run it first at the [NCBI SRA page](https://www.ncbi.nlm.nih.gov/sra). If there are too many SRA runs, then select a few of them and list it in the input yaml. + +- First, test EGAPx on the example provided (`input_D_farinae_small.yaml`, a dust mite) to make sure everything works. This example usually runs under 30 minutes depending upon resource availability. There are other examples you can try: `input_C_longicornis.yaml`, a green fly, and `input_Gavia_tellata.yaml`, a bird. These will take close to two hours. You can prepare your input YAML file following these examples. + +## Run EGAPx + +- The `egapx` folder contains the following directories: + - examples + - nf + - test + - third_party_licenses + - ui + +- The runner script is within the ui directory (`ui/egapx.py`). + +- Create a virtual environment where you can run EGAPx. There is a `requirements.txt` file. PyYAML will be installed in this environment. + ``` + python -m venv /path/to/new/virtual/environment + source /path/to/new/virtual/environment/bin/activate + pip install -r ui/requirements.txt + ``` + + + + + +- Run EGAPx for the first time to copy the config files so you can edit them: + ``` + python3 ui/egapx.py ./examples/input_D_farinae_small.yaml -o example_out + ``` + - When you run `egapx.py` for the first time it copies the template config files to the directory `./egapx_config`. + - You will need to edit these templates to reflect the actual parameters of your setup. + - For AWS Batch execution, set up AWS Batch Service following advice in the AWS link above. Then edit the value for `process.queue` in `./egapx_config/aws.config` file. + - For execution on the local machine you don't need to adjust anything. + + +- Run EGAPx with the following command for real this time. + - For AWS Batch execution, replace temp_datapath with an existing S3 bucket. + - For local execution, use a local path for `-w` + ``` + python3 ui/egapx.py ./examples/input_D_farinae_small.yaml -e aws -w s3://temp_datapath/D_farinae -o example_out + ``` + + - use `-e aws` for AWS batch using Docker image + - use `-e docker` for using Docker image + - use `-e singularity` for using the Singularity image + - use `-e biowulf_cluster` for Biowulf cluster using Singularity image + - use '-e slurm` for using SLURM in your HPC. + - Note that for this option, you have to edit `./egapx_config/slurm.config` according to your cluster specifications. + - type `python3 ui/egapx.py  -h ` for the help menu + + ``` + $ ui/egapx.py -h + + + !!WARNING!! + This is an alpha release with limited features and organism scope to collect initial feedback on execution. Outputs are not yet complete and not intended for production use. + + usage: egapx.py [-h] [-o OUTPUT] [-e EXECUTOR] [-c CONFIG_DIR] [-w WORKDIR] [-r REPORT] [-n] [-st] + [-so] [-dl] [-lc LOCAL_CACHE] [-q] [-v] [-fn FUNC_NAME] + [filename] + + Main script for EGAPx + + optional arguments: + -h, --help show this help message and exit + -e EXECUTOR, --executor EXECUTOR + Nextflow executor, one of docker, singularity, aws, or local (for NCBI + internal use only). Uses corresponding Nextflow config file + -c CONFIG_DIR, --config-dir CONFIG_DIR + Directory for executor config files, default is ./egapx_config. Can be also + set as env EGAPX_CONFIG_DIR + -w WORKDIR, --workdir WORKDIR + Working directory for cloud executor + -r REPORT, --report REPORT + Report file prefix for report (.report.html) and timeline (.timeline.html) + files, default is in output directory + -n, --dry-run + -st, --stub-run + -so, --summary-only Print result statistics only if available, do not compute result + -lc LOCAL_CACHE, --local-cache LOCAL_CACHE + Where to store the downloaded files + -q, --quiet + -v, --verbose + -fn FUNC_NAME, --func_name FUNC_NAME + func_name + + run: + filename YAML file with input: section with at least genome: and reads: parameters + -o OUTPUT, --output OUTPUT + Output path + + download: + -dl, --download-only Download external files to local storage, so that future runs can be + isolated + + + ``` + + +## Test run + +``` +$ python3 ui/egapx.py examples/input_D_farinae_small.yaml -e aws -o example_out -w s3://temp_datapath/D_farinae + +!!WARNING!! +This is an alpha release with limited features and organism scope to collect initial feedback on execution. Outputs are not yet complete and not intended for production use. + +N E X T F L O W ~ version 23.10.1 +Launching `/../home/user/egapx/ui/../nf/ui.nf` [golden_mercator] DSL2 - revision: c134f40af5 +in egapx block +executor > awsbatch (67) +[f5/3007b8] process > egapx:setup_genome:get_genome_info [100%] 1 of 1 ✔ +[32/a1bfa5] process > egapx:setup_proteins:convert_proteins [100%] 1 of 1 ✔ +[96/621c4b] process > egapx:miniprot:run_miniprot [100%] 1 of 1 ✔ +[6d/766c2f] process > egapx:paf2asn:run_paf2asn [100%] 1 of 1 ✔ +[56/f1dd6b] process > egapx:best_aligned_prot:run_best_aligned_prot [100%] 1 of 1 ✔ +[c1/ccc4a3] process > egapx:align_filter_sa:run_align_filter_sa [100%] 1 of 1 ✔ +[e0/5548d0] process > egapx:run_align_sort [100%] 1 of 1 ✔ +[a8/456a0e] process > egapx:star_index:build_index [100%] 1 of 1 ✔ +[d5/6469a6] process > egapx:star_simplified:exec (1) [100%] 2 of 2 ✔ +[64/99ab35] process > egapx:bam_strandedness:exec (2) [100%] 2 of 2 ✔ +[98/a12969] process > egapx:bam_strandedness:merge [100%] 1 of 1 ✔ +[78/0d7007] process > egapx:bam_bin_and_sort:calc_assembly_sizes [100%] 1 of 1 ✔ +[74/bb014e] process > egapx:bam_bin_and_sort:bam_bin (2) [100%] 2 of 2 ✔ +[39/3cdd00] process > egapx:bam_bin_and_sort:merge_prepare [100%] 1 of 1 ✔ +[01/f64e38] process > egapx:bam_bin_and_sort:merge (1) [100%] 1 of 1 ✔ +[aa/47a002] process > egapx:bam2asn:convert (1) [100%] 1 of 1 ✔ +[45/6661b3] process > egapx:rnaseq_collapse:generate_jobs [100%] 1 of 1 ✔ +[64/68bc37] process > egapx:rnaseq_collapse:run_rnaseq_collapse (3) [100%] 9 of 9 ✔ +[18/bff1ac] process > egapx:rnaseq_collapse:run_gpx_make_outputs [100%] 1 of 1 ✔ +[a4/76a4a5] process > egapx:get_hmm_params:run_get_hmm [100%] 1 of 1 ✔ +[3c/b71c42] process > egapx:chainer:run_align_sort (1) [100%] 1 of 1 ✔ +[e1/340b6d] process > egapx:chainer:generate_jobs [100%] 1 of 1 ✔ +[c0/477d02] process > egapx:chainer:run_chainer (16) [100%] 16 of 16 ✔ +[9f/27c1c8] process > egapx:chainer:run_gpx_make_outputs [100%] 1 of 1 ✔ +[5c/8f65d0] process > egapx:gnomon_wnode:gpx_qsubmit [100%] 1 of 1 ✔ +[34/6ab0c9] process > egapx:gnomon_wnode:annot (1) [100%] 10 of 10 ✔ +[a9/e38221] process > egapx:gnomon_wnode:gpx_qdump [100%] 1 of 1 ✔ +[bc/8ebca4] process > egapx:annot_builder:annot_builder_main [100%] 1 of 1 ✔ +[5f/6b72c0] process > egapx:annot_builder:annot_builder_input [100%] 1 of 1 ✔ +[eb/1ccdd0] process > egapx:annot_builder:annot_builder_run [100%] 1 of 1 ✔ +[4d/6c33db] process > egapx:annotwriter:run_annotwriter [100%] 1 of 1 ✔ +[b6/d73d18] process > export [100%] 1 of 1 ✔ +Waiting for file transfers to complete (1 files) +Completed at: 27-Mar-2024 11:43:15 +Duration : 27m 36s +CPU hours : 4.2 +Succeeded : 67 +``` +## Output + +Look at the output in the out diectory (`example_out`) that was supplied in the command line. The annotation file is called `accept.gff`. +``` +accept.gff +annot_builder_output +nextflow.log +run.report.html +run.timeline.html +run.trace.txt +run_params.yaml +``` +The `nextflow.log` is the log file that captures all the process information and their work directories. `run_params.yaml` has all the parameters that were used in the EGAPx run. More information about the process time and resources can be found in the other run* files. + + + +## Intermediate files + +In the above log, each line denotes the process that completed in the workflow. The first column (_e.g._ `[96/621c4b]`) is the subdirectory where the intermediate output files and logs are found for the process in the same line, _i.e._, `egapx:miniprot:run_miniprot`. To see the intermediate files for that process, you can go to the work directory path that you had supplied and traverse to the subdirectory `96/621c4b`: + +``` +$ aws s3 ls s3://temp_datapath/D_farinae/96/ + PRE 06834b76c8d7ceb8c97d2ccf75cda4/ + PRE 621c4ba4e6e87a4d869c696fe50034/ +$ aws s3 ls s3://temp_datapath/D_farinae/96/621c4ba4e6e87a4d869c696fe50034/ + PRE output/ +2024-03-27 11:19:18 0 +2024-03-27 11:19:28 6 .command.begin +2024-03-27 11:20:24 762 .command.err +2024-03-27 11:20:26 762 .command.log +2024-03-27 11:20:23 0 .command.out +2024-03-27 11:19:18 13103 .command.run +2024-03-27 11:19:18 129 .command.sh +2024-03-27 11:20:24 276 .command.trace +2024-03-27 11:20:25 1 .exitcode +$ aws s3 ls s3://temp_datapath/D_farinae/96/621c4ba4e6e87a4d869c696fe50034/output/ +2024-03-27 11:20:24 17127134 aligns.paf +``` + +## Offline mode + +If you do not have internet access from your cluster, you can run EGAPx in offline mode. To do this, you would first pull the Singularity image, then download the necessary files from NCBI FTP using `egapx.py` script, and then finally use the path of the downloaded folder in the run command. Here is an example of how to download the files and execute EGAPx in the Biowulf cluster. + + +- Download the Singularity image: +``` +rm egap*sif +singularity cache clean +singularity pull docker://ncbi/egapx:0.2-alpha +``` + +- Clone the repo: +``` +git clone https://github.com/ncbi/egapx.git +cd egapx +``` + +- Download EGAPx related files from NCBI: +``` +python3 ui/egapx.py -dl -lc ../local_cache +``` + +- Download SRA reads: +``` +prefetch SRR8506572 +prefetch SRR9005248 +fasterq-dump --skip-technical --threads 6 --split-files --seq-defline ">\$ac.\$si.\$ri" --fasta -O sradir/ ./SRR8506572 +fasterq-dump --skip-technical --threads 6 --split-files --seq-defline ">\$ac.\$si.\$ri" --fasta -O sradir/ ./SRR9005248 + +``` +You should see downloaded files inside the 'sradir' folder": +``` +ls sradir/ +SRR8506572_1.fasta SRR8506572_2.fasta SRR9005248_1.fasta SRR9005248_2.fasta +``` +Now edit the file paths of SRA reads files in `examples/input_D_farinae_small.yaml` to include the above SRA files. + +- Run `egapx.py` first to edit the `biowulf_cluster.config`: +``` +ui/egapx.py examples/input_D_farinae_small.yaml -e biowulf_cluster -w dfs_work -o dfs_out -lc ../local_cache +echo "process.container = '/path_to_/egapx_0.2-alpha.sif'" >> egapx_config/biowulf_cluster.config +``` + +- Run `egapx.py`: +``` +ui/egapx.py examples/input_D_farinae_small.yaml -e biowulf_cluster -w dfs_work -o dfs_out -lc ../local_cache + +``` + + +## References + +Buchfink B, Reuter K, Drost HG. Sensitive protein alignments at tree-of-life scale using DIAMOND. Nat Methods. 2021 Apr;18(4):366-368. doi: 10.1038/s41592-021-01101-x. Epub 2021 Apr 7. PMID: 33828273; PMCID: PMC8026399. + +Danecek P, Bonfield JK, Liddle J, Marshall J, Ohan V, Pollard MO, Whitwham A, Keane T, McCarthy SA, Davies RM, Li H. Twelve years of SAMtools and BCFtools. Gigascience. 2021 Feb 16;10(2):giab008. doi: 10.1093/gigascience/giab008. PMID: 33590861; PMCID: PMC7931819. + +Dobin A, Davis CA, Schlesinger F, Drenkow J, Zaleski C, Jha S, Batut P, Chaisson M, Gingeras TR. STAR: ultrafast universal RNA-seq aligner. Bioinformatics. 2013 Jan 1;29(1):15-21. doi: 10.1093/bioinformatics/bts635. Epub 2012 Oct 25. PMID: 23104886; PMCID: PMC3530905. + +Li H. Protein-to-genome alignment with miniprot. Bioinformatics. 2023 Jan 1;39(1):btad014. doi: 10.1093/bioinformatics/btad014. PMID: 36648328; PMCID: PMC9869432. + +Shen W, Le S, Li Y, Hu F. SeqKit: A Cross-Platform and Ultrafast Toolkit for FASTA/Q File Manipulation. PLoS One. 2016 Oct 5;11(10):e0163962. doi: 10.1371/journal.pone.0163962. PMID: 27706213; PMCID: PMC5051824. + + + +## Contact us + +Please open a GitHub [Issue](https://github.com/ncbi/egapx/issues) if you encounter any problems with EGAPx. You can also write to cgr@nlm.nih.gov to give us your feedback or if you have any questions.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/input_C_longicornis.yaml Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,3 @@ +genome: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/029//603/195/GCF_029603195.1_ASM2960319v2/GCF_029603195.1_ASM2960319v2_genomic.fna.gz +reads: txid2530218[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession] +taxid: 2530218 \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/input_D_farinae_minimal.yaml Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,16 @@ +# This is a very minimal example of EGAPx, it fits into 4 CPU cores and 6GB of memory. +# To be able to do this, we culled the input files and some stages of execution. +# To limit the requirements you also need to use -e docker_minimal + +genome: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/020/809/275/GCF_020809275.1_ASM2080927v1/GCF_020809275.1_ASM2080927v1_genomic.fna.gz +reads: + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR8506572.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR8506572.2 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR9005248.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR9005248.2 +taxid: 6954 +proteins: [] +hmm: https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/gnomon/hmm_parameters/6956.params +tasks: + star_wnode: + star_wnode: -cpus-per-worker 4
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/input_D_farinae_small.yaml Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,7 @@ +genome: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/020/809/275/GCF_020809275.1_ASM2080927v1/GCF_020809275.1_ASM2080927v1_genomic.fna.gz +taxid: 6954 +reads: + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR8506572.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR8506572.2 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR9005248.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR9005248.2
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/input_D_farinae_small_proteins.yaml Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,3 @@ +genome: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/020/809/275/GCF_020809275.1_ASM2080927v1/GCF_020809275.1_ASM2080927v1_genomic.fna.gz +proteins: https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/target_proteins/6954.faa.gz +taxid: 6954
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/input_D_farinae_small_rnaseq.yaml Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,9 @@ +genome: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/020/809/275/GCF_020809275.1_ASM2080927v1/GCF_020809275.1_ASM2080927v1_genomic.fna.gz +reads: + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR8506572.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR8506572.2 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR9005248.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR9005248.2 +# To prevent the system from searching for protein bag by taxid we do not specify it here, but we need to specify hmm explicitly in this case. +# taxid: 6954 +hmm: https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/params.asn
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/input_D_farinae_small_rnaseq_proteins.yaml Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,8 @@ +genome: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/020/809/275/GCF_020809275.1_ASM2080927v1/GCF_020809275.1_ASM2080927v1_genomic.fna.gz +reads: + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR8506572.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR8506572.2 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR9005248.1 + - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/sample_data/Dermatophagoides_farinae_small/SRR9005248.2 +proteins: https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/target_proteins/6954.faa.gz +taxid: 6954
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/examples/input_Gavia_stellata.yaml Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,3 @@ +genome: https://ftp.ncbi.nlm.nih.gov/genomes/all/GCF/030/936/135/GCF_030936135.1_bGavSte3.hap2/GCF_030936135.1_bGavSte3.hap2_genomic.fna.gz +reads: txid37040[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession] +taxid: 37040
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/default/align_sort_sa/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,45 @@ +#!/usr/bin/env nextflow + +nextflow.enable.dsl=2 + +include { merge_params} from '../../utilities' + + +workflow align_sort_sa { + take: + genome_asn + proteins_asn + alignments //path: alignment files + parameters // Map : extra parameter and parameter update + main: + default_params = "" + effective_params = merge_params(default_params, parameters, 'align_sort') + run_align_sort( genome_asn, proteins_asn, alignments, effective_params) + + emit: + sorted_asn_file = run_align_sort.out.sorted_asn_file +} + + +process run_align_sort { + input: + path genome, stageAs: 'LDS_Index/genome.asnt' + path proteins, stageAs: 'LDS_Index/proteins.asnt' + path alignments + val parameters + output: + path ('output/sorted_aligns.asn') , emit: 'sorted_asn_file' + script: + """ + mkdir -p output + mkdir -p LDS_Index + lds2_indexer -source LDS_Index + echo "${alignments.join('\n')}" > alignments.mft + align_sort $parameters -input-manifest alignments.mft -o output/sorted_aligns.asn -lds2 LDS_Index/lds2.db + """ + stub: + """ + mkdir -p output + touch output/sorted_aligns.asn + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/default/annot_builder/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,196 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + +// annot_builder_main collection_dir ${output}/COLLECTION accept_dir ${output}/ACCEPT conflict_dir ${output}/CONFLICT report_dir ${output}/REPORT test_dir ${output}/TEST i +// reftrack_attrs_manifest ${input.reftrack_attrs} loss_pct_ccds 0.0 loss_pct_refseq_ref_primary 1.0 loss_pct_refseq_alt_ref_loci 100.0 loss_pct_refseq_patches 100.0 loss_pct_refseq_other 1.0 +// annot_builder_input name gnomon desc Gnomon aliases Gnomon|Chainer|PartAbInitio|FullAbInitio|Chainer_GapFilled|PartAbInitio_GapFilled +// is_primary 1 input_manifest ${input.gnomon_models} model_maker gnomon2model use_secondary_support 1 keep_top_N_models 50 +// drop_alt_brs_overlap 1 merge_variants 1 enable_AR0050_AR0048 1 max_pct_ab_initio 50 +// annot_builder -accept-output both -asn-cache ${GP_cache_dir} -conffile ${conffile} -gc-assembly-manifest ${input.gencoll_asn} -logfile ${logfile} + +// not implimented, future examples +//load_annot_builder_tracking_data -stats-xml ${output}/REPORT/stats.xml -taskrun ${taskrun.id} +//annot_builder_input name bestrs desc BestRefSeq is_primary 1 input_manifest ${input.best_rs_seqalign} model_maker splign2model user_filter lxr_data.is_refseq=1 +//annot_builder_input name ng desc Curated Genomic is_primary 1 input_manifest ${input.best_ng_seqalign} model_maker ng2model score_filter rank=1 exclude_subtypes CloneRef,misc_difference,STS,tRNA,variation,VariationRef exclude_types Biosrc,Pub +//annot_builder_input name imgt desc IMGT is_primary 1 input_manifest ${input.imgt} model_maker imgt2model use_secondary_support 0 +//annot_builder_input name rfam desc cmsearch aliases Rfam is_primary 1 input_manifest ${input.rfam} model_maker gnomon2model +//annot_builder_input name trna desc tRNAscan-SE is_primary 1 input_manifest ${input.trna_annot} model_maker passthru +//annot_builder_input name blessed desc SelectedGeneRepresentative is_primary 0 input_manifest ${input.best_rs_seqalign} model_maker splign2model score_filter rank=1 user_filter lxr_data.is_refseq=0 + +workflow annot_builder { + take: + gencoll_asn + gnomon_file + genome_asn + parameters // Map : extra parameter and parameter update + main: + + def m = annot_builder_main('outdir', params).collect() + def i = annot_builder_input('outdir', m, '01', gnomon_file, params) + // FIXME: intended params 4-5 to be lists of all input files and all input manifests, but it complained with only one entry + def (all, accept, accept_ftable, annot) = annot_builder_run('outdir', i[0], gencoll_asn, i[1], gnomon_file, genome_asn, params) + + emit: + outputs = all + accept_asn = accept + accept_ftable_annot = accept_ftable + annot_files = annot +} + + +// [Main] +// accept_dir = "/netmnt/vast01/gpi/prod/GPIPE_PROD/data00/Lagenorhynchus_albirostris/1.1.470794/6389647/annot_builder.46361542/out/ACCEPT" +// collection_dir = "/netmnt/vast01/gpi/prod/GPIPE_PROD/data00/Lagenorhynchus_albirostris/1.1.470794/6389647/annot_builder.46361542/out/COLLECTION" +// conflict_dir = "/netmnt/vast01/gpi/prod/GPIPE_PROD/data00/Lagenorhynchus_albirostris/1.1.470794/6389647/annot_builder.46361542/out/CONFLICT" +// loss_pct_ccds = "0.0" +// loss_pct_refseq_alt_ref_loci = "100.0" +// loss_pct_refseq_other = "1.0" +// loss_pct_refseq_patches = "100.0" +// loss_pct_refseq_ref_primary = "1.0" +// reftrack_attrs_manifest = "/netmnt/vast01/gpi/prod/GPIPE_PROD/data00/Lagenorhynchus_albirostris/1.1.470794/6389647/annot_builder.46361542/inp/reftrack_attrs.mft" +// report_dir = "/netmnt/vast01/gpi/prod/GPIPE_PROD/data00/Lagenorhynchus_albirostris/1.1.470794/6389647/annot_builder.46361542/out/REPORT" +// test_dir = "/netmnt/vast01/gpi/prod/GPIPE_PROD/data00/Lagenorhynchus_albirostris/1.1.470794/6389647/annot_builder.46361542/out/TEST" + +process annot_builder_main { + input: + val outdir + val params + output: + path "annot_builder_main.ini" + script: + """ + #!/usr/bin/env python3 + with open('annot_builder_main.ini', 'w') as outf: + print('[Main]', file=outf) + print('accept_dir = "$outdir/ACCEPT"', file=outf) + print('collection_dir = "$outdir/COLLECTION"', file=outf) + print('conflict_dir = "$outdir/CONFLICT"', file=outf) + print('loss_pct_ccds = "0.0"', file=outf) + print('loss_pct_refseq_alt_ref_loci = "100.0"', file=outf) + print('loss_pct_refseq_other = "1.0"', file=outf) + print('loss_pct_refseq_patches = "100.0"', file=outf) + print('loss_pct_refseq_ref_primary = "1.0"', file=outf) + print('report_dir = "$outdir/REPORT"', file=outf) + print('test_dir = "$outdir/TEST"', file=outf) + """ + stub: + """ + touch annot_builder_main.ini + echo 'main' > annot_builder_main.ini + """ +} + + +// [DataProvider06] +// aliases = "Gnomon|Chainer|PartAbInitio|FullAbInitio|Chainer_GapFilled|PartAbInitio_GapFilled" +// desc = "Gnomon" +// drop_alt_brs_overlap = "1" +// enable_AR0050_AR0048 = "1" +// input_manifest = "/netmnt/vast01/gpi/prod/GPIPE_PROD/data00/Lagenorhynchus_albirostris/1.1.470794/6389647/annot_builder.46361542/inp/gnomon_models.mft" +// is_primary = "1" +// keep_top_N_models = "50" +// max_pct_ab_initio = "50" +// merge_variants = "1" +// model_maker = "gnomon2model" +// name = "gnomon" +// use_secondary_support = "1" + +process annot_builder_input { + input: + val outdir + path prior_file + val provider_number + path input_file + val params + output: + path("annot_builder_input.ini") + path("input_manifest_${provider_number}.mft") + script: + """ + #!/usr/bin/env python3 + with open('annot_builder_input.ini', 'w') as outf: + + with open('${prior_file}', 'r') as f: + print(f.read(), file=outf) + + print('[DataProvider${provider_number}]', file=outf) + + im = 'input_manifest_${provider_number}.mft' + inpf = '${input_file}' + with open(im, 'w') as mft: + print(inpf, file=mft) + print(f'input_manifest="{im}"', file=outf) + + print('aliases = "Gnomon|Chainer|PartAbInitio|FullAbInitio|Chainer_GapFilled|PartAbInitio_GapFilled"', file=outf) + print('desc = "Gnomon"', file=outf) + print('name = "gnomon"', file=outf) + print('model_maker = "gnomon2model"', file=outf) + + print('drop_alt_brs_overlap = "1"', file=outf) + print('enable_AR0050_AR0048 = "1"', file=outf) + print('is_primary = "1"', file=outf) + print('keep_top_N_models = "50"', file=outf) + print('max_pct_ab_initio = "50"', file=outf) + print('merge_variants = "1"', file=outf) + print('use_secondary_support = "1"', file=outf) + """ + stub: + """ + touch annot_builder_input.ini + touch input_manifest_${provider_number}.mft + cp ${prior_file} annot_builder_input.ini + echo 'input ${provider_number}' >> annot_builder_input.ini + """ +} + + +// ## annot_builder -accept-output both -asn-cache ${GP_cache_dir} -conffile ${conffile} -gc-assembly-manifest ${input.gencoll_asn} -logfile ${logfile} +process annot_builder_run { + input: + val outdir + path conffile, stageAs: 'annot_builder_final.ini' + path gencoll_asn + path input_manifests + path input_files + path genome_asn, stageAs: 'genome/*' + val params + output: + path "${outdir}/*", emit: "all" + path "${outdir}/ACCEPT/accept.asn", emit: "accept", optional: true + path "${outdir}/ACCEPT/accept.ftable_annot", emit: "accept_ftable_annot", optional: true + path "${outdir}/ACCEPT/*.annot", optional: true + script: + """ + mkdir -p $outdir/ACCEPT + mkdir -p $outdir/COLLECTION + mkdir -p $outdir/CONFLICT + mkdir -p $outdir/REPORT + mkdir -p $outdir/TEST + + lds2_indexer -source genome/ -db LDS2 + # EXCEPTION_STACK_TRACE_LEVEL=Warning DEBUG_STACK_TRACE_LEVEL=Warning DIAG_POST_LEVEL=Trace + annot_builder -accept-output both -nogenbank -lds2 LDS2 -conffile $conffile -gc-assembly $gencoll_asn -logfile ${outdir}/annot_builder.log + cat ${outdir}/ACCEPT/*.ftable.annot > ${outdir}/ACCEPT/accept.ftable_annot + """ + stub: + """ + mkdir -p $outdir/ACCEPT + mkdir -p $outdir/COLLECTION + mkdir -p $outdir/CONFLICT + mkdir -p $outdir/REPORT + mkdir -p $outdir/TEST + + echo "1" > ${outdir}/annot_builder.log + echo "2" > ${outdir}/accept.asn + echo "3" > ${outdir}/accept.ftable.annot + + + echo "4" > ${outdir}/ACCEPT/accept.asn + echo "5" > ${outdir}/ACCEPT/accept.ftable_annot + echo "S1" > ${outdir}/ACCEPT/S1.annot + echo "S2" > ${outdir}/ACCEPT/S2.annot + + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/default/annotwriter/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,37 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + + +workflow annotwriter { + take: + accept_asn_file // Channel: accept.asn file + parameters // Map : extra parameter and parameter update + main: + c = run_annotwriter(accept_asn_file) + emit: + annoted_file = c +} + + +process run_annotwriter { + input: + path accept_asn_file + output: + path ('output/accept.gff'), emit: 'annoted_file' + + script: + """ + mkdir -p output + if [ -s ${accept_asn_file} ]; then + annotwriter -i ${accept_asn_file} -nogenbank -format gff3 -o output/accept.gff + else + touch output/accept.gff + fi + """ + + stub: + """ + mkdir -p output + echo "1" > output/accept.gff + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/default/get_hmm_params/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,114 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow get_hmm_params { + take: + taxid + parameters // Map : extra parameter and parameter update + main: + def effective_taxid + if (taxid) { + effective_taxid = taxid + } else { + String params = parameters.get("gnomon_hmm_params", "") + if (params.startsWith("taxid")) { + effective_taxid = params.substring(6).toInteger() + } else { + effective_taxid = 9606 + } + } + + def hmm = run_get_hmm(effective_taxid) + emit: + outputs = hmm +} + + +process run_get_hmm { + input: + val taxid + output: + stdout + script: + """ + #!/usr/bin/env python3 + import json + from urllib.request import urlopen + def get_closest_hmm(taxid): + taxon_str = str(taxid) + if not taxon_str: + return "" + dataset_taxonomy_url = "https://api.ncbi.nlm.nih.gov/datasets/v2alpha/taxonomy/taxon/" + + taxids_file = urlopen("https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/gnomon/hmm_parameters/taxid.list") + taxids_list = [] + lineages = [] + for line in taxids_file: + parts = line.decode("utf-8").strip().split('\t') + if len(parts) > 0: + t = parts[0] + taxids_list.append(t) + if len(parts) > 1: + l = map(lambda x: int(x) if x[-1] != ';' else int(x[:-1]), parts[1].split()) + lineages.append((int(t), list(l)+[int(t)])) + + if len(lineages) < len(taxids_list): + taxonomy_json_file = urlopen(dataset_taxonomy_url+','.join(taxids_list)) + taxonomy = json.load(taxonomy_json_file)["taxonomy_nodes"] + lineages = [ (t["taxonomy"]["tax_id"], t["taxonomy"]["lineage"] + [t["taxonomy"]["tax_id"]]) for t in taxonomy ] + + taxon_json_file = urlopen(dataset_taxonomy_url+taxon_str) + taxon = json.load(taxon_json_file)["taxonomy_nodes"][0] + lineage = taxon["taxonomy"]["lineage"] + lineage.append(taxon["taxonomy"]["tax_id"]) + # print(lineage) + # print(taxon["taxonomy"]["organism_name"]) + + best_lineage = None + best_taxid = None + best_score = 0 + for (t, l) in lineages: + pos1 = 0 + last_match = 0 + for pos in range(len(lineage)): + tax_id = lineage[pos] + while tax_id != l[pos1]: + if pos1 + 1 < len(l): + pos1 += 1 + else: + break + if tax_id == l[pos1]: + last_match = pos1 + else: + break + if last_match > best_score: + best_score = last_match + best_taxid = t + best_lineage = l + + if best_score == 0: + return "" + # print(best_lineage) + # print(best_taxid, best_score) + return ( best_taxid, f'https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/gnomon/hmm_parameters/{best_taxid}.params') + + (t, url) = get_closest_hmm(${taxid}) + print(t) + print(url) + """ + stub: + """ + r=\$RANDOM + flip=\$(( r % 2 )) + if [ "\$flip" -eq "0" ] + then + r=${taxid} + fi + touch \${r}.params + echo \$r + echo "file:///\${r}.params" + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon-training-iteration/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,98 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 +//nextflow.preview.recursion=true + + +include { gnomon_training_iteration; gnomon_training_iteration as gnomon_training_iteration2; + gnomon_training_iteration as gnomon_training_iteration3; gnomon_training_iteration as gnomon_training_iteration4 } from './utilities' + + +workflow gnomon_training_iterations { + take: + models_file + genome_asn + proteins_asn + chainer_alignments + chainer_evidence_denylist + chainer_gap_fill_allowlist + chainer_trusted_genes + chainer_scaffolds + gnomon_softmask_lds2 + gnomon_softmask_lds2_source + gnomon_scaffolds + max_intron + parameters + main: + gnomon_training_iteration(models_file, genome_asn, proteins_asn ,chainer_alignments,chainer_evidence_denylist,chainer_gap_fill_allowlist, + chainer_trusted_genes, chainer_scaffolds, gnomon_softmask_lds2, + gnomon_softmask_lds2_source, gnomon_scaffolds, max_intron, parameters) + gnomon_training_iteration2(gnomon_training_iteration.out.hmm_params_file, genome_asn, proteins_asn ,chainer_alignments, + chainer_evidence_denylist,chainer_gap_fill_allowlist, chainer_trusted_genes, chainer_scaffolds, gnomon_softmask_lds2, + gnomon_softmask_lds2_source, gnomon_scaffolds, max_intron, parameters) + gnomon_training_iteration3(gnomon_training_iteration2.out.hmm_params_file, genome_asn, proteins_asn ,chainer_alignments, + chainer_evidence_denylist,chainer_gap_fill_allowlist, chainer_trusted_genes, chainer_scaffolds, gnomon_softmask_lds2, + gnomon_softmask_lds2_source, gnomon_scaffolds, max_intron, parameters) + gnomon_training_iteration4(gnomon_training_iteration3.out.hmm_params_file, genome_asn, proteins_asn ,chainer_alignments, + chainer_evidence_denylist,chainer_gap_fill_allowlist, chainer_trusted_genes, chainer_scaffolds, gnomon_softmask_lds2, + gnomon_softmask_lds2_source, gnomon_scaffolds, max_intron, parameters) + + emit: + hmm_params_file = gnomon_training_iteration4.out.hmm_params_file +} + +workflow gnomon_no_training { + take: + hmm + main: + process_no_training(hmm) + emit: + hmm_params_file = process_no_training.out.file +} + +process process_no_training +{ + input: + val hmm + output: + path "*.params" , emit: 'file' + script: + """ + curl -O ${hmm} + """ + stub: + """ + touch hmm.params + """ +} + + +/* + +//experimental (preview.recursion) +// to be used in the future +workflow gnomon_training_iterations { + take: + models_file + genome_asn + proteins_asn + chainer_alignments + chainer_evidence_denylist + chainer_gap_fill_allowlist + chainer_trusted_genes + chainer_scaffolds + gnomon_softmask_lds2 + gnomon_softmask_lds2_source + gnomon_scaffolds + max_intron + parameters + main: + gnomon_training_iteration + .recurse(models_file, genome_asn, proteins_asn ,chainer_alignments,chainer_evidence_denylist,chainer_gap_fill_allowlist, + chainer_trusted_genes, chainer_scaffolds, gnomon_softmask_lds2, + gnomon_softmask_lds2_source, gnomon_scaffolds, max_intron, parameters) + .times(4) + emit: + hmm_params_file = gnomon_training_iteration.out.hmm_params_file +} + +*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon-training-iteration/utilities.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,45 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 +// nextflow.preview.recursion=true + +include { chainer_wnode as chainer } from '../gnomon/chainer_wnode/main' +include { gnomon_wnode } from '../gnomon/gnomon_wnode/main' +include { gnomon_training } from '../gnomon/gnomon_training/main' + + +workflow gnomon_training_iteration { + take: + models_file + genome_asn + proteins_asn + chainer_alignments + chainer_evidence_denylist + chainer_gap_fill_allowlist + chainer_trusted_genes + chainer_scaffolds + gnomon_softmask_lds2 + gnomon_softmask_lds2_source + gnomon_scaffolds + max_intron + parameters + main: + + chainer(chainer_alignments, models_file, chainer_evidence_denylist, chainer_gap_fill_allowlist, chainer_scaffolds, chainer_trusted_genes, genome_asn, proteins_asn, parameters.get('chainer', [:])) + gnomon_wnode(gnomon_scaffolds, chainer.out.chains, chainer.out.chains_slices, models_file, gnomon_softmask_lds2, gnomon_softmask_lds2_source, genome_asn, proteins_asn, parameters.get('gnomon', [:])) + gnomon_training(genome_asn, gnomon_wnode.out.outputs, max_intron, parameters.get('gnomon_training', [:])) + + emit: + hmm_params_file = gnomon_training.out.hmm_params_file + genome_asn = genome_asn + proteins_asn = proteins_asn + chainer_alignments = chainer_alignments + chainer_evidence_denylist = chainer_evidence_denylist + chainer_gap_fill_allowlist = chainer_gap_fill_allowlist + chainer_trusted_genes = chainer_trusted_genes + chainer_scaffolds = chainer_scaffolds + gnomon_softmask_lds2 = gnomon_softmask_lds2 + gnomon_softmask_lds2_source = gnomon_softmask_lds2_source + gnomon_scaffolds = gnomon_scaffolds + max_intron = max_intron + parameters = parameters +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/chainer_wnode/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,167 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + + +include { merge_params } from '../../utilities' +include { run_align_sort } from '../../default/align_sort_sa/main.nf' + +split_count=16 + + +workflow chainer_wnode { + take: + alignments + hmm_params + evidence_denylist + gap_fill_allowlist + scaffolds + trusted_genes + genome + proteins + parameters // Map : extra parameter and parameter update + main: + String input_sorting = parameters.get('input_aligns_sort', '') + def sort_aligns = alignments + if (!input_sorting.contains("presorted")) { + String align_sort_params = "" + if (input_sorting.contains("merge_only")) { + align_sort_params = "-merge" + } + align_sort_params += " -ifmt seq-align -compression none -k subject,subject_start,-subject_end " + // print(align_sort_params) + sort_aligns = run_align_sort([], [], alignments, align_sort_params).collect() + //sort_aligns = align_sort(alignments, align_sort_params) + } + String submit_chainer_params = merge_params("-minimum-abut-margin 20 -separate-within-introns", parameters, 'submit_chainer') + String chainer_wnode_params = merge_params("", parameters, 'chainer_wnode') + String gpx_make_outputs_params = merge_params("-default-output-name chains -slices-for affinity -sort-by affinity", parameters, 'gpx_make_outputs') + + def (jobs, lines_per_file) = generate_jobs(sort_aligns, submit_chainer_params) + def collected = run_chainer(jobs.flatten(), sort_aligns, hmm_params, evidence_denylist, gap_fill_allowlist, scaffolds, trusted_genes, genome, proteins, lines_per_file, chainer_wnode_params) | collect + + run_gpx_make_outputs(collected, gpx_make_outputs_params) + emit: + chains = run_gpx_make_outputs.out.chains + chains_slices = run_gpx_make_outputs.out.chains_slices + evidence = run_gpx_make_outputs.out.evidence + evidence_slices = run_gpx_make_outputs.out.evidence_slices +} + + +process generate_jobs { + input: + path sort_aligns + val params + output: + path "job.*" + env lines_per_file + script: + njobs=split_count + """ + #!/usr/bin/env bash + # generate_jobs $sort_aligns $params -output chains -output-slices chains_slices -output-evidence evidence -output-evidence-slices evidence_slices + submit_chainer $params -asn $sort_aligns -o jobs + total_lines=\$(wc -l <jobs) + (( lines_per_file = (total_lines + ${njobs} - 1) / ${njobs} )) + echo total_lines=\$total_lines, lines_per_file=\$lines_per_file + ####split -l\$lines_per_file jobs job. -da 3 + # Use round robin to distribute jobs across nodes more evenly + if [ \$total_lines -lt $njobs ]; then + effective_njobs=\$total_lines + else + effective_njobs=$njobs + fi + split -nr/\$effective_njobs jobs job. -da 3 + """ + stub: + """ + for i in {1..$split_count}; do + echo "<job query =\\\"lcl|${sort_aligns}:\${i}-\${i}\\\"></job>" >> jobs + done + split -nr/$split_count jobs job. -da 3 + lines_per_file=10 + """ +} + + +process run_chainer { + input: + path job + path alignments + path hmm_params + path evidence_denylist + path gap_fill_allowlist + path scaffolds + path trusted_genes + path genome, stageAs: 'indexed/*' + path proteins_asn, stageAs: 'indexed/*' + val lines_per_file + val params + output: + path "output/*" + script: + job_num = job.toString().tokenize('.').last().toInteger() + """ + echo "${evidence_denylist.join('\n')}" > evidence_denylist.mft + echo "${gap_fill_allowlist.join('\n')}" > gap_fill_allowlist.mft + echo "${scaffolds.join('\n')}" > scaffolds.mft + echo "${trusted_genes.join('\n')}" > trusted_genes.mft + # HACK: derive start_job_id from job file extension + filename=\$(basename -- "$job") + extension="\${filename##*.}" + (( start_job_id = ((10#\$extension) * $lines_per_file) + 1 )) + + # make the local LDS of the genomic and protein (if present) sequences + lds2_indexer -source indexed -db LDS2 + + # When running multiple jobs on the cluster there is a chance that + # several jobs will run on the same node and thus generate files + # with the same filename. We need to avoid that to be able to stage + # the output files for gpx_make_outputs. We add the job file numeric + # extension as a prefix to the filename. + mkdir interim + chainer_wnode $params -start-job-id \$start_job_id -workers 32 -input-jobs ${job} -O interim -nogenbank -lds2 LDS2 -evidence-denylist-manifest evidence_denylist.mft -gap-fill-allowlist-manifest gap_fill_allowlist.mft -param ${hmm_params} -scaffolds-manifest scaffolds.mft -trusted-genes-manifest trusted_genes.mft + mkdir output + for f in interim/*; do + if [ -f \$f ]; then + mv \$f output/\${extension}_\$(basename \$f) + fi + done + """ + + stub: + job_num = job.toString().tokenize('.').last().toInteger() + """ + mkdir -p output + touch output/sample_chainer_wnode.${job_num}.out + """ +} + + +process run_gpx_make_outputs { + input: + path files, stageAs: "gpx_inputs/*" + val params + output: + path "output/chains.*.out.gz", emit: 'chains' + path "output/chains.*.out.gz.slices", emit: 'chains_slices' + path "output/evidence.*.out.gz", emit: 'evidence', optional: true + path "output/evidence.*.out.gz.slices", emit: 'evidence_slices', optional: true + script: + """ + ls -1 gpx_inputs/* > gpx_inputs.mft + mkdir -p output + gpx_make_outputs $params -input-manifest gpx_inputs.mft -output output/@.#.out.gz -output-manifest output/@.mft -slices-manifest output/@_slices.mft -num-partitions $split_count + """ + stub: + """ + mkdir -p output + echo ${files} + for i in {1..$split_count}; do + touch output/chains.\$i.out.gz + touch output/chains.\$i.out.gz.slices + touch output/evidence.\$i.out.gz + touch output/evidence.\$i.out.gz.slices + done + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/diamond/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,24 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params; to_map; shellSplit } from '../../utilities' +include { run_diamond_egap;} from '../../shared/diamond/main' + + +workflow diamond_worker { + take: + gnomon_prot_ids + swiss_prot_ids + gnomon_prot_asn + swiss_prot_asn + parameters // Map : extra parameter and parameter update + main: + String diamond_blastp_params = merge_params('--sam-query-len --very-sensitive --unal 0 --comp-based-stats 0 --masking 0', parameters, 'diamond_blastp') + String diamond_regular_params = merge_params('-ofmt seq-align-set -query-fmt seq-ids -subject-fmt seq-ids -output-prefix hits', parameters, 'diamond') + String diamond_egap_params = '-blastp-args \'' + diamond_blastp_params + '\' ' + diamond_regular_params + + run_diamond_egap(gnomon_prot_ids, swiss_prot_ids, gnomon_prot_asn, swiss_prot_asn, diamond_egap_params) + + emit: + alignments = run_diamond_egap.out +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/gnomon_biotype/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,67 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + +workflow gnomon_biotype { + take: + models_files + splices_files + denylist + gencoll_asn + swiss_prot_asn + lds2_source + raw_blastp_hits + parameters // Map : extra parameter and parameter update + main: + default_params = "" + effective_params = merge_params(default_params, parameters, 'gnomon_biotype') + run_gnomon_biotype(models_files, splices_files, denylist, gencoll_asn, swiss_prot_asn, lds2_source, raw_blastp_hits, default_params) + emit: + biotypes = run_gnomon_biotype.out.biotypes + prots_rpt = run_gnomon_biotype.out.prots_rpt + all = run_gnomon_biotype.out.all +} + + + +process run_gnomon_biotype { + input: + path models_files + path splices_files + path denylist + path gencoll_asn + path swiss_prot_asn + path lds2_source, stageAs: 'genome/*' + path raw_blastp_hits + val parameters + output: + path ('output/biotypes.tsv'), emit: 'biotypes' + path ('output/prots_rpt.tsv'), emit: 'prots_rpt' + path ('output/*'), emit: 'all' + script: + """ + mkdir -p output + mkdir -p ./asncache/ + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i ${swiss_prot_asn} -oseq-ids /dev/null -split-sequences + echo "${raw_blastp_hits.join('\n')}" > raw_blastp_hits.mft + lds2_indexer -source genome/ -db LDS2 + merge_blastp_hits -asn-cache ./asncache/ -nogenbank -lds2 LDS2 -input-manifest raw_blastp_hits.mft -o prot_hits.asn + echo "${models_files.join('\n')}" > models.mft + echo "prot_hits.asn" > prot_hits.mft + echo "${splices_files.join('\n')}" > splices.mft + if [ -z "$denylist" ] + then + gnomon_biotype -gc $gencoll_asn -asn-cache ./asncache/ -nogenbank -gnomon_models models.mft -o output/biotypes.tsv -o_prots_rpt output/prots_rpt.tsv -prot_hits prot_hits.mft -prot_splices splices.mft -reftrack-server 'NONE' -allow_lt631 true + else + gnomon_biotype -gc $gencoll_asn -asn-cache ./asncache/ -nogenbank -gnomon_models models.mft -o output/biotypes.tsv -o_prots_rpt output/prots_rpt.tsv -prot_denylist $denylist -prot_hits prot_hits.mft -prot_splices splices.mft -reftrack-server 'NONE' -allow_lt631 true + fi + """ + stub: + """ + mkdir -p output + touch output/prots_rpt.tsv + touch output/biotypes.tsv + """ +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/gnomon_training/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,47 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + +workflow gnomon_training { + take: + genome_asn + models_file + max_intron1 // max intron length, name modified from max_intron to pacify stupid Nextflow compiler + parameters // Map : extra parameter and parameter update + main: + default_params = "-b -asn -maxintron 1200000" + effective_params = merge_params(default_params, parameters, 'gnomon_training') + run_gnomon_training(genome_asn, models_file, max_intron1, effective_params) + emit: + hmm_params_file = run_gnomon_training.out.hmm_params_file +} + + +process run_gnomon_training { + input: + path genome_asn, stageAs: 'indexed/*' + path models_file + val max_intron1 + val parameters + output: + path ('output/hmm_params.asn'), emit: 'hmm_params_file' + + script: + // Substitute -maxintron with correct value coming from max_intron + def dummy = ["dummy" : "-maxintron ${max_intron1}"] + parameters = merge_params(parameters, dummy, "dummy") + """ + mkdir -p output + lds2_indexer -source indexed -db ./indexed_lds + gnomon_training ${parameters} -nogenbank -lds2 ./indexed_lds -input ${models_file} -out output/hmm_params.asn + """ + stub: + def dummy = ["dummy" : "-maxintron ${max_intron1}"] + parameters = merge_params(parameters, dummy, "dummy") + println("Gnomon training parameters: ${parameters}") + """ + mkdir -p output + touch output/hmm_params.asn + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/gnomon_wnode/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,157 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow gnomon_wnode { + take: + scaffolds + chains + chains_slices + hmm_params + softmask_lds2 + softmask_lds2_source + genome + proteins + parameters // Map : extra parameter and parameter update + main: + String gpx_qsubmit_params = merge_params("", parameters, 'gpx_qsubmit') + String annot_params = merge_params("-margin 1000 -mincont 1000 -minlen 225 -mpp 10.0 -ncsp 25 -window 200000 -nonconsens -open", parameters, 'annot_wnode') + String gpx_qdump_params = merge_params("-slices-for affinity -sort-by affinity", parameters, 'gpx_qdump') + + def (jobs, lines_per_file) = gpx_qsubmit(scaffolds, chains, chains_slices, gpx_qsubmit_params) + def annot_files = annot(jobs.flatten(), chains, hmm_params, softmask_lds2, softmask_lds2_source, genome, proteins, lines_per_file, annot_params) + gpx_qdump(annot_files.collect(), gpx_qdump_params) + emit: + outputs = gpx_qdump.out.outputs +} + + +process gpx_qsubmit { + input: + path scaffolds + path chains + path chains_slices + val params + output: + path "job.*" + env lines_per_file + script: + njobs=16 + """ + echo $scaffolds | tr ' ' '\\n' > scaffolds.mft + for file in $chains_slices; do + echo \$file >> chains_slices.mft + # remove path from the first line of this file + sed -i -e '1s/\\(.*\\)\\/\\(.*\\)\$/\\2/' \$file + done + gpx_qsubmit $params -ids-manifest scaffolds.mft -slices-manifest chains_slices.mft -o jobs + total_lines=\$(wc -l <jobs) + (( lines_per_file = (total_lines + ${njobs} - 1) / ${njobs} )) + echo total_lines=\$total_lines, lines_per_file=\$lines_per_file + # split -l\$lines_per_file jobs job. -da 3 + # Use round robin to distribute jobs across nodes more evenly + if [ \$total_lines -lt $njobs ]; then + effective_njobs=\$total_lines + else + effective_njobs=$njobs + fi + split -nr/\$effective_njobs jobs job. -da 3 + """ + stub: + njobs=16 + """ + for i in {1..$njobs}; do + echo j.\${i} >> jobs + done + split -nr/$njobs jobs job. -da 3 + lines_per_file=10 + """ +} + + +process annot { + input: + path jobs + path chains // used for staging chain files, referred from jobs + path hmm_params + path softmask_lds2 + path softmask + path genome, stageAs: 'indexed/*' + path proteins_asn, stageAs: 'indexed/*' + val lines_per_file + val params + output: + path "output/*" + script: + job_num = jobs.toString().tokenize('.').last().toInteger() + """ + njobs=`wc -l <$jobs` + if [ \$njobs -lt 16 ]; then + threads=\$njobs + else + threads=16 + fi + + lds2=indexed_lds + if [ -n "$softmask_lds2" ]; then + # patch LDS2 to point to the source + files=\$(sqlite3 $softmask_lds2 -cmd "SELECT file_name FROM file" ".exit") + for f in \$files; do + base=\$(basename \$f) + sqlite3 $softmask_lds2 -cmd "UPDATE file SET file_name = '\$base' WHERE file_name = '\$f'" ".exit" + done + lds2+=",$softmask_lds2" + elif [ -n "$softmask" ]; then + mkdir sm_src + mv $softmask ./sm_src/ + lds2_indexer -source ./sm_src/ -db softmask_lds2 + lds2+=",softmask_lds2" + fi + + filename=\$(basename -- "$jobs") + extension="\${filename##*.}" + (( start_job_id = ((10#\$extension) * $lines_per_file) + 1 )) + + # make the local LDS of the genomic fasta + lds2_indexer -source indexed -db indexed_lds + + # When running multiple jobs on the cluster there is a chance that + # several jobs will run on the same node and thus generate files + # with the same filename. We need to avoid that to be able to stage + # the output files for gpx_make_outputs. We add the job file numeric + # extension as a prefix to the filename. + mkdir interim + annot_wnode $params -nogenbank -lds2 \$lds2 -start-job-id \$start_job_id -workers \$threads -input-jobs $jobs -param $hmm_params -O interim || true + mkdir output + for f in interim/*; do + if [ -f \$f ]; then + mv \$f output/\${extension}_\$(basename \$f) + fi + done + """ + stub: + job_num = jobs.toString().tokenize('.').last().toInteger() + """ + mkdir -p output + touch output/sample_gnomon_wnode.${job_num}.out + """ +} + + +process gpx_qdump { + input: + path files, stageAs: "inputs/*" + val params + output: + path "*.out", emit: "outputs" + script: + """ + gpx_qdump $params -input-path inputs -output gnomon_wnode.out + """ + stub: + """ + touch gnomon_wnode.out + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/locus_link/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,116 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + +workflow locus_link { + take: + best_refseq_prot_hit + orthologs + annotation + gencoll_asn + gnomon_lds2_source + best_prot_hit + track_loci + comparisons + curr_prev_compare + gnomon_biotypes + lxr_data + proteins_asn + name_from_ortholog + parameters // Map : extra parameter and parameter update + main: + default_params = "" + effective_params = merge_params(default_params, parameters, 'locus_link') + run_locus_link(best_refseq_prot_hit, orthologs, annotation, + gencoll_asn, gnomon_lds2_source, best_prot_hit, track_loci, comparisons, curr_prev_compare, + gnomon_biotypes, lxr_data, proteins_asn, name_from_ortholog, default_params) + emit: + best_gnomon_prot_hit = run_locus_link.out.best_gnomon_prot_hit + best_refseq_prot_hit = run_locus_link.out.best_refseq_prot_hit + locustypes = run_locus_link.out.locustypes + locus = run_locus_link.out.locus + stats = run_locus_link.out.stats + all = run_locus_link.out.all +} + + + +process run_locus_link { + input: + path best_refseq_prot_hit + path orthologs + path annotation + path gencoll_asn + path gnomon_lds2_source, stageAs: 'genome/*' + path best_prot_hit + path track_loci + path comparisons + path curr_prev_compare + path gnomon_biotypes + path lxr_data + path proteins_asn + path name_from_ortholog + val parameters + output: + path ('output/best_gnomon_prot_hit.tsv'), emit: 'best_gnomon_prot_hit' + path ('output/best_refseq_prot_hit.tsv'), emit: 'best_refseq_prot_hit' + path ('output/locustypes.tsv'), emit: 'locustypes' + path ('output/locus.lnk'), emit: 'locus' + path ('output/stats.xml'), emit: 'stats' + path ('output/*'), emit: 'all' + script: + """ + mkdir -p output + mkdir -p ./asncache/ + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i $proteins_asn -oseq-ids /dev/null -split-sequences + + lds2_indexer -source genome/ -db LDS2 + echo "${best_prot_hit.join('\n')}" > best_prot_hit.mft + extract_prot_names -alns best_prot_hit.mft -nogenbank -o output/best_gnomon_prot_hit.tsv -asn-cache ./asncache/ -lds2 LDS2 + echo "${best_refseq_prot_hit.join('\n')}" > best_refseq_prot_hit.mft + extract_prot_names -alns best_refseq_prot_hit.mft -nogenbank -o output/best_refseq_prot_hit.tsv -asn-cache ./asncache/ -lds2 LDS2 + echo "${annotation.join('\n')}" > annotation.mft + echo "${curr_prev_compare.join('\n')}" > curr_prev_compare.mft + echo "${comparisons.join('\n')}" > comparisons.mft + str="" + if [ ! -z "$orthologs" ] + then + str="\$str -orthologs $orthologs" + fi + if [ ! -z "$lxr_data" ] + then + str="\$str -lxr $lxr_data" + else + touch lxr_data + str="\$str -lxr lxr_data" + fi + + if [ ! -z "$track_loci" ] + then + str="\$str -locus_track $track_loci" + else + touch track_loci + str="\$str -locus_track track_loci" + fi + if [ ! -z "$name_from_ortholog" ] + then + str="\$str -name_from_ortholog_rpt $name_from_ortholog" + else + touch name_from_ortholog + str="\$str -name_from_ortholog_rpt name_from_ortholog" + fi + + locus_type -no_acc_reserve -annots annotation.mft -gc $gencoll_asn -gnomon_biotype $gnomon_biotypes -o_stats output/stats.xml -o_locustypes output/locustypes.tsv -o_locus_lnk output/locus.lnk -annotcmp comparisons.mft -annotcmp_pb curr_prev_compare.mft \$str + """ + stub: + """ + mkdir -p output + touch output/best_gnomon_prot_hit.tsv + touch output/best_refseq_prot_hit.tsv + touch output/locustypes.tsv + touch output/locus.lnk + touch output/stats.xml + """ +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,96 @@ +#!/usr/bin/env nextflow +// gnomon plane workflow +// route data to tasks + +nextflow.enable.dsl=2 + +include { chainer_wnode as chainer } from './chainer_wnode/main' +include { gnomon_wnode } from './gnomon_wnode/main' +include { prot_gnomon_prepare } from './prot_gnomon_prepare/main' +include { gnomon_training_iterations } from '../gnomon-training-iteration/main' + +include { diamond_worker} from './diamond/main' +include { best_protein_hits } from './protein_filter/main' +include { gnomon_biotype} from './gnomon_biotype/main' +include { fetch_swiss_prot_asn; get_swiss_prot_ids } from '../shared/diamond/main' +include { diamond_orthology } from '../orthology/diamond_orthology/main' +include { locus_link } from './locus_link/main' + + +params.intermediate = false + +workflow gnomon_plane { + take: + genome_asn + scaffolds + gencoll_asn + proteins_asn + alignments // list of all relevent input alignments + + // Alternative parameters, one of them should be set + // tax_id - NCBI tax id of the closest taxon to the genome + // hmm_params - HMM parameters + tax_id // NCBI tax id of the closest taxon to the genome + hmm_params // HMM parameters + hmm_taxid // NCBI tax id of the taxon of the HMM + // + softmask // softmask for GNOMON, optional + max_intron // max intron length + task_params // task parameters for every task + main: + // GNOMON + def effective_hmm + if (tax_id == hmm_taxid) { + effective_hmm = hmm_params + } else { + effective_hmm = gnomon_training_iterations(hmm_params, genome_asn, proteins_asn, alignments, /* evidence_denylist */ [], /* gap_fill_allowlist */ [], + /* trusted_genes */ [], scaffolds, softmask, + softmask, scaffolds, + max_intron, + task_params) + } + + chainer(alignments, effective_hmm, /* evidence_denylist */ [], /* gap_fill_allowlist */ [], scaffolds, /* trusted_genes */ [], genome_asn, proteins_asn, task_params.get('chainer', [:])) + + def gn_models = [] + gnomon_wnode(scaffolds, chainer.out.chains, chainer.out.chains_slices, effective_hmm, [], softmask, genome_asn, proteins_asn, task_params.get('gnomon', [:])) + + emit: + gnomon_models = gnomon_wnode.out.outputs + // trained_hmm = effective_hmm +} + + + +workflow post_gnomon_plane { + take: + gnomon_models + gencoll_asn + orthologs + + + // Alternative parameters, one of them should be set + // tax_id - NCBI tax id of the closest taxon to the genome + // hmm_params - HMM parameters + tax_id // NCBI tax id of the closest taxon to the genome + task_params // task parameters for every task + main: + // Post GNOMON + // might come its own plane + def swiss_prot_asn = fetch_swiss_prot_asn() + def swiss_prot_ids = get_swiss_prot_ids(swiss_prot_asn) + + prot_gnomon_prepare(gnomon_models, task_params.get('prot_gnomon_prepare', [:])) + // Seed Protein-Model Hits + diamond_worker(prot_gnomon_prepare.out.prot_ids, swiss_prot_ids, gnomon_models, swiss_prot_asn, task_params.get('diamond', [:])) + best_protein_hits(gnomon_models, swiss_prot_asn, diamond_worker.out.alignments , task_params.get('protein_filter', [:])) + + gnomon_biotype([] /*models*/,/*splices_file -- constant*/ [], /*denylist -- constant*/ [], gencoll_asn, swiss_prot_asn, gnomon_models, diamond_worker.out.alignments,task_params.get('gnomon_biotype', [:])) + locus_link(/*best_refseq_prot_hit -- best protein hits from refseq plane*/ [], orthologs, [] /*annot_builder.out.annot_files*/, + gencoll_asn, gnomon_models, best_protein_hits.out.alignments , /*track_loci*/ [], /*comparisons*/ [], /*curr_prev_compare*/ [], + gnomon_biotype.out.biotypes, /*lxr_data*/ [], swiss_prot_asn, /*name_from_ortholog */ [], task_params.get('locus_link', [:])) + + + emit: + locus = locus_link.out.locus +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/prot_gnomon_prepare/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,44 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow prot_gnomon_prepare { + take: + models + parameters // Map : extra parameter and parameter update + main: + String prot_gnomon_prepare_params = merge_params('', parameters, 'prot_gnomon_prepare') + + prot_gnomon_prepare_p(models, prot_gnomon_prepare_params) + emit: + outputs = prot_gnomon_prepare_p.out.outputs + LDS2 = prot_gnomon_prepare_p.out.LDS2 + prot_ids = prot_gnomon_prepare_p.out.prot_ids + nuc_ids = prot_gnomon_prepare_p.out.nuc_ids +} + + +process prot_gnomon_prepare_p { + input: + path models + val params + output: + path "*", emit: 'outputs' + path "LDS2", emit: 'LDS2' + path "prot_ids.seq_id", emit: 'prot_ids' + path "nuc_ids.seq_id", emit: 'nuc_ids' + script: + """ + echo ${models} |tr ' ' '\\n' > models.mft + prot_gnomon_prepare ${params} -input-manifest models.mft -olds2 LDS2 -oprot-ids prot_ids.seq_id -onuc-ids nuc_ids.seq_id + """ + stub: + """ + touch LDS2 + touch prot_ids.seq_id + touch nuc_ids.seq_id + """ +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/gnomon/protein_filter/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,64 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + + + +/* + * align_filter -filter 'pct_coverage >= 50' -nogenbank + * | align_sort -ifmt seq-align-set -k query,-bit_score,slen,-align_length -group 1 -top 1 -nogenbank + */ + + +include { merge_params; to_map; shellSplit } from '../../utilities' + + +workflow best_protein_hits { + take: + gnomon_prot_asn + swiss_prot_asn + prot_alignments + parameters // Map : extra parameter and parameter update + main: + String align_filter_params = merge_params(' -ifmt seq-align-set -filter \'pct_coverage >= 50\' -nogenbank', parameters, 'align_filter') + String align_sort_params = merge_params(' -ifmt seq-align-set -k query,-bit_score,slen,-align_length -group 1 -top 1 -nogenbank', parameters, 'align_sort') + + run_protein_filter_replacement(gnomon_prot_asn, swiss_prot_asn, prot_alignments, align_filter_params, align_sort_params) + + emit: + alignments = run_protein_filter_replacement.out +} + + +process run_protein_filter_replacement { + input: + path gnomon_prot_asn, stageAs: 'indexed/*' + path swiss_prot_asn, stageAs: 'indexed/*' + path input_prot_alignments, stageAs: "input_alignments.asnb" + val align_filter_params + val align_sort_params + output: + path "output/*" + script: + """ + mkdir -p ./asncache/ + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i ${gnomon_prot_asn} -oseq-ids /dev/null -split-sequences + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i ${swiss_prot_asn} -oseq-ids /dev/null -split-sequences + + mkdir -p ./output + + align_filter $align_filter_params -asn-cache ./asncache -i ./input_alignments.asnb -o - | align_sort -i - $align_sort_params -asn-cache ./asncache -o - | align_pack -ifmt seq-align -i - -ofmt seq-align-set -o ./output/best_protein_hits.asnb + ##align_filter $align_filter_params -asn-cache ./asncache -i ./input_alignments.asnb -o ./t1.asnb + ##align_sort -i ./t1.asnb $align_sort_params -asn-cache ./asncache -o ./t2.asnb + ##align_pack -ifmt seq-align -i ./t2.asnb -ofmt seq-align-set -o ./t3.asnb + ##cp ./t3.asnb ./output/best_protein_hits.asnb + + """ + + stub: + """ + mkdir -p output + touch ./output/best_protein_hits.asnb + """ +} + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,116 @@ +#!/usr/bin/env nextflow +// main nextflow script for EGAPx execution +// route data to subworkflows + +nextflow.enable.dsl=2 + +include { rnaseq_short_plane } from './rnaseq_short/main' +include { target_proteins_plane } from './target_proteins/main' +include { gnomon_plane; post_gnomon_plane } from './gnomon/main' +include { orthology_plane } from './orthology/main' +include { setup_genome; setup_proteins } from './setup/main' +include { annot_builder } from './default/annot_builder/main' +include { annotwriter } from './default/annotwriter/main' + + +params.intermediate = false +params.use_orthology = false +params.use_post_gnomon = false + + +workflow egapx { + take: + genome // path to genome + proteins // path to proteins, optional + + // Alternative groups of parameters, one of them should be set + // reads_query - SRA query in the form accepted by NCBI + // reads_ids - list of SRA IDs + // reads, reads_metadata - path to reads accompanied by metadata + reads_query // SRA query + reads_ids // list of SRA IDs + reads // path to reads + reads_metadata // path to reads metadata 13 tab-delimited fields, 1-st - SRA ID, 3-rd paired or unpaired, everything else - not used, but must be present + // 4, 5, 13 - numbers, 5 - non zero number + + organelles // path to organelle list + // Alternative parameters, one of them should be set + // tax_id - NCBI tax id of the closest taxon to the genome + // hmm_params - HMM parameters + tax_id // NCBI tax id of the closest taxon to the genome + hmm_params // HMM parameters + hmm_taxid // NCBI tax id of the HMM + // + softmask // softmask for GNOMON, optional + // + max_intron // max intron length + genome_size_threshold // the threshold for calculating actual max intron length + task_params // task parameters for every task + main: + print "workflow.container: ${workflow.container}" + + def setup_genome_params = task_params.get('setup', [:]) + setup_genome_params['max_intron'] = max_intron + setup_genome_params['genome_size_threshold'] = genome_size_threshold + def (scaffolds, gencoll_asn, unpacked_genome, genome_asn, genome_asnb, eff_max_intron) = setup_genome(genome, organelles, setup_genome_params) + + // Protein alignments + def protein_alignments = [] + def unpacked_proteins + def proteins_asn = [] + def proteins_asnb = [] + if (proteins) { + // miniprot plane + (unpacked_proteins, proteins_asn) = setup_proteins(proteins, task_params.get('setup', [:])) + target_proteins_plane(unpacked_genome, genome_asn, gencoll_asn, unpacked_proteins, proteins_asn, eff_max_intron, task_params) + protein_alignments = target_proteins_plane.out.protein_alignments + } + + // RNASeq short alignments + def rnaseq_alignments = [] + if (reads_query || reads_ids || reads) { + rnaseq_short_plane(genome_asn, scaffolds, unpacked_genome, reads_query, reads_ids, reads, reads_metadata, organelles, tax_id, eff_max_intron, task_params) + rnaseq_alignments = rnaseq_short_plane.out.rnaseq_alignments + } + + // Combine RNASeq and protein alignments + def alignments + if (proteins && (reads_query || reads_ids || reads)) [ + alignments = rnaseq_alignments.combine(protein_alignments) + ] else if (proteins) { + alignments = protein_alignments + } else { + alignments = rnaseq_alignments + } + + // GNOMON + + def gnomon_models = [] + def effective_hmm + gnomon_plane(genome_asn, scaffolds, gencoll_asn, proteins_asn, alignments, tax_id, hmm_params, hmm_taxid, softmask, eff_max_intron, task_params) + gnomon_models = gnomon_plane.out.gnomon_models + + + // outputs + annot_builder(gencoll_asn, gnomon_models, genome_asn, task_params.get('annot_builder', [:])) + def accept_annot_file = annot_builder.out.accept_ftable_annot + def annot_files = annot_builder.out.annot_files + + if (params.use_orthology) { + // ORTHOLOGY + orthology_plane(genome_asnb, gencoll_asn, gnomon_models, annot_files, task_params) + def orthologs = orthology_plane.out.orthologs + if (params.use_post_gnomon) { + //POST GNOMON + post_gnomon_plane(gnomon_models, gencoll_asn, orthologs, tax_id, task_params) + } + } + + annotwriter(accept_annot_file, [:]) + annotwriter.out.annoted_file + + emit: + out_files = annotwriter.out.annoted_file + annot_builder_output = annot_builder.out.outputs + // locus = post_gnomon_plane.out.locus +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/only_gnomon.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,95 @@ +#!/usr/bin/env nextflow +// gnomon-only nextflow script for EGAPx execution +// route data to subworkflows + +nextflow.enable.dsl=2 + +include { setup_genome; setup_proteins } from './setup/main' +include { get_hmm_params; run_get_hmm } from './default/get_hmm_params/main' +include { chainer_wnode as chainer } from './gnomon/chainer_wnode/main' +include { gnomon_wnode } from './gnomon/gnomon_wnode/main' +include { prot_gnomon_prepare } from './gnomon/prot_gnomon_prepare/main' +include { annot_builder } from './default/annot_builder/main' +include { annotwriter } from './default/annotwriter/main' +include { run_align_sort} from './default/align_sort_sa/main' + +params.intermediate = false + +workflow only_gnomon { + take: + genome // path to genome + proteins // path to proteins, optional + // Alternative groups of parameters, one of them should be set + rnaseq_alignments // path to rnaseq_collapse'ed alignments + protein_alignments // path to miniprot, filtered, sorted, alignments + + organelles // path to organelle list + // Alternative parameters, one of them should be set + // tax_id - NCBI tax id of the closest taxon to the genome + // hmm_params - HMM parameters + tax_id // NCBI tax id of the closest taxon to the genome + hmm_params // HMM parameters + hmm_taxid // NCBI tax id of the taxon of the HMM + // + softmask // softmask for GNOMON, optional + task_params // task parameters for every task + main: + + def (scaffolds, gencoll_asn, unpacked_genome, genome_asn) = setup_genome(genome, organelles, task_params.get('setup', [:])) + + // Protein alignments + def unpacked_proteins + def proteins_asn = [] + if (proteins) { + // miniprot plane + (unpacked_proteins, proteins_asn) = setup_proteins(proteins, task_params.get('setup', [:])) + } + + // Combine RNASeq and protein alignments + + def alignments + if (protein_alignments && rnaseq_alignments) { + print(rnaseq_alignments.getClass()) + print(rnaseq_alignments) + print(protein_alignments.getClass()) + print(protein_alignments) + alignments = Channel.of(rnaseq_alignments).combine(Channel.of(protein_alignments)) + } else if (protein_alignments) { + alignments = protein_alignments + } else if (rnaseq_alignments) { + alignments = rnaseq_alignments + } else { + print("error") + } + + // GNOMON + + def effective_hmm + if (hmm_params) { + effective_hmm = hmm_params + } else { + tmp_hmm = run_get_hmm(tax_id) + b = tmp_hmm | splitText( { it.split('\n') } ) | flatten + c = b | last + effective_hmm = c + } + + chainer(alignments, effective_hmm, /* evidence_denylist */ [], /* gap_fill_allowlist */ [], scaffolds, /* trusted_genes */ [], genome_asn, proteins_asn, task_params.get('chainer', [:])) + + gnomon_wnode(scaffolds, chainer.out.chains, chainer.out.chains_slices, effective_hmm, [], softmask, genome_asn, proteins_asn, task_params.get('gnomon', [:])) + def models = gnomon_wnode.out.outputs + + // prot_gnomon_prepare(models, task_params.get('prot_gnomon_prepare', [:])) + + // actual gnomon end but whatever + + + annot_builder(gencoll_asn, models, genome_asn, task_params.get('annot_builder', [:])) + def accept_asn = annot_builder.out.accept_asn + + annotwriter(accept_asn, [:]) + annotwriter.out.annoted_file + emit: + out_files = annotwriter.out.annoted_file + evidence = annot_builder.out.outputs +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/orthology/diamond_orthology/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,25 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params;} from '../../utilities' +include { run_diamond_egap;} from '../../shared/diamond/main' + + + +workflow diamond_orthology { + take: + gnomon_prot_ids + proteins_ids + gnomon_prot_asn + proteins_asn + parameters // Map : extra parameter and parameter update + main: + String diamond_blastp_params = merge_params('--sam-query-len --very-sensitive --unal 0 --comp-based-stats 0 --masking 0', parameters, 'diamond_orthology_blastp') + String diamond_regular_params = merge_params('-ofmt seq-align-set -query-fmt seq-ids -subject-fmt seq-ids -output-prefix hits', parameters, 'diamond_orthology') + String diamond_egap_params = '-blastp-args \'' + diamond_blastp_params + '\' ' + diamond_regular_params + + run_diamond_egap(gnomon_prot_ids, proteins_ids, gnomon_prot_asn, proteins_asn, diamond_egap_params) + + emit: + alignments = run_diamond_egap.out +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/orthology/extract_products_from_models/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,45 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + +// extract_products -input-manifest models.mft -it -ifmt seq-annot -rna-ids out/rna.ids -prot-ids out/prot.ids + +workflow extract_products_from_models { + take: + models //path: models + parameters // Map : extra parameter and parameter update + main: + default_params = "" + effective_params = merge_params(default_params, parameters, 'extract_products_from_models') + run_extract_products_from_models(models, effective_params) + + emit: + rna_ids = run_extract_products_from_models.out.rna_ids + prot_ids = run_extract_products_from_models.out.prot_ids + all = run_extract_products_from_models.out.all +} + + +process run_extract_products_from_models { + input: + path models + val parameters + output: + path ('output/rna.ids'), emit: 'rna_ids' + path ('output/prot.ids'), emit: 'prot_ids' + path ('output/*'), emit: 'all' + script: + """ + mkdir -p output + echo "${models.join('\n')}" > models.mft + extract_products -input-manifest models.mft -it -ifmt seq-annot -rna-ids output/rna.ids -prot-ids output/prot.ids + + """ + stub: + """ + mkdir -p output + touch output/rna.ids + touch output/prot.ids + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/orthology/find_orthologs/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,170 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + +workflow find_orthologs { + take: + input_gencoll_asn //path: gencoll + ref_gencoll_asn //path: gencoll + input_annotations //path: annotations + ref_annotations //path: annotations + prot_hits + blastdb + input_proteins_asn + ref_proteins_asn + input_genome_asn + ref_genome_asn + parameters // Map : extra parameter and parameter update + main: + default_params = "-check_exome -annots1_serial_type Seq-annot -annots2_serial_type Seq-annot " + effective_params = merge_params(default_params, parameters, 'find_orthologs') + run_find_orthologs(input_gencoll_asn, ref_gencoll_asn, input_annotations, ref_annotations, prot_hits, blastdb, + input_proteins_asn, ref_proteins_asn, input_genome_asn, ref_genome_asn, effective_params) + + emit: + orthologs = run_find_orthologs.out.orthologs + stats = run_find_orthologs.out.stats + all = run_find_orthologs.out.all +} + + +process run_find_orthologs { + input: + path input_gencoll_asn + path ref_gencoll_asn, stageAs: 'input/ref_gencoll.asn' + path input_annotations + path ref_annotations + path prot_hits + path blastdb + path input_proteins_asn + path ref_proteins_asn + path input_genome_asn + path ref_genome_asn, stageAs: 'input/ref_genome.asn' + val parameters + output: + path ('output/orthologs.rpt'), emit: 'orthologs' + path ('output/stats.xml'), emit: 'stats' + path ('output/*'), emit: 'all' + script: + """ + mkdir -p output + echo "${input_annotations.join('\n')}" > annotations1.mft + echo "${ref_annotations.join('\n')}" > annotations2.mft + str="" + if [ -z "$blastdb" ] + then + mkdir -p ./asncache/ + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i $ref_proteins_asn -oseq-ids /dev/null -split-sequences + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i $input_genome_asn -oseq-ids /dev/null -split-sequences + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i $input_proteins_asn -oseq-ids /dev/null -split-sequences + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i input/ref_genome.asn -oseq-ids /dev/null -split-sequences + str="-asn-cache ./asncache/ -prot_hits_serial_type Seq-align-set" + else + str="-blastdb $blastdb/prot.blastdb,$blastdb/nucl.blastdb -prot_hits_serial_type Seq-align" + fi + find_orthologs $parameters -gc1 $input_gencoll_asn -gc2 input/ref_gencoll.asn -annots1 annotations1.mft -annots2 annotations2.mft \ + \$str -o_orthologs output/orthologs.rpt -prot_hits $prot_hits \ + -o_stats output/stats.xml -nogenbank + + """ + stub: + """ + mkdir -p output + touch output/stats.xml + touch output/orthologs.rpt + """ +} + + + + +ref_prot_url='https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/ortholog_references/9606/current/GCF_000001405.40_GRCh38.p14_protein.faa.gz' +ref_genf_url='https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/ortholog_references/9606/current/GCF_000001405.40_GRCh38.p14_genomic.fna.gz' +ref_geng_url='https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/ortholog_references/9606/current/GCF_000001405.40_GRCh38.p14_genomic.gff.gz' +process fetch_ortholog_references { + input: + output: + path "output/p14_protein.faa", emit: "p14_protein_faa" + path "output/p14_genomic.fna", emit: "p14_genomic_fna" + path "output/gc1.annot.asnt.gz", emit: "annot_file" + script: + """ + curl -O '$ref_prot_url' + curl -O '$ref_genf_url' + curl -O '$ref_geng_url' + gunzip GCF_000001405.40_GRCh38.p14_protein.faa.gz + gunzip GCF_000001405.40_GRCh38.p14_genomic.fna.gz + #gunzip GCF_000001405.40_GRCh38.p14_genomic.gff.gz + mkdir -p output + zcat GCF_000001405.40_GRCh38.p14_genomic.gff.gz | multireader -format gff3 | gzip -c > output/gc1.annot.asnt.gz + mv GCF_000001405.40_GRCh38.p14_protein.faa output/p14_protein.faa + mv GCF_000001405.40_GRCh38.p14_genomic.fna output/p14_genomic.fna + #mv GCF_000001405.40_GRCh38.p14_genomic.gff output/p14_genomic.gff + + """ + stub: + """ + mkdir -p output + touch output/p14_protein.faa + touch output/p14_genomic.fna + touch output/gc1.annot.asnt.gz + """ +} + + +/* +#!/usr/bin/bash +set -exuo pipefail + +gc1=GCF_000364345.1 # macaca ([Q]uery) +gc2=GCF_000001405.40 # homo sapiens ([S]ubject) + +inp_dir1=/am/ftp-genomes/all/GCF/000/364/345/GCF_000364345.1_Macaca_fascicularis_5.0/ +inp_dir2=/am/ftp-genomes/all/GCF/000/001/405/GCF_000001405.40_GRCh38.p14/ + + +cleanup() { + kill -- -$$ +} +trap cleanup SIGTERM + + +mkdir -p data + +# Required by find_orthologs +gc_get_assembly -acc $gc1 -level 2 -o data/$gc1.gc.asn +gc_get_assembly -acc $gc2 -level 2 -o data/$gc2.gc.asn + +# Convert GFF3 to ASN.1 +zcat $inp_dir1/*_genomic.gff.gz | multireader -format gff3 | gzip -c > data/$gc1.annot.asnt.gz +zcat $inp_dir2/*_genomic.gff.gz | multireader -format gff3 | gzip -c > data/$gc2.annot.asnt.gz + +# Genomic sequence required for aligning nucleotide neighborhood beween putative pairs of orthologs (-check_exome) +# Protein sequence required for computing ortholog-specific scores. +# (takes about 5 minutes) +zcat $inp_dir1/*_genomic.fna.gz $inp_dir2/*_genomic.fna.gz | makeblastdb -dbtype nucl -input_type fasta -parse_seqids -title nucs -out data/nucl.blastdb +zcat $inp_dir1/*_protein.faa.gz $inp_dir2/*_protein.faa.gz | makeblastdb -dbtype prot -input_type fasta -parse_seqids -title prots -out data/prot.blastdb + +# Make diamond-db for subject sequences +zcat $inp_dir2/*_protein.faa.gz | diamond makedb --db $gc2.prots + +# Compute protein hits (takes about 3 minutes with 96 CPUs) +time zcat $inp_dir1/*_protein.faa.gz | + nice -n19 diamond blastp --db ./$gc2.prots.dmnd --very-sensitive --sam-query-len --outfmt sam | + sam2asn -diamond -align-type prot-to-prot -nogenbank | + gzip -c > data/$gc1-$gc2.prot-hits.seq-align.asnb.gz + +# Compute orthologs (takes about 10 minutes) +zcat data/$gc1-$gc2.prot-hits.seq-align.asnb.gz | + time find_orthologs -prot_hits - -prot_hits_serial_type Seq-align \ + -gc1 data/$gc1.gc.asn \ + -gc2 data/$gc2.gc.asn \ + -annots1_serial_type Seq-annot -annots1 <(ls data/$gc1.annot.asnt.gz) \ + -annots2_serial_type Seq-annot -annots2 <(ls data/$gc2.annot.asnt.gz) \ + -check_exome \ + -blastdb data/prot.blastdb,data/nucl.blastdb \ + -o_orthologs orthologs.rpt \ + -nogenbank + +*/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/orthology/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,43 @@ +#!/usr/bin/env nextflow +// main nextflow script for EGAPx execution +// route data to subworkflows + +nextflow.enable.dsl=2 + + +include { extract_products_from_models } from './extract_products_from_models/main' +include { find_orthologs; fetch_ortholog_references; } from './find_orthologs/main' +include { diamond_orthology } from './diamond_orthology/main' +include { setup_genome; setup_proteins } from './../setup/main' +include { get_swiss_prot_ids as get_prot_ref_ids } from '../shared/diamond/main' + +params.intermediate = false + + +workflow orthology_plane { + take: + genome_asnb + gencoll_asn + models + annot_files + task_params // task parameters for every task + main: + // Protein alignments + fetch_ortholog_references() + def (scaffolds_ref, gencoll_ref_asn, unpacked_genome_ref, genome_ref_asn, genome_ref_asnb) = setup_genome(fetch_ortholog_references.out.p14_genomic_fna, [], task_params.get('setup', [:])) + def (unpacked_proteins_ref, proteins_ref_asn, proteins_ref_asnb) = setup_proteins(fetch_ortholog_references.out.p14_protein_faa, task_params.get('setup', [:])) + def prot_ref_ids = get_prot_ref_ids(proteins_ref_asnb) + //orthology plane + extract_products_from_models(annot_files, task_params.get('extract_products_from_models', [:])) + // reference side. 1) gencoll, annotation , genome and protein sequence --> asn cashe or LDS demon + + diamond_orthology(extract_products_from_models.out.prot_ids, prot_ref_ids , models, proteins_ref_asnb , task_params.get('diamond_orthology', [:])) + + // input side 1) gencoll asn from setup, genome_asn from setup, protein from gnomon_wnode.out, annotation it is from annotbuilder annot_files or accepts_asn + find_orthologs( gencoll_asn, gencoll_ref_asn, annot_files, fetch_ortholog_references.out.annot_file, diamond_orthology.out.alignments, [], + models, proteins_ref_asnb , genome_asnb, genome_ref_asnb , task_params.get('find_orthologs', [:])) + + emit: + orthologs = find_orthologs.out.orthologs +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/bam_bin_and_sort/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,188 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow bam_bin_and_sort { + take: + ch_bam // channel: BAM + ch_index // channel: BAM index + genome // path: genome fasta + organelle // list of path: organelles + parameters // Map : extra parameter and parameter update + main: + def assembly_sizes = calc_assembly_sizes(ch_bam.collect()) + def bam_bin_params = "-avg-size-per-bin 200000000 -file-pattern 'bin#.bam' -exclude-organelle" + out = bam_bin(ch_bam, ch_index, genome, organelle, assembly_sizes, merge_params(bam_bin_params, parameters, 'bam_bin')) + bins = out.collect() + merge_args = merge_prepare(bins) + // HACK: relies on the same filenames for files in bins as + // they were at the merge_prepare step. + merge(merge_args.flatten(), bins) + emit: + sorted = merge.out +} + + +process calc_assembly_sizes { + label 'large_disk' + input: + path bam_files + output: + path "assembly_sizes.hash" + script: + """ + #!/usr/bin/env bash + + declare -A assembly_sizes + for s in ${bam_files}; do + chunk_size=`wc -c \${s} | awk '{print \$1}'` + # Select assembly name + s=\$(basename \${s}) + regex="^(.+)-([^-]+)-Aligned[.]out[.]Sorted[.]bam\$" + if [[ \$s =~ \$regex ]]; then + assembly="\${BASH_REMATCH[1]}" + else + echo "Malformed BAM name, \${s}" + exit 1 + fi + # Update assembly -> total_size map + echo "Assembly: \${assembly}, chunk size: \${chunk_size}" + if [[ -z "\${assembly_sizes[\${assembly}]}" ]]; then + assembly_sizes[\${assembly}]=\${chunk_size} + else + assembly_sizes[\${assembly}]=\$((assembly_sizes[\${assembly}] + chunk_size)) + fi + done + declare -p assembly_sizes > assembly_sizes.hash + """ + + stub: + """ + touch assembly_sizes.hash + """ +} + + +process bam_bin { + input: + path sorted_bam + path sorted_bam_index + path genome + path organelle + path assembly_sizes + val bam_bin_params + output: + path "output/*" + script: + output = "output" + """ + #!/usr/bin/env bash + + mkdir -p $output + echo "bam file : ${sorted_bam}, index file : ${sorted_bam_index}" + s=\$(basename ${sorted_bam}) + regex="^(.+)-([^-]+)-Aligned[.]out[.]Sorted[.]bam\$" + if [[ \$s =~ \$regex ]]; then + assembly="\${BASH_REMATCH[1]}" + run="\${BASH_REMATCH[2]}" + else + echo "Malformed BAM name, ${sorted_bam}" + exit 1 + fi + + source $assembly_sizes + total_size=\${assembly_sizes[\$assembly]} + echo "Assembly \$assembly, run \$run, total size \$total_size" + + echo "genome ${genome}" + head -5 ${genome} + echo "organelle ${organelle}" + head -5 ${organelle} + echo "${genome}" > genome.mft + echo "${organelle.join('\n')}" > organelle.mft + samtools=`which samtools` + bam_bin $bam_bin_params -bam $sorted_bam -o $output/\$assembly-\$run.bins -total-bam-size \$total_size \ + -fasta-manifest genome.mft -organelle-manifest organelle.mft -samtools-path \$samtools + """ + + stub: + output = "output" + """ + mkdir -p $output + + s=\$(basename ${sorted_bam}) + regex="^(.+)-([^-]+)-Aligned[.]out[.]Sorted[.]bam\$" + if [[ \$s =~ \$regex ]]; then + assembly="\${BASH_REMATCH[1]}" + run="\${BASH_REMATCH[2]}" + else + echo "Malformed BAM name, ${sorted_bam}" + exit 1 + fi + + touch $output/\$assembly-\$run.bins + """ +} + + +process merge_prepare { + label 'large_disk' + input: + path runs + output: + path "*.bin_args" + script: + """ + #!/usr/bin/env bash + + declare -A bin_map + for run in $runs; do + s=\$(basename \${run}) + regex="^(.+)-([^-]+)[.]bins\$" + if [[ \$s =~ \$regex ]]; then + assembly="\${BASH_REMATCH[1]}" + else + echo "Malformed bins name, \${run}" + exit 1 + fi + for bam in \$run/*.bam; do + key="\$assembly-\$(basename \$bam)" + if [[ -z \${bin_map[\$key]} ]]; then + bin_map[\$key]=\$bam + else + bin_map[\$key]="\${bin_map[\$key]} \$bam" + fi + done + done + for bin in \${!bin_map[@]}; do + echo "merge --threads 8 \$bin \${bin_map[\$bin]}" >\$bin.bin_args + done + """ + + stub: + """ + touch 1.bin_args + """ +} + + +process merge { + label 'big_job' + label 'large_disk' + input: + path merge_args + path bins + output: + path "*.bam" + script: + """ + samtools `cat $merge_args` + """ + + stub: + """ + touch 1.bam + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/bam_strandedness/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,49 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow bam_strandedness { + take: + bam_list // list: BAM + sra_metadata // path: file with sra metadata + parameters // Map : extra parameter and parameter update + main: + // Not yet used but supposed to be used by rnaseq_divide_by_strandedness + rnaseq_divide_by_strandedness_params = merge_params("-min-aligned 1000000 -min-unambiguous 200 -min-unambiguous-pct 2 -max-unambiguous-pct 100 -percentage-threshold 98", parameters, 'rnaseq_divide_by_strandedness') + rnaseq_divide_by_strandedness(bam_list, sra_metadata, rnaseq_divide_by_strandedness_params) + emit: + strandedness = rnaseq_divide_by_strandedness.out.strandedness + stranded_runs = rnaseq_divide_by_strandedness.out.stranded_runs + unstranded_runs = rnaseq_divide_by_strandedness.out.unstranded_runs + all = rnaseq_divide_by_strandedness.out.all +} + + +process rnaseq_divide_by_strandedness { + label 'large_disk' + input: + path bam_list + path metadata_file + val parameters + output: + path "output/run.strandedness", emit: 'strandedness' + path "output/stranded.list", emit: 'stranded_runs', optional: true + path "output/unstranded.list", emit: 'unstranded_runs', optional: true + path "output/*", emit: 'all' + script: + """ + mkdir -p output + samtools=\$(which samtools) + echo "${bam_list.join('\n')}" > bam_list.mft + rnaseq_divide_by_strandedness -align-manifest bam_list.mft -metadata $metadata_file $parameters -samtools-executable \$samtools -stranded-output output/stranded.list -strandedness-output output/run.strandedness -unstranded-output output/unstranded.list + """ + stub: + """ + mkdir -p output + touch output/run.strandedness + touch output/stranded.list + touch output/unstranded.list + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/convert_from_bam/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,53 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow bam2asn { + take: + ch_bam // channel: BAM + strandedness // path: file with strandedness info for assemblies in BAM files + genome // path: genome in either FASTA or ASN format + parameters // Map: extra parameter and parameter update + main: + conv_param = "-filter 'pct_identity_gap >= 85' -ofmt seq-align-compressed -collapse-identical -no-scores -ifmt bam" + convert(ch_bam, strandedness, genome, merge_params(conv_param, parameters, 'sam2asn')) + emit: + align = convert.out.align + keylist = convert.out.keylist +} + + +process convert { + label 'long_job' + label 'large_disk' + input: + path in_bam + path strandedness + path genome, stageAs: 'genome/*' + val conv_param + output: + path "${prefix}.align.asnb.gz", emit: 'align', optional: true + path "${prefix}.align_counts.txt", emit: 'keylist', optional: true + script: + prefix = in_bam.name.replaceAll(/\.bam$/, '') + min_file_size = 100000 + """ + samtools=`which samtools` + if [ `stat -L -c%s $in_bam` -lt $min_file_size ] && [ `\$samtools view -c $in_bam` -eq 0 ]; then + exit 0 + fi + tmpdir=`mktemp -d` + lds2_indexer -source genome/ -db LDS2 + # EXCEPTION_STACK_TRACE_LEVEL=Warning DEBUG_STACK_TRACE_LEVEL=Warning DIAG_POST_LEVEL=Trace + sam2asn $conv_param -refs-local-by-default -nogenbank -lds2 LDS2 -tmp-dir \$tmpdir -align-counts "${prefix}.align_counts.txt" -o "${prefix}.align.asnb.gz" -strandedness $strandedness -input $in_bam -samtools-path \$samtools + """ + + stub: + prefix = in_bam.name.replaceAll(/\.bam$/, '') + """ + touch ${prefix}.align_counts.txt + touch ${prefix}.align.asnb.gz + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/fetch_sra_fasta/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,63 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' +params.inpdir = "" +workflow fetch_sra_fasta { + take: + sra_run_file // Channel: sra run file + parameters // Map : extra parameter and parameter update + main: + a = read_sra_file(sra_run_file) + b = a.map { it -> it.split()} + c = run_fetch_sra_fasta(b.flatten()) + + emit: + //fasta_pair_list = run_fetch_sra_fasta.out.fasta_pair_list + fasta_pair_list = c +} + + +process read_sra_file { + input: + path sra_run_file + output: + env exitvar + script: + + """ + exitvar=() + while read -r line; do [[ \$line = \\#* ]] && continue; exitvar+=(\"\$line\"); done < ${sra_run_file} + """ + + stub: + """ + exitvar=SRA000001 + """ +} + + +process run_fetch_sra_fasta { + input: + val sra + output: + tuple val (sra), path ('output/*.{1,2}') , emit: 'fasta_pair_list' + script: + """ + output_${sra}=\$(srapath ${sra}) + curl -o ${sra} \$output_${sra} + fasterq-dump --skip-technical --threads 6 --split-files --seq-defline ">\\\$ac.\\\$si.\\\$ri" --fasta -O . ./${sra} + rm -f ${sra} + mkdir output + mv ${sra}_1.fasta output/${sra}.1 + if [ -f ${sra}_2.fasta ]; then + mv ${sra}_2.fasta output/${sra}.2 + fi + """ + stub: + """ + mkdir -p output + touch output/${sra}.1 + touch output/${sra}.2 + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,78 @@ +#!/usr/bin/env nextflow +// rnaseq short EGAPx execution +// route data to tasks + +nextflow.enable.dsl=2 + +include { sra_query } from './sra_qry/main' +include { fetch_sra_fasta } from './fetch_sra_fasta/main' +include { star_index } from './star_index/main' +include { star_wnode as star } from './star_wnode/main' +include { bam_strandedness } from './bam_strandedness/main' +include { bam_bin_and_sort } from './bam_bin_and_sort/main' +include { bam2asn } from './convert_from_bam/main' +include { rnaseq_collapse } from './rnaseq_collapse/main' + +params.intermediate = false + + +workflow rnaseq_short_plane { + take: + genome_asn + scaffolds + unpacked_genome_fasta + + // Alternative groups of parameters, one of them should be set + // reads_query - SRA query in the form accepted by NCBI + // reads_ids - list of SRA IDs + // reads, reads_metadata - path to reads accompanied by metadata + reads_query // SRA query + reads_ids // list of SRA IDs + reads // path to reads + reads_metadata // path to reads metadata 13 tab-delimited fields, 1-st - SRA ID, 3-rd paired or unpaired, everything else - not used, but must be present + // 4, 5, 13 - numbers, 5 - non zero number + organelles // path to organelle list + // Alternative parameters, one of them should be set + // tax_id - NCBI tax id of the closest taxon to the genome + // hmm_params - HMM parameters + tax_id // NCBI tax id of the closest taxon to the genome + max_intron // max intron length + task_params // task parameters for every task + main: + // Satisfy quirks of Nextflow compiler + def reads_query1 = reads_query + def reads_ids1 = reads_ids + def ch_reads = Channel.fromList(reads) + // Conditional code on SRA reads source + if (reads_query || reads_ids || reads) { + def index = star_index(unpacked_genome_fasta, task_params.get('star_index', [:])) + def ch_align, ch_align_index, sra_metadata, sra_run_list + if (reads_query || reads_ids) { + def query = reads_query1 ? reads_query1 : reads_ids1.join("[Accession] OR ") + "[Accession]" + (sra_metadata, sra_run_list) = sra_query(query, task_params.get('sra_qry', [:])) + def reads_fasta_pairs = fetch_sra_fasta(sra_run_list, task_params.get('fetch_sra_fasta', [:])) + (ch_align, ch_align_index) = star(scaffolds, reads_fasta_pairs, genome_asn, index, max_intron, task_params.get('star_wnode', [:])) + } else { + sra_metadata = reads_metadata + (ch_align, ch_align_index) = star(scaffolds, ch_reads, genome_asn, index, max_intron, task_params.get('star_wnode', [:])) + } + // + + bam_strandedness(ch_align.collect(), sra_metadata, task_params.get('bam_strandedness', [:])) + def strandedness = bam_strandedness.out.strandedness + + // Run bam_bin_and_sort + bam_bin_and_sort(ch_align, ch_align_index, unpacked_genome_fasta, organelles, task_params.get('bam_bin_and_sort', [:])) + def bam_bins = bam_bin_and_sort.out.sorted + + // Run BAM2ASN + bam2asn(bam_bins, strandedness, genome_asn, task_params.get('convert_from_bam', [:])) + def asn_align = bam2asn.out.align.collect() + def keylist = bam2asn.out.keylist.collect() + + rnaseq_collapse(genome_asn, keylist, asn_align, sra_metadata, 10, task_params.get('rnaseq_collapse', [:])) + } + + emit: + rnaseq_alignments = rnaseq_collapse.out.alignments +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/rnaseq_align_report/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,59 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow rnaseq_align_report { + take: + gencoll_asn + input_metadata + intron_counts + run_stats + run_list + parameters // Map : extra parameter and parameter update + main: + String report_params = merge_params("-tracking-server NONE", parameters, 'rnaseq_align_report') + run_align_report(gencoll_asn, input_metadata, intron_counts, run_stats, run_list, report_params) + emit: + align_report = run_align_report.out.align_report + run_reports = run_align_report.out.run_reports +} + + +process run_align_report { + input: + path gencoll_asn + path input_metadata + path intron_counts + path run_stats + path run_list + val params + output: + path "rnaseq_align_report.xml", emit: "align_report" + path "*_runs.txt", emit: "run_reports" + script: + """ + ##echo "${gencoll_asn.join('\n')}" > ./gencoll_asn.mft + echo "${input_metadata.join('\n')}" > ./input_metadata.mft + echo "${intron_counts.join('\n')}" > ./intron_counts.mft + echo "${run_stats.join('\n')}" > ./run_stats.mft + echo "${run_list.join('\n')}" > ./run_list.mft + + rnaseq_align_report \ + -gencoll-asn ${gencoll_asn} \ + -input-manifest ./input_metadata.mft \ + -intron-counts-manifest ./intron_counts.mft \ + -run-stats-manifest ./run_stats.mft \ + -run-list-manifest ./run_list.mft \ + $params \ + -output ./rnaseq_align_report.xml \ + -run-report-output '@-RS_2023_11_rnaseq_runs.txt' + """ + stub: + """ + touch rnaseq_align_report.xml + touch stub_report_runs.txt + """ +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/rnaseq_collapse/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,145 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow rnaseq_collapse { + take: + genome // path: file of genomic sequences, FASTA or ASN + scaffold_list // path: file with list of scaffolds + alignments // value channel path: align files + sra_metadata_list // path: file with sra metadata + max_jobs // val: max number of jobs + parameters // Map: extra parameter and parameter update + main: + String create_jobs_params = merge_params("-alignments-per-job 50000 -min-range 100000", parameters, 'rnaseq_collapse_create_jobs') + String rnaseq_collapse_params = merge_params("-backlog 1 -max-jobs 1 -support-non-sra", parameters, 'rnaseq_collapse') + String gpx_make_outputs_params = merge_params("-default-output-name align -slices-for affinity -sort-by job-id -unzip align", parameters, 'gpx_make_outputs') + + def (jobs, lines_per_file) = generate_jobs(genome, scaffold_list, max_jobs, create_jobs_params) + def collected = run_rnaseq_collapse(genome, scaffold_list, alignments, sra_metadata_list, jobs.flatten(), lines_per_file, rnaseq_collapse_params) | collect + run_gpx_make_outputs(collected, gpx_make_outputs_params) + emit: + alignments = run_gpx_make_outputs.out.alignments + alignment_slices = run_gpx_make_outputs.out.alignment_slices +} + + +process generate_jobs { + input: + path genome, stageAs: 'genome/*' + path scaffold_list + val njobs + val params + output: + path "job.*" + env lines_per_file + script: + """ + echo "${scaffold_list.join('\n')}" > scaffold_list.mft + + # make the local LDS of the genomic sequences + lds2_indexer -source ./genome -db ./genome_lds + + rnaseq_collapse_create_jobs $params -nogenbank -lds2 ./genome_lds -scaffold-list scaffold_list.mft > jobs + total_lines=\$(wc -l <jobs) + (( lines_per_file = (total_lines + ${njobs} - 1) / ${njobs} )) + split -l\$lines_per_file jobs job. -da 3 + """ + + stub: + """ + for i in {1..$njobs}; do + echo "<job query =\\\"lcl|SOME_GENOME_ID:\${i}-\${i}\\\"></job>" >> jobs + done + split -l1 jobs job. -da 3 + lines_per_file=1 + """ +} + + +process run_rnaseq_collapse { + input: + path genome, stageAs: 'genome/*' + path scaffold_list + path in_align + path sra_metadata_list + path job + val lines_per_file + val params + output: + path "output/*" + script: + """ + njobs=`wc -l <$job` + if [ \$njobs -lt 16 ]; then + threads=\$njobs + else + threads=16 + fi + + echo "${scaffold_list.join('\n')}" > scaffold_list.mft + echo "${in_align.join('\n')}" > align.mft + echo "${sra_metadata_list.join('\n')}" > metadata.mft + + # HACK: derive start_job_id from job file extension + filename=\$(basename -- "$job") + extension="\${filename##*.}" + # NB: for successful gather phase all job id should be unique, + # so we must supply start_job_id. + (( start_job_id = ((10#\$extension) * $lines_per_file) + 1 )) + + # make the local LDS of the genomic sequences + lds2_indexer -source ./genome -db ./genome_lds + + # When running multiple jobs on the cluster there is a chance that + # several jobs will run on the same node and thus generate files + # with the same filename. We need to avoid that to be able to stage + # the output files for gpx_make_outputs. We add the job file numeric + # extension as a prefix to the filename. + mkdir interim + rnaseq_collapse $params -O interim -nogenbank -lds2 ./genome_lds -sorted-vols align.mft -scaffold-list scaffold_list.mft -sra-metadata-manifest metadata.mft -start-job-id \$start_job_id -input-jobs $job -workers \$threads + mkdir output + for f in interim/*; do + if [ -f \$f ]; then + mv \$f output/\${extension}_\$(basename \$f) + fi + done + """ + + stub: + """ + filename=\$(basename -- "$job") + extension="\${filename##*.}" + mkdir -p output + touch output/rnaseq_collapse_wnode.\${extension}.out + """ + +} + + +process run_gpx_make_outputs { + input: + path files, stageAs: 'input/*' + val params + output: + path "output/align.*.out", emit: 'alignments' + path "output/align.*.out.slices", emit: 'alignment_slices' + script: + """ + mkdir -p output + gpx_make_outputs $params -input-path input -output output/@.#.out -output-manifest output/@.mft -slices-manifest output/@_slices.mft -num-partitions 1 + """ + + stub: + """ + mkdir -p output + echo ${files} + for i in {1..10}; do + touch output/align.\$i.out + touch output/align.\$i.out.slices + done + + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/rnaseq_register_stats/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,61 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow rnaseq_register_stats { + take: + gencoll_asn + sra_metadata + collapsed_aligns + per_run_counts + stranded_runs + unstranded_runs + parameters // Map : extra parameter and parameter update + main: + String stats_params = merge_params(" -TS NONE -TU NONE -TP NONE ", parameters, 'rnaseq_register_stats') + register_stats(gencoll_asn, sra_metadata, collapsed_aligns, per_run_counts, stranded_runs, unstranded_runs, stats_params) + emit: + outputs = register_stats.out.outputs +} + + +process register_stats { + input: + path gencoll_asn + path sra_metadata + path collapsed_aligns + path per_run_counts + path stranded_runs + path unstranded_runs + val params + output: + path "run_stats.tsv", emit: "outputs" + script: + """ + ##echo "${gencoll_asn.join('\n')}" > ./gencoll_asn.mft + echo "${sra_metadata.join('\n')}" > ./sra_metadata.mft + echo "${collapsed_aligns.join('\n')}" > ./collapsed_aligns.mft + echo "${per_run_counts.join('\n')}" > ./per_run_counts.mft + echo "${stranded_runs.join('\n')}" > ./stranded_runs.mft + echo "${unstranded_runs.join('\n')}" > ./unstranded_runs.mft + + rnaseq_register_stats \ + -gencoll-asn ${gencoll_asn} \ + -sra-metadata-manifest ./sra_metadata.mft \ + -collapsed-aligns-manifest ./collapsed_aligns.mft \ + -per-run-counts-manifest ./per_run_counts.mft \ + -stranded-runs-manifest ./stranded_runs.mft \ + -unstranded-runs-manifest ./unstranded_runs.mft \ + $params -o ./run_stats.tsv + + ls -l + """ + + stub: + """ + touch run_stats.tsv + """ +} +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/sra_qry/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,124 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + +sra_api_url = "https://trace.ncbi.nlm.nih.gov/Traces/sra-db-be/runinfo" + + +workflow sra_query { + take: + // The SRA query should be present either in parameters map in sra_query section or in query + // The parameter 'query' overrides the one set in 'parameters' + query // String : query + parameters // Map : extra parameter and parameter update + main: + String params = merge_params("", parameters, "sra_query") + if (query) { + params = merge_params(params, ["sra_query" : "-query '${query}'"], "sra_query") + } + run_sra_query(params) + + emit: + sra_metadata = run_sra_query.out.sra_metadata + sra_run_list = run_sra_query.out.sra_run_list +} + + +process run_sra_query { + input: + val parameters + output: + path './sra_metadata.dat', emit: 'sra_metadata' + path './sra_run_accessions.ids', emit: 'sra_run_list' + + script: + """ + #!/usr/bin/env python3 + # sra_query.py - proxy compliant replacement for sra_query + + import csv + import json + from urllib.request import urlopen + from urllib.parse import quote + + import shlex + from sys import exit + + esearch_url = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=sra&retmode=json&retmax=2147483647&idtype=gi&term=" + runinfo_url = "https://trace.ncbi.nlm.nih.gov/Traces/sra-db-be/runinfo?retmode=csv&sp=runinfo&uid=" + TAB=chr(9) + NL=chr(10) + + parameters = shlex.split("$parameters") + if len(parameters) < 2 and parameters[0] != "-query": + exit(1) + + query = parameters[1] + + esearch = urlopen(esearch_url+quote(query)) + esearch_json = json.load(esearch) + uids = ','.join(esearch_json["esearchresult"]["idlist"]) + + runinfo = urlopen(runinfo_url+uids) + runinfo_csv = runinfo.read().decode("utf-8") + # print(runinfo_csv) + + lines = runinfo_csv.split(NL) + header = lines[0] + keypos = {} + for i, k in enumerate(header.split(",")): + keypos[k] = i + sra_meta_keys = ["SRA run accession", "SRA sample accession", "Run type", "SRA read count", "SRA base count", "Average insert size", "Insert size stdev", + "Platform type", "Model", "SRA Experiment accession", "SRA Study accession", "Biosample accession", "Bioproject ID", "Bioproject Accession", "Scientific name", "TaxID", "Release date"] + with open("sra_metadata.dat", 'wt') as outf: + print(f"#{TAB.join(sra_meta_keys)}", file=outf) + for line in lines[1:]: + line = line.strip() + if not line: + continue + for l in csv.reader([line], quotechar='"', delimiter=',', quoting=csv.QUOTE_ALL, skipinitialspace=True): + parts = l + printable = [] + paired = False + for k in ["Run", "Sample", "LibraryLayout", "spots", "bases", "NA", "NA", "Platform", "Model", "Experiment", "SRAStudy", "BioSample", "ProjectID", "BioProject", "ScientificName", "TaxID", "ReleaseDate"]: + if k not in keypos: + printable.append("NA") + continue + v = parts[keypos[k]] + if k == "LibraryLayout": + if parts[keypos["LibraryLayout"]] == "PAIRED": + printable.append("paired") + paired = True + else: + printable.append("unpaired") + elif k == "spots": + if not paired: + printable.append(v) + else: + i = int(v) + if 'spots_with_mates' in keypos: + i += int(parts[keypos['spots_with_mates']]) + printable.append(str(i)) + else: + printable.append(v) + print(TAB.join(printable), file=outf) + with open("sra_run_accessions.ids", 'wt') as outf: + print("#SRA run accession", file=outf) + for line in lines[1:]: + line = line.strip() + if not line: + continue + parts = line.split(",") + run_acc = parts[keypos["Run"]] + if not run_acc: + continue + print(run_acc, file=outf) + """ + + stub: + """ + touch sra_metadata.dat + touch sra_run_accessions.ids + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/star_index/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,48 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +process build_index { + label 'big_job' + input: + path genome_file + val parameters + output: + path out_dir + script: + out_dir = genome_file.toString().replaceFirst(/\.(fa(sta)?|fna)$/, ".index") + """ + echo "in $genome_file, out $out_dir" + STAR $parameters --runMode genomeGenerate --genomeDir $out_dir --genomeFastaFiles $genome_file + chmod a+rx $out_dir + """ + + stub: + out_dir = genome_file.toString().replaceFirst(/\.(fa(sta)?|fna)$/, ".index") + """ + mkdir -p ${out_dir} + touch ${out_dir}/Genome + touch ${out_dir}/Log.out + touch ${out_dir}/SA + touch ${out_dir}/SAindex + touch ${out_dir}/chrLength.txt + touch ${out_dir}/chrName.txt + touch ${out_dir}/chrNameLength.txt + touch ${out_dir}/chrStart.txt + touch ${out_dir}/genomeParameters.txt + """ +} + + +workflow star_index { + take: + genome //path: genome + parameters // Map : extra parameter and parameter update + main: + default_params = "--runThreadN 6 --genomeSAindexNbases 14" + build_index(genome, merge_params(default_params, parameters, 'STAR')) + emit: + build_index.out +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/rnaseq_short/star_wnode/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,114 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +def get_effective_params(parameters, use_zcat, max_intron) { + def effective_star_params = "" + // Check that parameters for star_wnode doesn't contain 'star-params' + boolean back_compat = parameters.get("star_wnode", "").contains("-star-params") + if (!back_compat) { + def star_params = "--alignSJoverhangMin 8 --outFilterMultimapNmax 200 --outFilterMismatchNmax 50 --runThreadN 16 --genomeLoad NoSharedMemory --outSAMtype SAM --outSAMattributes 'NH HI AS nM NM MD jM jI XS MC' --outSAMprimaryFlag AllBestScore --outFilterMultimapScoreRange 50 --seedSearchStartLmax 15 --limitOutSAMoneReadBytes 1000000 --outSJtype None" + effective_star_params = ' -star-params "' + (use_zcat ? "--readFilesCommand zcat " : "") + merge_params(star_params, parameters, 'star-params') + '"' + } + def default_params = "-cpus-per-worker 4 -csi-threshold 512000000 -max-intron ${max_intron} -preserve-star-logs" + def effective_params = merge_params(default_params, parameters, 'star_wnode') + effective_star_params + if (!back_compat) { + // Ad-hoc post processing - remove single quotes from effective_params + effective_params = effective_params.replaceAll("'", "") + } + return effective_params +} + + +process run_star { + label 'huge_job' + label 'long_job' + input: + path seqid_list + tuple val(sampleID), path(fasta_rna_file) + val use_zcat + path genome_file, stageAs: 'genome/*' + path Star_Index + val max_intron + val parameters + output: + path "*-Aligned.out.Sorted.bam", emit: 'align' + path "*-Aligned.out.Sorted.bam.bai", emit: 'align_index' + // path "per_run_counts.txt", emit: 'per_run_counts' + script: + def assembly=genome_file.baseName.toString().replaceFirst(/\.(fa(sta)?|asn[bt]?)$/, "") + seqkit_cmd = "" + if ( fasta_rna_file[0] && fasta_rna_file[1] ) { + query_str = "${fasta_rna_file[0]},${fasta_rna_file[1]}" + seqkit_cmd = "seqkit stats ${fasta_rna_file[0]} ${fasta_rna_file[1]}" + } else { + query_str = fasta_rna_file[0] + seqkit_cmd = "seqkit stats ${fasta_rna_file[0]} " + } + def effective_params = get_effective_params(parameters, use_zcat, max_intron) + // println("Effective STAR parameters: $effective_params") + """ + echo "Assembly: ${assembly} sampleID: ${sampleID} Query: ${query_str}" + echo "${seqid_list.join('\n')}" > seqid_list.mft + lds2_indexer -source genome + mkdir -p out + mkdir -p wrkarea + echo "<job query =\\\"lcl|${query_str}\\\" subject=\\\"$Star_Index\\\"></job>" > jobfile + star=\$(which star-with-filter) + samtools=\$(which samtools) + fastq=\$(which fasterq-dump) + ${seqkit_cmd}; + star_wnode ${effective_params} -input-jobs jobfile -genome-sequences-manifest seqid_list.mft -fastq-executable \$fastq -samtools-executable \$samtools -star-executable \$star -output-dir . -work-area wrkarea -O out -lds2 genome/lds2.db + """ + + stub: + def assembly=genome_file.baseName.toString().replaceFirst(/\.(fa(sta)?|asn[bt]?)$/, "") + println("Assembly: ${assembly} sampleID: ${sampleID}, max_intron: ${max_intron}") + def effective_params = get_effective_params(parameters, use_zcat, max_intron) + println("Effective STAR parameters: $effective_params") + """ + touch ${assembly}-${sampleID}-Aligned.out.Sorted.bam + touch ${assembly}-${sampleID}-Aligned.out.Sorted.bam.bai + """ +} + + +workflow star_wnode { + take: + seqid_list // path: list of seq ids in the index (SEQID_LIST) + reads // channel: FASTA file pairs generated from SRA reads, see e.g., https://www.nextflow.io/docs/latest/channel.html#fromfilepairs + genome_file // path: genome file, fasta or ASN + star_index // path: index path + max_intron // int: maximum intron length + parameters // Map : extra parameter and parameter update + main: + + def use_zcat_ch = reads.map { it[1][0] ==~ /.*gz$/ } + run_star(seqid_list, reads, use_zcat_ch, genome_file, star_index, max_intron, parameters) + emit: + align = run_star.out.align + align_index = run_star.out.align_index +} + + +workflow star_wnode_simplified { + take: + seqid_list // path: list of seq ids in the index (SEQID_LIST) + reads // list of FASTA read files, expects pairs in form SRAxxx.1, SRAxxx.2 + genome_file // path: genome file, fasta or ASN + star_index // path: index path + max_intron // int: maximum intron length + parameters // Map : extra parameter and parameter update + main: + def filePairs = Channel.of(reads).flatten().map { read -> + def m = read =~ /\/([^\/]+).[12](.gz)?$/ + [m[0][1], read] + }.groupTuple() + def use_zcat_ch = filePairs.map { it[1][0] ==~ /.*gz$/ } + run_star(seqid_list, filePairs, use_zcat_ch, genome_file, star_index, max_intron, parameters) + emit: + align = exec.out.align + align_index = exec.out.align_index +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/setup/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,171 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + +include { merge_params } from '../utilities' + +workflow setup_genome { + take: + genome + organelles + parameters // Map : extra parameter and parameter update + main: + get_genome_info(genome, organelles, parameters) + emit: + seqid_list = get_genome_info.out.seqid_list + gencoll_asn = get_genome_info.out.gencoll_asn + unpacked_genome = get_genome_info.out.fasta + genome_asn = get_genome_info.out.genome_asn + genome_asnb = get_genome_info.out.genome_asnb + max_intron = get_genome_info.out.max_intron +} + + +process get_genome_info { + debug true + input: + path fasta_genome_file, stageAs: 'src/*' + path organelles + val parameters + output: + path '*.seqids', emit: 'seqid_list' + path '*.asn', emit: 'gencoll_asn' + path "${out_fasta}", emit: 'fasta' + path "${genome_asn}", emit: 'genome_asn' + path "${genome_asnb}", emit: 'genome_asnb' + env max_intron, emit: 'max_intron' + script: + need_zcat = fasta_genome_file.toString().endsWith('.gz') + base_name_stripped = fasta_genome_file.baseName.toString().replaceAll(/\.(fa(sta)?|fna)(\.gz)?$/, "") + indexed_fasta_name = fasta_genome_file.baseName.toString().replaceFirst(/\.(fa(sta)?|fna)(\.gz)?$/, ".fasta") + if (! indexed_fasta_name.endsWith(".fasta")) { + indexed_fasta_name += ".fasta" + } + genome_dir = "genome" + fasta_dir = "fasta" + out_fasta = fasta_dir + "/" + indexed_fasta_name + genome_asn = genome_dir + "/" + base_name_stripped + ".asn" + genome_asnb = genome_dir + "/" + base_name_stripped + ".asnb" + max_intron = parameters.max_intron + genome_size_threshold = parameters.genome_size_threshold + """ + # echo "need_zcat: ${need_zcat}, out_fasta: ${out_fasta}" + mkdir -p ${genome_dir} + mkdir -p ${fasta_dir} + if [[ ${need_zcat} == true ]]; then + # zcat ${fasta_genome_file} | sed 's/^\\(>gi|[0-9]\\+\\)|\\?\\([^ ]\\+\\)\\(.*\\)/\\1\\3/' > ${out_fasta} + # zcat ${fasta_genome_file} > ${out_fasta} + zcat ${fasta_genome_file} | sed 's/>\\([^ |]\\+\\)\\( .*\\)\\?\$/>lcl\\|\\1\\2/' > ${out_fasta} + else + # sed 's/^\\(>gi|[0-9]\\+\\)|\\?\\([^ ]\\+\\)\\(.*\\)/\\1\\3/' ${fasta_genome_file} > ${out_fasta} + # mv ${fasta_genome_file} ${out_fasta} + sed 's/>\\([^ |]\\+\\)\\( .*\\)\\?\$/>lcl\\|\\1\\2/' ${fasta_genome_file} > ${out_fasta} + fi + # Old way, now use gc_get_molecules. For multipart ids with gi first use the second part + # grep -oP "^>\\K[^ ]+" ${out_fasta} | sed 's/^\\(gi|[0-9]\\+\\)|\\([^|]\\+|[^|]\\+\\)|\\?/\\2/' >list.seqids + multireader -flags ParseRawID -out-format asn_text -input ${out_fasta} -output ${genome_asn} + multireader -flags ParseRawID -out-format asn_binary -input ${out_fasta} -output ${genome_asnb} + lds2_indexer -source ${genome_dir}/ -db LDS2 + # Using all parts of multipart ids is preferrable, but slower - one more pass over genomic FASTA + gc_create -unplaced ${out_fasta} -unplaced-fmt fasta -fasta-parse-raw-id -gc-assm-name "EGAPx Test Assembly" -nogenbank -lds2 LDS2 >gencoll.asn + gc_get_molecules -gc-assembly gencoll.asn -filter all -level top-level > list.seqids + + #TODO: subtract organelles from list + + # This is a rough estimate because we don't need the more accurate size + genome_size=`wc -c <${out_fasta}` + # Max intron logic + if [ $genome_size_threshold -gt 0 ] && [ \$genome_size -lt $genome_size_threshold ]; then + # scale max intron to genome size, rounding up to nearest 100kb + (( max_intron = ($max_intron * genome_size / $genome_size_threshold + 99999) / 100000 * 100000 )) + # echo "Setting max_intron to \$max_intron" + else + max_intron=$max_intron + fi + """ + + stub: + base_name_stripped = fasta_genome_file.baseName.toString().replaceAll(/\.(fa(sta)?|fna)(\.gz)?$/, "") + indexed_fasta_name = fasta_genome_file.baseName.toString().replaceFirst(/\.(fa(sta)?|fna)(\.gz)?$/, ".fasta") + if (! indexed_fasta_name.endsWith(".fasta")) { + indexed_fasta_name += ".fasta" + } + genome_dir = "genome" + fasta_dir = "fasta" + out_fasta = fasta_dir + "/" + indexed_fasta_name + genome_asn = genome_dir + "/" + base_name_stripped + ".asn" + genome_asnb = genome_dir + "/" + base_name_stripped + ".asnb" + """ + mkdir -p $genome_dir + mkdir -p $fasta_dir + touch $out_fasta + touch $genome_asn + touch $genome_asnb + touch gencoll.asn + touch list.seqids + max_intron=10000 + echo "Processing genome $fasta_genome_file" + echo "Setting max_intron to \$max_intron" + """ +} + + +workflow setup_proteins { + take: + proteins + parameters // Map : extra parameter and parameter update + main: + convert_proteins(proteins) + emit: + unpacked_proteins = convert_proteins.out.unpacked_proteins + proteins_asn = convert_proteins.out.proteins_asn + proteins_asnb = convert_proteins.out.proteins_asnb +} + + +process convert_proteins { + input: + path fasta_proteins_file, stageAs: 'src/*' + output: + path out_fasta, emit: 'unpacked_proteins' + path proteins_asn, emit: 'proteins_asn' + path proteins_asnb, emit: 'proteins_asnb' + script: + need_zcat = fasta_proteins_file.toString().endsWith('.gz') + base_name_stripped = fasta_proteins_file.baseName.toString().replaceAll(/\.(fa(sta)?|faa)(\.gz)?$/, "") + fasta_name = base_name_stripped + ".faa" + + asn_dir = "asn" + fasta_dir = "fasta" + out_fasta = fasta_dir + "/" + fasta_name + proteins_asn = asn_dir + "/" + base_name_stripped + ".asn" + proteins_asnb = asn_dir + "/" + base_name_stripped + ".asnb" + """ + mkdir -p ${asn_dir} + mkdir -p ${fasta_dir} + if [[ ${need_zcat} == true ]]; then + zcat ${fasta_proteins_file} | sed 's/>\\([^ |]\\+\\)\\( .*\\)\\?\$/>lcl\\|\\1\\2/' > ${out_fasta} + else + sed 's/>\\([^ |]\\+\\)\\( .*\\)\\?\$/>lcl\\|\\1\\2/' ${fasta_proteins_file} > ${out_fasta} + fi + multireader -flags ParseRawID -out-format asn_text -input ${out_fasta} -output ${proteins_asn} + multireader -flags ParseRawID -out-format asn_binary -input ${out_fasta} -output ${proteins_asnb} + """ + + stub: + base_name_stripped = fasta_proteins_file.baseName.toString().replaceAll(/\.(fa(sta)?|faa)(\.gz)?$/, "") + fasta_name = base_name_stripped + ".faa" + asn_dir = "asn" + fasta_dir = "fasta" + out_fasta = fasta_dir + "/" + fasta_name + proteins_asn = asn_dir + "/" + base_name_stripped + ".asn" + proteins_asnb = asn_dir + "/" + base_name_stripped + ".asnb" + + """ + mkdir -p $asn_dir + mkdir -p $fasta_dir + touch $out_fasta + touch $proteins_asn + touch $proteins_asnb + """ + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/shared/diamond/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,107 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + + +/* + *Execution of: + * /netmnt/vast01/gpi/regr/GPIPE_REGR1/system/2024-03-27.prod.build25780/bin/diamond + * -asn-cache /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/sequence_cache + * -blastp-args '--sam-query-len --comp-based-stats 0 --evalue 0.0001 --very-sensitive --max-hsps 3' + * -diamond-executable /netmnt/vast01/gpi/regr/GPIPE_REGR1/system/2024-03-27.prod.build25780/third-party/diamond/diamond + * -lds2 /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/prot_gnomon_prepare.8202002/out/LDS2 + * -ofmt seq-align-set + * -output-dir /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/diamond.8202022/out + * -output-manifest /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/diamond.8202022/out/align.mft + * -output-prefix hits + * ## query is gnomon-made proteins 'gnl|GNOMON|23016146.p' + * ## query-fmt is <String, `fasta', `seq-ids'> + * -query-fmt seq-ids + * -query-manifest /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/diamond.8202022/inp/query_ids.mft + * ## subject is swiss-prot ids 'sp|A0A009IHW8.1|ABTIR_ACIB9' + * -subject-fmt seq-ids + * -subject-manifest /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/diamond.8202022/inp/subject_ids.mft + * -work-area /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/diamond.8202022/tmp + + */ + +include {to_map; shellSplit } from '../../utilities' + + +swiss_prot_url='https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/reference_sets/swissprot.asnb.gz' +process fetch_swiss_prot_asn { + input: + output: + path "output/swissprot.asnb", emit: "swiss_prot_asn" + script: + """ + curl -O '$swiss_prot_url' + gunzip swissprot.asnb.gz + mkdir -p output + mv swissprot.asnb output/swissprot.asnb + """ + stub: + """ + mkdir -p output + touch output/swissprot.asnb + """ +} + +process get_swiss_prot_ids { + input: + path swiss_prot_asn + output: + path "output/swiss_prot_ids" + script: + """ + mkdir -p output + lds2_indexer -db lds -source . + sqlite3 ./lds "SELECT txt_id FROM seq_id WHERE orig=1 AND int_id IS NULL;" > output/swiss_prot_ids + """ + stub: + """ + mkdir -p output + touch output/swiss_prot_ids + """ +} + +process run_diamond_egap { + input: + path gnomon_prot_ids + path swiss_prot_ids + path gnomon_prot_asn, stageAs: 'indexed/*' + path swiss_prot_asn, stageAs: 'indexed/*' + val params + output: + path "output/*" + script: + // print(params) + """ + + ###diamond_bin=`which diamond` + #diamond_egap uses GP_HOME to build paths to both some gp apps, and third-party + #GP_HOME needs to be the directory that contains third-party, and the directory that contains bin/<gp apps> + diamond_bin=\${GP_HOME}/third-party/diamond/diamond + + mkdir -p ./asncache/ + + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i ${gnomon_prot_asn} -oseq-ids /dev/null -split-sequences + prime_cache -cache ./asncache/ -ifmt asnb-seq-entry -i ${swiss_prot_asn} -oseq-ids /dev/null -split-sequences + + mkdir ./output + mkdir ./work + + echo ${params} + echo "${gnomon_prot_ids.join('\n')}" > query.mft + diamond_egap ${params} -asn-cache ./asncache/ -nogenbank -query-manifest query.mft -subject ${swiss_prot_ids} \ + -output-dir ./output/ -work-area ./work/ -diamond-executable \${diamond_bin} + rm -rf ./work + """ + + stub: + """ + mkdir -p output + touch output/diamond_output.asn + """ +} + +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/target_proteins/align_filter_sa/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,50 @@ +#!/usr/bin/env nextflow + +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow align_filter_sa { + take: + genome_asn_file //path: genome asn file + proteins_asn_file //path: protein asn file + alignment_asn_file //path: asn file from best_aligned_prot + parameters // Map : extra parameter and parameter update + main: + default_params = "" + effective_params = merge_params(default_params, parameters, 'align_filter') + run_align_filter_sa(genome_asn_file, proteins_asn_file, alignment_asn_file, effective_params) + + emit: + filtered_file = run_align_filter_sa.out.filtered_file + non_match_file = run_align_filter_sa.out.non_match_file + report_file = run_align_filter_sa.out.report_file +} + + +process run_align_filter_sa { + input: + path genome, stageAs: 'LDS_Index/genome.asnt' + path proteins, stageAs: 'LDS_Index/proteins.asnt' + path asn_file + val parameters + output: + path 'output/align.asn', emit: 'filtered_file' + path 'output/align-nomatch.asn', emit: 'non_match_file' + path 'output/report.txt', emit: 'report_file' + + script: + """ + mkdir -p output + lds2_indexer -source LDS_Index + align_filter ${parameters} -lds2 LDS_Index/lds2.db -nogenbank -input $asn_file -output output/align.asn -non-match-output output/align-nomatch.asn -report-output output/report.txt + """ + stub: + """ + mkdir -p output + touch output/align.asn + touch output/align-nomatch.asn + touch output/report.txt + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/target_proteins/best_aligned_prot/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,52 @@ +#!/usr/bin/env nextflow + +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow best_aligned_prot { + take: + genome_asn_file //path: genome file + proteins_asn_file //path: protein file + alignment_asn_file //path: alignment asn file from paf2asn + gencoll_file //path: + parameters // Map : extra parameter and parameter update + main: + default_params = "" + effective_params = merge_params(default_params, parameters, 'best_aligned_prot') + run_best_aligned_prot(genome_asn_file, proteins_asn_file, alignment_asn_file, gencoll_file, effective_params) + + emit: + asn_file = run_best_aligned_prot.out.asn_file + report_file = run_best_aligned_prot.out.report_file + +} + + +process run_best_aligned_prot { + input: + path genome, stageAs: 'LDS_Index/genome.asnt' + path proteins, stageAs: 'LDS_Index/proteins.asnt' + path alignment_asn_file // list of alignment files + path gencoll_file + val parameters + output: + path 'output/align.asn', emit: 'asn_file' + path 'output/report.txt', emit: 'report_file' + + script: + """ + mkdir -p output + lds2_indexer -source LDS_Index + echo "${alignment_asn_file.join('\n')}" > align.mft + best_placement ${parameters} -lds2 LDS_Index/lds2.db -nogenbank -gc_path $gencoll_file -in_alns align.mft -out_alns output/align.asn -out_rpt output/report.txt + """ + stub: + print("Best aligned prot input ${alignment_asn_file}") + """ + mkdir -p output + touch output/align.asn + touch output/report.txt + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/target_proteins/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,37 @@ +#!/usr/bin/env nextflow +// main nextflow script for EGAPx execution +// route data to subworkflows + +nextflow.enable.dsl=2 + +include { miniprot } from './miniprot/main' +include { align_filter_sa } from './align_filter_sa/main' +include { best_aligned_prot } from './best_aligned_prot/main' +include { paf2asn } from './paf2asn/main' +include { run_align_sort} from '../default/align_sort_sa/main' + +params.intermediate = false + + +workflow target_proteins_plane { + take: + unpacked_genome_fasta + genome_asn + gencoll_asn + unpacked_proteins_fasta + proteins_asn + max_intron + task_params // task parameters for every task + main: + // Protein alignments + miniprot(unpacked_genome_fasta, unpacked_proteins_fasta, max_intron, task_params.get('miniprot', [:])) + def miniprot_file = miniprot.out.miniprot_file + paf2asn(genome_asn, proteins_asn, miniprot_file, task_params.get('paf2asn', [:])) + def converted_asn = paf2asn.out.asn_file + best_aligned_prot(genome_asn, proteins_asn, converted_asn.collect(), gencoll_asn, task_params.get('best_aligned_prot', [:])) + align_filter_sa(genome_asn, proteins_asn, best_aligned_prot.out.asn_file, task_params.get('align_filter_sa', [:])) + run_align_sort(genome_asn, proteins_asn,align_filter_sa.out.filtered_file, + "-k subject,subject_start,-subject_end,subject_strand,query,query_start,-query_end,query_strand,-num_ident,gap_count" ) + emit: + protein_alignments = run_align_sort.out +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/target_proteins/miniprot/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,108 @@ +#!/usr/bin/env nextflow + +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +def get_effective_params(parameters, max_intron) { + def default_params = "-t 8 -G ${max_intron}" + def value = parameters.get("miniprot", "") + value = value.replaceFirst("-cpu-count", "-t") + value = value.replaceFirst("-max-intron", "-G") + parameters['miniprot'] = value + def effective_params = merge_params(default_params, parameters, "miniprot") + return effective_params +} + +workflow miniprot { + take: + fasta_genome_file //path: genome fasta file + fasta_proteins_file //path: protein fasta file + max_intron //int: max intron length + parameters // Map : extra parameter and parameter update + main: + // println("Miniprot max intron: ${max_intron}") + def items_per_chunk = merge_params("-n 1000000000", parameters, "split_proteins").replaceFirst("-n ", "").toInteger() + def protein_chunks + if (items_per_chunk == 1000000000) { + protein_chunks = fasta_proteins_file + } else { + protein_chunks = split_proteins(fasta_proteins_file, items_per_chunk) + } + run_miniprot(fasta_genome_file, protein_chunks.flatten(), max_intron, parameters) + + emit: + miniprot_file = run_miniprot.out.miniprot_file +} + + +process split_proteins { + input: + path fasta_proteins_file + val items_per_chunk + output: + path 'output/*' + script: + """ + #!/usr/bin/env python3 + import os + + os.makedirs("output", exist_ok=True) + with open("${fasta_proteins_file}", 'rt') as f: + items = 0 + chunk = [] + nextfile = 1 + for line in f: + if line and line[0] == '>': + items += 1 + if items >= ${items_per_chunk}: + with open(f"output/{nextfile}.fa", "w") as outf: + outf.write(''.join(chunk)) + chunk = [] + nextfile += 1 + items = 1 + chunk.append(line) + if chunk: + with open(f"output/{nextfile}.fa", "w") as outf: + outf.write(''.join(chunk)) + """ + stub: + print("items_per_chunk ${items_per_chunk}") + """ + mkdir -p output + touch output/1.fa + touch output/2.fa + touch output/3.fa + """ +} + + +process run_miniprot { + label 'huge_job' + label 'long_job' + input: + path fasta_genome_file + path fasta_proteins_file + val max_intron + val parameters + output: + path ('output/*.paf'), emit: 'miniprot_file' + + script: + def paf_name = fasta_proteins_file.baseName.toString() + ".paf" + def effective_params = get_effective_params(parameters, max_intron) + // println("Miniprot params: ${effective_params}") + """ + mkdir -p output + miniprot ${effective_params} ${fasta_genome_file} ${fasta_proteins_file} > output/${paf_name} + """ + stub: + def paf_name = fasta_proteins_file.baseName.toString() + ".paf" + def effective_params = get_effective_params(parameters, max_intron) + println("Miniprot params: ${effective_params}") + """ + mkdir -p output + touch output/${paf_name} + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/target_proteins/paf2asn/main.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,47 @@ +#!/usr/bin/env nextflow + +nextflow.enable.dsl=2 + +include { merge_params } from '../../utilities' + + +workflow paf2asn { + take: + genome_asn_file //path: genome asn file + proteins_asn_file //path: protein asn file + paf_file //path: paf alignment file from miniprot + parameters // Map : extra parameter and parameter update + main: + default_params = "" + effective_params = merge_params(default_params, parameters, 'paf2asn') + run_paf2asn(genome_asn_file, proteins_asn_file, paf_file, effective_params) + + emit: + asn_file = run_paf2asn.out.asn_file +} + + +process run_paf2asn { + label 'long_job' + input: + path genome, stageAs: 'LDS_Index/genome.asnt' + path proteins, stageAs: 'LDS_Index/proteins.asnt' + path paf_file // list of PAF files to convert + val parameters + output: + path 'output/*.asn', emit: 'asn_file' + script: + def asn_name = paf_file.baseName.toString() + ".asn" + """ + mkdir -p output + lds2_indexer -source LDS_Index + echo "${paf_file.join('\n')}" > input.mft + paf2asn ${parameters} -lds2 LDS_Index/lds2.db -nogenbank -input-manifest input.mft -o output/${asn_name} + """ + stub: + def asn_name = paf_file.baseName.toString() + ".asn" + """ + mkdir -p output + touch output/${asn_name} + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/subworkflows/ncbi/utilities.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,162 @@ +#!/usr/bin/env nextflow +nextflow.enable.dsl=2 + + +// Analog of shlex.split +def List<String> shellSplit(CharSequence s) { + List<String> tokens = [] + boolean escaping = false + char quoteChar = ' ' + boolean quoting = false + int lastCloseQuoteIndex = Integer.MIN_VALUE + StringBuilder current = new StringBuilder() + + s.eachWithIndex { c, i -> + if (escaping) { + current.append(c) + escaping = false + // } else if (c == '\\' && !(quoting && quoteChar == '\'')) { + } else if (c == '\\' && !quoting) { + escaping = true + } else if (quoting && c == quoteChar) { + quoting = false + lastCloseQuoteIndex = i + } else if (!quoting && (c == '\'' || c == '"')) { + quoting = true + quoteChar = c + } else if (!quoting && c.isAllWhitespace()) { + if (current.size() > 0 || lastCloseQuoteIndex == (i - 1)) { + tokens.add(current.toString()) + current = new StringBuilder() + } + } else { + current.append(c) + } + } + if (current.size() > 0 || lastCloseQuoteIndex == (s.length() - 1)) { + tokens.add(current.toString()) + } + + return tokens +} + + +// Convert a parameter list into a map +def Map<String, String> to_map(List<String> list ) +{ + def map = [:] + def s = list.size() + def i = 0 + while (i < s) + { + def elem = list.get(i) + i = i + 1 + if (elem.size() > 0 && elem[0] == '-') + { + if (i < s) { + def val = list.get(i) + if ( val.size() > 0 && (val[0] != '-' || val.contains(' ')) ) + { + map[elem] = val + i = i + 1 + } else { + map[elem] = "" + } + } else { + map[elem] = "" + } + } else { + println("Error: parameter string not well formed, map ${map}, elem ${elem}, i ${i}, s ${s}") + return map + } + } + return map +} + + +def quote(String s) +{ + if (s.size() > 0 && !(s =~ /[^\w@%+=:,.\/-]/)) { + return s + } + return "'" + s + "'" +} + + +// Read a section of the parameters and merge them into the default parameters +// Parameters: +// default_params: the default parameters, string +// parameters: the parameters as a map from string to string +// section_name: the name of the section in the parameters map to use +// Return: the merged parameters +def merge_params(default_params, parameters, section_name) +{ + def section = parameters.get(section_name, "") + def update_map = to_map(shellSplit(section)) + def default_params_map = to_map(shellSplit(default_params)) + default_params_map.putAll(update_map) + def l = [] + default_params_map.each { parameter, value -> + l << quote(parameter) + if (value.size() > 0) { + l << quote(value) + } + } + + return l.join(" ") +} + + + +process clean_fasta_ids { + input: + path fasta_in + output: + path "fasta_out", emit: 'fasta_out' + script: + """ + ## turns Fasta inputs formatted with multi-part IDs into + ## single-part IDs, like + ## >gi|1234|ref|NW_1234.1 Some Defline For This Org + ## >gi|1234 Some Defline For This Org + ## LDS chokes on the multi-part IDs. + # the base64 nonsense is because I couldnt get it to not complain about the regex as syntax errors in some way. + # its just this: + # import re,sys; + # for l in sys.stdin: + # <I had to delete the regex here because even in a comment nextflow lost it> + echo 'aW1wb3J0IHJlLHN5czsKZm9yIGwgaW4gc3lzLnN0ZGluOgogICAgcHJpbnQocmUuc3ViKHIiXig+' > reol.b64 + echo 'Z2lcfFxkKylcfD8oW2Etel0rXHxbQS1aX10rW1xkXC5dK1x8KSguKikiLCAiXGc8MT5cZzwzPiIs' >> reol.b64 + echo 'IGwuc3RyaXAoKSkpCg==' >> reol.b64 + base64 -d ./reol.b64 > ./reol.py + cat ${fasta_in} | python reol.py > ./fasta_out + """ + stub: + """ + touch ./fasta.out + """ +} + + + +process multireader { + input: + path fasta_file + val parameters + output: + path ('output/fasta_file.asnt') , emit: 'multireader_file' + script: + """ + mkdir -p output + if [ -n "$fasta_file" ]; then + multireader $parameters -out-format asn_text -input $fasta_file -output output/fasta_file.asnt + else + touch output/fasta_file.asnt + fi + """ + stub: + """ + mkdir -p output + touch output/fasta_file.asnt + """ +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/nf/ui.nf Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,88 @@ +#!/usr/bin/env nextflow +// main nextflow script for EGAPx ui execution +// prepare data channels and call main subworkflow + +nextflow.enable.dsl=2 + +include { egapx } from './subworkflows/ncbi/main' +include { only_gnomon } from './subworkflows/ncbi/only_gnomon' + +params.verbose = false + + +process export { + publishDir "${params.output}", mode: 'copy', saveAs: { fn -> fn.substring(fn.lastIndexOf('/')+1) } + input: + path out_files + path annot_builder_output, stageAs: 'annot_builder_output/*' + // path locus + output: + path "*", includeInputs: true + script: + """ + echo "export script" + """ + stub: + """ + echo "export stub" + """ +} + + +workflow { + // Parse input parameters + def input_params = params.get('input', [:]) + def genome = input_params.get('genome', []) + def proteins = input_params.get('proteins', []) + def reads_query = input_params.get('reads_query', []) + def reads_ids = input_params.get('reads_ids', []) + def reads = input_params.get('reads', []) + def reads_metadata = input_params.get('reads_metadata', []) + def organelles = input_params.get('organelles', []) ?: [] + def tax_id = input_params.get('taxid', []) + def hmm_params = input_params.get('hmm', []) ?: [] + def hmm_taxid = input_params.get('hmm_taxid', []) ?: [] + def softmask = input_params.get('softmask', []) ?: [] + def max_intron = input_params.get('max_intron', []) + def genome_size_threshold = input_params.get('genome_size_threshold', []) + def rnaseq_alignments = input_params.get('rnaseq_alignments', []) ?: [] + def protein_alignments = input_params.get('protein_alignments', []) ?: [] + def task_params = params.get('tasks', [:]) + def func_name = params.get('func_name', '') + if (params.verbose) { + println("input params:\ngenome ${genome}") + println("proteins ${proteins}") + println("reads_query ${reads_query}") + println("reads_ids ${reads_ids}") + println("reads ${reads}") + println("reads_metadata ${reads_metadata}") + println("organelles ${organelles}") + println("tax_id ${tax_id}") + println("hmm_params ${hmm_params}") + println("hmm_taxid ${hmm_taxid}") + println("softmask ${softmask}") + println("max_intron ${max_intron}") + println("genome_size_threshold ${genome_size_threshold}") + println("rnaseq_alignments ${rnaseq_alignments}") + println("protein_alignments ${protein_alignments}") + println("func_name ${func_name}") + // Keep it last as it is large + println("task_params ${task_params}") + } + + if(func_name == 'only_gnomon') { + if (params.verbose) { + print('in gnomon block') + } + only_gnomon(genome, proteins, rnaseq_alignments, protein_alignments, organelles, tax_id, hmm_params, hmm_taxid, softmask, task_params) + export(only_gnomon.out.out_files, only_gnomon.out.evidence) + } + else { + if (params.verbose) { + print('in egapx block') + } + egapx(genome, proteins, reads_query, reads_ids, reads, reads_metadata, organelles, tax_id, hmm_params, hmm_taxid, softmask, max_intron, genome_size_threshold, task_params) + // export(egapx.out.out_files, egapx.out.annot_builder_output, egapx.out.locus) + export(egapx.out.out_files, egapx.out.annot_builder_output) + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/third_party_licenses/LICENSE_STAR Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Alexander Dobin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/third_party_licenses/LICENSE_diamond Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,622 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is 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. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + 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. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + 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 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. Use with the GNU Affero General Public License. + + 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 Affero 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 special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU 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 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 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 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 +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/third_party_licenses/LICENSE_miniprot Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,23 @@ +The MIT License + +Copyright (c) 2022- Dana-Farber Cancer Institute + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/third_party_licenses/LICENSE_samtools Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,33 @@ +The MIT/Expat License + +Copyright (C) 2008-2024 Genome Research Ltd. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +[The use of a range of years within a copyright notice in this distribution +should be interpreted as being equivalent to a list of years including the +first and last year specified and all consecutive years between them. + +For example, a copyright notice that reads "Copyright (C) 2005, 2007-2009, +2011-2012" should be interpreted as being identical to a notice that reads +"Copyright (C) 2005, 2007, 2008, 2009, 2011, 2012" and a copyright notice +that reads "Copyright (C) 2005-2012" should be interpreted as being identical +to a notice that reads "Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012".]
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/third_party_licenses/LICENSE_seqkit Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2016-2019 Wei Shen, 2019 Oxford Nanopore Technologies. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/default.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,4 @@ +dag.overwrite = true +report.overwrite = true +timeline.overwrite = true +trace.overwrite = true \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/docker_image.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,1 @@ +process.container = 'ncbi/egapx:0.2-alpha'
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/aws.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,25 @@ +process { + executor = 'awsbatch' + // Queue points to a compute environment with a mix of r6i.2xlarge, r6i.4xlarge, and r6i.8xlarge + // with 200GB EBS gp3 disks, using modified Amazon Linux 2 image with aws cli and docker installed + // as described in https://www.nextflow.io/docs/latest/aws.html + queue = 'egapx-small-and-medium-ds' + // If jobs fail with the message 'out of disk space', create compute environment + // with r6i.4xlarge instances with 1000GB EBS gp3 disk, connect a queue to it + // and put the queue name here + withLabel: 'large_disk' { + queue = 'egapx-large-disk' + } +} + +aws { + region = 'us-east-2' + batch { + cliPath = '/home/ec2-user/miniconda/bin/aws' + maxTransferAttempts = 3 + } + client { + maxErrorRetry = 3 + socketTimeout = 3600000 // 1 hours in milliseconds + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/biowulf_cluster.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,51 @@ +// Config for https://hpc.nih.gov/ +// This config doesn't use profiles because EGAPx can't use them now. +// It is a copy of 'biowulf' profile from config at https://hpc.nih.gov/apps/nextflow.html + +params { + config_profile_description = 'Biowulf nf-core config' + config_profile_contact = 'staff@hpc.nih.gov' + config_profile_url = 'https://hpc.nih.gov/apps/nextflow.html' + max_memory = '224 GB' + max_cpus = 32 + max_time = '72 h' + + igenomes_base = '/fdb/igenomes_nf/' +} + + +singularity { + enabled = true + autoMounts = true + cacheDir = "/data/$USER/singularity" + envWhitelist='https_proxy,http_proxy,ftp_proxy,DISPLAY,SLURM_JOB_ID,SINGULARITY_BINDPATH' +} + +env { + SINGULARITY_CACHEDIR="/data/$USER/singularity" + PYTHONNOUSERSITE = 1 +} + +process { + executor = 'slurm' + maxRetries = 1 + queue = 'norm' + queueSize = 200 + pollInterval = '2 min' + queueStatInterval = '5 min' + submitRateLimit = '6/1min' + retry.maxAttempts = 1 + + clusterOptions = ' --gres=lscratch:200 ' + + scratch = '/lscratch/$SLURM_JOB_ID' + // with the default stageIn and stageOut settings using scratch can + // result in humungous work folders + // see https://github.com/nextflow-io/nextflow/issues/961 and + // https://www.nextflow.io/docs/latest/process.html?highlight=stageinmode + stageInMode = 'symlink' + stageOutMode = 'rsync' + + // for running pipeline on group sharing data directory, this can avoid inconsistent files timestamps + cache = 'lenient' +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/biowulf_local.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,13 @@ +// This is config for EGAPx run on a single node on Biowulf cluster +// The node should be started with --cpus-per-task=32 --mem=224g --time=1-00:00:00 + +singularity { + enabled = true + autoMounts = true + cacheDir = "/data/$USER/singularity" + envWhitelist='https_proxy,http_proxy,ftp_proxy,DISPLAY,SLURM_JOB_ID,SINGULARITY_BINDPATH' +} + +env { + SINGULARITY_CACHEDIR="/data/$USER/singularity" +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/docker.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,1 @@ +docker.enabled = true
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/docker_minimal.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,5 @@ +docker.enabled = true +process { + memory = 6.GB + cpus = 4 +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/local.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,3 @@ +docker.enabled = false +env.GP_HOME="/netmnt/vast01/egapx/bin/" +env.PATH = "/netmnt/vast01/egapx/bin/gp:/netmnt/vast01/egapx/bin/third-party/STAR/bin/Linux_x86_64:\$PATH"
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/ncbi-sge.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,29 @@ +// This is an example of SGE executor configuration +// It is specific for internal NCBI use, you need to supply -P and -A parameters specific to your HPC +// account. Keep -V, maybe adjust osverfull parameters (set to use Alma Linux 8) +// This configuration uses binaries setup directly on network accessible drive. We currently don't support +// such configurations for third party, use docker or singularity for this. Uncomment corresponding line below +//docker.enabled = true +//singularity.enabled = true +process { + executor = 'sge' + clusterOptions = "-m n -V -P progressive -w n -A annotations-euk -l express=TRUE,h_vmem=INFINITY,m_core=12,osverfull='8*'" +} +env.GP_HOME="/netmnt/vast01/egapx/bin/" +env.PATH = "/netmnt/vast01/egapx/bin:/netmnt/vast01/egapx/bin/gp:/netmnt/vast01/egapx/bin/third-party/STAR/bin/Linux_x86_64:\$PATH" +process { + memory = 60.GB + time = 3.h + + withLabel: 'big_job' { + memory = 120.GB + } + + withLabel: 'huge_job' { + memory = 200.GB + } + + withLabel: 'long_job' { + time = 6.h + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/singularity.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,1 @@ +singularity.enabled = true
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/executor/slurm.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,37 @@ +// Config for typical SLURM cluster +// Adjust the parameters for your cluster - queue name, temp dir, etc. +// Use your temp space instead of /data/$USER in the following config + +singularity { + enabled = true + autoMounts = true + cacheDir = "/data/$USER/singularity" + envWhitelist='https_proxy,http_proxy,ftp_proxy,DISPLAY,SLURM_JOB_ID,SINGULARITY_BINDPATH' +} + +env { + SINGULARITY_CACHEDIR="/data/$USER/singularity" + SINGULARITY_TMPDIR="/data/$USER/tmp" +} + +process { + executor = 'slurm' + // Set other parameters specific to your cluser here + // maxRetries = 1 + // queue = 'norm' + // queueSize = 200 + // pollInterval = '2 min' + // queueStatInterval = '5 min' + // submitRateLimit = '6/1min' + // retry.maxAttempts = 1 + + // clusterOptions = ' --gres=lscratch:200 ' + + // scratch = '/lscratch/$SLURM_JOB_ID' + // with the default stageIn and stageOut settings using scratch can + // result in humungous work folders + // see https://github.com/nextflow-io/nextflow/issues/961 and + // https://www.nextflow.io/docs/latest/process.html?highlight=stageinmode + //stageInMode = 'symlink' + //stageOutMode = 'rsync' +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/config/process_resources.config Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,51 @@ +// Part of nextflow config describing resource requirements for EGAPx processes +// We rely on labels to define 3 tiers of processes - default, big, and huge. +// Make sure that executor you use supports job memory and CPU requirements +process { + memory = 60.GB + cpus = 7 + time = 6.h + errorStrategy = 'retry' + maxRetries = 3 + + withLabel: 'big_job' { + memory = 120.GB + cpus = 15 + } + + withLabel: 'huge_job' { + memory = 200.GB + cpus = 31 + } + + withLabel: 'long_job' { + time = 16.h + } +} + +profiles { + + stubrun { + + process { + memory = 1.GB + cpus = 1 + time = 1.h + + withLabel: 'big_job' { + memory = 1.GB + cpus = 1 + } + + withLabel: 'huge_job' { + memory = 1.GB + cpus = 1 + } + + withLabel: 'long_job' { + time = 1.h + } + } + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/assets/default_task_params.yaml Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,71 @@ +tasks: + setup: + convert_genome: force-local-ids + convert_proteins: force-local-ids + bam_bin_and_sort: + bam_bin: -avg-size-per-bin 200000000 -file-pattern 'bin#.bam' -exclude-organelle + bam_strandedness: + rnaseq_divide_by_strandedness: -min-aligned 1000000 -min-unambiguous 200 -min-unambiguous-pct + 2 -percentage-threshold 98 + chainer: + chainer_wnode: -altfrac 80.0 -capgap 5 -cdsbonus 0.05 -composite 10000 -end-pair-support-cutoff + 0.1 -endprotfrac 0.05 -filters 'remove_single_exon_est_models remove_single_exon_noncoding_models' + -high-identity 0.98 -hmaxlen 0.25 -hthresh 0.02 -i3p 14.0 -i5p 7.0 -lenpen 0.005 + -longenoughcds 900 -max-extension 20 -min-consensus-support 2 -min-edge-coverage + 5 -min-non-consensussupport 10 -min-support-fraction 0.03 -minex 10 -mininframefrac + 0.95 -minlen 225 -minpolya 6 -minprotfrac 0.9 -minscor 40.0 -minsupport 3 -minsupport_mrna + 1 -minsupport_rnaseq 5 -mrnaCDS use_objmgr -oep 10 -protcdslen 450 -sharp-boundary + 0.2 -tolerance 3 -trim 6 -utrclipthreshold 0.01 -fillgenomicgaps -filterest + -filtermrna -filterprots -opposite + gpx_make_outputs: -default-output-name chains -slices-for affinity -sort-by affinity + input_aligns_sort: merge_only + submit_chainer: -minimum-abut-margin 20 -separate-within-introns + convert_from_bam: + sam2asn: -filter 'pct_identity_gap >= 95' -ofmt seq-align-compressed -collapse-identical + -no-scores + getfasta: + getfasta: -u full-assembly -bare-accession -use-reference-non-nuclear + gnomon: + annot_wnode: -margin 1000 -mincont 1000 -minlen 225 -mpp 10.0 -ncsp 25 -window + 200000 -nonconsens -open + generic_action_node: -app annot_wnode + gpx_qdump: -slices-for affinity -sort-by affinity -unzip '*' + gpx_qsubmit: '' + prot_gnomon_prepare: + prot_gnomon_prepare: '' + rnaseq_collapse: + gpx_make_outputs: -default-output-name align -slices-for affinity -sort-by job-id + -unzip align + gpx_qsubmit: -affinity subject + rnaseq_collapse: -backlog 1 -max-jobs 1 -support-non-sra + # -rank-counts-precalculated + rnaseq_collapse_create_jobs: -alignments-per-job 50000 -min-range 100000 + star_index: + STAR: --runThreadN 8 + star_wnode: + gpx_qdump: -unzip '*' + gpx_qsubmit: -affinity subject + star_wnode: -cpus-per-worker 16 -csi-threshold 512000000 -preserve-star-logs + star-params: --alignSJoverhangMin 8 --outFilterMultimapNmax 200 --outFilterMismatchNmax + 50 --runThreadN 16 --genomeLoad NoSharedMemory --outSAMtype SAM --outSAMattributes + 'NH HI AS nM NM MD jM jI XS MC' --outSAMprimaryFlag AllBestScore --outFilterMultimapScoreRange + 50 --seedSearchStartLmax 15 --limitOutSAMoneReadBytes 1000000 --outSJtype None + miniprot: + split_proteins: -n 100000 + miniprot: -t 31 -p 0.4 --outs=0.4 + paf2asn: + paf2asn: -prosplign-refinement + best_aligned_prot: + best_aligned_prot: -asm_alns_filter 'reciprocity = 3' + chainer_sort_alignments: + align_sort: -ifmt seq-align -k subject,subject_start,-subject_end,subject_strand,query,query_start,-query_end,query_strand,-num_ident,gap_count + align_filter_sa: + align_filter: -filter 'rank=1 OR (pct_identity_gapopen_only > 58 AND (pct_coverage > 50 OR align_length_ungap > 1000))' -ifmt seq-align + gnomon_training: + gnomon_training: -asn -b + diamond: + diamond: -query-fmt seq-ids -subject-fmt seq-ids -output-prefix hits -ofmt seq-align-set + diamond_blastp: --sam-query-len --very-sensitive --unal 0 --comp-based-stats 0 --masking 0 + diamond_orthology: + diamond_orhtology: -ofmt seq-align-set -query-fmt seq-ids -subject-fmt seq-ids -output-prefix hits + diamond_orthology_blastp: --sam-query-len --very-sensitive --unal 0 --comp-based-stats 0 --masking 0
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ui/egapx.py Sat Aug 03 11:16:53 2024 +0000 @@ -0,0 +1,810 @@ +#!/usr/bin/env python +# requires pip install pyyaml +# +import shlex +import shutil +import sys +import os +import argparse +import subprocess +import tempfile +import re +import time +import datetime +from collections import defaultdict +from ftplib import FTP +from ftplib import FTP_TLS +import ftplib +from pathlib import Path +from typing import List +from urllib.request import urlopen +import json +import sqlite3 +import stat + +import yaml + +VERBOSITY_DEFAULT=0 +VERBOSITY_QUIET=-1 +VERBOSITY_VERBOSE=1 + +FTP_EGAP_PROTOCOL = "https" +FTP_EGAP_SERVER = "ftp.ncbi.nlm.nih.gov" +FTP_EGAP_ROOT_PATH = "genomes/TOOLS/EGAP/support_data" +FTP_EGAP_ROOT = f"{FTP_EGAP_PROTOCOL}://{FTP_EGAP_SERVER}/{FTP_EGAP_ROOT_PATH}" +DATA_VERSION = "current" +dataset_taxonomy_url = "https://api.ncbi.nlm.nih.gov/datasets/v2alpha/taxonomy/taxon/" + +user_cache_dir = '' + +def parse_args(argv): + parser = argparse.ArgumentParser(description="Main script for EGAPx") + group = parser.add_argument_group('run') + group.add_argument("filename", nargs='?', help="YAML file with input: section with at least genome: and reads: parameters") + group.add_argument("-o", "--output", help="Output path", default="") + parser.add_argument("-e", "--executor", help="Nextflow executor, one of docker, singularity, aws, or local (for NCBI internal use only). Uses corresponding Nextflow config file", default="local") + parser.add_argument("-c", "--config-dir", help="Directory for executor config files, default is ./egapx_config. Can be also set as env EGAPX_CONFIG_DIR", default="") + parser.add_argument("-w", "--workdir", help="Working directory for cloud executor", default="") + parser.add_argument("-r", "--report", help="Report file prefix for report (.report.html) and timeline (.timeline.html) files, default is in output directory", default="") + parser.add_argument("-n", "--dry-run", action="store_true", default=False) + parser.add_argument("-st", "--stub-run", action="store_true", default=False) + parser.add_argument("-so", "--summary-only", help="Print result statistics only if available, do not compute result", action="store_true", default=False) + group = parser.add_argument_group('download') + group.add_argument("-dl", "--download-only", help="Download external files to local storage, so that future runs can be isolated", action="store_true", default=False) + parser.add_argument("-lc", "--local-cache", help="Where to store the downloaded files", default="") + parser.add_argument("-q", "--quiet", dest='verbosity', action='store_const', const=VERBOSITY_QUIET, default=VERBOSITY_DEFAULT) + parser.add_argument("-v", "--verbose", dest='verbosity', action='store_const', const=VERBOSITY_VERBOSE, default=VERBOSITY_DEFAULT) + parser.add_argument("-fn", "--func_name", help="func_name", default="") + return parser.parse_args(argv[1:]) + + +class FtpDownloader: + def __init__(self): + self.ftp = None + + def connect(self, host): + self.host = host + self.reconnect() + + def reconnect(self): + self.ftp = FTP(self.host) + self.ftp.login() + self.ftp.set_debuglevel(0) + + ##ftp_types = set() + def download_ftp_file(self, ftp_name, local_path): + # print(f"file: {ftp_name}") + # print(f"f: { os.path.dirname(local_path)}") + + os.makedirs(os.path.dirname(local_path), exist_ok=True) + try: + with open(local_path, 'wb') as f: + self.ftp.retrbinary("RETR {0}".format(ftp_name), f.write) + # print("downloaded: {0}".format(local_path)) + return True + except FileNotFoundError: + print("FAILED FNF: {0}".format(local_path)) + except EOFError: + print("FAILED EOF: {0}".format(local_path)) + time.sleep(1) + self.reconnect() + print("retrying...") + r = self.download_ftp_file(ftp_name, local_path) + print("downloaded on retry: {0}".format(local_path)) + return r + except BrokenPipeError: + print("FAILED BP: {0}".format(local_path)) + except IsADirectoryError: + ## same as 550 but pre-exists + ## os.remove(local_path) + return 550 + except ftplib.error_perm: + ## ftplib.error_perm: 550 genomes/TOOLS/EGAP/ortholog_references/9606/current: Not a regular file + ## its a symlink to a dir. + os.remove(local_path) + return 550 + return False + + # item: ('Eublepharis_macularius', {'modify': '20240125225739', 'perm': 'fle', 'size': '4096', 'type': 'dir', 'unique': '6CU599079F', 'unix.group': '562', 'unix.mode': '0444', 'unix.owner': '14'} + def should_download_file(self, ftp_item, local_name): + metadata = ftp_item[1] + ftp_modify = datetime.datetime.strptime(metadata['modify'], '%Y%m%d%H%M%S') + ftp_size = int(metadata['size']) + ftp_type = metadata['type'] + + local_stat = [] + try: + local_stat = os.stat(local_name) + except FileNotFoundError: + return True + except NotADirectoryError: + return True + local_is_dir = stat.S_ISDIR(local_stat.st_mode) + #print(f"item: {ftp_item}") + #print(f"stat: {local_stat}") + + local_stat_dt = datetime.datetime.fromtimestamp(local_stat.st_mtime) + + #print(f"should_dl: {ftp_size != local_stat.st_size} {ftp_modify > local_stat_dt} ") + + if (ftp_type == 'file' and ftp_size != local_stat.st_size) or (ftp_type=='OS.unix=symlink' and ftp_size >= local_stat.st_size): + return True + + if ftp_modify > local_stat_dt: + return True + + return False + + ## types + ## cdir and pdir: . and ..: do nothing + ## file: a file + ## dir: a dir + ## OS.unix=symlink: symlink to a file, treat like a file + def download_ftp_dir(self, ftp_path, local_path): + """ replicates a directory on an ftp server recursively """ + for ftp_item in self.ftp.mlsd(ftp_path): + # print(f"ftp_item: {ftp_item}") + ##print(f" name: {ftp_item[0]}") + ##print(f" type: {ftp_item[1]['type']}") + name = ftp_item[0] + next_ftp_name="/".join([ftp_path,name]) + next_local_name=os.sep.join([local_path,name]) + ftp_type = ftp_item[1]['type'] + ##ftp_types.add(ftp_type) + if ftp_type=='dir': + self.download_ftp_dir(next_ftp_name, next_local_name) + elif ftp_type=='file' or ftp_type=='OS.unix=symlink': + if self.should_download_file(ftp_item, next_local_name): + r = self.download_ftp_file(next_ftp_name, next_local_name) + if r == 550: + self.download_ftp_dir(next_ftp_name, next_local_name) + ##time.sleep(0.1) + ## else: . or .. do nothing + + +def download_egapx_ftp_data(local_cache_dir): + global user_cache_dir + manifest_url = f"{FTP_EGAP_ROOT}/{DATA_VERSION}.mft" + manifest = urlopen(manifest_url) + manifest_path = f"{user_cache_dir}/{DATA_VERSION}.mft" + manifest_list = [] + for line in manifest: + line = line.decode("utf-8").strip() + if not line or line[0] == '#': + continue + manifest_list.append(line) + print(f"Downloading {line}") + ftpd = FtpDownloader() + ftpd.connect(FTP_EGAP_SERVER) + ftpd.download_ftp_dir(FTP_EGAP_ROOT_PATH+f"/{line}", f"{local_cache_dir}/{line}") + if user_cache_dir: + with open(manifest_path, 'wt') as f: + for line in manifest_list: + f.write(f"{line}\n") + return 0 + + +def repackage_inputs(run_inputs): + "Repackage input parameters into 'input' key if not already there" + if 'input' in run_inputs: + return run_inputs + new_inputs = {} + new_inputs['input'] = {} + for key in run_inputs: + if key not in { 'tasks', 'output' }: + new_inputs['input'][key] = run_inputs[key] + else: + new_inputs[key] = run_inputs[key] + return new_inputs + + +def convert_value(value): + "Convert paths to absolute paths when possible, look into objects and lists" + if isinstance(value, dict): + return {k: convert_value(v) for k, v in value.items()} + elif isinstance(value, list): + return [convert_value(v) for v in value] + else: + if value == '' or re.match(r'[a-z0-9]{2,5}://', value) or not os.path.exists(value): + # do not convert - this is a URL or empty string or non-file + return value + # convert to absolute path + return str(Path(value).absolute()) + + +path_inputs = { 'genome', 'hmm', 'softmask', 'reads_metadata', 'organelles', 'proteins', 'reads', 'rnaseq_alignments', 'protein_alignments' } +def convert_paths(run_inputs): + "Convert paths to absolute paths where appropriate" + input_root = run_inputs['input'] + for key in input_root: + if key in path_inputs: + if isinstance(input_root[key], list): + input_root[key] = [convert_value(v) for v in input_root[key]] + else: + input_root[key] = convert_value(input_root[key]) + if 'output' in run_inputs: + run_inputs['output'] = convert_value(run_inputs['output']) + + +def prepare_reads(run_inputs): + """Reformat reads input to be in 'fromPairs' format expected by egapx, i.e. [sample_id, [read1, read2]] + Generate reads metadata file with minimal information - paired/unpaired and valid for existing libraries""" + if 'reads' not in run_inputs['input'] or 'output' not in run_inputs: + return + prefixes = defaultdict(list) + reads = run_inputs['input']['reads'] + if type(reads) == str: + del run_inputs['input']['reads'] + run_inputs['input']['reads_query'] = reads + return + # Create fake metadata file for reads containing only one meaningful information piece - pairedness + # Have an entry in this file only for SRA runs - files with prefixes SRR, ERR, and DRR and digits + # Non-SRA reads are handled by rnaseq_collapse internally + has_files = False + for rf in run_inputs['input']['reads']: + if type(rf) == str: + name = Path(rf).parts[-1] + mo = re.match(r'([^._]+)', name) + if mo and mo.group(1) != name: + has_files = True + prefixes[mo.group(1)].append(rf) + elif type(rf) == list: + has_files = True + names = list(map(lambda x: re.match(r'([^.]+)', Path(x).parts[-1]).group(1), rf)) + # Find common prefix + names.sort() + if len(names) == 1: + sample_id = names[0] + else: + for i in range(min(len(names[0]), len(names[-1]))): + if names[0][i] != names[-1][i]: + break + sample_id = names[0][0:i] + # Dont end prefix with . or _ + i = len(sample_id) - 1 + while i > 0 and sample_id[-1] in "._": + sample_id = sample_id[:-1] + i -= 1 + prefixes[sample_id] = rf + if has_files: # len(prefixes): + # Always create metadata file even if it's empty + output = run_inputs['output'] + with tempfile.NamedTemporaryFile(mode='w', delete=False, dir=output, prefix='egapx_reads_metadata_', suffix='.tsv') as f: + for k, v in prefixes.items(): + if re.fullmatch(r'([DES]RR[0-9]+)', k): + paired = 'paired' if len(v) == 2 else 'unpaired' + # SRR9005248 NA paired 2 2 NA NA NA NA NA NA NA 0 + rec = "\t".join([k, 'NA', paired, '2', '2', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', 'NA', '0']) + f.write(rec + '\n') + f.flush() + run_inputs['input']['reads_metadata'] = f.name + run_inputs['input']['reads'] = [ [k, v] for k, v in prefixes.items() ] + elif reads: + del run_inputs['input']['reads'] + run_inputs['input']['reads_query'] = "[Accession] OR ".join(reads) + "[Accession]" + + +def expand_and_validate_params(run_inputs): + """ Expand implicit parameters and validate inputs + Args: + run_inputs (dict): Input parameters + Returns: + bool: True if parameters are valid, False otherwise + """ + inputs = run_inputs['input'] + + if 'taxid' not in inputs: + print("ERROR: Missing parameter: 'taxid'") + return False + + taxid = inputs['taxid'] + + if 'genome' not in inputs: + print("ERROR: Missing parameter: 'genome'") + return False + + # Check for proteins input and if empty or no input at all, add closest protein bag + if 'proteins' not in inputs: + proteins = get_closest_protein_bag(taxid) + if not proteins: + # Proteins are not specified explicitly and not found by taxid + print(f"ERROR: Proteins are not found for tax id {inputs['taxid']}") + print(" This organism is not supported by current NCBI protein database") + print(" You can specify proteins manually using 'proteins' parameter") + return False + inputs['proteins'] = proteins + + has_rnaseq = 'reads' in inputs or 'reads_ids' in inputs or 'reads_query' in inputs + if not has_rnaseq: + if inputs['proteins']: + print("WARNING: It is strongly advised to specify RNA-seq reads using 'reads' parameter\n") + else: + print("ERROR: Either proteins or RNA-seq reads should be provided for annotation") + return False + + if 'hmm' not in inputs: + best_taxid, best_hmm = get_closest_hmm(taxid) + inputs['hmm'] = best_hmm + inputs['hmm_taxid'] = best_taxid + else: + # We assume the user knows what they're doing and the training is not necessary + inputs['hmm_taxid'] = taxid + + if 'max_intron' not in inputs: + max_intron, genome_size_threshold = get_max_intron(taxid) + inputs['max_intron'] = max_intron + inputs['genome_size_threshold'] = genome_size_threshold + else: + # Given max_intron is a hard limit, no further calculation is necessary + inputs['genome_size_threshold'] = 0 + + return True + + +def manage_workdir(args): + workdir_file = f"work_dir_{args.executor}.last" + if args.workdir: + os.environ['NXF_WORK'] = args.workdir + with open(workdir_file, 'w') as f: + f.write(args.workdir) + else: + if os.path.exists(workdir_file): + with open(workdir_file) as f: + os.environ['NXF_WORK'] = f.read().strip() + else: + if args.executor == 'aws': + print("Work directory not set, use -w at least once") + return False + return True + + +def get_cache_dir(): + global user_cache_dir + if user_cache_dir and os.path.exists(user_cache_dir): + return user_cache_dir + ##elif os.path.exists("/am/ftp-genomes/TOOLS/EGAP"): + ## return "/am/ftp-genomes/TOOLS/EGAP" + return "" + + +data_version_cache = {} +def get_versioned_path(subsystem, filename): + global data_version_cache + global user_cache_dir + if not data_version_cache: + manifest_path = f"{user_cache_dir}/{DATA_VERSION}.mft" + if user_cache_dir and os.path.exists(manifest_path): + with open(manifest_path, 'rt') as f: + for line in f: + line = line.strip() + if not line or line[0] == '#': + continue + parts = line.split('/') + if len(parts) == 2: + data_version_cache[parts[0]] = parts[1] + else: + manifest_url = f"{FTP_EGAP_ROOT}/{DATA_VERSION}.mft" + manifest = urlopen(manifest_url) + manifest_list = [] + for line in manifest: + line = line.decode("utf-8").strip() + if not line or line[0] == '#': + continue + parts = line.split('/') + if len(parts) == 2: + data_version_cache[parts[0]] = parts[1] + manifest_list.append(line) + if user_cache_dir: + with open(manifest_path, 'wt') as f: + for line in manifest_list: + f.write(f"{line}\n") + + if subsystem not in data_version_cache: + return os.path.join(subsystem, filename) + version = data_version_cache[subsystem] + return os.path.join(subsystem, version, filename) + + +# Get file path for subsystem, either from cache or from remote server +def get_file_path(subsystem, filename): + cache_dir = get_cache_dir() + vfn = get_versioned_path(subsystem, filename) + file_path = os.path.join(cache_dir, vfn) + file_url = f"{FTP_EGAP_ROOT}/{vfn}" + if os.path.exists(file_path): + return file_path + return file_url + + +def get_config(script_directory, args): + config_file = "" + config_dir = args.config_dir if args.config_dir else os.environ.get("EGAPX_CONFIG_DIR") + if not config_dir: + config_dir = Path(os.getcwd()) / "egapx_config" + if not Path(config_dir).is_dir(): + # Create directory and copy executor config files there + from_dir = Path(script_directory) / 'assets' / 'config' / 'executor' + if args.verbosity >= VERBOSITY_VERBOSE: + print(f"Copy config files from {from_dir} to {config_dir}") + if not args.dry_run: + os.mkdir(config_dir) + ld = os.listdir(from_dir) + for f in ld: + shutil.copy2(from_dir / f, config_dir) + print(f"Edit config files in {config_dir} to reflect your actual configuration, then repeat the command") + return "" + config_file = Path(config_dir) / (args.executor + '.config') + if not config_file.is_file(): + print(f"Executor {args.executor} not supported") + return "" + default_configs = [ "default.config" ] + with open(str(config_file), 'r') as f: + config_txt = f.read().replace('\n', ' ') + # Check whether the config sets the container + mo = re.search(r"process.+container *=", config_txt) + if not mo: + default_configs.append("docker_image.config") + # Check whether the config specifies proccess memory or CPUs + mo = re.search(r"process.+(memory|cpus) *=", config_txt) + if not mo: + default_configs.append("process_resources.config") + + # Add mandatory configs + config_files = [str(config_file)] + for cf in default_configs: + config_files.append(os.path.join(script_directory, "assets/config", cf)) + return ",".join(config_files) + + +lineage_cache = {} +def get_lineage(taxid): + global lineage_cache + if not taxid: + return [] + if taxid in lineage_cache: + return lineage_cache[taxid] + # Try cached taxonomy database + taxonomy_db_name = os.path.join(get_cache_dir(), get_versioned_path("taxonomy", "taxonomy4blast.sqlite3")) + if os.path.exists(taxonomy_db_name): + conn = sqlite3.connect(taxonomy_db_name) + if conn: + c = conn.cursor() + lineage = [taxid] + cur_taxid = taxid + while cur_taxid != 1: + c.execute("SELECT parent FROM TaxidInfo WHERE taxid = ?", (cur_taxid,)) + cur_taxid = c.fetchone()[0] + lineage.append(cur_taxid) + lineage.reverse() + lineage_cache[taxid] = lineage + return lineage + + # Fallback to API + taxon_json_file = urlopen(dataset_taxonomy_url+str(taxid)) + taxon = json.load(taxon_json_file)["taxonomy_nodes"][0] + lineage = taxon["taxonomy"]["lineage"] + lineage.append(taxon["taxonomy"]["tax_id"]) + lineage_cache[taxid] = lineage + return lineage + + +def get_tax_file(subsystem, tax_path): + vfn = get_versioned_path(subsystem, tax_path) + taxids_path = os.path.join(get_cache_dir(), vfn) + taxids_url = f"{FTP_EGAP_ROOT}/{vfn}" + taxids_file = [] + if os.path.exists(taxids_path): + with open(taxids_path, "rb") as r: + taxids_file = r.readlines() + else: + taxids_file = urlopen(taxids_url) + return taxids_file + +def get_closest_protein_bag(taxid): + if not taxid: + return '' + + taxids_file = get_tax_file("target_proteins", "taxid.list") + taxids_list = [] + for line in taxids_file: + line = line.decode("utf-8").strip() + if len(line) == 0 or line[0] == '#': + continue + parts = line.split('\t') + if len(parts) > 0: + t = parts[0] + taxids_list.append(int(t)) + + lineage = get_lineage(taxid) + + best_taxid = None + best_score = 0 + for t in taxids_list: + try: + pos = lineage.index(t) + except ValueError: + continue + if pos > best_score: + best_score = pos + best_taxid = t + + if best_score == 0: + return '' + # print(best_taxid, best_score) + return get_file_path("target_proteins", f"{best_taxid}.faa.gz") + + +def get_closest_hmm(taxid): + if not taxid: + return 0, "" + + taxids_file = get_tax_file("gnomon", "hmm_parameters/taxid.list") + + taxids_list = [] + lineages = [] + for line in taxids_file: + parts = line.decode("utf-8").strip().split('\t') + if len(parts) > 0: + t = parts[0] + taxids_list.append(t) + if len(parts) > 1: + l = map(lambda x: int(x) if x[-1] != ';' else int(x[:-1]), parts[1].split()) + lineages.append((int(t), list(l)+[int(t)])) + + #if len(lineages) < len(taxids_list): + # taxonomy_json_file = urlopen(dataset_taxonomy_url+','.join(taxids_list)) + # taxonomy = json.load(taxonomy_json_file)["taxonomy_nodes"] + # lineages = [ (t["taxonomy"]["tax_id"], t["taxonomy"]["lineage"] + [t["taxonomy"]["tax_id"]]) for t in taxonomy ] + + lineage = get_lineage(taxid) + + best_lineage = None + best_taxid = None + best_score = 0 + for (t, l) in lineages: + pos1 = 0 + last_match = 0 + for pos in range(len(lineage)): + tax_id = lineage[pos] + while tax_id != l[pos1]: + if pos1 + 1 < len(l): + pos1 += 1 + else: + break + if tax_id == l[pos1]: + last_match = pos1 + else: + break + if last_match > best_score: + best_score = last_match + best_taxid = t + best_lineage = l + + if best_score == 0: + return 0, "" + # print(best_lineage) + # print(best_taxid, best_score) + return best_taxid, get_file_path("gnomon", f"hmm_parameters/{best_taxid}.params") + + +PLANTS=33090 +VERTEBRATES=7742 +def get_max_intron(taxid): + if not taxid: + return 0, 0 + lineage = get_lineage(taxid) + if PLANTS in lineage: + return 300000, 3000000000 + elif VERTEBRATES in lineage: + return 1200000, 2000000000 + else: + return 600000, 500000000 + + +def to_dict(x: List[str]): + d = {} + s = len(x) + i = 0 + while i < s: + el = x[i] + i += 1 + if el and el[0] == '-': + if i < s: + v = x[i] + if v and (v[0] != '-' or (v[0] == '-' and ' ' in v)): + d[el] = v + i += 1 + else: + d[el] = "" + else: + d[el] = "" + else: + d[el] = "" + return d + +def merge_params(task_params, run_inputs): + # Walk over the keys in run_inputs and merge them into task_params + for k in run_inputs.keys(): + if k in task_params: + if isinstance(task_params[k], dict) and isinstance(run_inputs[k], dict): + task_params[k] = merge_params(task_params[k], run_inputs[k]) + else: + task_params_dict = to_dict(shlex.split(task_params[k])) + run_inputs_dict = to_dict(shlex.split(run_inputs[k])) + task_params_dict.update(run_inputs_dict) + task_params_list = [] + for k1, v in task_params_dict.items(): + task_params_list.append(k1) + if v: + task_params_list.append(v) + task_params[k] = shlex.join(task_params_list) + else: + task_params[k] = run_inputs[k] + return task_params + + +def print_statistics(output): + accept_gff = Path(output) / 'accept.gff' + print(f"Statistics for {accept_gff}") + counter = defaultdict(int) + if accept_gff.exists(): + with open(accept_gff, 'rt') as f: + for line in f: + line = line.strip() + if not line or line[0] == '#': + continue + parts = line.split() + if len(parts) < 3: + continue + counter[parts[2]] += 1 + keys = list(counter.keys()) + keys.sort() + for k in keys: + print(f"{k:12s} {counter[k]}") + + +def main(argv): + "Main script for EGAPx" + #warn user that this is an alpha release + print("\n!!WARNING!!\nThis is an alpha release with limited features and organism scope to collect initial feedback on execution. Outputs are not yet complete and not intended for production use.\n") + + # Parse command line + args = parse_args(argv) + + global user_cache_dir + if args.local_cache: + # print(f"Local cache: {args.local_cache}") + user_cache_dir = args.local_cache + if args.download_only: + if args.local_cache: + if not args.dry_run: + # print(f"Download only: {args.download_only}") + os.makedirs(args.local_cache, exist_ok=True) + download_egapx_ftp_data(args.local_cache) + else: + print(f"Download only to {args.local_cache}") + return 0 + else: + print("Local cache not set") + return 1 + else: + # Check that input and output set + if not args.filename or not args.output: + print("Input file and output directory must be set") + return 1 + + packaged_distro = bool(getattr(sys, '_MEIPASS', '')) + script_directory = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__))) + config_file = get_config(script_directory, args) + if not config_file: + return 1 + + # Check for workdir, set if not set, and manage last used workdir + if not manage_workdir(args): + return 1 + + files_to_delete = [] + + # Read default task parameters into a dict + task_params = yaml.safe_load(open(Path(script_directory) / 'assets' / 'default_task_params.yaml', 'r')) + run_inputs = repackage_inputs(yaml.safe_load(open(args.filename, 'r'))) + + if not expand_and_validate_params(run_inputs): + return 1 + + # Command line overrides manifest input + if args.output: + run_inputs['output'] = args.output + + # Convert inputs to absolute paths + convert_paths(run_inputs) + + # Create output directory if needed + os.makedirs(run_inputs['output'], exist_ok=True) + + if args.summary_only: + print_statistics(run_inputs['output']) + return 0 + + # Reformat reads into pairs in fromPairs format and add reads_metadata.tsv file + prepare_reads(run_inputs) + + + ##if True or args.download_only: + ## with open("./dumped_input.yaml", 'w') as f: + ## yaml.dump(run_inputs, f) + ## f.flush() + ##return 0 + + # Add to default task parameters, if input file has some task parameters they will override the default + task_params = merge_params(task_params, run_inputs) + + # Move output from YAML file to arguments to have more transparent Nextflow log + output = task_params['output'] + del task_params['output'] + + if args.func_name: + task_params['func_name'] = args.func_name + + # Run nextflow process + if args.verbosity >= VERBOSITY_VERBOSE: + task_params['verbose'] = True + print("Nextflow inputs:") + print(yaml.dump(task_params)) + if 'reads_metadata' in run_inputs['input']: + print("Reads metadata:") + with open(run_inputs['input']['reads_metadata'], 'r') as f: + print(f.read()) + if packaged_distro: + main_nf = Path(script_directory) / 'nf' / 'ui.nf' + else: + main_nf = Path(script_directory) / '..' / 'nf' / 'ui.nf' + nf_cmd = ["nextflow", "-C", config_file, "-log", f"{output}/nextflow.log", "run", main_nf, "--output", output] + if args.stub_run: + nf_cmd += ["-stub-run", "-profile", "stubrun"] + if args.report: + nf_cmd += ["-with-report", f"{args.report}.report.html", "-with-timeline", f"{args.report}.timeline.html"] + else: + nf_cmd += ["-with-report", f"{output}/run.report.html", "-with-timeline", f"{output}/run.timeline.html"] + + nf_cmd += ["-with-trace", f"{output}/run.trace.txt"] + # if output directory does not exist, it will be created + if not os.path.exists(output): + os.makedirs(output) + params_file = Path(output) / "run_params.yaml" + nf_cmd += ["-params-file", str(params_file)] + + if args.dry_run: + print(" ".join(map(str, nf_cmd))) + else: + with open(params_file, 'w') as f: + yaml.dump(task_params, f) + f.flush() + if args.verbosity >= VERBOSITY_VERBOSE: + print(" ".join(map(str, nf_cmd))) + resume_file = Path(output) / "resume.sh" + with open(resume_file, 'w') as f: + f.write("#!/bin/bash\n") + f.write(" ".join(map(str, nf_cmd))) + f.write(" -resume") + if os.environ.get('NXF_WORK'): + f.write(" -work-dir " + os.environ['NXF_WORK']) + f.write("\n") + try: + subprocess.run(nf_cmd, check=True, capture_output=(args.verbosity <= VERBOSITY_QUIET), text=True) + except subprocess.CalledProcessError as e: + print(e.stderr) + print(f"To resume execution, run: sh {resume_file}") + if files_to_delete: + print(f"Don't forget to delete file(s) {' '.join(files_to_delete)}") + return 1 + if not args.dry_run and not args.stub_run: + print_statistics(output) + # TODO: Use try-finally to delete the metadata file + for f in files_to_delete: + os.unlink(f) + + return 0 + +if __name__ == "__main__": + sys.exit(main(sys.argv))