From 38bed3b1b4d7888dcfed995871b3d0e44e66569e Mon Sep 17 00:00:00 2001 From: "Strope, Pooja" Date: Thu, 25 Jul 2024 14:42:23 -0400 Subject: [PATCH 1/4] updating to v0.2 --- LICENSE | 11 +- examples/input_C_longicornis.yaml | 2 +- examples/input_Gavia_stellata.yaml | 2 +- .../{gnomon => default}/align_sort_sa/main.nf | 0 .../ncbi/default/annot_builder/main.nf | 26 +- .../ncbi/default/annotwriter/main.nf | 10 +- .../ncbi/gnomon-training-iteration/main.nf | 30 +- .../gnomon-training-iteration/utilities.nf | 18 +- .../ncbi/gnomon/chainer_wnode/main.nf | 6 +- nf/subworkflows/ncbi/gnomon/diamond/main.nf | 112 +--- .../ncbi/gnomon/gnomon_biotype/main.nf | 10 +- .../ncbi/gnomon/gnomon_training/main.nf | 11 +- .../ncbi/gnomon/locus_link/main.nf | 116 ++++ nf/subworkflows/ncbi/gnomon/main.nf | 96 +++ .../ncbi/gnomon/prot_gnomon_prepare/main.nf | 6 + .../ncbi/gnomon/protein_filter/main.nf | 59 +- nf/subworkflows/ncbi/main.nf | 132 ++-- nf/subworkflows/ncbi/only_gnomon.nf | 16 +- .../ncbi/orthology/diamond_orthology/main.nf | 25 + .../extract_products_from_models/main.nf | 45 ++ .../ncbi/orthology/find_orthologs/main.nf | 170 +++++ nf/subworkflows/ncbi/orthology/main.nf | 43 ++ .../rnaseq_short/bam_bin_and_sort/main.nf | 6 +- .../rnaseq_short/bam_strandedness/main.nf | 6 +- .../rnaseq_short/convert_from_bam/main.nf | 12 +- nf/subworkflows/ncbi/rnaseq_short/main.nf | 78 +++ .../ncbi/rnaseq_short/rnaseq_collapse/main.nf | 2 +- .../ncbi/rnaseq_short/sra_qry/main.nf | 4 +- .../ncbi/rnaseq_short/star_index/main.nf | 4 +- .../ncbi/rnaseq_short/star_wnode/main.nf | 74 ++- nf/subworkflows/ncbi/setup/main.nf | 38 +- nf/subworkflows/ncbi/shared/diamond/main.nf | 107 +++ .../target_proteins/best_aligned_prot/main.nf | 9 +- nf/subworkflows/ncbi/target_proteins/main.nf | 37 ++ .../ncbi/target_proteins/miniprot/main.nf | 81 ++- .../ncbi/target_proteins/paf2asn/main.nf | 16 +- nf/subworkflows/ncbi/utilities.nf | 22 +- nf/ui.nf | 68 +- third_party_licenses/LICENSE_diamond | 622 ++++++++++++++++++ .../{LICENSE_bamtools => LICENSE_seqkit} | 5 +- ui/assets/config/docker_image.config | 2 +- ui/assets/config/executor/aws.config | 15 +- ui/assets/config/executor/ncbi-sge.config | 29 + ui/assets/config/process_resources.config | 33 +- ui/assets/default_task_params.yaml | 23 +- ui/egapx.py | 560 ++++++++++++++-- 46 files changed, 2322 insertions(+), 477 deletions(-) rename nf/subworkflows/ncbi/{gnomon => default}/align_sort_sa/main.nf (100%) create mode 100644 nf/subworkflows/ncbi/gnomon/locus_link/main.nf create mode 100644 nf/subworkflows/ncbi/gnomon/main.nf create mode 100644 nf/subworkflows/ncbi/orthology/diamond_orthology/main.nf create mode 100644 nf/subworkflows/ncbi/orthology/extract_products_from_models/main.nf create mode 100644 nf/subworkflows/ncbi/orthology/find_orthologs/main.nf create mode 100644 nf/subworkflows/ncbi/orthology/main.nf create mode 100644 nf/subworkflows/ncbi/rnaseq_short/main.nf create mode 100644 nf/subworkflows/ncbi/shared/diamond/main.nf create mode 100644 nf/subworkflows/ncbi/target_proteins/main.nf create mode 100644 third_party_licenses/LICENSE_diamond rename third_party_licenses/{LICENSE_bamtools => LICENSE_seqkit} (90%) create mode 100644 ui/assets/config/executor/ncbi-sge.config diff --git a/LICENSE b/LICENSE index 8a95065..d34a2eb 100644 --- a/LICENSE +++ b/LICENSE @@ -43,10 +43,15 @@ Authors: Dana-Farber Cancer Institute License: MIT License [https://github.com/lh3/miniprot/blob/master/LICENSE.txt] -Location: img/gp/third-party/bamtools -Authors: Derek Barnett, Erik Garrison, Gabor Marth, Michael Stromberg +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/pezmaster31/bamtools/blob/master/LICENSE] + [https://github.com/shenwei356/seqkit/blob/master/LICENSE] ================================================================================ diff --git a/examples/input_C_longicornis.yaml b/examples/input_C_longicornis.yaml index 208f080..78887a2 100644 --- a/examples/input_C_longicornis.yaml +++ b/examples/input_C_longicornis.yaml @@ -1,3 +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_query: 'txid2530218[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession]' +reads: txid2530218[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession] taxid: 2530218 \ No newline at end of file diff --git a/examples/input_Gavia_stellata.yaml b/examples/input_Gavia_stellata.yaml index 9196df1..ad08b5e 100644 --- a/examples/input_Gavia_stellata.yaml +++ b/examples/input_Gavia_stellata.yaml @@ -1,3 +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_query: 'txid37040[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession]' +reads: txid37040[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession] taxid: 37040 diff --git a/nf/subworkflows/ncbi/gnomon/align_sort_sa/main.nf b/nf/subworkflows/ncbi/default/align_sort_sa/main.nf similarity index 100% rename from nf/subworkflows/ncbi/gnomon/align_sort_sa/main.nf rename to nf/subworkflows/ncbi/default/align_sort_sa/main.nf diff --git a/nf/subworkflows/ncbi/default/annot_builder/main.nf b/nf/subworkflows/ncbi/default/annot_builder/main.nf index 5c37ea6..66393a9 100644 --- a/nf/subworkflows/ncbi/default/annot_builder/main.nf +++ b/nf/subworkflows/ncbi/default/annot_builder/main.nf @@ -30,11 +30,13 @@ workflow annot_builder { 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) = annot_builder_run('outdir', i[0], gencoll_asn, i[1], gnomon_file, genome_asn, params) + 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 } @@ -76,6 +78,7 @@ process annot_builder_main { stub: """ touch annot_builder_main.ini + echo 'main' > annot_builder_main.ini """ } @@ -137,6 +140,8 @@ process annot_builder_input { """ 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 """ } @@ -152,8 +157,10 @@ process annot_builder_run { path genome_asn, stageAs: 'genome/*' val params output: - path "${outdir}/*" - path "${outdir}/ACCEPT/accept.asn", optional: true + 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 @@ -165,6 +172,7 @@ process annot_builder_run { 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: """ @@ -174,7 +182,15 @@ process annot_builder_run { mkdir -p $outdir/REPORT mkdir -p $outdir/TEST - touch ${outdir}/annot_builder.log - touch ${outdir}/accept.asn + 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 + """ } diff --git a/nf/subworkflows/ncbi/default/annotwriter/main.nf b/nf/subworkflows/ncbi/default/annotwriter/main.nf index 3cd83be..9267e1f 100644 --- a/nf/subworkflows/ncbi/default/annotwriter/main.nf +++ b/nf/subworkflows/ncbi/default/annotwriter/main.nf @@ -17,17 +17,21 @@ process run_annotwriter { input: path accept_asn_file output: - path ('output/accept.gff') , emit: 'annoted_file' + path ('output/accept.gff'), emit: 'annoted_file' script: """ mkdir -p output - annotwriter -i ${accept_asn_file} -nogenbank -format gff3 -o output/accept.gff + 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 - touch output/accept.gff + echo "1" > output/accept.gff """ } diff --git a/nf/subworkflows/ncbi/gnomon-training-iteration/main.nf b/nf/subworkflows/ncbi/gnomon-training-iteration/main.nf index d30159c..82b2acc 100644 --- a/nf/subworkflows/ncbi/gnomon-training-iteration/main.nf +++ b/nf/subworkflows/ncbi/gnomon-training-iteration/main.nf @@ -1,6 +1,6 @@ #!/usr/bin/env nextflow nextflow.enable.dsl=2 -nextflow.preview.recursion=true +//nextflow.preview.recursion=true include { gnomon_training_iteration; gnomon_training_iteration as gnomon_training_iteration2; @@ -20,22 +20,21 @@ workflow gnomon_training_iterations { gnomon_softmask_lds2 gnomon_softmask_lds2_source gnomon_scaffolds - chainer_parameters - gnomon_parameters - gnomon_training_parameters + 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, chainer_parameters, gnomon_parameters, gnomon_training_parameters) + 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, chainer_parameters, gnomon_parameters, gnomon_training_parameters) + 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, chainer_parameters, gnomon_parameters, gnomon_training_parameters) + 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, chainer_parameters, gnomon_parameters, gnomon_training_parameters) + 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 @@ -84,14 +83,13 @@ workflow gnomon_training_iterations { gnomon_softmask_lds2 gnomon_softmask_lds2_source gnomon_scaffolds - chainer_parameters - gnomon_parameters - gnomon_training_parameters + 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, chainer_parameters, gnomon_parameters, gnomon_training_parameters) + gnomon_softmask_lds2_source, gnomon_scaffolds, max_intron, parameters) .times(4) emit: hmm_params_file = gnomon_training_iteration.out.hmm_params_file diff --git a/nf/subworkflows/ncbi/gnomon-training-iteration/utilities.nf b/nf/subworkflows/ncbi/gnomon-training-iteration/utilities.nf index 06e01fd..0bdb480 100644 --- a/nf/subworkflows/ncbi/gnomon-training-iteration/utilities.nf +++ b/nf/subworkflows/ncbi/gnomon-training-iteration/utilities.nf @@ -1,6 +1,6 @@ #!/usr/bin/env nextflow nextflow.enable.dsl=2 -nextflow.preview.recursion=true +// nextflow.preview.recursion=true include { chainer_wnode as chainer } from '../gnomon/chainer_wnode/main' include { gnomon_wnode } from '../gnomon/gnomon_wnode/main' @@ -20,14 +20,13 @@ workflow gnomon_training_iteration { gnomon_softmask_lds2 gnomon_softmask_lds2_source gnomon_scaffolds - chainer_parameters - gnomon_parameters - gnomon_training_parameters + 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, chainer_parameters) - gnomon_wnode(gnomon_scaffolds, chainer.out.chains, chainer.out.chains_slices, models_file, gnomon_softmask_lds2, gnomon_softmask_lds2_source, genome_asn, proteins_asn, gnomon_parameters) - gnomon_training(genome_asn, gnomon_wnode.out.outputs, gnomon_training_parameters) + 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 @@ -41,7 +40,6 @@ workflow gnomon_training_iteration { gnomon_softmask_lds2 = gnomon_softmask_lds2 gnomon_softmask_lds2_source = gnomon_softmask_lds2_source gnomon_scaffolds = gnomon_scaffolds - chainer_parameters = chainer_parameters - gnomon_parameters = gnomon_parameters - gnomon_training_parameters = gnomon_training_parameters + max_intron = max_intron + parameters = parameters } diff --git a/nf/subworkflows/ncbi/gnomon/chainer_wnode/main.nf b/nf/subworkflows/ncbi/gnomon/chainer_wnode/main.nf index e645d8c..478eaf8 100644 --- a/nf/subworkflows/ncbi/gnomon/chainer_wnode/main.nf +++ b/nf/subworkflows/ncbi/gnomon/chainer_wnode/main.nf @@ -3,7 +3,7 @@ nextflow.enable.dsl=2 include { merge_params } from '../../utilities' -include { run_align_sort } from '../align_sort_sa/main.nf' +include { run_align_sort } from '../../default/align_sort_sa/main.nf' split_count=16 @@ -145,8 +145,8 @@ process run_gpx_make_outputs { output: path "output/chains.*.out.gz", emit: 'chains' path "output/chains.*.out.gz.slices", emit: 'chains_slices' - path "output/evidence.*.out.gz", emit: 'evidence' - path "output/evidence.*.out.gz.slices", emit: 'evidence_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 diff --git a/nf/subworkflows/ncbi/gnomon/diamond/main.nf b/nf/subworkflows/ncbi/gnomon/diamond/main.nf index 0ed88c1..ad37a5c 100644 --- a/nf/subworkflows/ncbi/gnomon/diamond/main.nf +++ b/nf/subworkflows/ncbi/gnomon/diamond/main.nf @@ -1,30 +1,8 @@ #!/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 - * -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 { merge_params; to_map; shellSplit } from '../../utilities' +include { run_diamond_egap;} from '../../shared/diamond/main' workflow diamond_worker { @@ -35,92 +13,12 @@ workflow diamond_worker { swiss_prot_asn parameters // Map : extra parameter and parameter update main: - String diamond_egap_params = merge_params('-query-fmt seq-ids -subject-fmt seq-ids -output-prefix hits -ofmt seq-align-set', parameters, 'diamond') - // move out or above? - //swiss_prot_asn = fetch_swiss_prot_asn() - //swiss_prot_ids = get_swiss_prot_ids(swiss_prot_asn) + 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 } - - -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" - 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/ - 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} - - diamond_egap ${params} -asn-cache ./asncache/ -nogenbank -query ${gnomon_prot_ids} -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 - """ -} - - diff --git a/nf/subworkflows/ncbi/gnomon/gnomon_biotype/main.nf b/nf/subworkflows/ncbi/gnomon/gnomon_biotype/main.nf index 22adf6c..fd10c2a 100644 --- a/nf/subworkflows/ncbi/gnomon/gnomon_biotype/main.nf +++ b/nf/subworkflows/ncbi/gnomon/gnomon_biotype/main.nf @@ -15,7 +15,7 @@ workflow gnomon_biotype { parameters // Map : extra parameter and parameter update main: default_params = "" - effective_params = merge_params(default_params, parameters, 'gnomon_training') + 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 @@ -50,7 +50,12 @@ process run_gnomon_biotype { echo "${models_files.join('\n')}" > models.mft echo "prot_hits.asn" > prot_hits.mft echo "${splices_files.join('\n')}" > splices.mft - 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 + 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: """ @@ -59,3 +64,4 @@ process run_gnomon_biotype { touch output/biotypes.tsv """ } + diff --git a/nf/subworkflows/ncbi/gnomon/gnomon_training/main.nf b/nf/subworkflows/ncbi/gnomon/gnomon_training/main.nf index 4427ad9..bcb5957 100644 --- a/nf/subworkflows/ncbi/gnomon/gnomon_training/main.nf +++ b/nf/subworkflows/ncbi/gnomon/gnomon_training/main.nf @@ -7,32 +7,39 @@ 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, default_params) + 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 diff --git a/nf/subworkflows/ncbi/gnomon/locus_link/main.nf b/nf/subworkflows/ncbi/gnomon/locus_link/main.nf new file mode 100644 index 0000000..e4d3ffb --- /dev/null +++ b/nf/subworkflows/ncbi/gnomon/locus_link/main.nf @@ -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 + """ +} + diff --git a/nf/subworkflows/ncbi/gnomon/main.nf b/nf/subworkflows/ncbi/gnomon/main.nf new file mode 100644 index 0000000..5787e1b --- /dev/null +++ b/nf/subworkflows/ncbi/gnomon/main.nf @@ -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 +} diff --git a/nf/subworkflows/ncbi/gnomon/prot_gnomon_prepare/main.nf b/nf/subworkflows/ncbi/gnomon/prot_gnomon_prepare/main.nf index ba5db1e..715eddd 100644 --- a/nf/subworkflows/ncbi/gnomon/prot_gnomon_prepare/main.nf +++ b/nf/subworkflows/ncbi/gnomon/prot_gnomon_prepare/main.nf @@ -14,6 +14,9 @@ workflow 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 } @@ -23,6 +26,9 @@ process prot_gnomon_prepare_p { 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 diff --git a/nf/subworkflows/ncbi/gnomon/protein_filter/main.nf b/nf/subworkflows/ncbi/gnomon/protein_filter/main.nf index f07639a..7381ef6 100644 --- a/nf/subworkflows/ncbi/gnomon/protein_filter/main.nf +++ b/nf/subworkflows/ncbi/gnomon/protein_filter/main.nf @@ -2,32 +2,13 @@ nextflow.enable.dsl=2 + /* - *Execution of: - * /netmnt/vast01/gpi/prod/GPIPE_PROD/system/current/arch/x86_64/bin/gp_makeblastdb - -nogenbank - -asn-cache '' - -db ./spdb - -asnb swissprot.asnb - -dbtype prot - -title 'BLASTdb used for naming tasks in GPipe' - - * /netmnt/vast01/gpi/regr/GPIPE_REGR1/system/2024-03-27.prod.build25780/bin/align_sort - * -ifmt seq-align-set -input-manifest /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/protein_filter.8201942/inp/blast_align.mft - * -k query,query_start,-query_end,query_strand,subject,subject_start,-subject_end,subject_strand,-num_ident,gap_count - * -o /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/protein_filter.8201942/var/blast_align_sorted.asnb - * -tmp /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/protein_filter.8201942/var - * -nogenbank -limit-mem 13G - * /netmnt/vast01/gpi/regr/GPIPE_REGR1/system/2024-03-27.prod.build25780/bin/protein_filter - * -lds2 /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/prot_gnomon_prepare.8202002/out/LDS2 - * -asn-cache /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/sequence_cache - * -filter 'pct_coverage >= 50' - * -input /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/protein_filter.8201942/var/blast_align_sorted.asnb - * -nr-path /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/create_nr_blast_db.8200792/out/blastdb - * -output /netmnt/vast01/gpi/regr/GPIPE_REGR1/data00/Gavia_stellata/GP37025.85624/846757/protein_filter.8201942/out/blast.asn - * -taxid 37040 + * 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' @@ -36,49 +17,41 @@ workflow best_protein_hits { gnomon_prot_asn swiss_prot_asn prot_alignments - taxid parameters // Map : extra parameter and parameter update main: - String align_sort_params = merge_params('-nogenbank', parameters, 'align_sort') - String protein_filter_params = merge_params('-nogenbank', parameters, 'protein_filter') + 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(gnomon_prot_asn, swiss_prot_asn, prot_alignments, taxid, align_sort_params, protein_filter_params) + run_protein_filter_replacement(gnomon_prot_asn, swiss_prot_asn, prot_alignments, align_filter_params, align_sort_params) emit: - alignments = run_protein_filter.out + alignments = run_protein_filter_replacement.out } - -process run_protein_filter { +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 taxid + val align_filter_params val align_sort_params - val protein_filter_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 ./output - mkdir ./work - mkdir ./spdb - - /netmnt/vast01/gpi/prod/GPIPE_PROD/system/current/arch/x86_64/bin/gp_makeblastdb -nogenbank -asn-cache ./asncache/ -db ./spdb/spdb -asnb ${swiss_prot_asn} -dbtype prot -title 'BLASTdb used for naming tasks in GPipe' + mkdir -p ./output - align_sort $align_sort_params -asn-cache ./asncache/ -input $input_prot_alignments -o ./sorted_prot_alignments.asnb -tmp ./work/ + 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 - protein_filter $protein_filter_params -asn-cache ./asncache/ -taxid $taxid -input ./sorted_prot_alignments.asnb -output ./output/best_protein_hits.asnb -nr-path ./spdb/spdb - - rm -rf ./work """ stub: diff --git a/nf/subworkflows/ncbi/main.nf b/nf/subworkflows/ncbi/main.nf index de959bd..fe19bd1 100644 --- a/nf/subworkflows/ncbi/main.nf +++ b/nf/subworkflows/ncbi/main.nf @@ -4,35 +4,25 @@ 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 { sra_query } from './rnaseq_short/sra_qry/main' -include { fetch_sra_fasta } from './rnaseq_short/fetch_sra_fasta/main' -include { star_index } from './rnaseq_short/star_index/main' -include { star_wnode_simplified as star_simplified; star_wnode as star } from './rnaseq_short/star_wnode/main' -include { bam_strandedness } from './rnaseq_short/bam_strandedness/main' -include { bam_bin_and_sort } from './rnaseq_short/bam_bin_and_sort/main' -include { bam2asn } from './rnaseq_short/convert_from_bam/main' -include { rnaseq_collapse } from './rnaseq_short/rnaseq_collapse/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 { miniprot } from './target_proteins/miniprot/main' -include { align_filter_sa } from './target_proteins/align_filter_sa/main' -include { best_aligned_prot } from './target_proteins/best_aligned_prot/main' -include { paf2asn } from './target_proteins/paf2asn/main' -include { run_align_sort} from './gnomon/align_sort_sa/main' -include { gnomon_training_iterations; gnomon_no_training } from './gnomon-training-iteration/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 @@ -42,71 +32,48 @@ workflow egapx { 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: - def (scaffolds, gencoll_asn, unpacked_genome, genome_asn) = setup_genome(genome, organelles, task_params.get('setup', [:])) + 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', [:])) - miniprot(unpacked_genome, unpacked_proteins, task_params.get('miniprot', [:])) - paf2asn(genome_asn, proteins_asn, miniprot.out.miniprot_file, task_params.get('paf2asn', [:])) - best_aligned_prot(genome_asn, proteins_asn, paf2asn.out.asn_file, 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', [:])) - protein_alignments = 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" ) + 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 = [] - // Satisfy quirks of Nextflow compiler - def reads_query1 = reads_query - def reads_ids1 = reads_ids - // Conditional code on SRA reads source if (reads_query || reads_ids || reads) { - def index = star_index(unpacked_genome, 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, task_params.get('star_wnode', [:])) - } else { - sra_metadata = reads_metadata - (ch_align, ch_align_index) = star_simplified(scaffolds, reads, genome_asn, index, 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, 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', [:])) - rnaseq_alignments = rnaseq_collapse.out.alignments + 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) @@ -118,41 +85,32 @@ workflow egapx { // GNOMON + def gnomon_models = [] 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 | collect - c = b | branch { n -> - exact: n[0] == tax_id.toString() - return n[1] - closest: n[0] != tax_id.toString() - return n[1] - } - hmm_params_closest = gnomon_training_iterations(c.closest, genome_asn, proteins_asn ,alignments , /* evidence_denylist */ [], /* gap_fill_allowlist */ [], - /* trusted_genes */ [], scaffolds, softmask, - softmask, scaffolds, task_params.get('chainer', [:]), task_params.get('gnomon', [:]), task_params.get('gnomon_training', [:])) - hmm_params_exact = gnomon_no_training (c.exact) - tmp_channel1 = Channel.of() - tmp_channel2 = tmp_channel1.concat(hmm_params_closest) - tmp_channel3 = tmp_channel2.concat(hmm_params_exact) - effective_hmm = tmp_channel3 | last + 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) + } } - 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 + annotwriter(accept_annot_file, [:]) + annotwriter.out.annoted_file - // prot_gnomon_prepare(models, task_params.get('prot_gnomon_prepare', [:])) - - 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 annot_builder_output = annot_builder.out.outputs + // locus = post_gnomon_plane.out.locus } diff --git a/nf/subworkflows/ncbi/only_gnomon.nf b/nf/subworkflows/ncbi/only_gnomon.nf index 524fa86..c18e512 100644 --- a/nf/subworkflows/ncbi/only_gnomon.nf +++ b/nf/subworkflows/ncbi/only_gnomon.nf @@ -5,13 +5,12 @@ 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 './gnomon/align_sort_sa/main' +include { run_align_sort} from './default/align_sort_sa/main' params.intermediate = false @@ -29,6 +28,7 @@ workflow only_gnomon { // 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 @@ -63,17 +63,7 @@ workflow only_gnomon { // 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', [:])) + chainer(alignments, hmm_params, /* 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 diff --git a/nf/subworkflows/ncbi/orthology/diamond_orthology/main.nf b/nf/subworkflows/ncbi/orthology/diamond_orthology/main.nf new file mode 100644 index 0000000..8efd88d --- /dev/null +++ b/nf/subworkflows/ncbi/orthology/diamond_orthology/main.nf @@ -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 +} diff --git a/nf/subworkflows/ncbi/orthology/extract_products_from_models/main.nf b/nf/subworkflows/ncbi/orthology/extract_products_from_models/main.nf new file mode 100644 index 0000000..d6b68e8 --- /dev/null +++ b/nf/subworkflows/ncbi/orthology/extract_products_from_models/main.nf @@ -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 + """ +} diff --git a/nf/subworkflows/ncbi/orthology/find_orthologs/main.nf b/nf/subworkflows/ncbi/orthology/find_orthologs/main.nf new file mode 100644 index 0000000..475dd3f --- /dev/null +++ b/nf/subworkflows/ncbi/orthology/find_orthologs/main.nf @@ -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 + +*/ diff --git a/nf/subworkflows/ncbi/orthology/main.nf b/nf/subworkflows/ncbi/orthology/main.nf new file mode 100644 index 0000000..2ce9fd5 --- /dev/null +++ b/nf/subworkflows/ncbi/orthology/main.nf @@ -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 +} + diff --git a/nf/subworkflows/ncbi/rnaseq_short/bam_bin_and_sort/main.nf b/nf/subworkflows/ncbi/rnaseq_short/bam_bin_and_sort/main.nf index 9a7ddff..ba3e9c5 100644 --- a/nf/subworkflows/ncbi/rnaseq_short/bam_bin_and_sort/main.nf +++ b/nf/subworkflows/ncbi/rnaseq_short/bam_bin_and_sort/main.nf @@ -26,6 +26,7 @@ workflow bam_bin_and_sort { process calc_assembly_sizes { + label 'large_disk' input: path bam_files output: @@ -127,6 +128,7 @@ process bam_bin { process merge_prepare { + label 'large_disk' input: path runs output: @@ -168,6 +170,7 @@ process merge_prepare { process merge { label 'big_job' + label 'large_disk' input: path merge_args path bins @@ -181,4 +184,5 @@ process merge { stub: """ touch 1.bam - """} + """ +} diff --git a/nf/subworkflows/ncbi/rnaseq_short/bam_strandedness/main.nf b/nf/subworkflows/ncbi/rnaseq_short/bam_strandedness/main.nf index 1b91c18..a59193d 100644 --- a/nf/subworkflows/ncbi/rnaseq_short/bam_strandedness/main.nf +++ b/nf/subworkflows/ncbi/rnaseq_short/bam_strandedness/main.nf @@ -21,9 +21,8 @@ workflow bam_strandedness { } - - process rnaseq_divide_by_strandedness { + label 'large_disk' input: path bam_list path metadata_file @@ -47,5 +46,4 @@ process rnaseq_divide_by_strandedness { touch output/stranded.list touch output/unstranded.list """ - } - +} diff --git a/nf/subworkflows/ncbi/rnaseq_short/convert_from_bam/main.nf b/nf/subworkflows/ncbi/rnaseq_short/convert_from_bam/main.nf index e59b733..1dbbcb0 100644 --- a/nf/subworkflows/ncbi/rnaseq_short/convert_from_bam/main.nf +++ b/nf/subworkflows/ncbi/rnaseq_short/convert_from_bam/main.nf @@ -20,19 +20,25 @@ workflow bam2asn { 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' - path "${prefix}.align_counts.txt", emit: 'keylist' + 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 """ - tmpdir=`mktemp -d` 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 diff --git a/nf/subworkflows/ncbi/rnaseq_short/main.nf b/nf/subworkflows/ncbi/rnaseq_short/main.nf new file mode 100644 index 0000000..a69c790 --- /dev/null +++ b/nf/subworkflows/ncbi/rnaseq_short/main.nf @@ -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 +} diff --git a/nf/subworkflows/ncbi/rnaseq_short/rnaseq_collapse/main.nf b/nf/subworkflows/ncbi/rnaseq_short/rnaseq_collapse/main.nf index 5bdaae9..07ea393 100644 --- a/nf/subworkflows/ncbi/rnaseq_short/rnaseq_collapse/main.nf +++ b/nf/subworkflows/ncbi/rnaseq_short/rnaseq_collapse/main.nf @@ -14,7 +14,7 @@ workflow rnaseq_collapse { 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 -rank-counts-precalculated", parameters, 'rnaseq_collapse') + 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) diff --git a/nf/subworkflows/ncbi/rnaseq_short/sra_qry/main.nf b/nf/subworkflows/ncbi/rnaseq_short/sra_qry/main.nf index f488c90..443d74b 100644 --- a/nf/subworkflows/ncbi/rnaseq_short/sra_qry/main.nf +++ b/nf/subworkflows/ncbi/rnaseq_short/sra_qry/main.nf @@ -37,6 +37,7 @@ process run_sra_query { #!/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 @@ -76,7 +77,8 @@ process run_sra_query { line = line.strip() if not line: continue - parts = line.split(",") + 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"]: diff --git a/nf/subworkflows/ncbi/rnaseq_short/star_index/main.nf b/nf/subworkflows/ncbi/rnaseq_short/star_index/main.nf index fa9f3b2..10d5d68 100644 --- a/nf/subworkflows/ncbi/rnaseq_short/star_index/main.nf +++ b/nf/subworkflows/ncbi/rnaseq_short/star_index/main.nf @@ -5,6 +5,7 @@ include { merge_params } from '../../utilities' process build_index { + label 'big_job' input: path genome_file val parameters @@ -14,7 +15,8 @@ process build_index { 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 + STAR $parameters --runMode genomeGenerate --genomeDir $out_dir --genomeFastaFiles $genome_file + chmod a+rx $out_dir """ stub: diff --git a/nf/subworkflows/ncbi/rnaseq_short/star_wnode/main.nf b/nf/subworkflows/ncbi/rnaseq_short/star_wnode/main.nf index e52d088..47a5cda 100644 --- a/nf/subworkflows/ncbi/rnaseq_short/star_wnode/main.nf +++ b/nf/subworkflows/ncbi/rnaseq_short/star_wnode/main.nf @@ -4,45 +4,70 @@ nextflow.enable.dsl=2 include { merge_params } from '../../utilities' -process exec { +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 parameters + val max_intron + val parameters output: - path "${assembly}-${sampleID}-Aligned.out.Sorted.bam", emit: 'align' - path "${assembly}-${sampleID}-Aligned.out.Sorted.bam.bai", emit: 'align_index' + 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: - assembly=genome_file.baseName.toString().replaceFirst(/\.(fa(sta)?|asn[bt]?)$/, "") + 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 "${fasta_rna_file[0]}" - #echo "${fasta_rna_file[1]}" - echo "$query_str" - #echo "" - ##echo "" > jobfile echo "" > jobfile star=\$(which star-with-filter) samtools=\$(which samtools) fastq=\$(which fasterq-dump) - star_wnode $parameters -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 + ${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: - assembly=genome_file.baseName.toString().replaceFirst(/\.(fa(sta)?|asn[bt]?)$/, "") + 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 @@ -54,19 +79,17 @@ 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 + 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: - 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 \"" - default_params = "-cpus-per-worker 4 -csi-threshold 512000000 -max-intron 1200000 -star-params $star_params -preserve-star-logs" - effective_params = merge_params(default_params, parameters, 'star_wnode') - // println("Effective parameters: $effective_params") - exec(seqid_list, reads, genome_file, star_index, effective_params) + 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 = exec.out.align - align_index = exec.out.align_index + align = run_star.out.align + align_index = run_star.out.align_index } @@ -74,18 +97,17 @@ 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 + 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 =~ /\/([A-Za-z0-9]+).{1,2}$/ + def m = read =~ /\/([^\/]+).[12](.gz)?$/ [m[0][1], read] }.groupTuple() - 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 \"" - default_params = "-cpus-per-worker 4 -csi-threshold 512000000 -max-intron 1200000 -star-params $star_params -preserve-star-logs" - effective_params = merge_params(default_params, parameters, 'star_wnode') - exec(seqid_list, filePairs, genome_file, star_index, effective_params) + 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 diff --git a/nf/subworkflows/ncbi/setup/main.nf b/nf/subworkflows/ncbi/setup/main.nf index 21eb9b0..15b6fa2 100644 --- a/nf/subworkflows/ncbi/setup/main.nf +++ b/nf/subworkflows/ncbi/setup/main.nf @@ -9,24 +9,30 @@ workflow setup_genome { organelles parameters // Map : extra parameter and parameter update main: - get_genome_info(genome, organelles) + 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)?$/, "") @@ -38,8 +44,11 @@ process get_genome_info { 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}" + # echo "need_zcat: ${need_zcat}, out_fasta: ${out_fasta}" mkdir -p ${genome_dir} mkdir -p ${fasta_dir} if [[ ${need_zcat} == true ]]; then @@ -54,13 +63,24 @@ process get_genome_info { # 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_create -unplaced list.seqids -unplaced-fmt seq-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: @@ -73,14 +93,18 @@ process get_genome_info { 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" """ } @@ -94,6 +118,7 @@ workflow setup_proteins { emit: unpacked_proteins = convert_proteins.out.unpacked_proteins proteins_asn = convert_proteins.out.proteins_asn + proteins_asnb = convert_proteins.out.proteins_asnb } @@ -103,6 +128,7 @@ process convert_proteins { 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)?$/, "") @@ -112,6 +138,7 @@ process convert_proteins { 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} @@ -121,6 +148,7 @@ process convert_proteins { 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: @@ -130,12 +158,14 @@ process convert_proteins { 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 """ } diff --git a/nf/subworkflows/ncbi/shared/diamond/main.nf b/nf/subworkflows/ncbi/shared/diamond/main.nf new file mode 100644 index 0000000..1ef6801 --- /dev/null +++ b/nf/subworkflows/ncbi/shared/diamond/main.nf @@ -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 + * -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/ + 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 + """ +} + + diff --git a/nf/subworkflows/ncbi/target_proteins/best_aligned_prot/main.nf b/nf/subworkflows/ncbi/target_proteins/best_aligned_prot/main.nf index f98a8bc..5e7a7ef 100644 --- a/nf/subworkflows/ncbi/target_proteins/best_aligned_prot/main.nf +++ b/nf/subworkflows/ncbi/target_proteins/best_aligned_prot/main.nf @@ -26,9 +26,9 @@ workflow best_aligned_prot { process run_best_aligned_prot { input: - path (genome, stageAs: 'LDS_Index/genome.asnt') - path (proteins, stageAs: 'LDS_Index/proteins.asnt') - path alignment_asn_file + 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: @@ -39,10 +39,11 @@ process run_best_aligned_prot { """ mkdir -p output lds2_indexer -source LDS_Index - echo "$alignment_asn_file" > align.mft + 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 diff --git a/nf/subworkflows/ncbi/target_proteins/main.nf b/nf/subworkflows/ncbi/target_proteins/main.nf new file mode 100644 index 0000000..6e3d705 --- /dev/null +++ b/nf/subworkflows/ncbi/target_proteins/main.nf @@ -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 +} diff --git a/nf/subworkflows/ncbi/target_proteins/miniprot/main.nf b/nf/subworkflows/ncbi/target_proteins/miniprot/main.nf index 74763c1..5f54118 100644 --- a/nf/subworkflows/ncbi/target_proteins/miniprot/main.nf +++ b/nf/subworkflows/ncbi/target_proteins/miniprot/main.nf @@ -5,43 +5,104 @@ 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: - default_params = "-t 8" - def value = parameters.get('miniprot', "") - value = value.replaceFirst("-cpu-count", "-t") - value = value.replaceFirst("-max-intron", "-G") - parameters['miniprot'] = value - effective_params = merge_params(default_params, parameters, 'miniprot') - run_miniprot(fasta_genome_file, fasta_proteins_file, effective_params) + // 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/aligns.paf'), emit: 'miniprot_file' + 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 ${parameters} ${fasta_genome_file} ${fasta_proteins_file} > output/aligns.paf + 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/aligns.paf + touch output/${paf_name} """ } diff --git a/nf/subworkflows/ncbi/target_proteins/paf2asn/main.nf b/nf/subworkflows/ncbi/target_proteins/paf2asn/main.nf index 0b5f291..ce33e59 100644 --- a/nf/subworkflows/ncbi/target_proteins/paf2asn/main.nf +++ b/nf/subworkflows/ncbi/target_proteins/paf2asn/main.nf @@ -22,22 +22,26 @@ workflow paf2asn { process run_paf2asn { + label 'long_job' input: - path (genome, stageAs: 'LDS_Index/genome.asnt') - path (proteins, stageAs: 'LDS_Index/proteins.asnt') - path paf_file + 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/align.asn', emit: 'asn_file' + path 'output/*.asn', emit: 'asn_file' script: + def asn_name = paf_file.baseName.toString() + ".asn" """ mkdir -p output lds2_indexer -source LDS_Index - paf2asn ${parameters} -lds2 LDS_Index/lds2.db -nogenbank -input ${paf_file} -o output/align.asn + 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/align.asn + touch output/${asn_name} """ } diff --git a/nf/subworkflows/ncbi/utilities.nf b/nf/subworkflows/ncbi/utilities.nf index cbb5135..57c66a6 100644 --- a/nf/subworkflows/ncbi/utilities.nf +++ b/nf/subworkflows/ncbi/utilities.nf @@ -44,18 +44,18 @@ def List shellSplit(CharSequence s) { // Convert a parameter list into a map def Map to_map(List list ) { - map = [:] - s = list.size() - i = 0 + def map = [:] + def s = list.size() + def i = 0 while (i < s) { - elem = list.get(i) + def elem = list.get(i) i = i + 1 if (elem.size() > 0 && elem[0] == '-') { if (i < s) { - val = list.get(i) - if (val.size() > 0 && (val[0] != '-' || (val[0] == '-' && val.contains(' ')))) + def val = list.get(i) + if ( val.size() > 0 && (val[0] != '-' || val.contains(' ')) ) { map[elem] = val i = i + 1 @@ -64,13 +64,13 @@ def Map to_map(List list ) } } else { map[elem] = "" - } + } } else { - println("Error: parameter string not well formed") - return map + println("Error: parameter string not well formed, map ${map}, elem ${elem}, i ${i}, s ${s}") + return map } } - return map + return map } @@ -102,7 +102,7 @@ def merge_params(default_params, parameters, section_name) l << quote(value) } } - + return l.join(" ") } diff --git a/nf/ui.nf b/nf/ui.nf index 8742883..bd8506c 100644 --- a/nf/ui.nf +++ b/nf/ui.nf @@ -15,6 +15,7 @@ process export { input: path out_files path annot_builder_output, stageAs: 'annot_builder_output/*' + // path locus output: path "*", includeInputs: true script: @@ -40,53 +41,48 @@ workflow { 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") - print(genome) - println("proteins") - print(proteins) - println("reads_query") - print(reads_query) - println("reads_ids") - print(reads_ids) - println("reads") - print(reads) - println("reads_metadata") - print(reads_metadata) - println("organelles") - print(organelles) - println("tax_id") - print(tax_id) - println("hmm_params") - print(hmm_params) - println("softmask") - print(softmask) - println("task_params") - print(task_params) - - println("rnaseq_alignments") - print(rnaseq_alignments) - println("protein_alignments") - print(protein_alignments) - println("func_name") - print(func_name) - + 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') { - print('in gnomon block') - only_gnomon(genome, proteins, rnaseq_alignments, protein_alignments, organelles, tax_id, hmm_params, softmask, 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 { - print('in egapx block') - egapx(genome, proteins, reads_query, reads_ids, reads, reads_metadata, organelles, tax_id, hmm_params, softmask, task_params) + 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) } - // Export egapx results } diff --git a/third_party_licenses/LICENSE_diamond b/third_party_licenses/LICENSE_diamond new file mode 100644 index 0000000..0a2daba --- /dev/null +++ b/third_party_licenses/LICENSE_diamond @@ -0,0 +1,622 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU 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 + diff --git a/third_party_licenses/LICENSE_bamtools b/third_party_licenses/LICENSE_seqkit similarity index 90% rename from third_party_licenses/LICENSE_bamtools rename to third_party_licenses/LICENSE_seqkit index eaee1fd..590e25d 100644 --- a/third_party_licenses/LICENSE_bamtools +++ b/third_party_licenses/LICENSE_seqkit @@ -1,6 +1,6 @@ -The MIT License +The MIT License (MIT) -Copyright (c) 2009-2010 Derek Barnett, Erik Garrison, Gabor Marth, Michael Stromberg +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 @@ -19,4 +19,3 @@ 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. - diff --git a/ui/assets/config/docker_image.config b/ui/assets/config/docker_image.config index 26abebf..203e80b 100644 --- a/ui/assets/config/docker_image.config +++ b/ui/assets/config/docker_image.config @@ -1 +1 @@ -process.container = 'ncbi/egapx:latest' +process.container = '737128524250.dkr.ecr.us-east-2.amazonaws.com/ncbi-egapx:latest' \ No newline at end of file diff --git a/ui/assets/config/executor/aws.config b/ui/assets/config/executor/aws.config index 3b82227..8fd958e 100644 --- a/ui/assets/config/executor/aws.config +++ b/ui/assets/config/executor/aws.config @@ -1,5 +1,16 @@ -process.executor = 'awsbatch' -process.queue = 'egapx-small-and-medium-ds' +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' diff --git a/ui/assets/config/executor/ncbi-sge.config b/ui/assets/config/executor/ncbi-sge.config new file mode 100644 index 0000000..41daf3b --- /dev/null +++ b/ui/assets/config/executor/ncbi-sge.config @@ -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 + } +} diff --git a/ui/assets/config/process_resources.config b/ui/assets/config/process_resources.config index a7e81db..efdf076 100644 --- a/ui/assets/config/process_resources.config +++ b/ui/assets/config/process_resources.config @@ -4,7 +4,9 @@ process { memory = 60.GB cpus = 7 - time = 3.h + time = 6.h + errorStrategy = 'retry' + maxRetries = 3 withLabel: 'big_job' { memory = 120.GB @@ -17,6 +19,33 @@ process { } withLabel: 'long_job' { - time = 6.h + 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 + } + } + } + +} diff --git a/ui/assets/default_task_params.yaml b/ui/assets/default_task_params.yaml index 145e28d..9569214 100644 --- a/ui/assets/default_task_params.yaml +++ b/ui/assets/default_task_params.yaml @@ -37,21 +37,22 @@ tasks: 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 -rank-counts-precalculated + 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 -max-intron 600000 -star-params - '--alignSJoverhangMin 8 --outFilterMultimapNmax 200 --outFilterMismatchNmax + 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' - -preserve-star-logs + 'NH HI AS nM NM MD jM jI XS MC' --outSAMprimaryFlag AllBestScore --outFilterMultimapScoreRange + 50 --seedSearchStartLmax 15 --limitOutSAMoneReadBytes 1000000 --outSJtype None miniprot: - miniprot: -t 31 -p 0.4 --outs=0.4 -G 600000 + split_proteins: -n 100000 + miniprot: -t 31 -p 0.4 --outs=0.4 paf2asn: paf2asn: -prosplign-refinement best_aligned_prot: @@ -61,4 +62,10 @@ tasks: 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: -maxintron 1200000 -asn -b + 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 diff --git a/ui/egapx.py b/ui/egapx.py index 1f822ad..490f0a3 100755 --- a/ui/egapx.py +++ b/ui/egapx.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # requires pip install pyyaml - +# import shlex import shutil import sys @@ -9,33 +9,181 @@ 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") - parser.add_argument("filename", help="YAML file with input: section with at least genome: and reads: parameters") - parser.add_argument("-o", "--output", help="Output path", required=True, default="") + 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: @@ -57,8 +205,8 @@ def convert_value(value): 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): - # do not convert - this is a URL or empty string + 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()) @@ -78,40 +226,119 @@ def convert_paths(run_inputs): run_inputs['output'] = convert_value(run_inputs['output']) -def generate_reads_metadata(run_inputs): - "Generate reads metadata file with minimal information - paired/unpaired and valid for existing libraries" +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 None - output = run_inputs['output'] + return prefixes = defaultdict(list) - with tempfile.NamedTemporaryFile(mode='w', delete=False, dir=output, prefix='egapx_reads_metadata_', suffix='.tsv') as f: - for rf in run_inputs['input']['reads']: - mo = re.match(r'([A-Za-z0-9]+)([^A-Za-z0-9].*)', Path(rf).parts[-1]) - if mo: - prefixes[mo.group(1)].append(mo.group(2)) - for k, v in prefixes.items(): - 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 - return f.name - - -def validate_params(run_inputs): - "Validate input parameters" + 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'] - success = True - has_genome = 'genome' in inputs + + 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 - has_taxid = 'taxid' in inputs - has_proteins = 'proteins' in inputs or ('taxid' in inputs and get_closest_protein_bag(inputs['taxid'])) - if not has_genome or not has_taxid or not (has_rnaseq or has_proteins): - print("Missing parameter: 'genome', 'taxid', and either 'proteins', or 'reads' should be specified") - print(" proteins can be indirectly specified by 'taxid'") - success = False - return success + 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): @@ -131,6 +358,64 @@ def manage_workdir(args): 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") @@ -171,13 +456,55 @@ def get_config(script_directory, args): 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 '' - taxon_str = str(taxid) - 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/target_proteins/taxid.list") + taxids_file = get_tax_file("target_proteins", "taxid.list") taxids_list = [] for line in taxids_file: line = line.decode("utf-8").strip() @@ -188,12 +515,7 @@ def get_closest_protein_bag(taxid): t = parts[0] taxids_list.append(int(t)) - 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"]) + lineage = get_lineage(taxid) best_taxid = None best_score = 0 @@ -208,9 +530,75 @@ def get_closest_protein_bag(taxid): 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 f'https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/target_proteins/{best_taxid}.faa.gz' + 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]): @@ -255,6 +643,26 @@ def merge_params(task_params, run_inputs): 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 @@ -263,6 +671,28 @@ def main(argv): # 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) @@ -272,22 +702,19 @@ def main(argv): # 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'))) - # Check for proteins input and if empty or no input at all, add closest protein bag - if 'proteins' not in run_inputs['input'] and 'taxid' in run_inputs['input']: - run_inputs['input']['proteins'] = get_closest_protein_bag(run_inputs['input']['taxid']) + if not expand_and_validate_params(run_inputs): + return 1 # Command line overrides manifest input if args.output: run_inputs['output'] = args.output - if not validate_params(run_inputs): - return 1 # Convert inputs to absolute paths convert_paths(run_inputs) @@ -295,8 +722,19 @@ def main(argv): # Create output directory if needed os.makedirs(run_inputs['output'], exist_ok=True) - # Add reads_metadata.tsv file - generate_reads_metadata(run_inputs) + 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) @@ -323,7 +761,7 @@ def main(argv): 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"] + 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: @@ -344,16 +782,24 @@ def main(argv): 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("To resume execution, run:") - nf_cmd.append("-resume") - print(" ".join(map(str, nf_cmd))) + 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) From 52aaa080c1332fcb477f6ab80ef182eb8f2075a9 Mon Sep 17 00:00:00 2001 From: "Strope, Pooja" Date: Thu, 25 Jul 2024 17:55:23 -0400 Subject: [PATCH 2/4] update from prod --- nf/subworkflows/ncbi/only_gnomon.nf | 13 ++++++++++++- ui/assets/config/docker_image.config | 3 ++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/nf/subworkflows/ncbi/only_gnomon.nf b/nf/subworkflows/ncbi/only_gnomon.nf index c18e512..3544dba 100644 --- a/nf/subworkflows/ncbi/only_gnomon.nf +++ b/nf/subworkflows/ncbi/only_gnomon.nf @@ -5,6 +5,7 @@ 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' @@ -63,7 +64,17 @@ workflow only_gnomon { // GNOMON - chainer(alignments, hmm_params, /* evidence_denylist */ [], /* gap_fill_allowlist */ [], scaffolds, /* trusted_genes */ [], genome_asn, proteins_asn, task_params.get('chainer', [:])) + 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 diff --git a/ui/assets/config/docker_image.config b/ui/assets/config/docker_image.config index 203e80b..17f1797 100644 --- a/ui/assets/config/docker_image.config +++ b/ui/assets/config/docker_image.config @@ -1 +1,2 @@ -process.container = '737128524250.dkr.ecr.us-east-2.amazonaws.com/ncbi-egapx:latest' \ No newline at end of file +#process.container = '737128524250.dkr.ecr.us-east-2.amazonaws.com/ncbi-egapx:latest' +process.container = 'ncbi/egapx:0.2-alpha' From ac29bd5baebc02defd9f108ce75957c154ce2930 Mon Sep 17 00:00:00 2001 From: Pooja Strope Date: Thu, 25 Jul 2024 18:01:45 -0400 Subject: [PATCH 3/4] Update docker_image.config --- ui/assets/config/docker_image.config | 1 - 1 file changed, 1 deletion(-) diff --git a/ui/assets/config/docker_image.config b/ui/assets/config/docker_image.config index 17f1797..aa41657 100644 --- a/ui/assets/config/docker_image.config +++ b/ui/assets/config/docker_image.config @@ -1,2 +1 @@ -#process.container = '737128524250.dkr.ecr.us-east-2.amazonaws.com/ncbi-egapx:latest' process.container = 'ncbi/egapx:0.2-alpha' From a886af6c8179a0949427fca152dfc2e2b2d359e5 Mon Sep 17 00:00:00 2001 From: "Strope, Pooja" Date: Thu, 25 Jul 2024 18:34:49 -0400 Subject: [PATCH 4/4] protein sets posted --- README.md | 152 ++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 126 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index d46fa65..08bc731 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,14 @@ EGAPx is the publicly accessible version of the updated NCBI [Eukaryotic Genome 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 for most vertebrates (mammals, sauropsids, ray-finned fishes), hymenoptera, diptera, lepidoptera and choleoptera. 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. +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. @@ -41,23 +48,46 @@ Notes: Input to EGAPx is in the form of a YAML file. -- The following two are the _required_ key-value pairs for the input 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). -- The following are the _optional_ key-value pairs for the input file: + - RNA-seq data can be supplied in any one of the following ways: - - RNA-seq data. Use one of the following options: ``` - reads: [ array of paths to reads FASTA files] - reads_ids: [ array of SRA run ids ] - reads_query: query for reads SRA + 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 headers need to be in the following format: ``` + head SRR8506572_1.fasta| grep ">" + >SRR8506572.1.1 + >SRR8506572.2.1 + + head SRR8506572_2.fasta| grep ">" + >SRR8506572.1.2 + >SRR8506572.2.2 + + head SRR8506572_2.fastq| grep "@" + @SRR8506572.1.2 + @SRR8506572.2.2 + + head SRR8506572_1.fastq| grep "@" + @SRR8506572.1.1 + @SRR8506572.2.1 + ``` + + - 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. ``` @@ -86,19 +116,19 @@ Input to EGAPx is in the form of a YAML file. - https://ftp.ncbi.nlm.nih.gov/genomes/TOOLS/EGAP/data/Dermatophagoides_farinae_small/SRR9005248.2 ``` -- To specify an array of NCBI SRA datasets using `reads_ids:` +- To specify an array of NCBI SRA datasets: ``` - reads_ids: + reads: - SRR8506572 - SRR9005248 ``` -- To specify an SRA entrez query using `reads_query:` +- To specify an SRA entrez query: ``` - reads_query: 'txid6954[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession] AND (SRR8506572[Accession] OR SRR9005248[Accession] )' + reads: 'txid6954[Organism] AND biomol_transcript[properties] NOT SRS024887[Accession] AND (SRR8506572[Accession] OR SRR9005248[Accession] )' ``` - **Note:** Both the above examples `reads_ids` and `reads_query` will have more RNA-seq data than the `input_D_farinae_small.yaml` example. To make sure the `reads_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 use the `reads_ids` option. + **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. @@ -144,40 +174,57 @@ Input to EGAPx is in the form of a YAML file. - 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 slurm` for using SLURM in your HPC. + - 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 ``` - $ ./egapx.py -h - + $ 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] [-e EXECUTOR] [-c CONFIG_DIR] [-o OUTPUT] [-w WORKDIR] [-r REPORT] [-n] [-q] [-v] [-fn FUNC_NAME] filename + 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 - positional arguments: - filename YAML file with input: section with at least genome: and reads: parameters - optional arguments: -h, --help show this help message and exit -e EXECUTOR, --executor EXECUTOR - Nextflow executor, one of local, docker, aws. Uses corresponding Nextflow config file + 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 - -o OUTPUT, --output OUTPUT - Output path + 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 + 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 + 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 + + ``` @@ -270,9 +317,60 @@ $ aws s3 ls s3://temp_datapath/D_farinae/96/621c4ba4e6e87a4d869c696fe50034/outpu 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 -Barnett DW, Garrison EK, Quinlan AR, Strömberg MP, Marth GT. BamTools: a C++ API and toolkit for analyzing and managing BAM files. Bioinformatics. 2011 Jun 15;27(12):1691-2. doi: 10.1093/bioinformatics/btr174. Epub 2011 Apr 14. PMID: 21493652; PMCID: PMC3106182. +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. @@ -280,6 +378,8 @@ Dobin A, Davis CA, Schlesinger F, Drenkow J, Zaleski C, Jha S, Batut P, Chaisson 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