From eb3c2eccb2182816bc6a2023bdae5ae44d479022 Mon Sep 17 00:00:00 2001 From: Dorien <41797896+dorien-er@users.noreply.github.com> Date: Wed, 17 Jan 2024 16:08:38 +0100 Subject: [PATCH] Revert "add nextflow schema" --- CHANGELOG.md | 10 +- _viash.yaml | 4 +- resources_test/input.csv | 3 - .../combine_columns/config.vsh.yaml | 7 +- .../combine_columns/script.R | 0 .../remove_comments/config.vsh.yaml | 13 +- .../remove_comments/script.sh | 0 .../remove_comments/test.sh | 0 .../take_column/config.vsh.yaml | 11 +- src/{template => demo}/take_column/script.py | 0 src/template/workflow/config.vsh.yaml | 54 - src/template/workflow/main.nf | 53 - src/template/workflow/nextflow_schema.json | 260 -- target/.build.yaml | 0 .../nextflow/join/vsh_toList/.config.vsh.yaml | 105 - .../v0.2.0/nextflow/join/vsh_toList/main.nf | 3059 --------------- .../nextflow/join/vsh_toList/nextflow.config | 107 - .../template/combine_columns/.config.vsh.yaml | 101 - .../template/combine_columns/combine_columns | 977 ----- .../template/remove_comments/.config.vsh.yaml | 109 - .../template/remove_comments/remove_comments | 924 ----- .../template/take_column/.config.vsh.yaml | 121 - .../docker/template/take_column/take_column | 970 ----- .../template/combine_columns/.config.vsh.yaml | 101 - .../nextflow/template/combine_columns/main.nf | 3410 ---------------- .../template/combine_columns/nextflow.config | 106 - .../template/remove_comments/.config.vsh.yaml | 109 - .../nextflow/template/remove_comments/main.nf | 3403 ---------------- .../template/remove_comments/nextflow.config | 106 - .../template/take_column/.config.vsh.yaml | 121 - target/nextflow/template/take_column/main.nf | 3434 ----------------- .../template/take_column/nextflow.config | 106 - .../template/workflow/.config.vsh.yaml | 190 - target/nextflow/template/workflow/main.nf | 3199 --------------- .../template/workflow/nextflow.config | 107 - workflows/demo_pipeline/main.nf | 43 + .../demo_pipeline}/nextflow.config | 0 37 files changed, 64 insertions(+), 21259 deletions(-) delete mode 100644 resources_test/input.csv rename src/{template => demo}/combine_columns/config.vsh.yaml (78%) rename src/{template => demo}/combine_columns/script.R (100%) rename src/{template => demo}/remove_comments/config.vsh.yaml (70%) rename src/{template => demo}/remove_comments/script.sh (100%) rename src/{template => demo}/remove_comments/test.sh (100%) rename src/{template => demo}/take_column/config.vsh.yaml (81%) rename src/{template => demo}/take_column/script.py (100%) delete mode 100644 src/template/workflow/config.vsh.yaml delete mode 100644 src/template/workflow/main.nf delete mode 100644 src/template/workflow/nextflow_schema.json delete mode 100644 target/.build.yaml delete mode 100644 target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/.config.vsh.yaml delete mode 100644 target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/main.nf delete mode 100644 target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/nextflow.config delete mode 100644 target/docker/template/combine_columns/.config.vsh.yaml delete mode 100755 target/docker/template/combine_columns/combine_columns delete mode 100644 target/docker/template/remove_comments/.config.vsh.yaml delete mode 100755 target/docker/template/remove_comments/remove_comments delete mode 100644 target/docker/template/take_column/.config.vsh.yaml delete mode 100755 target/docker/template/take_column/take_column delete mode 100644 target/nextflow/template/combine_columns/.config.vsh.yaml delete mode 100644 target/nextflow/template/combine_columns/main.nf delete mode 100644 target/nextflow/template/combine_columns/nextflow.config delete mode 100644 target/nextflow/template/remove_comments/.config.vsh.yaml delete mode 100644 target/nextflow/template/remove_comments/main.nf delete mode 100644 target/nextflow/template/remove_comments/nextflow.config delete mode 100644 target/nextflow/template/take_column/.config.vsh.yaml delete mode 100644 target/nextflow/template/take_column/main.nf delete mode 100644 target/nextflow/template/take_column/nextflow.config delete mode 100644 target/nextflow/template/workflow/.config.vsh.yaml delete mode 100644 target/nextflow/template/workflow/main.nf delete mode 100644 target/nextflow/template/workflow/nextflow.config create mode 100644 workflows/demo_pipeline/main.nf rename {src/template/workflow => workflows/demo_pipeline}/nextflow.config (100%) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad54459..6dfcf11 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,11 +1,3 @@ -# viash_project_template 0.3.0 - -* Update to Viash 0.8.2 - - * `demo_pipeline` is now built from `src/workflows/demo_pipeline` - * State management overhaul - * Use of helper functions (dependencies) from [`vsh_utils`](https://viash-hub.com/data-intuitive/vsh_utils) - # viash_project_template 0.2.0 * Update to Viash 0.7.1. @@ -30,4 +22,4 @@ Components: Pipelines: -* `workflows/demo_pipeline/main.nf`: A demo pipeline which uses abovementioned components. +* `workflows/demo_pipeline/main.nf`: A demo pipeline which uses abovementioned components. \ No newline at end of file diff --git a/_viash.yaml b/_viash.yaml index af3e934..9b3f1db 100644 --- a/_viash.yaml +++ b/_viash.yaml @@ -1,10 +1,10 @@ -viash_version: 0.8.4 +viash_version: 0.7.1 source: src target: target config_mods: | - .functionality.version := '0.2.2' + .functionality.version := 'dev' .platforms[.type == 'docker'].target_registry := 'ghcr.io' .platforms[.type == 'docker'].target_organization := 'viash-io/viash_project_template' .platforms[.type == 'docker'].target_image_source := 'https://github.com/viash-io/viash_project_template' diff --git a/resources_test/input.csv b/resources_test/input.csv deleted file mode 100644 index cc70240..0000000 --- a/resources_test/input.csv +++ /dev/null @@ -1,3 +0,0 @@ -"id","input","column" -"1","file1.tsv","2" -"2","file2.tsv","1" diff --git a/src/template/combine_columns/config.vsh.yaml b/src/demo/combine_columns/config.vsh.yaml similarity index 78% rename from src/template/combine_columns/config.vsh.yaml rename to src/demo/combine_columns/config.vsh.yaml index d2b0ce5..7635020 100644 --- a/src/template/combine_columns/config.vsh.yaml +++ b/src/demo/combine_columns/config.vsh.yaml @@ -1,6 +1,6 @@ functionality: name: combine_columns - namespace: template + namespace: demo arguments: - name: "--input" alternatives: [ "-i" ] @@ -12,10 +12,13 @@ functionality: type: file required: true direction: output + - type: string + name: --id + default: "combine_columns" resources: - type: r_script path: script.R platforms: - type: docker image: eddelbuettel/r2u:22.04 - - type: nextflow + - type: nextflow \ No newline at end of file diff --git a/src/template/combine_columns/script.R b/src/demo/combine_columns/script.R similarity index 100% rename from src/template/combine_columns/script.R rename to src/demo/combine_columns/script.R diff --git a/src/template/remove_comments/config.vsh.yaml b/src/demo/remove_comments/config.vsh.yaml similarity index 70% rename from src/template/remove_comments/config.vsh.yaml rename to src/demo/remove_comments/config.vsh.yaml index 76769ce..52e9297 100644 --- a/src/template/remove_comments/config.vsh.yaml +++ b/src/demo/remove_comments/config.vsh.yaml @@ -1,6 +1,6 @@ functionality: name: remove_comments - namespace: template + namespace: demo arguments: - name: "--input" alternatives: [ "-i" ] @@ -13,12 +13,15 @@ functionality: required: true direction: output example: "file.tsv" + - type: string + name: --id + default: "remove_comments" resources: - - type: bash_script - path: script.sh + - type: bash_script + path: script.sh test_resources: - - type: bash_script - path: test.sh + - type: bash_script + path: test.sh platforms: - type: docker image: ubuntu:20.04 diff --git a/src/template/remove_comments/script.sh b/src/demo/remove_comments/script.sh similarity index 100% rename from src/template/remove_comments/script.sh rename to src/demo/remove_comments/script.sh diff --git a/src/template/remove_comments/test.sh b/src/demo/remove_comments/test.sh similarity index 100% rename from src/template/remove_comments/test.sh rename to src/demo/remove_comments/test.sh diff --git a/src/template/take_column/config.vsh.yaml b/src/demo/take_column/config.vsh.yaml similarity index 81% rename from src/template/take_column/config.vsh.yaml rename to src/demo/take_column/config.vsh.yaml index d2676aa..b966d79 100644 --- a/src/template/take_column/config.vsh.yaml +++ b/src/demo/take_column/config.vsh.yaml @@ -1,6 +1,6 @@ functionality: name: take_column - namespace: template + namespace: demo arguments: - name: "--input" alternatives: [ "-i" ] @@ -15,6 +15,9 @@ functionality: type: integer required: false default: 2 + - type: string + name: --id + default: "take_column" resources: - type: python_script path: script.py @@ -23,9 +26,5 @@ platforms: image: python:3.10-slim setup: - type: python - packages: - - pandas - - type: apt - packages: - - procps + packages: pandas - type: nextflow diff --git a/src/template/take_column/script.py b/src/demo/take_column/script.py similarity index 100% rename from src/template/take_column/script.py rename to src/demo/take_column/script.py diff --git a/src/template/workflow/config.vsh.yaml b/src/template/workflow/config.vsh.yaml deleted file mode 100644 index 2cf6fff..0000000 --- a/src/template/workflow/config.vsh.yaml +++ /dev/null @@ -1,54 +0,0 @@ -functionality: - name: workflow - namespace: template - description: | - An example pipeline and project template. - - Multiple TSV files can be input, each with a 'column' identifier that - should be extracted. All extracted columns are then collated again. - - arguments: - - name: "--input" - alternatives: [ "-i" ] - type: file - required: true - description: Input TSV file - example: file1.tar.gz - - name: "--column" - type: integer - required: false - default: 2 - description: The column index to extract from the TSV input file - - name: "--output" - alternatives: [ "-o" ] - type: file - direction: output - required: true - description: Output TSV file - example: output.tsv - - resources: - - type: nextflow_script - path: main.nf - entrypoint: run_wf - - dependencies: - - name: template/combine_columns - repository: local - - name: template/remove_comments - repository: local - - name: template/take_column - repository: local - - name: join/vsh_toList - repository: vsh-pipeline-operators - - repositories: - - name: local - type: local - - name: vsh-pipeline-operators - type: vsh - repo: data-intuitive/vsh-pipeline-operators - tag: v0.2.0 - -platforms: - - type: nextflow diff --git a/src/template/workflow/main.nf b/src/template/workflow/main.nf deleted file mode 100644 index 213a7ce..0000000 --- a/src/template/workflow/main.nf +++ /dev/null @@ -1,53 +0,0 @@ -workflow run_wf { - take: - input_ch - - main: - - output_ch = - - input_ch - - // Remove comments from each TSV input file - | remove_comments.run( - fromState: [ input: "input" ], - toState: { id, result, state -> state + result } - ) - - // Extract a single column from each TSV - // The column to extract is specified in the sample sheet - | take_column.run( - fromState: - [ - input: "output", - column: "column" - ], - toState: { id, result, state -> result } - ) - - // Helper module with extra functionality around - // nextflow's `toSortedList` operator to reformat - // its output list into a channel item that can be used - // directly with downstream components. - | vsh_toList.run( - args: [ id: "combined" ], - fromState: [ input: "output" ], - toState: [ output: "output" ] - ) - - // Concatenate TSVs into one - // and prep the output state. - | combine_columns.run( - auto: [ publish: true ], - fromState: [ input: "output" ], - toState: { id, result, state -> - [ - output: result.output, - _meta: [ join_id: "1" ] - ] - } - ) - - emit: - output_ch -} diff --git a/src/template/workflow/nextflow_schema.json b/src/template/workflow/nextflow_schema.json deleted file mode 100644 index 3e8f67a..0000000 --- a/src/template/workflow/nextflow_schema.json +++ /dev/null @@ -1,260 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema", - "title": "full_pipeline", - "description": "A pipeline to analyse multiple multiomics samples.", - "type": "object", - "definitions": { - "inputs": { - "title": "Inputs", - "type": "object", - "description": "No description", - "properties": { - "id": { - "type": "string", - "description": "ID of the sample.", - "default": "" - }, - "input": { - "type": "string", - "description": "Path to the sample.", - "default": "" - } - } - }, - "outputs": { - "title": "Outputs", - "type": "object", - "description": "No description", - "properties": { - "output": { - "type": "string", - "description": "Destination path to the output.", - "default": "$id.$key.output.h5mu" - } - } - }, - "sample id options": { - "title": "Sample ID options", - "type": "object", - "description": "Options for adding the id to .obs on the MuData object. Having a sample \nid present in a requirement of several components for this pipeline.\n", - "properties": { - "add_id_to_obs": { - "type": "boolean", - "description": "Add the value passed with --id to .obs.", - "default": "True" - }, - "add_id_obs_output": { - "type": "string", - "description": ".Obs column to add the sample IDs to. Required and only used when ", - "help_text": ".Obs column to add the sample IDs to. Required and only used when \n--add_id_to_obs is set to \u0027true\u0027\n", - "default": "sample_id" - }, - "add_id_make_observation_keys_unique": { - "type": "boolean", - "description": "Join the id to the .obs index (.obs_names). ", - "help_text": "Join the id to the .obs index (.obs_names). \nOnly used when --add_id_to_obs is set to \u0027true\u0027.\n", - "default": "True" - } - } - }, - "rna filtering options": { - "title": "RNA filtering options", - "type": "object", - "description": "No description", - "properties": { - "rna_min_counts": { - "type": "integer", - "description": "Minimum number of counts captured per cell.", - "default": "" - }, - "rna_max_counts": { - "type": "integer", - "description": "Maximum number of counts captured per cell.", - "default": "" - }, - "rna_min_genes_per_cell": { - "type": "integer", - "description": "Minimum of non-zero values per cell.", - "default": "" - }, - "rna_max_genes_per_cell": { - "type": "integer", - "description": "Maximum of non-zero values per cell.", - "default": "" - }, - "rna_min_cells_per_gene": { - "type": "integer", - "description": "Minimum of non-zero values per gene.", - "default": "" - }, - "rna_min_fraction_mito": { - "type": "number", - "description": "Minimum fraction of UMIs that are mitochondrial.", - "default": "" - }, - "rna_max_fraction_mito": { - "type": "number", - "description": "Maximum fraction of UMIs that are mitochondrial.", - "default": "" - } - } - }, - "cite-seq filtering options": { - "title": "CITE-seq filtering options", - "type": "object", - "description": "No description", - "properties": { - "prot_min_counts": { - "type": "integer", - "description": "Minimum number of counts per cell.", - "default": "" - }, - "prot_max_counts": { - "type": "integer", - "description": "Minimum number of counts per cell.", - "default": "" - }, - "prot_min_proteins_per_cell": { - "type": "integer", - "description": "Minimum of non-zero values per cell.", - "default": "" - }, - "prot_max_proteins_per_cell": { - "type": "integer", - "description": "Maximum of non-zero values per cell.", - "default": "" - }, - "prot_min_cells_per_protein": { - "type": "integer", - "description": "Minimum of non-zero values per protein.", - "default": "" - } - } - }, - "highly variable gene detection": { - "title": "Highly variable gene detection", - "type": "object", - "description": "No description", - "properties": { - "filter_with_hvg_var_output": { - "type": "string", - "description": "In which .var slot to store a boolean array corresponding to the highly variable genes.", - "default": "filter_with_hvg" - }, - "filter_with_hvg_obs_batch_key": { - "type": "string", - "description": "If specified, highly-variable genes are selected within each batch separately and merged. This simple ", - "help_text": "If specified, highly-variable genes are selected within each batch separately and merged. This simple \nprocess avoids the selection of batch-specific genes and acts as a lightweight batch correction method.\n", - "default": "sample_id" - } - } - }, - "mitochondrial gene detection": { - "title": "Mitochondrial Gene Detection", - "type": "object", - "description": "No description", - "properties": { - "var_name_mitochondrial_genes": { - "type": "string", - "description": "In which .var slot to store a boolean array corresponding the mitochondrial genes.", - "help_text": "In which .var slot to store a boolean array corresponding the mitochondrial genes.\n", - "default": "" - }, - "var_gene_names": { - "type": "string", - "description": ".var column name to be used to detect mitochondrial genes instead of .var_names (default if not set).", - "help_text": ".var column name to be used to detect mitochondrial genes instead of .var_names (default if not set).\nGene names matching with the regex value from --mitochondrial_gene_regex will be identified\nas a mitochondrial gene.\n", - "default": "" - }, - "mitochondrial_gene_regex": { - "type": "string", - "description": "Regex string that identifies mitochondrial genes from --var_gene_names.", - "help_text": "Regex string that identifies mitochondrial genes from --var_gene_names.\nBy default will detect human and mouse mitochondrial genes from a gene symbol.\n", - "default": "^[mM][tT]-" - } - } - }, - "qc metrics calculation options": { - "title": "QC metrics calculation options", - "type": "object", - "description": "No description", - "properties": { - "var_qc_metrics": { - "type": "string", - "description": "Keys to select a boolean (containing only True or False) column from .var.", - "help_text": "Keys to select a boolean (containing only True or False) column from .var.\nFor each cell, calculate the proportion of total values for genes which are labeled \u0027True\u0027, \ncompared to the total sum of the values for all genes. Defaults to the combined values specified for\n--var_name_mitochondrial_genes and --filter_with_hvg_var_output.\n", - "default": "" - }, - "top_n_vars": { - "type": "integer", - "description": "Number of top vars to be used to calculate cumulative proportions.", - "help_text": "Number of top vars to be used to calculate cumulative proportions.\nIf not specified, proportions are not calculated. `--top_n_vars 20,50` finds\ncumulative proportion to the 20th and 50th most expressed vars.\n", - "default": "[50, 100, 200, 500]" - } - } - }, - "pca options": { - "title": "PCA options", - "type": "object", - "description": "No description", - "properties": { - "pca_overwrite": { - "type": "boolean", - "description": "Allow overwriting slots for PCA output.", - "default": "False" - } - } - }, - "nextflow input-output arguments": { - "title": "Nextflow input-output arguments", - "type": "object", - "description": "Input/output parameters for Nextflow itself. Please note that both publishDir and publish_dir are supported but at least one has to be configured.", - "properties": { - "publish_dir": { - "type": "string", - "description": "Path to an output directory.", - "default": "" - }, - "param_list": { - "type": "string", - "description": "Allows inputting multiple parameter sets to initialise a Nextflow channel. A `param_list` can either be a list of maps, a csv file, a json file, a yaml file, or simply a yaml blob.", - "help_text": "Allows inputting multiple parameter sets to initialise a Nextflow channel. A `param_list` can either be a list of maps, a csv file, a json file, a yaml file, or simply a yaml blob.\n\n* A list of maps (as-is) where the keys of each map corresponds to the arguments of the pipeline. Example: in a `nextflow.config` file: `param_list: [ [\u0027id\u0027: \u0027foo\u0027, \u0027input\u0027: \u0027foo.txt\u0027], [\u0027id\u0027: \u0027bar\u0027, \u0027input\u0027: \u0027bar.txt\u0027] ]`.\n* A csv file should have column names which correspond to the different arguments of this pipeline. Example: `--param_list data.csv` with columns `id,input`.\n* A json or a yaml file should be a list of maps, each of which has keys corresponding to the arguments of the pipeline. Example: `--param_list data.json` with contents `[ {\u0027id\u0027: \u0027foo\u0027, \u0027input\u0027: \u0027foo.txt\u0027}, {\u0027id\u0027: \u0027bar\u0027, \u0027input\u0027: \u0027bar.txt\u0027} ]`.\n* A yaml blob can also be passed directly as a string. Example: `--param_list \"[ {\u0027id\u0027: \u0027foo\u0027, \u0027input\u0027: \u0027foo.txt\u0027}, {\u0027id\u0027: \u0027bar\u0027, \u0027input\u0027: \u0027bar.txt\u0027} ]\"`.\n\nWhen passing a csv, json or yaml file, relative path names are relativized to the location of the parameter file. No relativation is performed when `param_list` is a list of maps (as-is) or a yaml blob.", - "hidden": true, - "default": "" - } - } - } - }, - "allOf": [ - { - "$ref": "#/definitions/inputs" - }, - { - "$ref": "#/definitions/outputs" - }, - { - "$ref": "#/definitions/sample id options" - }, - { - "$ref": "#/definitions/rna filtering options" - }, - { - "$ref": "#/definitions/cite-seq filtering options" - }, - { - "$ref": "#/definitions/highly variable gene detection" - }, - { - "$ref": "#/definitions/mitochondrial gene detection" - }, - { - "$ref": "#/definitions/qc metrics calculation options" - }, - { - "$ref": "#/definitions/pca options" - }, - { - "$ref": "#/definitions/nextflow input-output arguments" - } - ] -} \ No newline at end of file diff --git a/target/.build.yaml b/target/.build.yaml deleted file mode 100644 index e69de29..0000000 diff --git a/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/.config.vsh.yaml b/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/.config.vsh.yaml deleted file mode 100644 index 8b57287..0000000 --- a/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/.config.vsh.yaml +++ /dev/null @@ -1,105 +0,0 @@ -functionality: - name: "vsh_toList" - namespace: "join" - version: "0.2.0" - arguments: - - type: "string" - name: "--id" - description: "ID of the output event" - info: null - required: true - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "file" - name: "--input" - alternatives: - - "-i" - description: "Mutiple channel events to be combined under the output key" - info: null - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: false - multiple_sep: ";" - dest: "par" - - type: "file" - name: "--output" - alternatives: - - "-o" - description: "Content of the output key in the output channel" - info: null - must_exist: true - create_parent: true - required: true - direction: "output" - multiple: true - multiple_sep: ":" - dest: "par" - resources: - - type: "nextflow_script" - path: "main.nf" - is_executable: true - entrypoint: "run_wf" - description: "A wrapper component for the Nextflow toList operator\nthat fits the\ - \ Viash way of doing things.\n" - info: null - status: "enabled" - requirements: - commands: - - "ps" - set_wd_to_resources_dir: false -platforms: -- type: "nextflow" - id: "nextflow" - directives: - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1.GB" - mem2gb: "memory = 2.GB" - mem4gb: "memory = 4.GB" - mem8gb: "memory = 8.GB" - mem16gb: "memory = 16.GB" - mem32gb: "memory = 32.GB" - mem64gb: "memory = 64.GB" - mem128gb: "memory = 128.GB" - mem256gb: "memory = 256.GB" - mem512gb: "memory = 512.GB" - mem1tb: "memory = 1.TB" - mem2tb: "memory = 2.TB" - mem4tb: "memory = 4.TB" - mem8tb: "memory = 8.TB" - mem16tb: "memory = 16.TB" - mem32tb: "memory = 32.TB" - mem64tb: "memory = 64.TB" - mem128tb: "memory = 128.TB" - mem256tb: "memory = 256.TB" - mem512tb: "memory = 512.TB" - cpu1: "cpus = 1" - cpu2: "cpus = 2" - cpu5: "cpus = 5" - cpu10: "cpus = 10" - cpu20: "cpus = 20" - cpu50: "cpus = 50" - cpu100: "cpus = 100" - cpu200: "cpus = 200" - cpu500: "cpus = 500" - cpu1000: "cpus = 1000" - debug: false - container: "docker" -info: - config: "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/src/join/vsh_toList/config.vsh.yaml" - platform: "nextflow" - output: "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/target/nextflow/join/vsh_toList" - executable: "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/target/nextflow/join/vsh_toList/main.nf" - viash_version: "0.8.3" - git_commit: "05a5bfa4eaa2c04ba473671e4d30c6c18aceec6e" - git_remote: "git@viash-hub.com:data-intuitive/vsh-pipeline-operators.git" diff --git a/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/main.nf b/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/main.nf deleted file mode 100644 index 743d62d..0000000 --- a/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/main.nf +++ /dev/null @@ -1,3059 +0,0 @@ -// vsh_toList 0.2.0 -// -// This wrapper script is auto-generated by viash 0.8.3 and is thus a derivative -// work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data -// Intuitive. -// -// The component may contain files which fall under a different license. The -// authors of this component should specify the license in the header of such -// files, or include a separate license file detailing the licenses of all included -// files. - -//////////////////////////// -// VDSL3 helper functions // -//////////////////////////// - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_checkArgumentType.nf' -class UnexpectedArgumentTypeException extends Exception { - String errorIdentifier - String stage - String plainName - String expectedClass - String foundClass - - // ${key ? " in module '$key'" : ""}${id ? " id '$id'" : ""} - UnexpectedArgumentTypeException(String errorIdentifier, String stage, String plainName, String expectedClass, String foundClass) { - super("Error${errorIdentifier ? " $errorIdentifier" : ""}:${stage ? " $stage" : "" } argument '${plainName}' has the wrong type. " + - "Expected type: ${expectedClass}. Found type: ${foundClass}") - this.errorIdentifier = errorIdentifier - this.stage = stage - this.plainName = plainName - this.expectedClass = expectedClass - this.foundClass = foundClass - } -} - -/** - * Checks if the given value is of the expected type. If not, an exception is thrown. - * - * @param stage The stage of the argument (input or output) - * @param par The parameter definition - * @param value The value to check - * @param errorIdentifier The identifier to use in the error message - * @return The value, if it is of the expected type - * @throws UnexpectedArgumentTypeException If the value is not of the expected type -*/ -def _checkArgumentType(String stage, Map par, Object value, String errorIdentifier) { - // expectedClass will only be != null if value is not of the expected type - def expectedClass = null - def foundClass = null - - // todo: split if need be - - if (!par.required && value == null) { - expectedClass = null - } else if (par.multiple) { - if (value !instanceof Collection) { - value = [value] - } - - // split strings - value = value.collectMany{ val -> - if (val instanceof String) { - // collect() to ensure that the result is a List and not simply an array - val.split(par.multiple_sep).collect() - } else { - [val] - } - } - - // process globs - if (par.type == "file" && par.direction == "input") { - value = value.collect{ it instanceof String ? file(it, hidden: true) : it }.flatten() - } - - // check types of elements in list - try { - value = value.collect { listVal -> - _checkArgumentType(stage, par + [multiple: false], listVal, errorIdentifier) - } - } catch (UnexpectedArgumentTypeException e) { - expectedClass = "List[${e.expectedClass}]" - foundClass = "List[${e.foundClass}]" - } - } else if (par.type == "string") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else if (par.type == "integer") { - // cast to integer if need be - if (value instanceof String) { - try { - value = value.toInteger() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigInteger) { - value = value.intValue() - } - expectedClass = value instanceof Integer ? null : "Integer" - } else if (par.type == "long") { - // cast to long if need be - if (value instanceof String) { - try { - value = value.toLong() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof Integer) { - value = value.toLong() - } - expectedClass = value instanceof Long ? null : "Long" - } else if (par.type == "double") { - // cast to double if need be - if (value instanceof String) { - try { - value = value.toDouble() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigDecimal) { - value = value.doubleValue() - } - if (value instanceof Float) { - value = value.toDouble() - } - expectedClass = value instanceof Double ? null : "Double" - } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { - // cast to boolean if need ben - if (value instanceof String) { - def valueLower = value.toLowerCase() - if (valueLower == "true") { - value = true - } else if (valueLower == "false") { - value = false - } - } - expectedClass = value instanceof Boolean ? null : "Boolean" - } else if (par.type == "file" && (par.direction == "input" || stage == "output")) { - // cast to path if need be - if (value instanceof String) { - value = file(value, hidden: true) - } - if (value instanceof File) { - value = value.toPath() - } - expectedClass = value instanceof Path ? null : "Path" - } else if (par.type == "file" && stage == "input" && par.direction == "output") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else { - // didn't find a match for par.type - expectedClass = par.type - } - - if (expectedClass != null) { - if (foundClass == null) { - foundClass = value.getClass().getName() - } - throw new UnexpectedArgumentTypeException(errorIdentifier, stage, par.plainName, expectedClass, foundClass) - } - - return value -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processInputValues.nf' -Map _processInputValues(Map inputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.required) { - assert inputs.containsKey(arg.plainName) && inputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required input argument '${arg.plainName}' is missing" - } - } - - inputs = inputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid input argument" - - value = _checkArgumentType("input", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return inputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processOutputValues.nf' -Map _processOutputValues(Map outputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.direction == "output" && arg.required) { - assert outputs.containsKey(arg.plainName) && outputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required output argument '${arg.plainName}' is missing" - } - } - - outputs = outputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && it.direction == "output" } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid output argument" - - value = _checkArgumentType("output", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return outputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/IDChecker.nf' -class IDChecker { - final def items = [] as Set - - @groovy.transform.WithWriteLock - boolean observe(String item) { - if (items.contains(item)) { - return false - } else { - items << item - return true - } - } - - @groovy.transform.WithReadLock - boolean contains(String item) { - return items.contains(item) - } - - @groovy.transform.WithReadLock - Set getItems() { - return items.clone() - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_checkUniqueIds.nf' - -/** - * Check if the ids are unique across parameter sets - * - * @param parameterSets a list of parameter sets. - */ -private void _checkUniqueIds(List>> parameterSets) { - def ppIds = parameterSets.collect{it[0]} - assert ppIds.size() == ppIds.unique().size() : "All argument sets should have unique ids. Detected ids: $ppIds" -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_getChild.nf' - -// helper functions for reading params from file // -def _getChild(parent, child) { - if (child.contains("://") || java.nio.file.Paths.get(child).isAbsolute()) { - child - } else { - def parentAbsolute = java.nio.file.Paths.get(parent).toAbsolutePath().toString() - parentAbsolute.replaceAll('/[^/]*$', "/") + child - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_parseParamList.nf' -/** - * Figure out the param list format based on the file extension - * - * @param param_list A String containing the path to the parameter list file. - * - * @return A String containing the format of the parameter list file. - */ -def _paramListGuessFormat(param_list) { - if (param_list !instanceof String) { - "asis" - } else if (param_list.endsWith(".csv")) { - "csv" - } else if (param_list.endsWith(".json") || param_list.endsWith(".jsn")) { - "json" - } else if (param_list.endsWith(".yaml") || param_list.endsWith(".yml")) { - "yaml" - } else { - "yaml_blob" - } -} - - -/** - * Read the param list - * - * @param param_list One of the following: - * - A String containing the path to the parameter list file (csv, json or yaml), - * - A yaml blob of a list of maps (yaml_blob), - * - Or a groovy list of maps (asis). - * @param config A Map of the Viash configuration. - * - * @return A List of Maps containing the parameters. - */ -def _parseParamList(param_list, Map config) { - // first determine format by extension - def paramListFormat = _paramListGuessFormat(param_list) - - def paramListPath = (paramListFormat != "asis" && paramListFormat != "yaml_blob") ? - file(param_list, hidden: true) : - null - - // get the correct parser function for the detected params_list format - def paramSets = [] - if (paramListFormat == "asis") { - paramSets = param_list - } else if (paramListFormat == "yaml_blob") { - paramSets = readYamlBlob(param_list) - } else if (paramListFormat == "yaml") { - paramSets = readYaml(paramListPath) - } else if (paramListFormat == "json") { - paramSets = readJson(paramListPath) - } else if (paramListFormat == "csv") { - paramSets = readCsv(paramListPath) - } else { - error "Format of provided --param_list not recognised.\n" + - "Found: '$paramListFormat'.\n" + - "Expected: a csv file, a json file, a yaml file,\n" + - "a yaml blob or a groovy list of maps." - } - - // data checks - assert paramSets instanceof List: "--param_list should contain a list of maps" - for (value in paramSets) { - assert value instanceof Map: "--param_list should contain a list of maps" - } - - // id is argument - def idIsArgument = config.functionality.allArguments.any{it.plainName == "id"} - - // Reformat from List to List> by adding the ID as first element of a Tuple2 - paramSets = paramSets.collect({ data -> - def id = data.id - if (!idIsArgument) { - data = data.findAll{k, v -> k != "id"} - } - [id, data] - }) - - // Split parameters with 'multiple: true' - paramSets = paramSets.collect({ id, data -> - data = _splitParams(data, config) - [id, data] - }) - - // The paths of input files inside a param_list file may have been specified relatively to the - // location of the param_list file. These paths must be made absolute. - if (paramListPath) { - paramSets = paramSets.collect({ id, data -> - def new_data = data.collectEntries{ parName, parValue -> - def par = config.functionality.allArguments.find{it.plainName == parName} - if (par && par.type == "file" && par.direction == "input") { - if (parValue instanceof Collection) { - parValue = parValue.collectMany{path -> - def x = _resolveSiblingIfNotAbsolute(path, paramListPath) - x instanceof Collection ? x : [x] - } - } else { - parValue = _resolveSiblingIfNotAbsolute(parValue, paramListPath) - } - } - [parName, parValue] - } - [id, new_data] - }) - } - - return paramSets -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_splitParams.nf' -/** - * Split parameters for arguments that accept multiple values using their separator - * - * @param paramList A Map containing parameters to split. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A Map of parameters where the parameter values have been split into a list using - * their seperator. - */ -Map _splitParams(Map parValues, Map config){ - def parsedParamValues = parValues.collectEntries { parName, parValue -> - def parameterSettings = config.functionality.allArguments.find({it.plainName == parName}) - - if (!parameterSettings) { - // if argument is not found, do not alter - return [parName, parValue] - } - if (parameterSettings.multiple) { // Check if parameter can accept multiple values - if (parValue instanceof Collection) { - parValue = parValue.collect{it instanceof String ? it.split(parameterSettings.multiple_sep) : it } - } else if (parValue instanceof String) { - parValue = parValue.split(parameterSettings.multiple_sep) - } else if (parValue == null) { - parValue = [] - } else { - parValue = [ parValue ] - } - parValue = parValue.flatten() - } - // For all parameters check if multiple values are only passed for - // arguments that allow it. Quietly simplify lists of length 1. - if (!parameterSettings.multiple && parValue instanceof Collection) { - assert parValue.size() == 1 : - "Error: argument ${parName} has too many values.\n" + - " Expected amount: 1. Found: ${parValue.size()}" - parValue = parValue[0] - } - [parName, parValue] - } - return parsedParamValues -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/channelFromParams.nf' -/** - * Parse nextflow parameters based on settings defined in a viash config. - * Return a list of parameter sets, each parameter set corresponding to - * an event in a nextflow channel. The output from this function can be used - * with Channel.fromList to create a nextflow channel with Vdsl3 formatted - * events. - * - * This function performs: - * - A filtering of the params which can be found in the config file. - * - Process the params_list argument which allows a user to to initialise - * a Vsdl3 channel with multiple parameter sets. Possible formats are - * csv, json, yaml, or simply a yaml_blob. A csv should have column names - * which correspond to the different arguments of this pipeline. A json or a yaml - * file should be a list of maps, each of which has keys corresponding to the - * arguments of the pipeline. A yaml blob can also be passed directly as a parameter. - * When passing a csv, json or yaml, relative path names are relativized to the - * location of the parameter file. - * - Combine the parameter sets into a vdsl3 Channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A list of parameters with the first element of the event being - * the event ID and the second element containing a map of the parsed parameters. - */ - -private List>> _paramsToParamSets(Map params, Map config){ - // todo: fetch key from run args - def key_ = config.functionality.name - - /* parse regular parameters (not in param_list) */ - /*************************************************/ - def globalParams = config.functionality.allArguments - .findAll { params.containsKey(it.plainName) } - .collectEntries { [ it.plainName, params[it.plainName] ] } - def globalID = params.get("id", null) - - /* process params_list arguments */ - /*********************************/ - def paramList = params.containsKey("param_list") && params.param_list != null ? - params.param_list : [] - // if (paramList instanceof String) { - // paramList = [paramList] - // } - // def paramSets = paramList.collectMany{ _parseParamList(it, config) } - // TODO: be able to process param_list when it is a list of strings - def paramSets = _parseParamList(paramList, config) - if (paramSets.isEmpty()) { - paramSets = [[null, [:]]] - } - - /* combine arguments into channel */ - /**********************************/ - def processedParams = paramSets.indexed().collect{ index, tup -> - // Process ID - def id = tup[0] ?: globalID - - if (workflow.stubRun) { - // if stub run, explicitly add an id if missing - id = id ? id : "stub${index}" - } - assert id != null: "Each parameter set should have at least an 'id'" - - // Process params - def parValues = globalParams + tup[1] - // // Remove parameters which are null, if the default is also null - // parValues = parValues.collectEntries{paramName, paramValue -> - // parameterSettings = config.functionality.allArguments.find({it.plainName == paramName}) - // if ( paramValue != null || parameterSettings.get("default", null) != null ) { - // [paramName, paramValue] - // } - // } - parValues = parValues.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key_}' id '${id}': '${name}' is not a valid input argument" - - if (par == null) { - return [:] - } - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - - [ name, value ] - } - - [id, parValues] - } - - // Check if ids (first element of each list) is unique - _checkUniqueIds(processedParams) - return processedParams -} - -/** - * Parse nextflow parameters based on settings defined in a viash config - * and return a nextflow channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A nextflow Channel with events. Events are formatted as a tuple that contains - * first contains the ID of the event and as second element holds a parameter map. - * - * - */ -def channelFromParams(Map params, Map config) { - def processedParams = _paramsToParamSets(params, config) - return Channel.fromList(processedParams) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/checkUniqueIds.nf' -def checkUniqueIds(Map args) { - def stopOnError = args.stopOnError == null ? args.stopOnError : true - - def idChecker = new IDChecker() - - return filter { tup -> - if (!idChecker.observe(tup[0])) { - if (stopOnError) { - error "Duplicate id: ${tup[0]}" - } else { - log.warn "Duplicate id: ${tup[0]}, removing duplicate entry" - return false - } - } - return true - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/preprocessInputs.nf' -// This helper file will be deprecated soon -preprocessInputsDeprecationWarningPrinted = false - -def preprocessInputsDeprecationWarning() { - if (!preprocessInputsDeprecationWarningPrinted) { - preprocessInputsDeprecationWarningPrinted = true - System.err.println("Warning: preprocessInputs() is deprecated and will be removed in Viash 0.9.0.") - } -} - -/** - * Generate a nextflow Workflow that allows processing a channel of - * Vdsl3 formatted events and apply a Viash config to them: - * - Gather default parameters from the Viash config and make - * sure that they are correctly formatted (see applyConfig method). - * - Format the input parameters (also using the applyConfig method). - * - Apply the default parameter to the input parameters. - * - Do some assertions: - * ~ Check if the event IDs in the channel are unique. - * - * The events in the channel are formatted as tuples, with the - * first element of the tuples being a unique id of the parameter set, - * and the second element containg the the parameters themselves. - * Optional extra elements of the tuples will be passed to the output as is. - * - * @param args A map that must contain a 'config' key that points - * to a parsed config (see readConfig()). Optionally, a - * 'key' key can be provided which can be used to create a unique - * name for the workflow process. - * - * @return A workflow that allows processing a channel of Vdsl3 formatted events - * and apply a Viash config to them. - */ -def preprocessInputs(Map args) { - preprocessInputsDeprecationWarning() - - def config = args.config - assert config instanceof Map : - "Error in preprocessInputs: config must be a map. " + - "Expected class: Map. Found: config.getClass() is ${config.getClass()}" - def key_ = args.key ?: config.functionality.name - - // Get different parameter types (used throughout this function) - def defaultArgs = config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - map { tup -> - def id = tup[0] - def data = tup[1] - def passthrough = tup.drop(2) - - def new_data = (defaultArgs + data).collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - - if (par != null) { - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - } - - [ name, value ] - } - - [ id, new_data ] + passthrough - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runComponents.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component config. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component config. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component config. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component config. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runComponents(Map args) { - log.warn("runComponents is deprecated, use runEach instead") - assert args.components: "runComponents should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runComponents" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runComponentsWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def comp_config = comp_.config - - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_config) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - // def new_id = id_(tup[0], tup[1], comp_config) - def new_id = tup[0] - if (id_ instanceof String) { - new_id = id_ - } else if (id_ instanceof Closure) { - new_id = id_(new_id, tup[1], comp_config) - } - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_config) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_config) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runComponentsWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runEach.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component itself. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component itself. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component itself. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component itself. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runEach(Map args) { - assert args.components: "runEach should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runEach" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runEachWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - def new_id = id_ - if (new_id instanceof Closure) { - new_id = new_id(tup[0], tup[1], comp_) - } - assert new_id instanceof String : "Error in runEach: id should be a String or a Closure that returns a String. Expected: id instanceof String. Found: ${new_id.getClass()}" - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - def new_state = null - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runEachWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/safeJoin.nf' -/** - * Join sourceChannel to targetChannel - * - * This function joins the sourceChannel to the targetChannel. - * However, each id in the targetChannel must be present in the - * sourceChannel. If _meta.join_id exists in the targetChannel, that is - * used as an id instead. If the id doesn't match any id in the sourceChannel, - * an error is thrown. - */ - -def safeJoin(targetChannel, sourceChannel, key) { - def sourceIDs = new IDChecker() - - def sourceCheck = sourceChannel - | map { tup -> - sourceIDs.observe(tup[0]) - tup - } - def targetCheck = targetChannel - | map { tup -> - def id = tup[0] - - if (!sourceIDs.contains(id)) { - error ( - "Error in module '${key}' when merging output with original state.\n" + - " Reason: output with id '${id}' could not be joined with source channel.\n" + - " If the IDs in the output channel differ from the input channel,\n" + - " please set `tup[1]._meta.join_id to the original ID.\n" + - " Original IDs in input channel: ['${sourceIDs.getItems().join("', '")}'].\n" + - " Unexpected ID in the output channel: '${id}'.\n" + - " Example input event: [\"id\", [input: file(...)]],\n" + - " Example output event: [\"newid\", [output: file(...), _meta: [join_id: \"id\"]]]" - ) - } - // TODO: add link to our documentation on how to fix this - - tup - } - - sourceCheck.cross(targetChannel) - | map{ left, right -> - right + left.drop(1) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/_processArgument.nf' -def _processArgument(arg) { - arg.multiple = arg.multiple != null ? arg.multiple : false - arg.required = arg.required != null ? arg.required : false - arg.direction = arg.direction != null ? arg.direction : "input" - arg.multiple_sep = arg.multiple_sep != null ? arg.multiple_sep : ":" - arg.plainName = arg.name.replaceAll("^-*", "") - - if (arg.type == "file") { - arg.must_exist = arg.must_exist != null ? arg.must_exist : true - arg.create_parent = arg.create_parent != null ? arg.create_parent : true - } - - // add default values to output files which haven't already got a default - if (arg.type == "file" && arg.direction == "output" && arg.default == null) { - def mult = arg.multiple ? "_*" : "" - def extSearch = "" - if (arg.default != null) { - extSearch = arg.default - } else if (arg.example != null) { - extSearch = arg.example - } - if (extSearch instanceof List) { - extSearch = extSearch[0] - } - def extSearchResult = extSearch.find("\\.[^\\.]+\$") - def ext = extSearchResult != null ? extSearchResult : "" - arg.default = "\$id.\$key.${arg.plainName}${mult}${ext}" - if (arg.multiple) { - arg.default = [arg.default] - } - } - - if (!arg.multiple) { - if (arg.default != null && arg.default instanceof List) { - arg.default = arg.default[0] - } - if (arg.example != null && arg.example instanceof List) { - arg.example = arg.example[0] - } - } - - if (arg.type == "boolean_true") { - arg.default = false - } - if (arg.type == "boolean_false") { - arg.default = true - } - - arg -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/addGlobalParams.nf' -def addGlobalArguments(config) { - def localConfig = [ - "functionality" : [ - "argument_groups": [ - [ - "name": "Nextflow input-output arguments", - "description": "Input/output parameters for Nextflow itself. Please note that both publishDir and publish_dir are supported but at least one has to be configured.", - "arguments" : [ - [ - 'name': '--publish_dir', - 'required': true, - 'type': 'string', - 'description': 'Path to an output directory.', - 'example': 'output/', - 'multiple': false - ], - [ - 'name': '--param_list', - 'required': false, - 'type': 'string', - 'description': '''Allows inputting multiple parameter sets to initialise a Nextflow channel. A `param_list` can either be a list of maps, a csv file, a json file, a yaml file, or simply a yaml blob. - | - |* A list of maps (as-is) where the keys of each map corresponds to the arguments of the pipeline. Example: in a `nextflow.config` file: `param_list: [ ['id': 'foo', 'input': 'foo.txt'], ['id': 'bar', 'input': 'bar.txt'] ]`. - |* A csv file should have column names which correspond to the different arguments of this pipeline. Example: `--param_list data.csv` with columns `id,input`. - |* A json or a yaml file should be a list of maps, each of which has keys corresponding to the arguments of the pipeline. Example: `--param_list data.json` with contents `[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]`. - |* A yaml blob can also be passed directly as a string. Example: `--param_list "[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]"`. - | - |When passing a csv, json or yaml file, relative path names are relativized to the location of the parameter file. No relativation is performed when `param_list` is a list of maps (as-is) or a yaml blob.'''.stripMargin(), - 'example': 'my_params.yaml', - 'multiple': false, - 'hidden': true - ] - // TODO: allow multiple: true in param_list? - // TODO: allow to specify a --param_list_regex to filter the param_list? - // TODO: allow to specify a --param_list_from_state to remap entries in the param_list? - ] - ] - ] - ] - ] - - return processConfig(_mergeMap(config, localConfig)) -} - -def _mergeMap(Map lhs, Map rhs) { - return rhs.inject(lhs.clone()) { map, entry -> - if (map[entry.key] instanceof Map && entry.value instanceof Map) { - map[entry.key] = _mergeMap(map[entry.key], entry.value) - } else if (map[entry.key] instanceof Collection && entry.value instanceof Collection) { - map[entry.key] += entry.value - } else { - map[entry.key] = entry.value - } - return map - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/generateHelp.nf' -def _generateArgumentHelp(param) { - // alternatives are not supported - // def names = param.alternatives ::: List(param.name) - - def unnamedProps = [ - ["required parameter", param.required], - ["multiple values allowed", param.multiple], - ["output", param.direction.toLowerCase() == "output"], - ["file must exist", param.type == "file" && param.must_exist] - ].findAll{it[1]}.collect{it[0]} - - def dflt = null - if (param.default != null) { - if (param.default instanceof List) { - dflt = param.default.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - dflt = param.default.toString() - } - } - def example = null - if (param.example != null) { - if (param.example instanceof List) { - example = param.example.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - example = param.example.toString() - } - } - def min = param.min?.toString() - def max = param.max?.toString() - - def escapeChoice = { choice -> - def s1 = choice.replaceAll("\\n", "\\\\n") - def s2 = s1.replaceAll("\"", """\\\"""") - s2.contains(",") || s2 != choice ? "\"" + s2 + "\"" : s2 - } - def choices = param.choices == null ? - null : - "[ " + param.choices.collect{escapeChoice(it.toString())}.join(", ") + " ]" - - def namedPropsStr = [ - ["type", ([param.type] + unnamedProps).join(", ")], - ["default", dflt], - ["example", example], - ["choices", choices], - ["min", min], - ["max", max] - ] - .findAll{it[1]} - .collect{"\n " + it[0] + ": " + it[1].replaceAll("\n", "\\n")} - .join("") - - def descStr = param.description == null ? - "" : - _paragraphWrap("\n" + param.description.trim(), 80 - 8).join("\n ") - - "\n --" + param.plainName + - namedPropsStr + - descStr -} - -// Based on Helper.generateHelp() in Helper.scala -def _generateHelp(config) { - def fun = config.functionality - - // PART 1: NAME AND VERSION - def nameStr = fun.name + - (fun.version == null ? "" : " " + fun.version) - - // PART 2: DESCRIPTION - def descrStr = fun.description == null ? - "" : - "\n\n" + _paragraphWrap(fun.description.trim(), 80).join("\n") - - // PART 3: Usage - def usageStr = fun.usage == null ? - "" : - "\n\nUsage:\n" + fun.usage.trim() - - // PART 4: Options - def argGroupStrs = fun.allArgumentGroups.collect{argGroup -> - def name = argGroup.name - def descriptionStr = argGroup.description == null ? - "" : - "\n " + _paragraphWrap(argGroup.description.trim(), 80-4).join("\n ") + "\n" - def arguments = argGroup.arguments.collect{arg -> - arg instanceof String ? fun.allArguments.find{it.plainName == arg} : arg - }.findAll{it != null} - def argumentStrs = arguments.collect{param -> _generateArgumentHelp(param)} - - "\n\n$name:" + - descriptionStr + - argumentStrs.join("\n") - } - - // FINAL: combine - def out = nameStr + - descrStr + - usageStr + - argGroupStrs.join("") - - return out -} - -// based on Format._paragraphWrap -def _paragraphWrap(str, maxLength) { - def outLines = [] - str.split("\n").each{par -> - def words = par.split("\\s").toList() - - def word = null - def line = words.pop() - while(!words.isEmpty()) { - word = words.pop() - if (line.length() + word.length() + 1 <= maxLength) { - line = line + " " + word - } else { - outLines.add(line) - line = word - } - } - if (words.isEmpty()) { - outLines.add(line) - } - } - return outLines -} - -def helpMessage(config) { - if (params.containsKey("help") && params.help) { - def mergedConfig = addGlobalArguments(config) - def helpStr = _generateHelp(mergedConfig) - println(helpStr) - exit 0 - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/processConfig.nf' -def processConfig(config) { - // set defaults for arguments - config.functionality.arguments = - (config.functionality.arguments ?: []).collect{_processArgument(it)} - - // set defaults for argument_group arguments - config.functionality.argument_groups = - (config.functionality.argument_groups ?: []).collect{grp -> - grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} - grp - } - - // create combined arguments list - config.functionality.allArguments = - config.functionality.arguments + - config.functionality.argument_groups.collectMany{it.arguments} - - // add missing argument groups (based on Functionality::allArgumentGroups()) - def argGroups = config.functionality.argument_groups - if (argGroups.any{it.name.toLowerCase() == "arguments"}) { - argGroups = argGroups.collect{ grp -> - if (grp.name.toLowerCase() == "arguments") { - grp = grp + [ - arguments: grp.arguments + config.functionality.arguments - ] - } - grp - } - } else { - argGroups = argGroups + [ - name: "Arguments", - arguments: config.functionality.arguments - ] - } - config.functionality.allArgumentGroups = argGroups - - config -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/readConfig.nf' - -def readConfig(file) { - def config = readYaml(file ?: moduleDir.resolve("config.vsh.yaml")) - processConfig(config) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_resolveSiblingIfNotAbsolute.nf' -/** - * Resolve a path relative to the current file. - * - * @param str The path to resolve, as a String. - * @param parentPath The path to resolve relative to, as a Path. - * - * @return The path that may have been resovled, as a Path. - */ -def _resolveSiblingIfNotAbsolute(str, parentPath) { - if (str !instanceof String) { - return str - } - if (!_stringIsAbsolutePath(str)) { - return parentPath.resolveSibling(str) - } else { - return file(str, hidden: true) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_stringIsAbsolutePath.nf' -/** - * Check whether a path as a string is absolute. - * - * In the past, we tried using `file(., relative: true).isAbsolute()`, - * but the 'relative' option was added in 22.10.0. - * - * @param path The path to check, as a String. - * - * @return Whether the path is absolute, as a boolean. - */ -def _stringIsAbsolutePath(path) { - _resolve_URL_PROTOCOL = ~/^([a-zA-Z][a-zA-Z0-9]*:)?\\/.+/ - - assert path instanceof String - return _resolve_URL_PROTOCOL.matcher(path).matches() -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/collectTraces.nf' -class CustomTraceObserver implements nextflow.trace.TraceObserver { - List traces - - CustomTraceObserver(List traces) { - this.traces = traces - } - - @Override - void onProcessComplete(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } - - @Override - void onProcessCached(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } -} - -def collectTraces() { - def traces = Collections.synchronizedList([]) - - // add custom trace observer which stores traces in the traces object - session.observers.add(new CustomTraceObserver(traces)) - - traces -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/deepClone.nf' -/** - * Performs a deep clone of the given object. - * @param x an object - */ -def deepClone(x) { - iterateMap(x, {it instanceof Cloneable ? it.clone() : it}) -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getPublishDir.nf' -def getPublishDir() { - return params.containsKey("publish_dir") ? params.publish_dir : - params.containsKey("publishDir") ? params.publishDir : - null -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getRootDir.nf' - -// Recurse upwards until we find a '.build.yaml' file -def _findBuildYamlFile(pathPossiblySymlink) { - def path = pathPossiblySymlink.toRealPath() - def child = path.resolve(".build.yaml") - if (java.nio.file.Files.isDirectory(path) && java.nio.file.Files.exists(child)) { - return child - } else { - def parent = path.getParent() - if (parent == null) { - return null - } else { - return _findBuildYamlFile(parent) - } - } -} - -// get the root of the target folder -def getRootDir() { - def dir = _findBuildYamlFile(meta.resources_dir) - assert dir != null: "Could not find .build.yaml in the folder structure" - dir.getParent() -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/iterateMap.nf' -/** - * Recursively apply a function over the leaves of an object. - * @param obj The object to iterate over. - * @param fun The function to apply to each value. - * @return The object with the function applied to each value. - */ -def iterateMap(obj, fun) { - if (obj instanceof List && obj !instanceof String) { - return obj.collect{item -> - iterateMap(item, fun) - } - } else if (obj instanceof Map) { - return obj.collectEntries{key, item -> - [key.toString(), iterateMap(item, fun)] - } - } else { - return fun(obj) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/niceView.nf' -/** - * A view for printing the event of each channel as a YAML blob. - * This is useful for debugging. - */ -def niceView() { - workflow niceViewWf { - take: input - main: - output = input - | view{toYamlBlob(it)} - emit: output - } - return niceViewWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readCsv.nf' - -def readCsv(file_path) { - def output = [] - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - - // todo: allow escaped quotes in string - // todo: allow single quotes? - def splitRegex = java.util.regex.Pattern.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''') - def removeQuote = java.util.regex.Pattern.compile('''"(.*)"''') - - def br = java.nio.file.Files.newBufferedReader(inputFile) - - def row = -1 - def header = null - while (br.ready() && header == null) { - def line = br.readLine() - row++ - if (!line.startsWith("#")) { - header = splitRegex.split(line, -1).collect{field -> - m = removeQuote.matcher(field) - m.find() ? m.replaceFirst('$1') : field - } - } - } - assert header != null: "CSV file should contain a header" - - while (br.ready()) { - def line = br.readLine() - row++ - if (line == null) { - br.close() - break - } - - if (!line.startsWith("#")) { - def predata = splitRegex.split(line, -1) - def data = predata.collect{field -> - if (field == "") { - return null - } - m = removeQuote.matcher(field) - if (m.find()) { - return m.replaceFirst('$1') - } else { - return field - } - } - assert header.size() == data.size(): "Row $row should contain the same number as fields as the header" - - def dataMap = [header, data].transpose().collectEntries().findAll{it.value != null} - output.add(dataMap) - } - } - - output -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJson.nf' -def readJson(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parse(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJsonBlob.nf' -def readJsonBlob(str) { - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parseText(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readTaggedYaml.nf' -// Custom constructor to modify how certain objects are parsed from YAML -class CustomConstructor extends org.yaml.snakeyaml.constructor.Constructor { - Path root - - class ConstructPath extends org.yaml.snakeyaml.constructor.AbstractConstruct { - public Object construct(org.yaml.snakeyaml.nodes.Node node) { - String filename = (String) constructScalar(node); - if (root != null) { - return root.resolve(filename); - } - return java.nio.file.Paths.get(filename); - } - } - - CustomConstructor(org.yaml.snakeyaml.LoaderOptions options, Path root) { - super(options) - this.root = root - // Handling !file tag and parse it back to a File type - this.yamlConstructors.put(new org.yaml.snakeyaml.nodes.Tag("!file"), new ConstructPath()) - } -} - -def readTaggedYaml(Path path) { - def options = new org.yaml.snakeyaml.LoaderOptions() - def constructor = new CustomConstructor(options, path.getParent()) - def yaml = new org.yaml.snakeyaml.Yaml(constructor) - return yaml.load(path.text) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYaml.nf' -def readYaml(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYamlBlob.nf' -def readYamlBlob(str) { - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toJsonBlob.nf' -String toJsonBlob(data) { - return groovy.json.JsonOutput.toJson(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toTaggedYamlBlob.nf' -// Custom representer to modify how certain objects are represented in YAML -class CustomRepresenter extends org.yaml.snakeyaml.representer.Representer { - Path relativizer - - class RepresentPath implements org.yaml.snakeyaml.representer.Represent { - public String getFileName(Object obj) { - if (obj instanceof File) { - obj = ((File) obj).toPath(); - } - if (obj !instanceof Path) { - throw new IllegalArgumentException("Object: " + obj + " is not a Path or File"); - } - def path = (Path) obj; - - if (relativizer != null) { - return relativizer.relativize(path).toString() - } else { - return path.toString() - } - } - - public org.yaml.snakeyaml.nodes.Node representData(Object data) { - String filename = getFileName(data); - def tag = new org.yaml.snakeyaml.nodes.Tag("!file"); - return representScalar(tag, filename); - } - } - CustomRepresenter(org.yaml.snakeyaml.DumperOptions options, Path relativizer) { - super(options) - this.relativizer = relativizer - this.representers.put(sun.nio.fs.UnixPath, new RepresentPath()) - this.representers.put(Path, new RepresentPath()) - this.representers.put(File, new RepresentPath()) - } -} - -String toTaggedYamlBlob(data) { - return toRelativeTaggedYamlBlob(data, null) -} -String toRelativeTaggedYamlBlob(data, Path relativizer) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - def representer = new CustomRepresenter(options, relativizer) - def yaml = new org.yaml.snakeyaml.Yaml(representer, options) - return yaml.dump(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toYamlBlob.nf' -String toYamlBlob(data) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - options.setPrettyFlow(true) - def yaml = new org.yaml.snakeyaml.Yaml(options) - def cleanData = iterateMap(data, { it instanceof Path ? it.toString() : it }) - return yaml.dump(cleanData) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeJson.nf' -void writeJson(data, file) { - assert data: "writeJson: data should not be null" - assert file: "writeJson: file should not be null" - file.write(toJsonBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeYaml.nf' -void writeYaml(data, file) { - assert data: "writeYaml: data should not be null" - assert file: "writeYaml: file should not be null" - file.write(toYamlBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/findStates.nf' -def findStates(Map params, Map config) { - // TODO: do a deep clone of config - def auto_config = deepClone(config) - def auto_params = deepClone(params) - - auto_config = auto_config.clone() - // override arguments - auto_config.functionality.argument_groups = [] - auto_config.functionality.arguments = [ - [ - type: "string", - name: "--id", - description: "A dummy identifier", - required: false - ], - [ - type: "file", - name: "--input_states", - example: "/path/to/input/directory/**/state.yaml", - description: "Path to input directory containing the datasets to be integrated.", - required: true, - multiple: true, - multiple_sep: ";" - ], - [ - type: "string", - name: "--filter", - example: "foo/.*/state.yaml", - description: "Regex to filter state files by path.", - required: false - ], - // to do: make this a yaml blob? - [ - type: "string", - name: "--rename_keys", - example: ["newKey1:oldKey1", "newKey2:oldKey2"], - description: "Rename keys in the detected input files. This is useful if the input files do not match the set of input arguments of the workflow.", - required: false, - multiple: true, - multiple_sep: "," - ], - [ - type: "string", - name: "--settings", - example: '{"output_dataset": "dataset.h5ad", "k": 10}', - description: "Global arguments as a JSON glob to be passed to all components.", - required: false - ] - ] - if (!(auto_params.containsKey("id"))) { - auto_params["id"] = "auto" - } - - // run auto config through processConfig once more - auto_config = processConfig(auto_config) - - workflow findStatesWf { - helpMessage(auto_config) - - output_ch = - channelFromParams(auto_params, auto_config) - | flatMap { autoId, args -> - - def globalSettings = args.settings ? readYamlBlob(args.settings) : [:] - - // look for state files in input dir - def stateFiles = args.input_states - - // filter state files by regex - if (args.filter) { - stateFiles = stateFiles.findAll{ stateFile -> - def stateFileStr = stateFile.toString() - def matcher = stateFileStr =~ args.filter - matcher.matches()} - } - - // read in states - def states = stateFiles.collect { stateFile -> - def state_ = readTaggedYaml(stateFile) - [state_.id, state_] - } - - // construct renameMap - if (args.rename_keys) { - def renameMap = args.rename_keys.collectEntries{renameString -> - def split = renameString.split(":") - assert split.size() == 2: "Argument 'rename_keys' should be of the form 'newKey:oldKey,newKey:oldKey'" - split - } - - // rename keys in state, only let states through which have all keys - // also add global settings - states = states.collectMany{id, state -> - def newState = [:] - - for (key in renameMap.keySet()) { - def origKey = renameMap[key] - if (!(state.containsKey(origKey))) { - return [] - } - newState[key] = state[origKey] - } - - [[id, globalSettings + newState]] - } - } - - states - } - emit: - output_ch - } - - return findStatesWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/joinStates.nf' -def joinStates(Closure apply_) { - workflow joinStatesWf { - take: input_ch - main: - output_ch = input_ch - | toSortedList - | filter{ it.size() > 0 } - | map{ tups -> - def ids = tups.collect{it[0]} - def states = tups.collect{it[1]} - apply_(ids, states) - } - - emit: output_ch - } - return joinStatesWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/publishStates.nf' -def collectFiles(obj) { - if (obj instanceof java.io.File || obj instanceof Path) { - return [obj] - } else if (obj instanceof List && obj !instanceof String) { - return obj.collectMany{item -> - collectFiles(item) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectFiles(item) - } - } else { - return [] - } -} - -/** - * Recurse through a state and collect all input files and their target output filenames. - * @param obj The state to recurse through. - * @param prefix The prefix to prepend to the output filenames. - */ -def collectInputOutputPaths(obj, prefix) { - if (obj instanceof File || obj instanceof Path) { - def path = obj instanceof Path ? obj : obj.toPath() - def ext = path.getFileName().toString().find("\\.[^\\.]+\$") ?: "" - def newFilename = prefix + ext - return [[obj, newFilename]] - } else if (obj instanceof List && obj !instanceof String) { - return obj.withIndex().collectMany{item, ix -> - collectInputOutputPaths(item, prefix + "_" + ix) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectInputOutputPaths(item, prefix + "." + key) - } - } else { - return [] - } -} - -def publishStates(Map args) { - def key_ = args.get("key") - def yamlTemplate_ = args.get("output_state", args.get("outputState", '$id.$key.state.yaml')) - - assert key_ != null : "publishStates: key must be specified" - - workflow publishStatesWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] - - // the input files and the target output filenames - def inputOutputFiles_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() - def inputFiles_ = inputOutputFiles_[0] - def outputFiles_ = inputOutputFiles_[1] - - def yamlFilename = yamlTemplate_ - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - - // TODO: do the pathnames in state_ match up with the outputFiles_? - - // convert state to yaml blob - def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesWf -} -process publishStatesProc { - // todo: check publishpath? - publishDir path: "${getPublishDir()}/", mode: "copy" - tag "$id" - input: - tuple val(id), val(yamlBlob), val(yamlFile), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) - output: - tuple val(id), path{[yamlFile] + outputFiles} - script: - def copyCommands = [ - inputFiles instanceof List ? inputFiles : [inputFiles], - outputFiles instanceof List ? outputFiles : [outputFiles] - ] - .transpose() - .collectMany{infile, outfile -> - if (infile.toString() != outfile.toString()) { - [ - "[ -d \"\$(dirname '${outfile.toString()}')\" ] || mkdir -p \"\$(dirname '${outfile.toString()}')\"", - "cp -r '${infile.toString()}' '${outfile.toString()}'" - ] - } else { - // no need to copy if infile is the same as outfile - [] - } - } - """ - mkdir -p "\$(dirname '${yamlFile}')" - echo "Storing state as yaml" - echo '${yamlBlob}' > '${yamlFile}' - echo "Copying output files to destination folder" - ${copyCommands.join("\n ")} - """ -} - - -// this assumes that the state contains no other values other than those specified in the config -def publishStatesByConfig(Map args) { - def config = args.get("config") - assert config != null : "publishStatesByConfig: config must be specified" - - def key_ = args.get("key", config.functionality.name) - assert key_ != null : "publishStatesByConfig: key must be specified" - - workflow publishStatesSimpleWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] // e.g. [output: new File("myoutput.h5ad"), k: 10] - def origState_ = tup[2] // e.g. [output: '$id.$key.foo.h5ad'] - - // TODO: allow overriding the state.yaml template - // TODO TODO: if auto.publish == "state", add output_state as an argument - def yamlTemplate = params.containsKey("output_state") ? params.output_state : '$id.$key.state.yaml' - def yamlFilename = yamlTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() - - // the processed state is a list of [key, value, srcPath, destPath] tuples, where - // - key, value is part of the state to be saved to disk - // - srcPath and destPath are lists of files to be copied from src to dest - def processedState = - config.functionality.allArguments - .findAll { it.direction == "output" } - .collectMany { par -> - def plainName_ = par.plainName - // if the state does not contain the key, it's an - // optional argument for which the component did - // not generate any output - if (!state_.containsKey(plainName_)) { - return [] - } - def value = state_[plainName_] - // if the parameter is not a file, it should be stored - // in the state as-is, but is not something that needs - // to be copied from the source path to the dest path - if (par.type != "file") { - return [[key: plainName_, value: value, srcPath: [], destPath: []]] - } - // if the orig state does not contain this filename, - // it's an optional argument for which the user specified - // that it should not be returned as a state - if (!origState_.containsKey(plainName_)) { - return [] - } - def filenameTemplate = origState_[plainName_] - // if the pararameter is multiple: true, fetch the template - if (par.multiple && filenameTemplate instanceof List) { - filenameTemplate = filenameTemplate[0] - } - // instantiate the template - def filename = filenameTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - if (par.multiple) { - // if the parameter is multiple: true, the filename - // should contain a wildcard '*' that is replaced with - // the index of the file - assert filename.contains("*") : "Module '${key_}' id '${id_}': Multiple output files specified, but no wildcard '*' in the filename: ${filename}" - def outputPerFile = value.withIndex().collect{ val, ix -> - def value_ = java.nio.file.Paths.get(filename.replace("*", ix.toString())) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = val instanceof File ? val.toPath() : val - [value: value_, srcPath: srcPath, destPath: destPath] - } - def transposedOutputs = ["value", "srcPath", "destPath"].collectEntries{ key -> - [key, outputPerFile.collect{dic -> dic[key]}] - } - return [[key: plainName_] + transposedOutputs] - } else { - def value_ = java.nio.file.Paths.get(filename) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = value instanceof File ? value.toPath() : value - return [[key: plainName_, value: value_, srcPath: [srcPath], destPath: [filename]]] - } - } - - def updatedState_ = processedState.collectEntries{[it.key, it.value]} - def inputFiles_ = processedState.collectMany{it.srcPath} - def outputFiles_ = processedState.collectMany{it.destPath} - - // convert state to yaml blob - def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesSimpleWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/setState.nf' -def setState(fun) { - assert fun instanceof Closure || fun instanceof Map || fun instanceof List : - "Error in setState: Expected process argument to be a Closure, a Map, or a List. Found: class ${fun.getClass()}" - - // if fun is a List, convert to map - if (fun instanceof List) { - // check whether fun is a list[string] - assert fun.every{it instanceof CharSequence} : "Error in setState: argument is a List, but not all elements are Strings" - fun = fun.collectEntries{[it, it]} - } - - // if fun is a map, convert to closure - if (fun instanceof Map) { - // check whether fun is a map[string, string] - assert fun.values().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all values are Strings" - assert fun.keySet().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all keys are Strings" - def funMap = fun.clone() - // turn the map into a closure to be used later on - fun = { id_, state_ -> - assert state_ instanceof Map : "Error in setState: the state is not a Map" - funMap.collectMany{newkey, origkey -> - if (state_.containsKey(origkey)) { - [[newkey, state_[origkey]]] - } else { - [] - } - }.collectEntries() - } - } - - map { tup -> - def id = tup[0] - def state = tup[1] - def unfilteredState = fun(id, state) - def newState = unfilteredState.findAll{key, val -> val != null} - [id, newState] + tup.drop(2) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processAuto.nf' -// TODO: unit test processAuto -def processAuto(Map auto) { - // remove null values - auto = auto.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = ["simplifyInput", "simplifyOutput", "transcript", "publish"] - def unexpectedKeys = auto.keySet() - expectedKeys - assert unexpectedKeys.isEmpty(), "unexpected keys in auto: '${unexpectedKeys.join("', '")}'" - - // check auto.simplifyInput - assert auto.simplifyInput instanceof Boolean, "auto.simplifyInput must be a boolean" - - // check auto.simplifyOutput - assert auto.simplifyOutput instanceof Boolean, "auto.simplifyOutput must be a boolean" - - // check auto.transcript - assert auto.transcript instanceof Boolean, "auto.transcript must be a boolean" - - // check auto.publish - assert auto.publish instanceof Boolean || auto.publish == "state", "auto.publish must be a boolean or 'state'" - - return auto.subMap(expectedKeys) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processDirectives.nf' -def assertMapKeys(map, expectedKeys, requiredKeys, mapName) { - assert map instanceof Map : "Expected argument '$mapName' to be a Map. Found: class ${map.getClass()}" - map.forEach { key, val -> - assert key in expectedKeys : "Unexpected key '$key' in ${mapName ? mapName + " " : ""}map" - } - requiredKeys.forEach { requiredKey -> - assert map.containsKey(requiredKey) : "Missing required key '$key' in ${mapName ? mapName + " " : ""}map" - } -} - -// TODO: unit test processDirectives -def processDirectives(Map drctv) { - // remove null values - drctv = drctv.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = [ - "accelerator", "afterScript", "beforeScript", "cache", "conda", "container", "containerOptions", "cpus", "disk", "echo", "errorStrategy", "executor", "machineType", "maxErrors", "maxForks", "maxRetries", "memory", "module", "penv", "pod", "publishDir", "queue", "label", "scratch", "storeDir", "stageInMode", "stageOutMode", "tag", "time" - ] - def unexpectedKeys = drctv.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Unexpected keys in process directive: '${unexpectedKeys.join("', '")}'" - - /* DIRECTIVE accelerator - accepted examples: - - [ limit: 4, type: "nvidia-tesla-k80" ] - */ - if (drctv.containsKey("accelerator")) { - assertMapKeys(drctv["accelerator"], ["type", "limit", "request", "runtime"], [], "accelerator") - } - - /* DIRECTIVE afterScript - accepted examples: - - "source /cluster/bin/cleanup" - */ - if (drctv.containsKey("afterScript")) { - assert drctv["afterScript"] instanceof CharSequence - } - - /* DIRECTIVE beforeScript - accepted examples: - - "source /cluster/bin/setup" - */ - if (drctv.containsKey("beforeScript")) { - assert drctv["beforeScript"] instanceof CharSequence - } - - /* DIRECTIVE cache - accepted examples: - - true - - false - - "deep" - - "lenient" - */ - if (drctv.containsKey("cache")) { - assert drctv["cache"] instanceof CharSequence || drctv["cache"] instanceof Boolean - if (drctv["cache"] instanceof CharSequence) { - assert drctv["cache"] in ["deep", "lenient"] : "Unexpected value for cache" - } - } - - /* DIRECTIVE conda - accepted examples: - - "bwa=0.7.15" - - "bwa=0.7.15 fastqc=0.11.5" - - ["bwa=0.7.15", "fastqc=0.11.5"] - */ - if (drctv.containsKey("conda")) { - if (drctv["conda"] instanceof List) { - drctv["conda"] = drctv["conda"].join(" ") - } - assert drctv["conda"] instanceof CharSequence - } - - /* DIRECTIVE container - accepted examples: - - "foo/bar:tag" - - [ registry: "reg", image: "im", tag: "ta" ] - is transformed to "reg/im:ta" - - [ image: "im" ] - is transformed to "im:latest" - */ - if (drctv.containsKey("container")) { - assert drctv["container"] instanceof Map || drctv["container"] instanceof CharSequence - if (drctv["container"] instanceof Map) { - def m = drctv["container"] - assertMapKeys(m, [ "registry", "image", "tag" ], ["image"], "container") - def part1 = - System.getenv('OVERRIDE_CONTAINER_REGISTRY') ? System.getenv('OVERRIDE_CONTAINER_REGISTRY') + "/" : - params.containsKey("override_container_registry") ? params["override_container_registry"] + "/" : // todo: remove? - m.registry ? m.registry + "/" : - "" - def part2 = m.image - def part3 = m.tag ? ":" + m.tag : ":latest" - drctv["container"] = part1 + part2 + part3 - } - } - - /* DIRECTIVE containerOptions - accepted examples: - - "--foo bar" - - ["--foo bar", "-f b"] - */ - if (drctv.containsKey("containerOptions")) { - if (drctv["containerOptions"] instanceof List) { - drctv["containerOptions"] = drctv["containerOptions"].join(" ") - } - assert drctv["containerOptions"] instanceof CharSequence - } - - /* DIRECTIVE cpus - accepted examples: - - 1 - - 10 - */ - if (drctv.containsKey("cpus")) { - assert drctv["cpus"] instanceof Integer - } - - /* DIRECTIVE disk - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("disk")) { - assert drctv["disk"] instanceof CharSequence - // assert drctv["disk"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE echo - accepted examples: - - true - - false - */ - if (drctv.containsKey("echo")) { - assert drctv["echo"] instanceof Boolean - } - - /* DIRECTIVE errorStrategy - accepted examples: - - "terminate" - - "finish" - */ - if (drctv.containsKey("errorStrategy")) { - assert drctv["errorStrategy"] instanceof CharSequence - assert drctv["errorStrategy"] in ["terminate", "finish", "ignore", "retry"] : "Unexpected value for errorStrategy" - } - - /* DIRECTIVE executor - accepted examples: - - "local" - - "sge" - */ - if (drctv.containsKey("executor")) { - assert drctv["executor"] instanceof CharSequence - assert drctv["executor"] in ["local", "sge", "uge", "lsf", "slurm", "pbs", "pbspro", "moab", "condor", "nqsii", "ignite", "k8s", "awsbatch", "google-pipelines"] : "Unexpected value for executor" - } - - /* DIRECTIVE machineType - accepted examples: - - "n1-highmem-8" - */ - if (drctv.containsKey("machineType")) { - assert drctv["machineType"] instanceof CharSequence - } - - /* DIRECTIVE maxErrors - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxErrors")) { - assert drctv["maxErrors"] instanceof Integer - } - - /* DIRECTIVE maxForks - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxForks")) { - assert drctv["maxForks"] instanceof Integer - } - - /* DIRECTIVE maxRetries - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxRetries")) { - assert drctv["maxRetries"] instanceof Integer - } - - /* DIRECTIVE memory - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("memory")) { - assert drctv["memory"] instanceof CharSequence - // assert drctv["memory"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE module - accepted examples: - - "ncbi-blast/2.2.27" - - "ncbi-blast/2.2.27:t_coffee/10.0" - - ["ncbi-blast/2.2.27", "t_coffee/10.0"] - */ - if (drctv.containsKey("module")) { - if (drctv["module"] instanceof List) { - drctv["module"] = drctv["module"].join(":") - } - assert drctv["module"] instanceof CharSequence - } - - /* DIRECTIVE penv - accepted examples: - - "smp" - */ - if (drctv.containsKey("penv")) { - assert drctv["penv"] instanceof CharSequence - } - - /* DIRECTIVE pod - accepted examples: - - [ label: "key", value: "val" ] - - [ annotation: "key", value: "val" ] - - [ env: "key", value: "val" ] - - [ [label: "l", value: "v"], [env: "e", value: "v"]] - */ - if (drctv.containsKey("pod")) { - if (drctv["pod"] instanceof Map) { - drctv["pod"] = [ drctv["pod"] ] - } - assert drctv["pod"] instanceof List - drctv["pod"].forEach { pod -> - assert pod instanceof Map - // TODO: should more checks be added? - // See https://www.nextflow.io/docs/latest/process.html?highlight=directives#pod - // e.g. does it contain 'label' and 'value', or 'annotation' and 'value', or ...? - } - } - - /* DIRECTIVE publishDir - accepted examples: - - [] - - [ [ path: "foo", enabled: true ], [ path: "bar", enabled: false ] ] - - "/path/to/dir" - is transformed to [[ path: "/path/to/dir" ]] - - [ path: "/path/to/dir", mode: "cache" ] - is transformed to [[ path: "/path/to/dir", mode: "cache" ]] - */ - // TODO: should we also look at params["publishDir"]? - if (drctv.containsKey("publishDir")) { - def pblsh = drctv["publishDir"] - - // check different options - assert pblsh instanceof List || pblsh instanceof Map || pblsh instanceof CharSequence - - // turn into list if not already so - // for some reason, 'if (!pblsh instanceof List) pblsh = [ pblsh ]' doesn't work. - pblsh = pblsh instanceof List ? pblsh : [ pblsh ] - - // check elements of publishDir - pblsh = pblsh.collect{ elem -> - // turn into map if not already so - elem = elem instanceof CharSequence ? [ path: elem ] : elem - - // check types and keys - assert elem instanceof Map : "Expected publish argument '$elem' to be a String or a Map. Found: class ${elem.getClass()}" - assertMapKeys(elem, [ "path", "mode", "overwrite", "pattern", "saveAs", "enabled" ], ["path"], "publishDir") - - // check elements in map - assert elem.containsKey("path") - assert elem["path"] instanceof CharSequence - if (elem.containsKey("mode")) { - assert elem["mode"] instanceof CharSequence - assert elem["mode"] in [ "symlink", "rellink", "link", "copy", "copyNoFollow", "move" ] - } - if (elem.containsKey("overwrite")) { - assert elem["overwrite"] instanceof Boolean - } - if (elem.containsKey("pattern")) { - assert elem["pattern"] instanceof CharSequence - } - if (elem.containsKey("saveAs")) { - assert elem["saveAs"] instanceof CharSequence //: "saveAs as a Closure is currently not supported. Surround your closure with single quotes to get the desired effect. Example: '\{ foo \}'" - } - if (elem.containsKey("enabled")) { - assert elem["enabled"] instanceof Boolean - } - - // return final result - elem - } - // store final directive - drctv["publishDir"] = pblsh - } - - /* DIRECTIVE queue - accepted examples: - - "long" - - "short,long" - - ["short", "long"] - */ - if (drctv.containsKey("queue")) { - if (drctv["queue"] instanceof List) { - drctv["queue"] = drctv["queue"].join(",") - } - assert drctv["queue"] instanceof CharSequence - } - - /* DIRECTIVE label - accepted examples: - - "big_mem" - - "big_cpu" - - ["big_mem", "big_cpu"] - */ - if (drctv.containsKey("label")) { - if (drctv["label"] instanceof CharSequence) { - drctv["label"] = [ drctv["label"] ] - } - assert drctv["label"] instanceof List - drctv["label"].forEach { label -> - assert label instanceof CharSequence - // assert label.matches("[a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?") - // ^ does not allow closures - } - } - - /* DIRECTIVE scratch - accepted examples: - - true - - "/path/to/scratch" - - '$MY_PATH_TO_SCRATCH' - - "ram-disk" - */ - if (drctv.containsKey("scratch")) { - assert drctv["scratch"] == true || drctv["scratch"] instanceof CharSequence - } - - /* DIRECTIVE storeDir - accepted examples: - - "/path/to/storeDir" - */ - if (drctv.containsKey("storeDir")) { - assert drctv["storeDir"] instanceof CharSequence - } - - /* DIRECTIVE stageInMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageInMode")) { - assert drctv["stageInMode"] instanceof CharSequence - assert drctv["stageInMode"] in ["copy", "link", "symlink", "rellink"] - } - - /* DIRECTIVE stageOutMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageOutMode")) { - assert drctv["stageOutMode"] instanceof CharSequence - assert drctv["stageOutMode"] in ["copy", "move", "rsync"] - } - - /* DIRECTIVE tag - accepted examples: - - "foo" - - '$id' - */ - if (drctv.containsKey("tag")) { - assert drctv["tag"] instanceof CharSequence - } - - /* DIRECTIVE time - accepted examples: - - "1h" - - "2days" - - "1day 6hours 3minutes 30seconds" - */ - if (drctv.containsKey("time")) { - assert drctv["time"] instanceof CharSequence - // todo: validation regex? - } - - return drctv -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processWorkflowArgs.nf' -def processWorkflowArgs(Map args, Map defaultWfArgs, Map meta) { - // override defaults with args - def workflowArgs = defaultWfArgs + args - - // check whether 'key' exists - assert workflowArgs.containsKey("key") : "Error in module '${meta.config.functionality.name}': key is a required argument" - - // if 'key' is a closure, apply it to the original key - if (workflowArgs["key"] instanceof Closure) { - workflowArgs["key"] = workflowArgs["key"](meta.config.functionality.name) - } - def key = workflowArgs["key"] - assert key instanceof CharSequence : "Expected process argument 'key' to be a String. Found: class ${key.getClass()}" - assert key ==~ /^[a-zA-Z_]\w*$/ : "Error in module '$key': Expected process argument 'key' to consist of only letters, digits or underscores. Found: ${key}" - - // check for any unexpected keys - def expectedKeys = ["key", "directives", "auto", "map", "mapId", "mapData", "mapPassthrough", "filter", "runIf", "fromState", "toState", "args", "renameKeys", "debug"] - def unexpectedKeys = workflowArgs.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Error in module '$key': unexpected arguments to the '.run()' function: '${unexpectedKeys.join("', '")}'" - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("directives") : "Error in module '$key': directives is a required argument" - assert workflowArgs["directives"] instanceof Map : "Error in module '$key': Expected process argument 'directives' to be a Map. Found: class ${workflowArgs['directives'].getClass()}" - workflowArgs["directives"] = processDirectives(defaultWfArgs.directives + workflowArgs["directives"]) - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("auto") : "Error in module '$key': auto is a required argument" - assert workflowArgs["auto"] instanceof Map : "Error in module '$key': Expected process argument 'auto' to be a Map. Found: class ${workflowArgs['auto'].getClass()}" - workflowArgs["auto"] = processAuto(defaultWfArgs.auto + workflowArgs["auto"]) - - // auto define publish, if so desired - if (workflowArgs.auto.publish == true && (workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : [:]).isEmpty()) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.publish is true, params.publish_dir needs to be defined.\n" + - // " Example: params.publish_dir = \"./output/\"" - def publishDir = getPublishDir() - - if (publishDir != null) { - workflowArgs.directives.publishDir = [[ - path: publishDir, - saveAs: "{ it.startsWith('.') ? null : it }", // don't publish hidden files, by default - mode: "copy" - ]] - } - } - - // auto define transcript, if so desired - if (workflowArgs.auto.transcript == true) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("transcriptsDir") || params.containsKey("transcripts_dir") || params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.transcript is true, either params.transcripts_dir or params.publish_dir needs to be defined.\n" + - // " Example: params.transcripts_dir = \"./transcripts/\"" - def transcriptsDir = - params.containsKey("transcripts_dir") ? params.transcripts_dir : - params.containsKey("transcriptsDir") ? params.transcriptsDir : - params.containsKey("publish_dir") ? params.publish_dir + "/_transcripts" : - params.containsKey("publishDir") ? params.publishDir + "/_transcripts" : - null - if (transcriptsDir != null) { - def timestamp = nextflow.Nextflow.getSession().getWorkflowMetadata().start.format('yyyy-MM-dd_HH-mm-ss') - def transcriptsPublishDir = [ - path: "$transcriptsDir/$timestamp/\${task.process.replaceAll(':', '-')}/\${id}/", - saveAs: "{ it.startsWith('.') ? it.replaceAll('^.', '') : null }", - mode: "copy" - ] - def publishDirs = workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : null ? workflowArgs.directives.publishDir : [] - workflowArgs.directives.publishDir = publishDirs + transcriptsPublishDir - } - } - - // if this is a stubrun, remove certain directives? - if (workflow.stubRun) { - workflowArgs.directives.keySet().removeAll(["publishDir", "cpus", "memory", "label"]) - } - - for (nam in ["map", "mapId", "mapData", "mapPassthrough", "filter", "runIf"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam]) { - assert workflowArgs[nam] instanceof Closure : "Error in module '$key': Expected process argument '$nam' to be null or a Closure. Found: class ${workflowArgs[nam].getClass()}" - } - } - - // TODO: should functions like 'map', 'mapId', 'mapData', 'mapPassthrough' be deprecated as well? - for (nam in ["map", "mapData", "mapPassthrough", "renameKeys"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam] != null) { - log.warn "module '$key': workflow argument '$nam' is deprecated and will be removed in Viash 0.9.0. Please use 'fromState' and 'toState' instead." - } - } - - // check fromState - workflowArgs["fromState"] = _processFromState(workflowArgs.get("fromState"), key, meta.config) - - // check toState - workflowArgs["toState"] = _processToState(workflowArgs.get("toState"), key, meta.config) - - // return output - return workflowArgs -} - -def _processFromState(fromState, key_, config_) { - assert fromState == null || fromState instanceof Closure || fromState instanceof Map || fromState instanceof List : - "Error in module '$key_': Expected process argument 'fromState' to be null, a Closure, a Map, or a List. Found: class ${fromState.getClass()}" - if (fromState == null) { - return null - } - - // if fromState is a List, convert to map - if (fromState instanceof List) { - // check whether fromstate is a list[string] - assert fromState.every{it instanceof CharSequence} : "Error in module '$key_': fromState is a List, but not all elements are Strings" - fromState = fromState.collectEntries{[it, it]} - } - - // if fromState is a map, convert to closure - if (fromState instanceof Map) { - // check whether fromstate is a map[string, string] - assert fromState.values().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all values are Strings" - assert fromState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all keys are Strings" - def fromStateMap = fromState.clone() - def requiredInputNames = meta.config.functionality.allArguments.findAll{it.required && it.direction == "Input"}.collect{it.plainName} - // turn the map into a closure to be used later on - fromState = { it -> - def state = it[1] - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def data = fromStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (state.containsKey(origkey)) { - [[newkey, state[origkey]]] - } else if (!requiredInputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': fromState key '$origkey' not found in current state") - } - }.collectEntries() - data - } - } - - return fromState -} - -def _processToState(toState, key_, config_) { - if (toState == null) { - toState = { tup -> tup[1] } - } - - // toState should be a closure, map[string, string], or list[string] - assert toState instanceof Closure || toState instanceof Map || toState instanceof List : - "Error in module '$key_': Expected process argument 'toState' to be a Closure, a Map, or a List. Found: class ${toState.getClass()}" - - // if toState is a List, convert to map - if (toState instanceof List) { - // check whether toState is a list[string] - assert toState.every{it instanceof CharSequence} : "Error in module '$key_': toState is a List, but not all elements are Strings" - toState = toState.collectEntries{[it, it]} - } - - // if toState is a map, convert to closure - if (toState instanceof Map) { - // check whether toState is a map[string, string] - assert toState.values().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all values are Strings" - assert toState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all keys are Strings" - def toStateMap = toState.clone() - def requiredOutputNames = config_.functionality.allArguments.findAll{it.required && it.direction == "Output"}.collect{it.plainName} - // turn the map into a closure to be used later on - toState = { it -> - def output = it[1] - def state = it[2] - assert output instanceof Map : "Error in module '$key_': the output is not a Map" - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def extraEntries = toStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (output.containsKey(origkey)) { - [[newkey, output[origkey]]] - } else if (!requiredOutputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': toState key '$origkey' not found in current output") - } - }.collectEntries() - state + extraEntries - } - } - - return toState -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/workflowFactory.nf' -def _debug(workflowArgs, debugKey) { - if (workflowArgs.debug) { - view { "process '${workflowArgs.key}' $debugKey tuple: $it" } - } else { - map { it } - } -} - -// depends on: innerWorkflowFactory -def workflowFactory(Map args, Map defaultWfArgs, Map meta) { - def workflowArgs = processWorkflowArgs(args, defaultWfArgs, meta) - def key_ = workflowArgs["key"] - - workflow workflowInstance { - take: input_ - - main: - chModified = input_ - | checkUniqueIds([:]) - | _debug(workflowArgs, "input") - | map { tuple -> - tuple = deepClone(tuple) - - if (workflowArgs.map) { - tuple = workflowArgs.map(tuple) - } - if (workflowArgs.mapId) { - tuple[0] = workflowArgs.mapId(tuple[0]) - } - if (workflowArgs.mapData) { - tuple[1] = workflowArgs.mapData(tuple[1]) - } - if (workflowArgs.mapPassthrough) { - tuple = tuple.take(2) + workflowArgs.mapPassthrough(tuple.drop(2)) - } - - // check tuple - assert tuple instanceof List : - "Error in module '${key_}': element in channel should be a tuple [id, data, ...otherargs...]\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: List. Found: tuple.getClass() is ${tuple.getClass()}" - assert tuple.size() >= 2 : - "Error in module '${key_}': expected length of tuple in input channel to be two or greater.\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: tuple.size() == ${tuple.size()}" - - // check id field - assert tuple[0] instanceof CharSequence : - "Error in module '${key_}': first element of tuple in channel should be a String\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: ${tuple[0]}" - - // match file to input file - if (workflowArgs.auto.simplifyInput && (tuple[1] instanceof Path || tuple[1] instanceof List)) { - def inputFiles = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - - assert inputFiles.size() == 1 : - "Error in module '${key_}' id '${tuple[0]}'.\n" + - " Anonymous file inputs are only allowed when the process has exactly one file input.\n" + - " Expected: inputFiles.size() == 1. Found: inputFiles.size() is ${inputFiles.size()}" - - tuple[1] = [[ inputFiles[0].plainName, tuple[1] ]].collectEntries() - } - - // check data field - assert tuple[1] instanceof Map : - "Error in module '${key_}' id '${tuple[0]}': second element of tuple in channel should be a Map\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // rename keys of data field in tuple - if (workflowArgs.renameKeys) { - assert workflowArgs.renameKeys instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class: Map. Found: renameKeys.getClass() is ${workflowArgs.renameKeys.getClass()}" - assert tuple[1] instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // TODO: allow renameKeys to be a function? - workflowArgs.renameKeys.each { newKey, oldKey -> - assert newKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of newKey: String. Found: newKey.getClass() is ${newKey.getClass()}" - assert oldKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of oldKey: String. Found: oldKey.getClass() is ${oldKey.getClass()}" - assert tuple[1].containsKey(oldKey) : - "Error renaming data keys in module '${key}' id '${tuple[0]}'.\n" + - " Key '$oldKey' is missing in the data map. tuple[1].keySet() is '${tuple[1].keySet()}'" - tuple[1].put(newKey, tuple[1][oldKey]) - } - tuple[1].keySet().removeAll(workflowArgs.renameKeys.collect{ newKey, oldKey -> oldKey }) - } - tuple - } - - chModifiedFiltered = workflowArgs.filter ? - chModified | filter{workflowArgs.filter(it)} : - chModified - - if (workflowArgs.runIf) { - runIfBranch = chModifiedFiltered.branch{ tup -> - run: workflowArgs.runIf(tup[0], tup[1]) - passthrough: true - } - chRun = runIfBranch.run - chPassthrough = runIfBranch.passthrough - } else { - chRun = chModifiedFiltered - chPassthrough = Channel.empty() - } - - chArgs = workflowArgs.fromState ? - chRun | map{ - def new_data = workflowArgs.fromState(it.take(2)) - [it[0], new_data] - } : - chRun | map {tup -> tup.take(2)} - - // fill in defaults - chArgsWithDefaults = chArgs - | map { tuple -> - def id_ = tuple[0] - def data_ = tuple[1] - - // TODO: could move fromState to here - - // fetch default params from functionality - def defaultArgs = meta.config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - // fetch overrides in params - def paramArgs = meta.config.functionality.allArguments - .findAll { par -> - def argKey = key_ + "__" + par.plainName - params.containsKey(argKey) - } - .collectEntries { [ it.plainName, params[key_ + "__" + it.plainName] ] } - - // fetch overrides in data - def dataArgs = meta.config.functionality.allArguments - .findAll { data_.containsKey(it.plainName) } - .collectEntries { [ it.plainName, data_[it.plainName] ] } - - // combine params - def combinedArgs = defaultArgs + paramArgs + workflowArgs.args + dataArgs - - // remove arguments with explicit null values - combinedArgs - .removeAll{_, val -> val == null || val == "viash_no_value" || val == "force_null"} - - combinedArgs = _processInputValues(combinedArgs, meta.config, id_, key_) - - [id_, combinedArgs] + tuple.drop(2) - } - - // TODO: move some of the _meta.join_id wrangling to the safeJoin() function. - chInitialOutput = chArgsWithDefaults - | _debug(workflowArgs, "processed") - // run workflow - | innerWorkflowFactory(workflowArgs) - // check output tuple - | map { id_, output_ -> - - // see if output map contains metadata - def meta_ = - output_ instanceof Map && output_.containsKey("_meta") ? - output_["_meta"] : - [:] - def join_id = meta_.join_id ?: id_ - - // remove metadata - output_ = output_.findAll{k, v -> k != "_meta"} - - // check value types - output_ = _processOutputValues(output_, meta.config, id_, key_) - - // simplify output if need be - if (workflowArgs.auto.simplifyOutput && output_.size() == 1) { - output_ = output_.values()[0] - } - - [join_id, id_, output_] - } - // | view{"chInitialOutput: ${it.take(3)}"} - - // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] - chNewState = safeJoin(chInitialOutput, chModifiedFiltered, key_) - // input tuple format: [join_id, id, output, prev_state, ...] - // output tuple format: [join_id, id, new_state, ...] - | map{ tup -> - def new_state = workflowArgs.toState(tup.drop(1).take(3)) - tup.take(2) + [new_state] + tup.drop(4) - } - - if (workflowArgs.auto.publish == "state") { - chPublish = chNewState - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [join_id, id, new_state] - | map{ tup -> - tup.take(3) - } - - safeJoin(chPublish, chArgsWithDefaults, key_) - // input tuple format: [join_id, id, new_state, orig_state, ...] - // output tuple format: [id, new_state, orig_state] - | map { tup -> - tup.drop(1).take(3) - } - | publishStatesByConfig(key: key_, config: meta.config) - } - - // remove join_id and meta - chReturn = chNewState - | map { tup -> - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [id, new_state, ...] - tup.drop(1) - } - | _debug(workflowArgs, "output") - | concat(chPassthrough) - - emit: chReturn - } - - def wf = workflowInstance.cloneWithName(key_) - - // add factory function - wf.metaClass.run = { runArgs -> - workflowFactory(runArgs, workflowArgs, meta) - } - // add config to module for later introspection - wf.metaClass.config = meta.config - - return wf -} - -nextflow.enable.dsl=2 - -// START COMPONENT-SPECIFIC CODE - -// create meta object -meta = [ - "resources_dir": moduleDir.toRealPath().normalize(), - "config": processConfig(readJsonBlob('''{ - "functionality" : { - "name" : "vsh_toList", - "namespace" : "join", - "version" : "0.2.0", - "arguments" : [ - { - "type" : "string", - "name" : "--id", - "description" : "ID of the output event", - "required" : true, - "direction" : "input", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - }, - { - "type" : "file", - "name" : "--input", - "alternatives" : [ - "-i" - ], - "description" : "Mutiple channel events to be combined under the output key", - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "input", - "multiple" : false, - "multiple_sep" : ";", - "dest" : "par" - }, - { - "type" : "file", - "name" : "--output", - "alternatives" : [ - "-o" - ], - "description" : "Content of the output key in the output channel", - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "output", - "multiple" : true, - "multiple_sep" : ":", - "dest" : "par" - } - ], - "resources" : [ - { - "type" : "nextflow_script", - "path" : "main.nf", - "is_executable" : true, - "parent" : "file:/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/src/join/vsh_toList/", - "entrypoint" : "run_wf" - } - ], - "description" : "A wrapper component for the Nextflow toList operator\nthat fits the Viash way of doing things.\n", - "status" : "enabled", - "requirements" : { - "commands" : [ - "ps" - ] - }, - "set_wd_to_resources_dir" : false - }, - "platforms" : [ - { - "type" : "nextflow", - "id" : "nextflow", - "directives" : { - "tag" : "$id" - }, - "auto" : { - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false - }, - "config" : { - "labels" : { - "mem1gb" : "memory = 1.GB", - "mem2gb" : "memory = 2.GB", - "mem4gb" : "memory = 4.GB", - "mem8gb" : "memory = 8.GB", - "mem16gb" : "memory = 16.GB", - "mem32gb" : "memory = 32.GB", - "mem64gb" : "memory = 64.GB", - "mem128gb" : "memory = 128.GB", - "mem256gb" : "memory = 256.GB", - "mem512gb" : "memory = 512.GB", - "mem1tb" : "memory = 1.TB", - "mem2tb" : "memory = 2.TB", - "mem4tb" : "memory = 4.TB", - "mem8tb" : "memory = 8.TB", - "mem16tb" : "memory = 16.TB", - "mem32tb" : "memory = 32.TB", - "mem64tb" : "memory = 64.TB", - "mem128tb" : "memory = 128.TB", - "mem256tb" : "memory = 256.TB", - "mem512tb" : "memory = 512.TB", - "cpu1" : "cpus = 1", - "cpu2" : "cpus = 2", - "cpu5" : "cpus = 5", - "cpu10" : "cpus = 10", - "cpu20" : "cpus = 20", - "cpu50" : "cpus = 50", - "cpu100" : "cpus = 100", - "cpu200" : "cpus = 200", - "cpu500" : "cpus = 500", - "cpu1000" : "cpus = 1000" - } - }, - "debug" : false, - "container" : "docker" - } - ], - "info" : { - "config" : "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/src/join/vsh_toList/config.vsh.yaml", - "platform" : "nextflow", - "output" : "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/target/nextflow/join/vsh_toList", - "viash_version" : "0.8.3", - "git_commit" : "05a5bfa4eaa2c04ba473671e4d30c6c18aceec6e", - "git_remote" : "git@viash-hub.com:data-intuitive/vsh-pipeline-operators.git" - } -}''')) -] - -// resolve dependencies dependencies (if any) - - -// inner workflow -// user-provided Nextflow code -workflow run_wf { - take: - input_ch - - main: - output_ch = input_ch - - | toSortedList - - | map{ lst -> - def new_id = lst[0][1].id - def old_id = lst[0][0] - [ - new_id, - [ - output: lst.collect{ id, state -> state.input }, - _meta: [ join_id: old_id ] - ] - ] - } - - emit: - output_ch -} - -// inner workflow hook -def innerWorkflowFactory(args) { - return run_wf -} - -// defaults -meta["defaults"] = [ - // key to be used to trace the process and determine output names - key: null, - - // fixed arguments to be passed to script - args: [:], - - // default directives - directives: readJsonBlob('''{ - "tag" : "$id" -}'''), - - // auto settings - auto: readJsonBlob('''{ - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false -}'''), - - // Apply a map over the incoming tuple - // Example: `{ tup -> [ tup[0], [input: tup[1].output] ] + tup.drop(2) }` - map: null, - - // Apply a map over the ID element of a tuple (i.e. the first element) - // Example: `{ id -> id + "_foo" }` - mapId: null, - - // Apply a map over the data element of a tuple (i.e. the second element) - // Example: `{ data -> [ input: data.output ] }` - mapData: null, - - // Apply a map over the passthrough elements of a tuple (i.e. the tuple excl. the first two elements) - // Example: `{ pt -> pt.drop(1) }` - mapPassthrough: null, - - // Filter the channel - // Example: `{ tup -> tup[0] == "foo" }` - filter: null, - - // Choose whether or not to run the component on the tuple if the condition is true. - // Otherwise, the tuple will be passed through. - // Example: `{ tup -> tup[0] != "skip_this" }` - runIf: null, - - // Rename keys in the data field of the tuple (i.e. the second element) - // Will likely be deprecated in favour of `fromState`. - // Example: `[ "new_key": "old_key" ]` - renameKeys: null, - - // Fetch data from the state and pass it to the module without altering the current state. - // - // `fromState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be passed to the module as is. - // - If it is a `List[String]`, the data will be the values of the state at the given keys. - // - If it is a `Map[String, String]`, the data will be the values of the state at the given keys, with the keys renamed according to the map. - // - If it is a function, the tuple (`[id, state]`) in the channel will be passed to the function, and the result will be used as the data. - // - // Example: `{ id, state -> [input: state.fastq_file] }` - // Default: `null` - fromState: null, - - // Determine how the state should be updated after the module has been run. - // - // `toState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be replaced with the output of the module. - // - If it is a `List[String]`, the state will be updated with the values of the data at the given keys. - // - If it is a `Map[String, String]`, the state will be updated with the values of the data at the given keys, with the keys renamed according to the map. - // - If it is a function, a tuple (`[id, output, state]`) will be passed to the function, and the result will be used as the new state. - // - // Example: `{ id, output, state -> state + [counts: state.output] }` - // Default: `{ id, output, state -> output }` - toState: null, - - // Whether or not to print debug messages - // Default: `false` - debug: false -] - -// initialise default workflow -meta["workflow"] = workflowFactory([key: meta.config.functionality.name], meta.defaults, meta) - -// add workflow to environment -nextflow.script.ScriptMeta.current().addDefinition(meta.workflow) - -// anonymous workflow for running this module as a standalone -workflow { - // add id argument if it's not already in the config - // TODO: deep copy - def newConfig = deepClone(meta.config) - def newParams = deepClone(params) - - def argsContainsId = newConfig.functionality.allArguments.any{it.plainName == "id"} - if (!argsContainsId) { - def idArg = [ - 'name': '--id', - 'required': false, - 'type': 'string', - 'description': 'A unique id for every entry.', - 'multiple': false - ] - newConfig.functionality.arguments.add(0, idArg) - newConfig = processConfig(newConfig) - } - if (!newParams.containsKey("id")) { - newParams.id = "run" - } - - helpMessage(newConfig) - - channelFromParams(newParams, newConfig) - // make sure id is not in the state if id is not in the args - | map {id, state -> - if (!argsContainsId) { - [id, state.findAll{k, v -> k != "id"}] - } else { - [id, state] - } - } - | meta.workflow.run( - auto: [ publish: "state" ] - ) -} - -// END COMPONENT-SPECIFIC CODE diff --git a/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/nextflow.config b/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/nextflow.config deleted file mode 100644 index 6ed6502..0000000 --- a/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/nextflow.config +++ /dev/null @@ -1,107 +0,0 @@ -manifest { - name = 'join/vsh_toList' - mainScript = 'main.nf' - nextflowVersion = '!>=20.12.1-edge' - version = '0.2.0' - description = 'A wrapper component for the Nextflow toList operator\nthat fits the Viash way of doing things.\n' -} - -process.container = 'nextflow/bash:latest' - -// detect tempdir -tempDir = java.nio.file.Paths.get( - System.getenv('NXF_TEMP') ?: - System.getenv('VIASH_TEMP') ?: - System.getenv('TEMPDIR') ?: - System.getenv('TMPDIR') ?: - '/tmp' -).toAbsolutePath() - -profiles { - no_publish { - process { - withName: '.*' { - publishDir = [ - enabled: false - ] - } - } - } - mount_temp { - docker.temp = tempDir - podman.temp = tempDir - charliecloud.temp = tempDir - } - docker { - docker.enabled = true - // docker.userEmulation = true - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - singularity { - singularity.enabled = true - singularity.autoMounts = true - docker.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - podman { - podman.enabled = true - docker.enabled = false - singularity.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - shifter { - shifter.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - charliecloud.enabled = false - } - charliecloud { - charliecloud.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - } -} - -process{ - withLabel: mem1gb { memory = 1.GB } - withLabel: mem2gb { memory = 2.GB } - withLabel: mem4gb { memory = 4.GB } - withLabel: mem8gb { memory = 8.GB } - withLabel: mem16gb { memory = 16.GB } - withLabel: mem32gb { memory = 32.GB } - withLabel: mem64gb { memory = 64.GB } - withLabel: mem128gb { memory = 128.GB } - withLabel: mem256gb { memory = 256.GB } - withLabel: mem512gb { memory = 512.GB } - withLabel: mem1tb { memory = 1.TB } - withLabel: mem2tb { memory = 2.TB } - withLabel: mem4tb { memory = 4.TB } - withLabel: mem8tb { memory = 8.TB } - withLabel: mem16tb { memory = 16.TB } - withLabel: mem32tb { memory = 32.TB } - withLabel: mem64tb { memory = 64.TB } - withLabel: mem128tb { memory = 128.TB } - withLabel: mem256tb { memory = 256.TB } - withLabel: mem512tb { memory = 512.TB } - withLabel: cpu1 { cpus = 1 } - withLabel: cpu2 { cpus = 2 } - withLabel: cpu5 { cpus = 5 } - withLabel: cpu10 { cpus = 10 } - withLabel: cpu20 { cpus = 20 } - withLabel: cpu50 { cpus = 50 } - withLabel: cpu100 { cpus = 100 } - withLabel: cpu200 { cpus = 200 } - withLabel: cpu500 { cpus = 500 } - withLabel: cpu1000 { cpus = 1000 } -} - - diff --git a/target/docker/template/combine_columns/.config.vsh.yaml b/target/docker/template/combine_columns/.config.vsh.yaml deleted file mode 100644 index 41807c6..0000000 --- a/target/docker/template/combine_columns/.config.vsh.yaml +++ /dev/null @@ -1,101 +0,0 @@ -functionality: - name: "combine_columns" - namespace: "template" - version: "0.2.2" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - info: null - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: true - multiple_sep: ":" - dest: "par" - - type: "file" - name: "--output" - alternatives: - - "-o" - info: null - must_exist: true - create_parent: true - required: true - direction: "output" - multiple: false - multiple_sep: ":" - dest: "par" - resources: - - type: "r_script" - path: "script.R" - is_executable: true - info: null - status: "enabled" - set_wd_to_resources_dir: false -platforms: -- type: "docker" - id: "docker" - image: "eddelbuettel/r2u:22.04" - target_organization: "viash-io/viash_project_template" - target_registry: "ghcr.io" - namespace_separator: "/" - resolve_volume: "Automatic" - chown: true - setup_strategy: "ifneedbepullelsecachedbuild" - target_image_source: "https://github.com/viash-io/viash_project_template" - entrypoint: [] - cmd: null -- type: "nextflow" - id: "nextflow" - directives: - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1.GB" - mem2gb: "memory = 2.GB" - mem4gb: "memory = 4.GB" - mem8gb: "memory = 8.GB" - mem16gb: "memory = 16.GB" - mem32gb: "memory = 32.GB" - mem64gb: "memory = 64.GB" - mem128gb: "memory = 128.GB" - mem256gb: "memory = 256.GB" - mem512gb: "memory = 512.GB" - mem1tb: "memory = 1.TB" - mem2tb: "memory = 2.TB" - mem4tb: "memory = 4.TB" - mem8tb: "memory = 8.TB" - mem16tb: "memory = 16.TB" - mem32tb: "memory = 32.TB" - mem64tb: "memory = 64.TB" - mem128tb: "memory = 128.TB" - mem256tb: "memory = 256.TB" - mem512tb: "memory = 512.TB" - cpu1: "cpus = 1" - cpu2: "cpus = 2" - cpu5: "cpus = 5" - cpu10: "cpus = 10" - cpu20: "cpus = 20" - cpu50: "cpus = 50" - cpu100: "cpus = 100" - cpu200: "cpus = 200" - cpu500: "cpus = 500" - cpu1000: "cpus = 1000" - debug: false - container: "docker" -info: - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/combine_columns/config.vsh.yaml" - platform: "docker" - output: "/Users/toni/code/projects/viash/viash_project_template/target/docker/template/combine_columns" - executable: "/Users/toni/code/projects/viash/viash_project_template/target/docker/template/combine_columns/combine_columns" - viash_version: "0.8.4" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - git_remote: "https://github.com/viash-io/viash_project_template" - git_tag: "v0.2.1" diff --git a/target/docker/template/combine_columns/combine_columns b/target/docker/template/combine_columns/combine_columns deleted file mode 100755 index a1b4984..0000000 --- a/target/docker/template/combine_columns/combine_columns +++ /dev/null @@ -1,977 +0,0 @@ -#!/usr/bin/env bash - -# combine_columns 0.2.2 -# -# This wrapper script is auto-generated by viash 0.8.4 and is thus a derivative -# work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data -# Intuitive. -# -# The component may contain files which fall under a different license. The -# authors of this component should specify the license in the header of such -# files, or include a separate license file detailing the licenses of all included -# files. - -set -e - -if [ -z "$VIASH_TEMP" ]; then - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TEMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMP} - VIASH_TEMP=${VIASH_TEMP:-$TMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$TMP} - VIASH_TEMP=${VIASH_TEMP:-$TEMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$TEMP} - VIASH_TEMP=${VIASH_TEMP:-/tmp} -fi - -# define helper functions -# ViashQuote: put quotes around non flag values -# $1 : unquoted string -# return : possibly quoted string -# examples: -# ViashQuote --foo # returns --foo -# ViashQuote bar # returns 'bar' -# Viashquote --foo=bar # returns --foo='bar' -function ViashQuote { - if [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+=.+$ ]]; then - echo "$1" | sed "s#=\(.*\)#='\1'#" - elif [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+$ ]]; then - echo "$1" - else - echo "'$1'" - fi -} -# ViashRemoveFlags: Remove leading flag -# $1 : string with a possible leading flag -# return : string without possible leading flag -# examples: -# ViashRemoveFlags --foo=bar # returns bar -function ViashRemoveFlags { - echo "$1" | sed 's/^--*[a-zA-Z0-9_\-]*=//' -} -# ViashSourceDir: return the path of a bash file, following symlinks -# usage : ViashSourceDir ${BASH_SOURCE[0]} -# $1 : Should always be set to ${BASH_SOURCE[0]} -# returns : The absolute path of the bash file -function ViashSourceDir { - SOURCE="$1" - while [ -h "$SOURCE" ]; do - DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )" - SOURCE="$(readlink "$SOURCE")" - [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" - done - cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd -} -# ViashFindTargetDir: return the path of the '.build.yaml' file, following symlinks -# usage : ViashFindTargetDir 'ScriptPath' -# $1 : The location from where to start the upward search -# returns : The absolute path of the '.build.yaml' file -function ViashFindTargetDir { - SOURCE="$1" - while [[ "$SOURCE" != "" && ! -e "$SOURCE/.build.yaml" ]]; do - SOURCE=${SOURCE%/*} - done - echo $SOURCE -} -# see https://en.wikipedia.org/wiki/Syslog#Severity_level -VIASH_LOGCODE_EMERGENCY=0 -VIASH_LOGCODE_ALERT=1 -VIASH_LOGCODE_CRITICAL=2 -VIASH_LOGCODE_ERROR=3 -VIASH_LOGCODE_WARNING=4 -VIASH_LOGCODE_NOTICE=5 -VIASH_LOGCODE_INFO=6 -VIASH_LOGCODE_DEBUG=7 -VIASH_VERBOSITY=$VIASH_LOGCODE_NOTICE - -# ViashLog: Log events depending on the verbosity level -# usage: ViashLog 1 alert Oh no something went wrong! -# $1: required verbosity level -# $2: display tag -# $3+: messages to display -# stdout: Your input, prepended by '[$2] '. -function ViashLog { - local required_level="$1" - local display_tag="$2" - shift 2 - if [ $VIASH_VERBOSITY -ge $required_level ]; then - >&2 echo "[$display_tag]" "$@" - fi -} - -# ViashEmergency: log events when the system is unstable -# usage: ViashEmergency Oh no something went wrong. -# stdout: Your input, prepended by '[emergency] '. -function ViashEmergency { - ViashLog $VIASH_LOGCODE_EMERGENCY emergency "$@" -} - -# ViashAlert: log events when actions must be taken immediately (e.g. corrupted system database) -# usage: ViashAlert Oh no something went wrong. -# stdout: Your input, prepended by '[alert] '. -function ViashAlert { - ViashLog $VIASH_LOGCODE_ALERT alert "$@" -} - -# ViashCritical: log events when a critical condition occurs -# usage: ViashCritical Oh no something went wrong. -# stdout: Your input, prepended by '[critical] '. -function ViashCritical { - ViashLog $VIASH_LOGCODE_CRITICAL critical "$@" -} - -# ViashError: log events when an error condition occurs -# usage: ViashError Oh no something went wrong. -# stdout: Your input, prepended by '[error] '. -function ViashError { - ViashLog $VIASH_LOGCODE_ERROR error "$@" -} - -# ViashWarning: log potentially abnormal events -# usage: ViashWarning Something may have gone wrong. -# stdout: Your input, prepended by '[warning] '. -function ViashWarning { - ViashLog $VIASH_LOGCODE_WARNING warning "$@" -} - -# ViashNotice: log significant but normal events -# usage: ViashNotice This just happened. -# stdout: Your input, prepended by '[notice] '. -function ViashNotice { - ViashLog $VIASH_LOGCODE_NOTICE notice "$@" -} - -# ViashInfo: log normal events -# usage: ViashInfo This just happened. -# stdout: Your input, prepended by '[info] '. -function ViashInfo { - ViashLog $VIASH_LOGCODE_INFO info "$@" -} - -# ViashDebug: log all events, for debugging purposes -# usage: ViashDebug This just happened. -# stdout: Your input, prepended by '[debug] '. -function ViashDebug { - ViashLog $VIASH_LOGCODE_DEBUG debug "$@" -} - -# find source folder of this component -VIASH_META_RESOURCES_DIR=`ViashSourceDir ${BASH_SOURCE[0]}` - -# find the root of the built components & dependencies -VIASH_TARGET_DIR=`ViashFindTargetDir $VIASH_META_RESOURCES_DIR` - -# define meta fields -VIASH_META_FUNCTIONALITY_NAME="combine_columns" -VIASH_META_EXECUTABLE="$VIASH_META_RESOURCES_DIR/$VIASH_META_FUNCTIONALITY_NAME" -VIASH_META_CONFIG="$VIASH_META_RESOURCES_DIR/.config.vsh.yaml" -VIASH_META_TEMP_DIR="$VIASH_TEMP" - - -# ViashHelp: Display helpful explanation about this executable -function ViashHelp { - echo "combine_columns 0.2.2" - echo "" - echo "Arguments:" - echo " -i, --input" - echo " type: file, required parameter, multiple values allowed, file must exist" - echo "" - echo " -o, --output" - echo " type: file, required parameter, output, file must exist" -} - -######## Helper functions for setting up Docker images for viash ######## -# expects: ViashDockerBuild - -# ViashDockerInstallationCheck: check whether Docker is installed correctly -# -# examples: -# ViashDockerInstallationCheck -function ViashDockerInstallationCheck { - ViashDebug "Checking whether Docker is installed" - if [ ! command -v docker &> /dev/null ]; then - ViashCritical "Docker doesn't seem to be installed. See 'https://docs.docker.com/get-docker/' for instructions." - exit 1 - fi - - ViashDebug "Checking whether the Docker daemon is running" - save=$-; set +e - docker_version=$(docker version --format '{{.Client.APIVersion}}' 2> /dev/null) - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashCritical "Docker daemon does not seem to be running. Try one of the following:" - ViashCritical "- Try running 'dockerd' in the command line" - ViashCritical "- See https://docs.docker.com/config/daemon/" - exit 1 - fi -} - -# ViashDockerRemoteTagCheck: check whether a Docker image is available -# on a remote. Assumes `docker login` has been performed, if relevant. -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerRemoteTagCheck python:latest -# echo $? # returns '0' -# ViashDockerRemoteTagCheck sdaizudceahifu -# echo $? # returns '1' -function ViashDockerRemoteTagCheck { - docker manifest inspect $1 > /dev/null 2> /dev/null -} - -# ViashDockerLocalTagCheck: check whether a Docker image is available locally -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# docker pull python:latest -# ViashDockerLocalTagCheck python:latest -# echo $? # returns '0' -# ViashDockerLocalTagCheck sdaizudceahifu -# echo $? # returns '1' -function ViashDockerLocalTagCheck { - [ -n "$(docker images -q $1)" ] -} - -# ViashDockerPull: pull a Docker image -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerPull python:latest -# echo $? # returns '0' -# ViashDockerPull sdaizudceahifu -# echo $? # returns '1' -function ViashDockerPull { - ViashNotice "Checking if Docker image is available at '$1'" - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker pull $1 && return 0 || return 1 - else - save=$-; set +e - docker pull $1 2> /dev/null > /dev/null - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashWarning "Could not pull from '$1'. Docker image doesn't exist or is not accessible." - fi - return $out - fi -} - -# ViashDockerPush: push a Docker image -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerPush python:latest -# echo $? # returns '0' -# ViashDockerPush sdaizudceahifu -# echo $? # returns '1' -function ViashDockerPush { - ViashNotice "Pushing image to '$1'" - save=$-; set +e - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker push $1 - out=$? - else - docker push $1 2> /dev/null > /dev/null - out=$? - fi - [[ $save =~ e ]] && set -e - if [ $out -eq 0 ]; then - ViashNotice "Container '$VSHD_ID' push succeeded." - else - ViashError "Container '$VSHD_ID' push errored. You might not be logged in or have the necessary permissions." - fi - return $out -} - -# ViashDockerPullElseBuild: pull a Docker image, else build it -# -# $1 : image identifier with format `[registry/]image[:tag]` -# ViashDockerBuild : a Bash function which builds a docker image, takes image identifier as argument. -# examples: -# ViashDockerPullElseBuild mynewcomponent -function ViashDockerPullElseBuild { - save=$-; set +e - ViashDockerPull $1 - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashDockerBuild $@ - fi -} - -# ViashDockerSetup: create a Docker image, according to specified docker setup strategy -# -# $1 : image identifier with format `[registry/]image[:tag]` -# $2 : docker setup strategy, see DockerSetupStrategy.scala -# ViashDockerBuild : a Bash function which builds a docker image, takes image identifier as argument. -# examples: -# ViashDockerSetup mynewcomponent alwaysbuild -function ViashDockerSetup { - VSHD_ID="$1" - VSHD_STRAT="$2" - if [ "$VSHD_STRAT" == "alwaysbuild" -o "$VSHD_STRAT" == "build" -o "$VSHD_STRAT" == "b" ]; then - ViashDockerBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "alwayspull" -o "$VSHD_STRAT" == "pull" -o "$VSHD_STRAT" == "p" ]; then - ViashDockerPull $VSHD_ID - elif [ "$VSHD_STRAT" == "alwayspullelsebuild" -o "$VSHD_STRAT" == "pullelsebuild" ]; then - ViashDockerPullElseBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "alwayspullelsecachedbuild" -o "$VSHD_STRAT" == "pullelsecachedbuild" ]; then - ViashDockerPullElseBuild $VSHD_ID - elif [ "$VSHD_STRAT" == "alwayscachedbuild" -o "$VSHD_STRAT" == "cachedbuild" -o "$VSHD_STRAT" == "cb" ]; then - ViashDockerBuild $VSHD_ID - elif [[ "$VSHD_STRAT" =~ ^ifneedbe ]]; then - save=$-; set +e - ViashDockerLocalTagCheck $VSHD_ID - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -eq 0 ]; then - ViashInfo "Image $VSHD_ID already exists" - elif [ "$VSHD_STRAT" == "ifneedbebuild" ]; then - ViashDockerBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "ifneedbecachedbuild" ]; then - ViashDockerBuild $VSHD_ID - elif [ "$VSHD_STRAT" == "ifneedbepull" ]; then - ViashDockerPull $VSHD_ID - elif [ "$VSHD_STRAT" == "ifneedbepullelsebuild" ]; then - ViashDockerPullElseBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "ifneedbepullelsecachedbuild" ]; then - ViashDockerPullElseBuild $VSHD_ID - else - ViashError "Unrecognised Docker strategy: $VSHD_STRAT" - exit 1 - fi - elif [ "$VSHD_STRAT" == "push" -o "$VSHD_STRAT" == "forcepush" -o "$VSHD_STRAT" == "alwayspush" ]; then - ViashDockerPush "$VSHD_ID" - elif [ "$VSHD_STRAT" == "pushifnotpresent" -o "$VSHD_STRAT" == "gentlepush" -o "$VSHD_STRAT" == "maybepush" ]; then - save=$-; set +e - ViashDockerRemoteTagCheck $VSHD_ID - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -eq 0 ]; then - ViashNotice "Container '$VSHD_ID' exists, doing nothing." - else - ViashNotice "Container '$VSHD_ID' does not yet exist." - ViashDockerPush "$VSHD_ID" - fi - elif [ "$VSHD_STRAT" == "donothing" -o "$VSHD_STRAT" == "meh" ]; then - ViashNotice "Skipping setup." - else - ViashError "Unrecognised Docker strategy: $VSHD_STRAT" - exit 1 - fi -} - -# ViashDockerCheckCommands: Check whether a docker container has the required commands -# -# $1 : image identifier with format `[registry/]image[:tag]` -# $@ : commands to verify being present -# examples: -# ViashDockerCheckCommands bash:4.0 bash ps foo -function ViashDockerCheckCommands { - tag=$1 - shift 1 - commands="$@" - save=$-; set +e - missing=$(docker run --rm --entrypoint=sh $tag -c "for command in $commands; do command -v \$command >/dev/null 2>&1; if [ \$? -ne 0 ]; then echo \$command; exit 1; fi; done") - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -ne 0 ]; then - ViashError "Docker container '$tag' does not contain command '$missing'." - exit 1 - fi -} - - -######## End of helper functions for setting up Docker images for viash ######## - -# ViashDockerFile: print the dockerfile to stdout -# return : dockerfile required to run this component -# examples: -# ViashDockerFile -function ViashDockerfile { - cat << 'VIASHDOCKER' -FROM eddelbuettel/r2u:22.04 - -ENTRYPOINT [] - - -RUN : -LABEL org.opencontainers.image.description="Companion container for running component template combine_columns" -LABEL org.opencontainers.image.created="2024-01-16T14:48:43+01:00" -LABEL org.opencontainers.image.source="https://github.com/viash-io/viash_project_template" -LABEL org.opencontainers.image.revision="11b6278597bf22afbfb56a8e83065a55553c9dd0" -LABEL org.opencontainers.image.version="0.2.2" - -VIASHDOCKER -} - -# ViashDockerBuild: build a docker container -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was built -function ViashDockerBuild { - # create temporary directory to store dockerfile & optional resources in - tmpdir=$(mktemp -d "$VIASH_META_TEMP_DIR/dockerbuild-combine_columns-XXXXXX") - dockerfile="$tmpdir/Dockerfile" - function clean_up { - rm -rf "$tmpdir" - } - trap clean_up EXIT - - # store dockerfile and resources - ViashDockerfile > $dockerfile - - # Build the container - ViashNotice "Building container '$1' with Dockerfile" - ViashInfo "Running 'docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile'" - save=$-; set +e - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile - else - docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile &> $tmpdir/docker_build.log - fi - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashError "Error occurred while building container '$1'" - if [ $VIASH_VERBOSITY -lt $VIASH_LOGCODE_INFO ]; then - ViashError "Transcript: --------------------------------" - cat "$tmpdir/docker_build.log" - ViashError "End of transcript --------------------------" - fi - exit 1 - fi - ViashDockerCheckCommands "$1" 'bash' -} - -# ViashAbsolutePath: generate absolute path from relative path -# borrowed from https://stackoverflow.com/a/21951256 -# $1 : relative filename -# return : absolute path -# examples: -# ViashAbsolutePath some_file.txt # returns /path/to/some_file.txt -# ViashAbsolutePath /foo/bar/.. # returns /foo -function ViashAbsolutePath { - local thePath - if [[ ! "$1" =~ ^/ ]]; then - thePath="$PWD/$1" - else - thePath="$1" - fi - echo "$thePath" | ( - IFS=/ - read -a parr - declare -a outp - for i in "${parr[@]}"; do - case "$i" in - ''|.) continue ;; - ..) - len=${#outp[@]} - if ((len==0)); then - continue - else - unset outp[$((len-1))] - fi - ;; - *) - len=${#outp[@]} - outp[$len]="$i" - ;; - esac - done - echo /"${outp[*]}" - ) -} -# ViashAutodetectMount: auto configuring docker mounts from parameters -# $1 : The parameter value -# returns : New parameter -# $VIASH_EXTRA_MOUNTS : Added another parameter to be passed to docker -# examples: -# ViashAutodetectMount /path/to/bar # returns '/viash_automount/path/to/bar' -# ViashAutodetectMountArg /path/to/bar # returns '--volume="/path/to:/viash_automount/path/to"' -function ViashAutodetectMount { - abs_path=$(ViashAbsolutePath "$1") - if [ -d "$abs_path" ]; then - mount_source="$abs_path" - base_name="" - else - mount_source=`dirname "$abs_path"` - base_name=`basename "$abs_path"` - fi - mount_target="/viash_automount$mount_source" - echo "$mount_target/$base_name" -} -function ViashAutodetectMountArg { - abs_path=$(ViashAbsolutePath "$1") - if [ -d "$abs_path" ]; then - mount_source="$abs_path" - base_name="" - else - mount_source=`dirname "$abs_path"` - base_name=`basename "$abs_path"` - fi - mount_target="/viash_automount$mount_source" - ViashDebug "ViashAutodetectMountArg $1 -> $mount_source -> $mount_target" - echo "--volume=\"$mount_source:$mount_target\"" -} -function ViashStripAutomount { - abs_path=$(ViashAbsolutePath "$1") - echo "${abs_path#/viash_automount}" -} -# ViashExtractFlags: Retain leading flag -# $1 : string with a possible leading flag -# return : leading flag -# examples: -# ViashExtractFlags --foo=bar # returns --foo -function ViashExtractFlags { - echo $1 | sed 's/=.*//' -} -# initialise variables -VIASH_EXTRA_MOUNTS=() - -# initialise array -VIASH_POSITIONAL_ARGS='' -VIASH_MODE='run' - -while [[ $# -gt 0 ]]; do - case "$1" in - -h|--help) - ViashHelp - exit - ;; - ---v|---verbose) - let "VIASH_VERBOSITY=VIASH_VERBOSITY+1" - shift 1 - ;; - ---verbosity) - VIASH_VERBOSITY="$2" - shift 2 - ;; - ---verbosity=*) - VIASH_VERBOSITY="$(ViashRemoveFlags "$1")" - shift 1 - ;; - --version) - echo "combine_columns 0.2.2" - exit - ;; - --input) - if [ -z "$VIASH_PAR_INPUT" ]; then - VIASH_PAR_INPUT="$2" - else - VIASH_PAR_INPUT="$VIASH_PAR_INPUT:""$2" - fi - [ $# -lt 2 ] && ViashError Not enough arguments passed to --input. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --input=*) - if [ -z "$VIASH_PAR_INPUT" ]; then - VIASH_PAR_INPUT=$(ViashRemoveFlags "$1") - else - VIASH_PAR_INPUT="$VIASH_PAR_INPUT:"$(ViashRemoveFlags "$1") - fi - shift 1 - ;; - -i) - if [ -z "$VIASH_PAR_INPUT" ]; then - VIASH_PAR_INPUT="$2" - else - VIASH_PAR_INPUT="$VIASH_PAR_INPUT:""$2" - fi - [ $# -lt 2 ] && ViashError Not enough arguments passed to -i. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --output) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'--output\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --output. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --output=*) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'--output=*\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT=$(ViashRemoveFlags "$1") - shift 1 - ;; - -o) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'-o\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to -o. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - ---setup) - VIASH_MODE='docker_setup' - VIASH_DOCKER_SETUP_STRATEGY="$2" - shift 1 - ;; - ---setup=*) - VIASH_MODE='docker_setup' - VIASH_DOCKER_SETUP_STRATEGY="$(ViashRemoveFlags "$1")" - shift 2 - ;; - ---dockerfile) - ViashDockerfile - exit 0 - ;; - ---v|---volume) - VIASH_EXTRA_MOUNTS+=("--volume='$2'") - shift 2 - ;; - ---volume=*) - VIASH_EXTRA_MOUNTS+=("--volume='$(ViashRemoveFlags "$2")'") - shift 1 - ;; - ---debug) - VIASH_MODE='docker_debug' - shift 1 - ;; - ---cpus) - [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_CPUS="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to ---cpus. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - ---cpus=*) - [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus=*\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_CPUS=$(ViashRemoveFlags "$1") - shift 1 - ;; - ---memory) - [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_MEMORY="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to ---memory. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - ---memory=*) - [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory=*\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_MEMORY=$(ViashRemoveFlags "$1") - shift 1 - ;; - *) # positional arg or unknown option - # since the positional args will be eval'd, can we always quote, instead of using ViashQuote - VIASH_POSITIONAL_ARGS="$VIASH_POSITIONAL_ARGS '$1'" - [[ $1 == -* ]] && ViashWarning $1 looks like a parameter but is not a defined parameter and will instead be treated as a positional argument. Use "--help" to get more information on the parameters. - shift # past argument - ;; - esac -done - -# parse positional parameters -eval set -- $VIASH_POSITIONAL_ARGS - - -ViashDockerInstallationCheck - -if [ $VIASH_MODE == "docker_setup" ]; then - ViashDockerSetup 'ghcr.io/viash-io/viash_project_template/template/combine_columns:0.2.2' "$VIASH_DOCKER_SETUP_STRATEGY" - exit 0 -fi -ViashDockerSetup 'ghcr.io/viash-io/viash_project_template/template/combine_columns:0.2.2' ifneedbepullelsecachedbuild - -if [ $VIASH_MODE == "docker_debug" ]; then - ViashNotice "+ docker run --entrypoint=bash -i --rm -v "$(pwd)":/pwd --workdir /pwd -t 'ghcr.io/viash-io/viash_project_template/template/combine_columns:0.2.2'" - docker run --entrypoint=bash -i --rm -v "$(pwd)":/pwd --workdir /pwd -t 'ghcr.io/viash-io/viash_project_template/template/combine_columns:0.2.2' - exit 0 -fi - -# setting computational defaults - -# helper function for parsing memory strings -function ViashMemoryAsBytes { - local memory=`echo "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]'` - local memory_regex='^([0-9]+)([kmgtp]b?|b)$' - if [[ $memory =~ $memory_regex ]]; then - local number=${memory/[^0-9]*/} - local symbol=${memory/*[0-9]/} - - case $symbol in - b) memory_b=$number ;; - kb|k) memory_b=$(( $number * 1024 )) ;; - mb|m) memory_b=$(( $number * 1024 * 1024 )) ;; - gb|g) memory_b=$(( $number * 1024 * 1024 * 1024 )) ;; - tb|t) memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 )) ;; - pb|p) memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 * 1024 )) ;; - esac - echo "$memory_b" - fi -} -# compute memory in different units -if [ ! -z ${VIASH_META_MEMORY+x} ]; then - VIASH_META_MEMORY_B=`ViashMemoryAsBytes $VIASH_META_MEMORY` - # do not define other variables if memory_b is an empty string - if [ ! -z "$VIASH_META_MEMORY_B" ]; then - VIASH_META_MEMORY_KB=$(( ($VIASH_META_MEMORY_B+1023) / 1024 )) - VIASH_META_MEMORY_MB=$(( ($VIASH_META_MEMORY_KB+1023) / 1024 )) - VIASH_META_MEMORY_GB=$(( ($VIASH_META_MEMORY_MB+1023) / 1024 )) - VIASH_META_MEMORY_TB=$(( ($VIASH_META_MEMORY_GB+1023) / 1024 )) - VIASH_META_MEMORY_PB=$(( ($VIASH_META_MEMORY_TB+1023) / 1024 )) - else - # unset memory if string is empty - unset $VIASH_META_MEMORY_B - fi -fi -# unset nproc if string is empty -if [ -z "$VIASH_META_CPUS" ]; then - unset $VIASH_META_CPUS -fi - - -# check whether required parameters exist -if [ -z ${VIASH_PAR_INPUT+x} ]; then - ViashError '--input' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_PAR_OUTPUT+x} ]; then - ViashError '--output' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then - ViashError 'functionality_name' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_RESOURCES_DIR+x} ]; then - ViashError 'resources_dir' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_EXECUTABLE+x} ]; then - ViashError 'executable' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_CONFIG+x} ]; then - ViashError 'config' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_TEMP_DIR+x} ]; then - ViashError 'temp_dir' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi - -# check whether required files exist -if [ ! -z "$VIASH_PAR_INPUT" ]; then - IFS=':' - set -f - for file in $VIASH_PAR_INPUT; do - unset IFS - if [ ! -e "$file" ]; then - ViashError "Input file '$file' does not exist." - exit 1 - fi - done - set +f -fi - -# check whether parameters values are of the right type -if [[ -n "$VIASH_META_CPUS" ]]; then - if ! [[ "$VIASH_META_CPUS" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'cpus' has to be an integer. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_B" ]]; then - if ! [[ "$VIASH_META_MEMORY_B" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_b' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_KB" ]]; then - if ! [[ "$VIASH_META_MEMORY_KB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_kb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_MB" ]]; then - if ! [[ "$VIASH_META_MEMORY_MB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_mb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_GB" ]]; then - if ! [[ "$VIASH_META_MEMORY_GB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_gb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_TB" ]]; then - if ! [[ "$VIASH_META_MEMORY_TB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_tb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_PB" ]]; then - if ! [[ "$VIASH_META_MEMORY_PB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_pb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi - -# create parent directories of output files, if so desired -if [ ! -z "$VIASH_PAR_OUTPUT" ] && [ ! -d "$(dirname "$VIASH_PAR_OUTPUT")" ]; then - mkdir -p "$(dirname "$VIASH_PAR_OUTPUT")" -fi - -# detect volumes from file arguments -VIASH_CHOWN_VARS=() -if [ ! -z "$VIASH_PAR_INPUT" ]; then - VIASH_TEST_INPUT=() - IFS=':' - for var in $VIASH_PAR_INPUT; do - unset IFS - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$var")" ) - var=$(ViashAutodetectMount "$var") - VIASH_TEST_INPUT+=( "$var" ) - done - VIASH_PAR_INPUT=$(IFS=':' ; echo "${VIASH_TEST_INPUT[*]}") -fi -if [ ! -z "$VIASH_PAR_OUTPUT" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_PAR_OUTPUT")" ) - VIASH_PAR_OUTPUT=$(ViashAutodetectMount "$VIASH_PAR_OUTPUT") - VIASH_CHOWN_VARS+=( "$VIASH_PAR_OUTPUT" ) -fi -if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_RESOURCES_DIR")" ) - VIASH_META_RESOURCES_DIR=$(ViashAutodetectMount "$VIASH_META_RESOURCES_DIR") -fi -if [ ! -z "$VIASH_META_EXECUTABLE" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_EXECUTABLE")" ) - VIASH_META_EXECUTABLE=$(ViashAutodetectMount "$VIASH_META_EXECUTABLE") -fi -if [ ! -z "$VIASH_META_CONFIG" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_CONFIG")" ) - VIASH_META_CONFIG=$(ViashAutodetectMount "$VIASH_META_CONFIG") -fi -if [ ! -z "$VIASH_META_TEMP_DIR" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_TEMP_DIR")" ) - VIASH_META_TEMP_DIR=$(ViashAutodetectMount "$VIASH_META_TEMP_DIR") -fi - -# get unique mounts -VIASH_UNIQUE_MOUNTS=($(for val in "${VIASH_EXTRA_MOUNTS[@]}"; do echo "$val"; done | sort -u)) - -# change file ownership -function ViashPerformChown { - if (( ${#VIASH_CHOWN_VARS[@]} )); then - set +e - eval docker run --entrypoint=chown -i --rm ${VIASH_UNIQUE_MOUNTS[@]} ghcr.io/viash-io/viash_project_template/template/combine_columns:0.2.2 "$(id -u):$(id -g)" --silent --recursive ${VIASH_CHOWN_VARS[@]} - set -e - fi -} -trap ViashPerformChown EXIT - -# helper function for filling in extra docker args -VIASH_EXTRA_DOCKER_ARGS="" -if [ ! -z "$VIASH_META_MEMORY_MB" ]; then - VIASH_EXTRA_DOCKER_ARGS="$VIASH_EXTRA_DOCKER_ARGS --memory=${VIASH_META_MEMORY_MB}m" -fi -if [ ! -z "$VIASH_META_CPUS" ]; then - VIASH_EXTRA_DOCKER_ARGS="$VIASH_EXTRA_DOCKER_ARGS --cpus=${VIASH_META_CPUS}" -fi - - -# set dependency paths - - -ViashDebug "Running command: $(echo docker run --entrypoint=bash -i --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_EXTRA_DOCKER_ARGS ghcr.io/viash-io/viash_project_template/template/combine_columns:0.2.2)" -cat << VIASHEOF | eval docker run --entrypoint=bash -i --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_EXTRA_DOCKER_ARGS ghcr.io/viash-io/viash_project_template/template/combine_columns:0.2.2 -set -e -tempscript=\$(mktemp "$VIASH_META_TEMP_DIR/viash-run-combine_columns-XXXXXX").R -function clean_up { - rm "\$tempscript" -} -function interrupt { - echo -e "\nCTRL-C Pressed..." - exit 1 -} -trap clean_up EXIT -trap interrupt INT SIGINT -cat > "\$tempscript" << 'VIASHMAIN' - -## VIASH START -# The following code has been auto-generated by Viash. -# treat warnings as errors -.viash_orig_warn <- options(warn = 2) - -par <- list( - "input" = $( if [ ! -z ${VIASH_PAR_INPUT+x} ]; then echo -n "strsplit('"; echo -n "$VIASH_PAR_INPUT" | sed "s#['\\]#\\\\&#g"; echo "', split = ':')[[1]]"; else echo NULL; fi ), - "output" = $( if [ ! -z ${VIASH_PAR_OUTPUT+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_OUTPUT" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ) -) -meta <- list( - "functionality_name" = $( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo -n "'"; echo -n "$VIASH_META_FUNCTIONALITY_NAME" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ), - "resources_dir" = $( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo -n "'"; echo -n "$VIASH_META_RESOURCES_DIR" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ), - "executable" = $( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo -n "'"; echo -n "$VIASH_META_EXECUTABLE" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ), - "config" = $( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo -n "'"; echo -n "$VIASH_META_CONFIG" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ), - "temp_dir" = $( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo -n "'"; echo -n "$VIASH_META_TEMP_DIR" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ), - "cpus" = $( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo -n "as.integer('"; echo -n "$VIASH_META_CPUS" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_b" = $( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_B" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_kb" = $( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_KB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_mb" = $( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_MB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_gb" = $( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_GB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_tb" = $( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_TB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_pb" = $( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_PB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ) -) -dep <- list( - -) - - -# restore original warn setting -options(.viash_orig_warn) -rm(.viash_orig_warn) - -## VIASH END - -outs <- lapply(par\$input, function(file) { - read.delim(file, comment.char = "#", sep = "\\t", header = FALSE) -}) - -table <- do.call(cbind, outs) - -write.table(table, par\$output, col.names = FALSE, sep = "\\t") -VIASHMAIN -Rscript "\$tempscript" & -wait "\$!" - -VIASHEOF - - -# strip viash automount from file paths -if [ ! -z "$VIASH_PAR_INPUT" ]; then - unset VIASH_TEST_INPUT - IFS=':' - for var in $VIASH_PAR_INPUT; do - unset IFS - if [ -z "$VIASH_TEST_INPUT" ]; then - VIASH_TEST_INPUT="$(ViashStripAutomount "$var")" - else - VIASH_TEST_INPUT="$VIASH_TEST_INPUT:""$(ViashStripAutomount "$var")" - fi - done - VIASH_PAR_INPUT="$VIASH_TEST_INPUT" -fi -if [ ! -z "$VIASH_PAR_OUTPUT" ]; then - VIASH_PAR_OUTPUT=$(ViashStripAutomount "$VIASH_PAR_OUTPUT") -fi -if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then - VIASH_META_RESOURCES_DIR=$(ViashStripAutomount "$VIASH_META_RESOURCES_DIR") -fi -if [ ! -z "$VIASH_META_EXECUTABLE" ]; then - VIASH_META_EXECUTABLE=$(ViashStripAutomount "$VIASH_META_EXECUTABLE") -fi -if [ ! -z "$VIASH_META_CONFIG" ]; then - VIASH_META_CONFIG=$(ViashStripAutomount "$VIASH_META_CONFIG") -fi -if [ ! -z "$VIASH_META_TEMP_DIR" ]; then - VIASH_META_TEMP_DIR=$(ViashStripAutomount "$VIASH_META_TEMP_DIR") -fi - - -# check whether required files exist -if [ ! -z "$VIASH_PAR_OUTPUT" ] && [ ! -e "$VIASH_PAR_OUTPUT" ]; then - ViashError "Output file '$VIASH_PAR_OUTPUT' does not exist." - exit 1 -fi - - -exit 0 diff --git a/target/docker/template/remove_comments/.config.vsh.yaml b/target/docker/template/remove_comments/.config.vsh.yaml deleted file mode 100644 index 2e6db73..0000000 --- a/target/docker/template/remove_comments/.config.vsh.yaml +++ /dev/null @@ -1,109 +0,0 @@ -functionality: - name: "remove_comments" - namespace: "template" - version: "0.2.2" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - info: null - example: - - "file.tsv" - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "file" - name: "--output" - alternatives: - - "-o" - info: null - example: - - "file.tsv" - must_exist: true - create_parent: true - required: true - direction: "output" - multiple: false - multiple_sep: ":" - dest: "par" - resources: - - type: "bash_script" - path: "script.sh" - is_executable: true - test_resources: - - type: "bash_script" - path: "test.sh" - is_executable: true - info: null - status: "enabled" - set_wd_to_resources_dir: false -platforms: -- type: "docker" - id: "docker" - image: "ubuntu:20.04" - target_organization: "viash-io/viash_project_template" - target_registry: "ghcr.io" - namespace_separator: "/" - resolve_volume: "Automatic" - chown: true - setup_strategy: "ifneedbepullelsecachedbuild" - target_image_source: "https://github.com/viash-io/viash_project_template" - entrypoint: [] - cmd: null -- type: "nextflow" - id: "nextflow" - directives: - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1.GB" - mem2gb: "memory = 2.GB" - mem4gb: "memory = 4.GB" - mem8gb: "memory = 8.GB" - mem16gb: "memory = 16.GB" - mem32gb: "memory = 32.GB" - mem64gb: "memory = 64.GB" - mem128gb: "memory = 128.GB" - mem256gb: "memory = 256.GB" - mem512gb: "memory = 512.GB" - mem1tb: "memory = 1.TB" - mem2tb: "memory = 2.TB" - mem4tb: "memory = 4.TB" - mem8tb: "memory = 8.TB" - mem16tb: "memory = 16.TB" - mem32tb: "memory = 32.TB" - mem64tb: "memory = 64.TB" - mem128tb: "memory = 128.TB" - mem256tb: "memory = 256.TB" - mem512tb: "memory = 512.TB" - cpu1: "cpus = 1" - cpu2: "cpus = 2" - cpu5: "cpus = 5" - cpu10: "cpus = 10" - cpu20: "cpus = 20" - cpu50: "cpus = 50" - cpu100: "cpus = 100" - cpu200: "cpus = 200" - cpu500: "cpus = 500" - cpu1000: "cpus = 1000" - debug: false - container: "docker" -info: - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/config.vsh.yaml" - platform: "docker" - output: "/Users/toni/code/projects/viash/viash_project_template/target/docker/template/remove_comments" - executable: "/Users/toni/code/projects/viash/viash_project_template/target/docker/template/remove_comments/remove_comments" - viash_version: "0.8.4" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - git_remote: "https://github.com/viash-io/viash_project_template" - git_tag: "v0.2.1" diff --git a/target/docker/template/remove_comments/remove_comments b/target/docker/template/remove_comments/remove_comments deleted file mode 100755 index 01d5884..0000000 --- a/target/docker/template/remove_comments/remove_comments +++ /dev/null @@ -1,924 +0,0 @@ -#!/usr/bin/env bash - -# remove_comments 0.2.2 -# -# This wrapper script is auto-generated by viash 0.8.4 and is thus a derivative -# work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data -# Intuitive. -# -# The component may contain files which fall under a different license. The -# authors of this component should specify the license in the header of such -# files, or include a separate license file detailing the licenses of all included -# files. - -set -e - -if [ -z "$VIASH_TEMP" ]; then - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TEMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMP} - VIASH_TEMP=${VIASH_TEMP:-$TMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$TMP} - VIASH_TEMP=${VIASH_TEMP:-$TEMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$TEMP} - VIASH_TEMP=${VIASH_TEMP:-/tmp} -fi - -# define helper functions -# ViashQuote: put quotes around non flag values -# $1 : unquoted string -# return : possibly quoted string -# examples: -# ViashQuote --foo # returns --foo -# ViashQuote bar # returns 'bar' -# Viashquote --foo=bar # returns --foo='bar' -function ViashQuote { - if [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+=.+$ ]]; then - echo "$1" | sed "s#=\(.*\)#='\1'#" - elif [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+$ ]]; then - echo "$1" - else - echo "'$1'" - fi -} -# ViashRemoveFlags: Remove leading flag -# $1 : string with a possible leading flag -# return : string without possible leading flag -# examples: -# ViashRemoveFlags --foo=bar # returns bar -function ViashRemoveFlags { - echo "$1" | sed 's/^--*[a-zA-Z0-9_\-]*=//' -} -# ViashSourceDir: return the path of a bash file, following symlinks -# usage : ViashSourceDir ${BASH_SOURCE[0]} -# $1 : Should always be set to ${BASH_SOURCE[0]} -# returns : The absolute path of the bash file -function ViashSourceDir { - SOURCE="$1" - while [ -h "$SOURCE" ]; do - DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )" - SOURCE="$(readlink "$SOURCE")" - [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" - done - cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd -} -# ViashFindTargetDir: return the path of the '.build.yaml' file, following symlinks -# usage : ViashFindTargetDir 'ScriptPath' -# $1 : The location from where to start the upward search -# returns : The absolute path of the '.build.yaml' file -function ViashFindTargetDir { - SOURCE="$1" - while [[ "$SOURCE" != "" && ! -e "$SOURCE/.build.yaml" ]]; do - SOURCE=${SOURCE%/*} - done - echo $SOURCE -} -# see https://en.wikipedia.org/wiki/Syslog#Severity_level -VIASH_LOGCODE_EMERGENCY=0 -VIASH_LOGCODE_ALERT=1 -VIASH_LOGCODE_CRITICAL=2 -VIASH_LOGCODE_ERROR=3 -VIASH_LOGCODE_WARNING=4 -VIASH_LOGCODE_NOTICE=5 -VIASH_LOGCODE_INFO=6 -VIASH_LOGCODE_DEBUG=7 -VIASH_VERBOSITY=$VIASH_LOGCODE_NOTICE - -# ViashLog: Log events depending on the verbosity level -# usage: ViashLog 1 alert Oh no something went wrong! -# $1: required verbosity level -# $2: display tag -# $3+: messages to display -# stdout: Your input, prepended by '[$2] '. -function ViashLog { - local required_level="$1" - local display_tag="$2" - shift 2 - if [ $VIASH_VERBOSITY -ge $required_level ]; then - >&2 echo "[$display_tag]" "$@" - fi -} - -# ViashEmergency: log events when the system is unstable -# usage: ViashEmergency Oh no something went wrong. -# stdout: Your input, prepended by '[emergency] '. -function ViashEmergency { - ViashLog $VIASH_LOGCODE_EMERGENCY emergency "$@" -} - -# ViashAlert: log events when actions must be taken immediately (e.g. corrupted system database) -# usage: ViashAlert Oh no something went wrong. -# stdout: Your input, prepended by '[alert] '. -function ViashAlert { - ViashLog $VIASH_LOGCODE_ALERT alert "$@" -} - -# ViashCritical: log events when a critical condition occurs -# usage: ViashCritical Oh no something went wrong. -# stdout: Your input, prepended by '[critical] '. -function ViashCritical { - ViashLog $VIASH_LOGCODE_CRITICAL critical "$@" -} - -# ViashError: log events when an error condition occurs -# usage: ViashError Oh no something went wrong. -# stdout: Your input, prepended by '[error] '. -function ViashError { - ViashLog $VIASH_LOGCODE_ERROR error "$@" -} - -# ViashWarning: log potentially abnormal events -# usage: ViashWarning Something may have gone wrong. -# stdout: Your input, prepended by '[warning] '. -function ViashWarning { - ViashLog $VIASH_LOGCODE_WARNING warning "$@" -} - -# ViashNotice: log significant but normal events -# usage: ViashNotice This just happened. -# stdout: Your input, prepended by '[notice] '. -function ViashNotice { - ViashLog $VIASH_LOGCODE_NOTICE notice "$@" -} - -# ViashInfo: log normal events -# usage: ViashInfo This just happened. -# stdout: Your input, prepended by '[info] '. -function ViashInfo { - ViashLog $VIASH_LOGCODE_INFO info "$@" -} - -# ViashDebug: log all events, for debugging purposes -# usage: ViashDebug This just happened. -# stdout: Your input, prepended by '[debug] '. -function ViashDebug { - ViashLog $VIASH_LOGCODE_DEBUG debug "$@" -} - -# find source folder of this component -VIASH_META_RESOURCES_DIR=`ViashSourceDir ${BASH_SOURCE[0]}` - -# find the root of the built components & dependencies -VIASH_TARGET_DIR=`ViashFindTargetDir $VIASH_META_RESOURCES_DIR` - -# define meta fields -VIASH_META_FUNCTIONALITY_NAME="remove_comments" -VIASH_META_EXECUTABLE="$VIASH_META_RESOURCES_DIR/$VIASH_META_FUNCTIONALITY_NAME" -VIASH_META_CONFIG="$VIASH_META_RESOURCES_DIR/.config.vsh.yaml" -VIASH_META_TEMP_DIR="$VIASH_TEMP" - - -# ViashHelp: Display helpful explanation about this executable -function ViashHelp { - echo "remove_comments 0.2.2" - echo "" - echo "Arguments:" - echo " -i, --input" - echo " type: file, required parameter, file must exist" - echo " example: file.tsv" - echo "" - echo " -o, --output" - echo " type: file, required parameter, output, file must exist" - echo " example: file.tsv" -} - -######## Helper functions for setting up Docker images for viash ######## -# expects: ViashDockerBuild - -# ViashDockerInstallationCheck: check whether Docker is installed correctly -# -# examples: -# ViashDockerInstallationCheck -function ViashDockerInstallationCheck { - ViashDebug "Checking whether Docker is installed" - if [ ! command -v docker &> /dev/null ]; then - ViashCritical "Docker doesn't seem to be installed. See 'https://docs.docker.com/get-docker/' for instructions." - exit 1 - fi - - ViashDebug "Checking whether the Docker daemon is running" - save=$-; set +e - docker_version=$(docker version --format '{{.Client.APIVersion}}' 2> /dev/null) - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashCritical "Docker daemon does not seem to be running. Try one of the following:" - ViashCritical "- Try running 'dockerd' in the command line" - ViashCritical "- See https://docs.docker.com/config/daemon/" - exit 1 - fi -} - -# ViashDockerRemoteTagCheck: check whether a Docker image is available -# on a remote. Assumes `docker login` has been performed, if relevant. -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerRemoteTagCheck python:latest -# echo $? # returns '0' -# ViashDockerRemoteTagCheck sdaizudceahifu -# echo $? # returns '1' -function ViashDockerRemoteTagCheck { - docker manifest inspect $1 > /dev/null 2> /dev/null -} - -# ViashDockerLocalTagCheck: check whether a Docker image is available locally -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# docker pull python:latest -# ViashDockerLocalTagCheck python:latest -# echo $? # returns '0' -# ViashDockerLocalTagCheck sdaizudceahifu -# echo $? # returns '1' -function ViashDockerLocalTagCheck { - [ -n "$(docker images -q $1)" ] -} - -# ViashDockerPull: pull a Docker image -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerPull python:latest -# echo $? # returns '0' -# ViashDockerPull sdaizudceahifu -# echo $? # returns '1' -function ViashDockerPull { - ViashNotice "Checking if Docker image is available at '$1'" - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker pull $1 && return 0 || return 1 - else - save=$-; set +e - docker pull $1 2> /dev/null > /dev/null - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashWarning "Could not pull from '$1'. Docker image doesn't exist or is not accessible." - fi - return $out - fi -} - -# ViashDockerPush: push a Docker image -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerPush python:latest -# echo $? # returns '0' -# ViashDockerPush sdaizudceahifu -# echo $? # returns '1' -function ViashDockerPush { - ViashNotice "Pushing image to '$1'" - save=$-; set +e - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker push $1 - out=$? - else - docker push $1 2> /dev/null > /dev/null - out=$? - fi - [[ $save =~ e ]] && set -e - if [ $out -eq 0 ]; then - ViashNotice "Container '$VSHD_ID' push succeeded." - else - ViashError "Container '$VSHD_ID' push errored. You might not be logged in or have the necessary permissions." - fi - return $out -} - -# ViashDockerPullElseBuild: pull a Docker image, else build it -# -# $1 : image identifier with format `[registry/]image[:tag]` -# ViashDockerBuild : a Bash function which builds a docker image, takes image identifier as argument. -# examples: -# ViashDockerPullElseBuild mynewcomponent -function ViashDockerPullElseBuild { - save=$-; set +e - ViashDockerPull $1 - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashDockerBuild $@ - fi -} - -# ViashDockerSetup: create a Docker image, according to specified docker setup strategy -# -# $1 : image identifier with format `[registry/]image[:tag]` -# $2 : docker setup strategy, see DockerSetupStrategy.scala -# ViashDockerBuild : a Bash function which builds a docker image, takes image identifier as argument. -# examples: -# ViashDockerSetup mynewcomponent alwaysbuild -function ViashDockerSetup { - VSHD_ID="$1" - VSHD_STRAT="$2" - if [ "$VSHD_STRAT" == "alwaysbuild" -o "$VSHD_STRAT" == "build" -o "$VSHD_STRAT" == "b" ]; then - ViashDockerBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "alwayspull" -o "$VSHD_STRAT" == "pull" -o "$VSHD_STRAT" == "p" ]; then - ViashDockerPull $VSHD_ID - elif [ "$VSHD_STRAT" == "alwayspullelsebuild" -o "$VSHD_STRAT" == "pullelsebuild" ]; then - ViashDockerPullElseBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "alwayspullelsecachedbuild" -o "$VSHD_STRAT" == "pullelsecachedbuild" ]; then - ViashDockerPullElseBuild $VSHD_ID - elif [ "$VSHD_STRAT" == "alwayscachedbuild" -o "$VSHD_STRAT" == "cachedbuild" -o "$VSHD_STRAT" == "cb" ]; then - ViashDockerBuild $VSHD_ID - elif [[ "$VSHD_STRAT" =~ ^ifneedbe ]]; then - save=$-; set +e - ViashDockerLocalTagCheck $VSHD_ID - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -eq 0 ]; then - ViashInfo "Image $VSHD_ID already exists" - elif [ "$VSHD_STRAT" == "ifneedbebuild" ]; then - ViashDockerBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "ifneedbecachedbuild" ]; then - ViashDockerBuild $VSHD_ID - elif [ "$VSHD_STRAT" == "ifneedbepull" ]; then - ViashDockerPull $VSHD_ID - elif [ "$VSHD_STRAT" == "ifneedbepullelsebuild" ]; then - ViashDockerPullElseBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "ifneedbepullelsecachedbuild" ]; then - ViashDockerPullElseBuild $VSHD_ID - else - ViashError "Unrecognised Docker strategy: $VSHD_STRAT" - exit 1 - fi - elif [ "$VSHD_STRAT" == "push" -o "$VSHD_STRAT" == "forcepush" -o "$VSHD_STRAT" == "alwayspush" ]; then - ViashDockerPush "$VSHD_ID" - elif [ "$VSHD_STRAT" == "pushifnotpresent" -o "$VSHD_STRAT" == "gentlepush" -o "$VSHD_STRAT" == "maybepush" ]; then - save=$-; set +e - ViashDockerRemoteTagCheck $VSHD_ID - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -eq 0 ]; then - ViashNotice "Container '$VSHD_ID' exists, doing nothing." - else - ViashNotice "Container '$VSHD_ID' does not yet exist." - ViashDockerPush "$VSHD_ID" - fi - elif [ "$VSHD_STRAT" == "donothing" -o "$VSHD_STRAT" == "meh" ]; then - ViashNotice "Skipping setup." - else - ViashError "Unrecognised Docker strategy: $VSHD_STRAT" - exit 1 - fi -} - -# ViashDockerCheckCommands: Check whether a docker container has the required commands -# -# $1 : image identifier with format `[registry/]image[:tag]` -# $@ : commands to verify being present -# examples: -# ViashDockerCheckCommands bash:4.0 bash ps foo -function ViashDockerCheckCommands { - tag=$1 - shift 1 - commands="$@" - save=$-; set +e - missing=$(docker run --rm --entrypoint=sh $tag -c "for command in $commands; do command -v \$command >/dev/null 2>&1; if [ \$? -ne 0 ]; then echo \$command; exit 1; fi; done") - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -ne 0 ]; then - ViashError "Docker container '$tag' does not contain command '$missing'." - exit 1 - fi -} - - -######## End of helper functions for setting up Docker images for viash ######## - -# ViashDockerFile: print the dockerfile to stdout -# return : dockerfile required to run this component -# examples: -# ViashDockerFile -function ViashDockerfile { - cat << 'VIASHDOCKER' -FROM ubuntu:20.04 - -ENTRYPOINT [] - - -RUN : -LABEL org.opencontainers.image.description="Companion container for running component template remove_comments" -LABEL org.opencontainers.image.created="2024-01-16T14:48:39+01:00" -LABEL org.opencontainers.image.source="https://github.com/viash-io/viash_project_template" -LABEL org.opencontainers.image.revision="11b6278597bf22afbfb56a8e83065a55553c9dd0" -LABEL org.opencontainers.image.version="0.2.2" - -VIASHDOCKER -} - -# ViashDockerBuild: build a docker container -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was built -function ViashDockerBuild { - # create temporary directory to store dockerfile & optional resources in - tmpdir=$(mktemp -d "$VIASH_META_TEMP_DIR/dockerbuild-remove_comments-XXXXXX") - dockerfile="$tmpdir/Dockerfile" - function clean_up { - rm -rf "$tmpdir" - } - trap clean_up EXIT - - # store dockerfile and resources - ViashDockerfile > $dockerfile - - # Build the container - ViashNotice "Building container '$1' with Dockerfile" - ViashInfo "Running 'docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile'" - save=$-; set +e - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile - else - docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile &> $tmpdir/docker_build.log - fi - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashError "Error occurred while building container '$1'" - if [ $VIASH_VERBOSITY -lt $VIASH_LOGCODE_INFO ]; then - ViashError "Transcript: --------------------------------" - cat "$tmpdir/docker_build.log" - ViashError "End of transcript --------------------------" - fi - exit 1 - fi - ViashDockerCheckCommands "$1" 'bash' -} - -# ViashAbsolutePath: generate absolute path from relative path -# borrowed from https://stackoverflow.com/a/21951256 -# $1 : relative filename -# return : absolute path -# examples: -# ViashAbsolutePath some_file.txt # returns /path/to/some_file.txt -# ViashAbsolutePath /foo/bar/.. # returns /foo -function ViashAbsolutePath { - local thePath - if [[ ! "$1" =~ ^/ ]]; then - thePath="$PWD/$1" - else - thePath="$1" - fi - echo "$thePath" | ( - IFS=/ - read -a parr - declare -a outp - for i in "${parr[@]}"; do - case "$i" in - ''|.) continue ;; - ..) - len=${#outp[@]} - if ((len==0)); then - continue - else - unset outp[$((len-1))] - fi - ;; - *) - len=${#outp[@]} - outp[$len]="$i" - ;; - esac - done - echo /"${outp[*]}" - ) -} -# ViashAutodetectMount: auto configuring docker mounts from parameters -# $1 : The parameter value -# returns : New parameter -# $VIASH_EXTRA_MOUNTS : Added another parameter to be passed to docker -# examples: -# ViashAutodetectMount /path/to/bar # returns '/viash_automount/path/to/bar' -# ViashAutodetectMountArg /path/to/bar # returns '--volume="/path/to:/viash_automount/path/to"' -function ViashAutodetectMount { - abs_path=$(ViashAbsolutePath "$1") - if [ -d "$abs_path" ]; then - mount_source="$abs_path" - base_name="" - else - mount_source=`dirname "$abs_path"` - base_name=`basename "$abs_path"` - fi - mount_target="/viash_automount$mount_source" - echo "$mount_target/$base_name" -} -function ViashAutodetectMountArg { - abs_path=$(ViashAbsolutePath "$1") - if [ -d "$abs_path" ]; then - mount_source="$abs_path" - base_name="" - else - mount_source=`dirname "$abs_path"` - base_name=`basename "$abs_path"` - fi - mount_target="/viash_automount$mount_source" - ViashDebug "ViashAutodetectMountArg $1 -> $mount_source -> $mount_target" - echo "--volume=\"$mount_source:$mount_target\"" -} -function ViashStripAutomount { - abs_path=$(ViashAbsolutePath "$1") - echo "${abs_path#/viash_automount}" -} -# ViashExtractFlags: Retain leading flag -# $1 : string with a possible leading flag -# return : leading flag -# examples: -# ViashExtractFlags --foo=bar # returns --foo -function ViashExtractFlags { - echo $1 | sed 's/=.*//' -} -# initialise variables -VIASH_EXTRA_MOUNTS=() - -# initialise array -VIASH_POSITIONAL_ARGS='' -VIASH_MODE='run' - -while [[ $# -gt 0 ]]; do - case "$1" in - -h|--help) - ViashHelp - exit - ;; - ---v|---verbose) - let "VIASH_VERBOSITY=VIASH_VERBOSITY+1" - shift 1 - ;; - ---verbosity) - VIASH_VERBOSITY="$2" - shift 2 - ;; - ---verbosity=*) - VIASH_VERBOSITY="$(ViashRemoveFlags "$1")" - shift 1 - ;; - --version) - echo "remove_comments 0.2.2" - exit - ;; - --input) - [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'--input\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_INPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --input. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --input=*) - [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'--input=*\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_INPUT=$(ViashRemoveFlags "$1") - shift 1 - ;; - -i) - [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'-i\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_INPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to -i. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --output) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'--output\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --output. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --output=*) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'--output=*\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT=$(ViashRemoveFlags "$1") - shift 1 - ;; - -o) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'-o\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to -o. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - ---setup) - VIASH_MODE='docker_setup' - VIASH_DOCKER_SETUP_STRATEGY="$2" - shift 1 - ;; - ---setup=*) - VIASH_MODE='docker_setup' - VIASH_DOCKER_SETUP_STRATEGY="$(ViashRemoveFlags "$1")" - shift 2 - ;; - ---dockerfile) - ViashDockerfile - exit 0 - ;; - ---v|---volume) - VIASH_EXTRA_MOUNTS+=("--volume='$2'") - shift 2 - ;; - ---volume=*) - VIASH_EXTRA_MOUNTS+=("--volume='$(ViashRemoveFlags "$2")'") - shift 1 - ;; - ---debug) - VIASH_MODE='docker_debug' - shift 1 - ;; - ---cpus) - [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_CPUS="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to ---cpus. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - ---cpus=*) - [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus=*\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_CPUS=$(ViashRemoveFlags "$1") - shift 1 - ;; - ---memory) - [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_MEMORY="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to ---memory. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - ---memory=*) - [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory=*\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_MEMORY=$(ViashRemoveFlags "$1") - shift 1 - ;; - *) # positional arg or unknown option - # since the positional args will be eval'd, can we always quote, instead of using ViashQuote - VIASH_POSITIONAL_ARGS="$VIASH_POSITIONAL_ARGS '$1'" - [[ $1 == -* ]] && ViashWarning $1 looks like a parameter but is not a defined parameter and will instead be treated as a positional argument. Use "--help" to get more information on the parameters. - shift # past argument - ;; - esac -done - -# parse positional parameters -eval set -- $VIASH_POSITIONAL_ARGS - - -ViashDockerInstallationCheck - -if [ $VIASH_MODE == "docker_setup" ]; then - ViashDockerSetup 'ghcr.io/viash-io/viash_project_template/template/remove_comments:0.2.2' "$VIASH_DOCKER_SETUP_STRATEGY" - exit 0 -fi -ViashDockerSetup 'ghcr.io/viash-io/viash_project_template/template/remove_comments:0.2.2' ifneedbepullelsecachedbuild - -if [ $VIASH_MODE == "docker_debug" ]; then - ViashNotice "+ docker run --entrypoint=bash -i --rm -v "$(pwd)":/pwd --workdir /pwd -t 'ghcr.io/viash-io/viash_project_template/template/remove_comments:0.2.2'" - docker run --entrypoint=bash -i --rm -v "$(pwd)":/pwd --workdir /pwd -t 'ghcr.io/viash-io/viash_project_template/template/remove_comments:0.2.2' - exit 0 -fi - -# setting computational defaults - -# helper function for parsing memory strings -function ViashMemoryAsBytes { - local memory=`echo "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]'` - local memory_regex='^([0-9]+)([kmgtp]b?|b)$' - if [[ $memory =~ $memory_regex ]]; then - local number=${memory/[^0-9]*/} - local symbol=${memory/*[0-9]/} - - case $symbol in - b) memory_b=$number ;; - kb|k) memory_b=$(( $number * 1024 )) ;; - mb|m) memory_b=$(( $number * 1024 * 1024 )) ;; - gb|g) memory_b=$(( $number * 1024 * 1024 * 1024 )) ;; - tb|t) memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 )) ;; - pb|p) memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 * 1024 )) ;; - esac - echo "$memory_b" - fi -} -# compute memory in different units -if [ ! -z ${VIASH_META_MEMORY+x} ]; then - VIASH_META_MEMORY_B=`ViashMemoryAsBytes $VIASH_META_MEMORY` - # do not define other variables if memory_b is an empty string - if [ ! -z "$VIASH_META_MEMORY_B" ]; then - VIASH_META_MEMORY_KB=$(( ($VIASH_META_MEMORY_B+1023) / 1024 )) - VIASH_META_MEMORY_MB=$(( ($VIASH_META_MEMORY_KB+1023) / 1024 )) - VIASH_META_MEMORY_GB=$(( ($VIASH_META_MEMORY_MB+1023) / 1024 )) - VIASH_META_MEMORY_TB=$(( ($VIASH_META_MEMORY_GB+1023) / 1024 )) - VIASH_META_MEMORY_PB=$(( ($VIASH_META_MEMORY_TB+1023) / 1024 )) - else - # unset memory if string is empty - unset $VIASH_META_MEMORY_B - fi -fi -# unset nproc if string is empty -if [ -z "$VIASH_META_CPUS" ]; then - unset $VIASH_META_CPUS -fi - - -# check whether required parameters exist -if [ -z ${VIASH_PAR_INPUT+x} ]; then - ViashError '--input' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_PAR_OUTPUT+x} ]; then - ViashError '--output' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then - ViashError 'functionality_name' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_RESOURCES_DIR+x} ]; then - ViashError 'resources_dir' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_EXECUTABLE+x} ]; then - ViashError 'executable' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_CONFIG+x} ]; then - ViashError 'config' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_TEMP_DIR+x} ]; then - ViashError 'temp_dir' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi - -# check whether required files exist -if [ ! -z "$VIASH_PAR_INPUT" ] && [ ! -e "$VIASH_PAR_INPUT" ]; then - ViashError "Input file '$VIASH_PAR_INPUT' does not exist." - exit 1 -fi - -# check whether parameters values are of the right type -if [[ -n "$VIASH_META_CPUS" ]]; then - if ! [[ "$VIASH_META_CPUS" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'cpus' has to be an integer. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_B" ]]; then - if ! [[ "$VIASH_META_MEMORY_B" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_b' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_KB" ]]; then - if ! [[ "$VIASH_META_MEMORY_KB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_kb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_MB" ]]; then - if ! [[ "$VIASH_META_MEMORY_MB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_mb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_GB" ]]; then - if ! [[ "$VIASH_META_MEMORY_GB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_gb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_TB" ]]; then - if ! [[ "$VIASH_META_MEMORY_TB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_tb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_PB" ]]; then - if ! [[ "$VIASH_META_MEMORY_PB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_pb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi - -# create parent directories of output files, if so desired -if [ ! -z "$VIASH_PAR_OUTPUT" ] && [ ! -d "$(dirname "$VIASH_PAR_OUTPUT")" ]; then - mkdir -p "$(dirname "$VIASH_PAR_OUTPUT")" -fi - -# detect volumes from file arguments -VIASH_CHOWN_VARS=() -if [ ! -z "$VIASH_PAR_INPUT" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_PAR_INPUT")" ) - VIASH_PAR_INPUT=$(ViashAutodetectMount "$VIASH_PAR_INPUT") -fi -if [ ! -z "$VIASH_PAR_OUTPUT" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_PAR_OUTPUT")" ) - VIASH_PAR_OUTPUT=$(ViashAutodetectMount "$VIASH_PAR_OUTPUT") - VIASH_CHOWN_VARS+=( "$VIASH_PAR_OUTPUT" ) -fi -if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_RESOURCES_DIR")" ) - VIASH_META_RESOURCES_DIR=$(ViashAutodetectMount "$VIASH_META_RESOURCES_DIR") -fi -if [ ! -z "$VIASH_META_EXECUTABLE" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_EXECUTABLE")" ) - VIASH_META_EXECUTABLE=$(ViashAutodetectMount "$VIASH_META_EXECUTABLE") -fi -if [ ! -z "$VIASH_META_CONFIG" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_CONFIG")" ) - VIASH_META_CONFIG=$(ViashAutodetectMount "$VIASH_META_CONFIG") -fi -if [ ! -z "$VIASH_META_TEMP_DIR" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_TEMP_DIR")" ) - VIASH_META_TEMP_DIR=$(ViashAutodetectMount "$VIASH_META_TEMP_DIR") -fi - -# get unique mounts -VIASH_UNIQUE_MOUNTS=($(for val in "${VIASH_EXTRA_MOUNTS[@]}"; do echo "$val"; done | sort -u)) - -# change file ownership -function ViashPerformChown { - if (( ${#VIASH_CHOWN_VARS[@]} )); then - set +e - eval docker run --entrypoint=chown -i --rm ${VIASH_UNIQUE_MOUNTS[@]} ghcr.io/viash-io/viash_project_template/template/remove_comments:0.2.2 "$(id -u):$(id -g)" --silent --recursive ${VIASH_CHOWN_VARS[@]} - set -e - fi -} -trap ViashPerformChown EXIT - -# helper function for filling in extra docker args -VIASH_EXTRA_DOCKER_ARGS="" -if [ ! -z "$VIASH_META_MEMORY_MB" ]; then - VIASH_EXTRA_DOCKER_ARGS="$VIASH_EXTRA_DOCKER_ARGS --memory=${VIASH_META_MEMORY_MB}m" -fi -if [ ! -z "$VIASH_META_CPUS" ]; then - VIASH_EXTRA_DOCKER_ARGS="$VIASH_EXTRA_DOCKER_ARGS --cpus=${VIASH_META_CPUS}" -fi - - -# set dependency paths - - -ViashDebug "Running command: $(echo docker run --entrypoint=bash -i --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_EXTRA_DOCKER_ARGS ghcr.io/viash-io/viash_project_template/template/remove_comments:0.2.2)" -cat << VIASHEOF | eval docker run --entrypoint=bash -i --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_EXTRA_DOCKER_ARGS ghcr.io/viash-io/viash_project_template/template/remove_comments:0.2.2 -set -e -tempscript=\$(mktemp "$VIASH_META_TEMP_DIR/viash-run-remove_comments-XXXXXX").sh -function clean_up { - rm "\$tempscript" -} -function interrupt { - echo -e "\nCTRL-C Pressed..." - exit 1 -} -trap clean_up EXIT -trap interrupt INT SIGINT -cat > "\$tempscript" << 'VIASHMAIN' -## VIASH START -# The following code has been auto-generated by Viash. -$( if [ ! -z ${VIASH_PAR_INPUT+x} ]; then echo "${VIASH_PAR_INPUT}" | sed "s#'#'\"'\"'#g;s#.*#par_input='&'#" ; else echo "# par_input="; fi ) -$( if [ ! -z ${VIASH_PAR_OUTPUT+x} ]; then echo "${VIASH_PAR_OUTPUT}" | sed "s#'#'\"'\"'#g;s#.*#par_output='&'#" ; else echo "# par_output="; fi ) -$( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo "${VIASH_META_FUNCTIONALITY_NAME}" | sed "s#'#'\"'\"'#g;s#.*#meta_functionality_name='&'#" ; else echo "# meta_functionality_name="; fi ) -$( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo "${VIASH_META_RESOURCES_DIR}" | sed "s#'#'\"'\"'#g;s#.*#meta_resources_dir='&'#" ; else echo "# meta_resources_dir="; fi ) -$( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo "${VIASH_META_EXECUTABLE}" | sed "s#'#'\"'\"'#g;s#.*#meta_executable='&'#" ; else echo "# meta_executable="; fi ) -$( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo "${VIASH_META_CONFIG}" | sed "s#'#'\"'\"'#g;s#.*#meta_config='&'#" ; else echo "# meta_config="; fi ) -$( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo "${VIASH_META_TEMP_DIR}" | sed "s#'#'\"'\"'#g;s#.*#meta_temp_dir='&'#" ; else echo "# meta_temp_dir="; fi ) -$( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo "${VIASH_META_CPUS}" | sed "s#'#'\"'\"'#g;s#.*#meta_cpus='&'#" ; else echo "# meta_cpus="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo "${VIASH_META_MEMORY_B}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_b='&'#" ; else echo "# meta_memory_b="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo "${VIASH_META_MEMORY_KB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_kb='&'#" ; else echo "# meta_memory_kb="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo "${VIASH_META_MEMORY_MB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_mb='&'#" ; else echo "# meta_memory_mb="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo "${VIASH_META_MEMORY_GB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_gb='&'#" ; else echo "# meta_memory_gb="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo "${VIASH_META_MEMORY_TB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_tb='&'#" ; else echo "# meta_memory_tb="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo "${VIASH_META_MEMORY_PB}" | sed "s#'#'\"'\"'#g;s#.*#meta_memory_pb='&'#" ; else echo "# meta_memory_pb="; fi ) - -## VIASH END -#!/bin/bash - -grep -v '^#' "\$par_input" > "\$par_output" -VIASHMAIN -bash "\$tempscript" & -wait "\$!" - -VIASHEOF - - -# strip viash automount from file paths -if [ ! -z "$VIASH_PAR_INPUT" ]; then - VIASH_PAR_INPUT=$(ViashStripAutomount "$VIASH_PAR_INPUT") -fi -if [ ! -z "$VIASH_PAR_OUTPUT" ]; then - VIASH_PAR_OUTPUT=$(ViashStripAutomount "$VIASH_PAR_OUTPUT") -fi -if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then - VIASH_META_RESOURCES_DIR=$(ViashStripAutomount "$VIASH_META_RESOURCES_DIR") -fi -if [ ! -z "$VIASH_META_EXECUTABLE" ]; then - VIASH_META_EXECUTABLE=$(ViashStripAutomount "$VIASH_META_EXECUTABLE") -fi -if [ ! -z "$VIASH_META_CONFIG" ]; then - VIASH_META_CONFIG=$(ViashStripAutomount "$VIASH_META_CONFIG") -fi -if [ ! -z "$VIASH_META_TEMP_DIR" ]; then - VIASH_META_TEMP_DIR=$(ViashStripAutomount "$VIASH_META_TEMP_DIR") -fi - - -# check whether required files exist -if [ ! -z "$VIASH_PAR_OUTPUT" ] && [ ! -e "$VIASH_PAR_OUTPUT" ]; then - ViashError "Output file '$VIASH_PAR_OUTPUT' does not exist." - exit 1 -fi - - -exit 0 diff --git a/target/docker/template/take_column/.config.vsh.yaml b/target/docker/template/take_column/.config.vsh.yaml deleted file mode 100644 index 2a882c0..0000000 --- a/target/docker/template/take_column/.config.vsh.yaml +++ /dev/null @@ -1,121 +0,0 @@ -functionality: - name: "take_column" - namespace: "template" - version: "0.2.2" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - info: null - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "file" - name: "--output" - alternatives: - - "-o" - info: null - must_exist: true - create_parent: true - required: true - direction: "output" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "integer" - name: "--column" - info: null - default: - - 2 - required: false - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - resources: - - type: "python_script" - path: "script.py" - is_executable: true - info: null - status: "enabled" - set_wd_to_resources_dir: false -platforms: -- type: "docker" - id: "docker" - image: "python:3.10-slim" - target_organization: "viash-io/viash_project_template" - target_registry: "ghcr.io" - namespace_separator: "/" - resolve_volume: "Automatic" - chown: true - setup_strategy: "ifneedbepullelsecachedbuild" - target_image_source: "https://github.com/viash-io/viash_project_template" - setup: - - type: "python" - user: false - packages: - - "pandas" - upgrade: true - - type: "apt" - packages: - - "procps" - interactive: false - entrypoint: [] - cmd: null -- type: "nextflow" - id: "nextflow" - directives: - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1.GB" - mem2gb: "memory = 2.GB" - mem4gb: "memory = 4.GB" - mem8gb: "memory = 8.GB" - mem16gb: "memory = 16.GB" - mem32gb: "memory = 32.GB" - mem64gb: "memory = 64.GB" - mem128gb: "memory = 128.GB" - mem256gb: "memory = 256.GB" - mem512gb: "memory = 512.GB" - mem1tb: "memory = 1.TB" - mem2tb: "memory = 2.TB" - mem4tb: "memory = 4.TB" - mem8tb: "memory = 8.TB" - mem16tb: "memory = 16.TB" - mem32tb: "memory = 32.TB" - mem64tb: "memory = 64.TB" - mem128tb: "memory = 128.TB" - mem256tb: "memory = 256.TB" - mem512tb: "memory = 512.TB" - cpu1: "cpus = 1" - cpu2: "cpus = 2" - cpu5: "cpus = 5" - cpu10: "cpus = 10" - cpu20: "cpus = 20" - cpu50: "cpus = 50" - cpu100: "cpus = 100" - cpu200: "cpus = 200" - cpu500: "cpus = 500" - cpu1000: "cpus = 1000" - debug: false - container: "docker" -info: - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/take_column/config.vsh.yaml" - platform: "docker" - output: "/Users/toni/code/projects/viash/viash_project_template/target/docker/template/take_column" - executable: "/Users/toni/code/projects/viash/viash_project_template/target/docker/template/take_column/take_column" - viash_version: "0.8.4" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - git_remote: "https://github.com/viash-io/viash_project_template" - git_tag: "v0.2.1" diff --git a/target/docker/template/take_column/take_column b/target/docker/template/take_column/take_column deleted file mode 100755 index b984133..0000000 --- a/target/docker/template/take_column/take_column +++ /dev/null @@ -1,970 +0,0 @@ -#!/usr/bin/env bash - -# take_column 0.2.2 -# -# This wrapper script is auto-generated by viash 0.8.4 and is thus a derivative -# work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data -# Intuitive. -# -# The component may contain files which fall under a different license. The -# authors of this component should specify the license in the header of such -# files, or include a separate license file detailing the licenses of all included -# files. - -set -e - -if [ -z "$VIASH_TEMP" ]; then - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TEMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMP} - VIASH_TEMP=${VIASH_TEMP:-$TMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$TMP} - VIASH_TEMP=${VIASH_TEMP:-$TEMPDIR} - VIASH_TEMP=${VIASH_TEMP:-$TEMP} - VIASH_TEMP=${VIASH_TEMP:-/tmp} -fi - -# define helper functions -# ViashQuote: put quotes around non flag values -# $1 : unquoted string -# return : possibly quoted string -# examples: -# ViashQuote --foo # returns --foo -# ViashQuote bar # returns 'bar' -# Viashquote --foo=bar # returns --foo='bar' -function ViashQuote { - if [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+=.+$ ]]; then - echo "$1" | sed "s#=\(.*\)#='\1'#" - elif [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+$ ]]; then - echo "$1" - else - echo "'$1'" - fi -} -# ViashRemoveFlags: Remove leading flag -# $1 : string with a possible leading flag -# return : string without possible leading flag -# examples: -# ViashRemoveFlags --foo=bar # returns bar -function ViashRemoveFlags { - echo "$1" | sed 's/^--*[a-zA-Z0-9_\-]*=//' -} -# ViashSourceDir: return the path of a bash file, following symlinks -# usage : ViashSourceDir ${BASH_SOURCE[0]} -# $1 : Should always be set to ${BASH_SOURCE[0]} -# returns : The absolute path of the bash file -function ViashSourceDir { - SOURCE="$1" - while [ -h "$SOURCE" ]; do - DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )" - SOURCE="$(readlink "$SOURCE")" - [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" - done - cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd -} -# ViashFindTargetDir: return the path of the '.build.yaml' file, following symlinks -# usage : ViashFindTargetDir 'ScriptPath' -# $1 : The location from where to start the upward search -# returns : The absolute path of the '.build.yaml' file -function ViashFindTargetDir { - SOURCE="$1" - while [[ "$SOURCE" != "" && ! -e "$SOURCE/.build.yaml" ]]; do - SOURCE=${SOURCE%/*} - done - echo $SOURCE -} -# see https://en.wikipedia.org/wiki/Syslog#Severity_level -VIASH_LOGCODE_EMERGENCY=0 -VIASH_LOGCODE_ALERT=1 -VIASH_LOGCODE_CRITICAL=2 -VIASH_LOGCODE_ERROR=3 -VIASH_LOGCODE_WARNING=4 -VIASH_LOGCODE_NOTICE=5 -VIASH_LOGCODE_INFO=6 -VIASH_LOGCODE_DEBUG=7 -VIASH_VERBOSITY=$VIASH_LOGCODE_NOTICE - -# ViashLog: Log events depending on the verbosity level -# usage: ViashLog 1 alert Oh no something went wrong! -# $1: required verbosity level -# $2: display tag -# $3+: messages to display -# stdout: Your input, prepended by '[$2] '. -function ViashLog { - local required_level="$1" - local display_tag="$2" - shift 2 - if [ $VIASH_VERBOSITY -ge $required_level ]; then - >&2 echo "[$display_tag]" "$@" - fi -} - -# ViashEmergency: log events when the system is unstable -# usage: ViashEmergency Oh no something went wrong. -# stdout: Your input, prepended by '[emergency] '. -function ViashEmergency { - ViashLog $VIASH_LOGCODE_EMERGENCY emergency "$@" -} - -# ViashAlert: log events when actions must be taken immediately (e.g. corrupted system database) -# usage: ViashAlert Oh no something went wrong. -# stdout: Your input, prepended by '[alert] '. -function ViashAlert { - ViashLog $VIASH_LOGCODE_ALERT alert "$@" -} - -# ViashCritical: log events when a critical condition occurs -# usage: ViashCritical Oh no something went wrong. -# stdout: Your input, prepended by '[critical] '. -function ViashCritical { - ViashLog $VIASH_LOGCODE_CRITICAL critical "$@" -} - -# ViashError: log events when an error condition occurs -# usage: ViashError Oh no something went wrong. -# stdout: Your input, prepended by '[error] '. -function ViashError { - ViashLog $VIASH_LOGCODE_ERROR error "$@" -} - -# ViashWarning: log potentially abnormal events -# usage: ViashWarning Something may have gone wrong. -# stdout: Your input, prepended by '[warning] '. -function ViashWarning { - ViashLog $VIASH_LOGCODE_WARNING warning "$@" -} - -# ViashNotice: log significant but normal events -# usage: ViashNotice This just happened. -# stdout: Your input, prepended by '[notice] '. -function ViashNotice { - ViashLog $VIASH_LOGCODE_NOTICE notice "$@" -} - -# ViashInfo: log normal events -# usage: ViashInfo This just happened. -# stdout: Your input, prepended by '[info] '. -function ViashInfo { - ViashLog $VIASH_LOGCODE_INFO info "$@" -} - -# ViashDebug: log all events, for debugging purposes -# usage: ViashDebug This just happened. -# stdout: Your input, prepended by '[debug] '. -function ViashDebug { - ViashLog $VIASH_LOGCODE_DEBUG debug "$@" -} - -# find source folder of this component -VIASH_META_RESOURCES_DIR=`ViashSourceDir ${BASH_SOURCE[0]}` - -# find the root of the built components & dependencies -VIASH_TARGET_DIR=`ViashFindTargetDir $VIASH_META_RESOURCES_DIR` - -# define meta fields -VIASH_META_FUNCTIONALITY_NAME="take_column" -VIASH_META_EXECUTABLE="$VIASH_META_RESOURCES_DIR/$VIASH_META_FUNCTIONALITY_NAME" -VIASH_META_CONFIG="$VIASH_META_RESOURCES_DIR/.config.vsh.yaml" -VIASH_META_TEMP_DIR="$VIASH_TEMP" - - -# ViashHelp: Display helpful explanation about this executable -function ViashHelp { - echo "take_column 0.2.2" - echo "" - echo "Arguments:" - echo " -i, --input" - echo " type: file, required parameter, file must exist" - echo "" - echo " -o, --output" - echo " type: file, required parameter, output, file must exist" - echo "" - echo " --column" - echo " type: integer" - echo " default: 2" -} - -######## Helper functions for setting up Docker images for viash ######## -# expects: ViashDockerBuild - -# ViashDockerInstallationCheck: check whether Docker is installed correctly -# -# examples: -# ViashDockerInstallationCheck -function ViashDockerInstallationCheck { - ViashDebug "Checking whether Docker is installed" - if [ ! command -v docker &> /dev/null ]; then - ViashCritical "Docker doesn't seem to be installed. See 'https://docs.docker.com/get-docker/' for instructions." - exit 1 - fi - - ViashDebug "Checking whether the Docker daemon is running" - save=$-; set +e - docker_version=$(docker version --format '{{.Client.APIVersion}}' 2> /dev/null) - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashCritical "Docker daemon does not seem to be running. Try one of the following:" - ViashCritical "- Try running 'dockerd' in the command line" - ViashCritical "- See https://docs.docker.com/config/daemon/" - exit 1 - fi -} - -# ViashDockerRemoteTagCheck: check whether a Docker image is available -# on a remote. Assumes `docker login` has been performed, if relevant. -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerRemoteTagCheck python:latest -# echo $? # returns '0' -# ViashDockerRemoteTagCheck sdaizudceahifu -# echo $? # returns '1' -function ViashDockerRemoteTagCheck { - docker manifest inspect $1 > /dev/null 2> /dev/null -} - -# ViashDockerLocalTagCheck: check whether a Docker image is available locally -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# docker pull python:latest -# ViashDockerLocalTagCheck python:latest -# echo $? # returns '0' -# ViashDockerLocalTagCheck sdaizudceahifu -# echo $? # returns '1' -function ViashDockerLocalTagCheck { - [ -n "$(docker images -q $1)" ] -} - -# ViashDockerPull: pull a Docker image -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerPull python:latest -# echo $? # returns '0' -# ViashDockerPull sdaizudceahifu -# echo $? # returns '1' -function ViashDockerPull { - ViashNotice "Checking if Docker image is available at '$1'" - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker pull $1 && return 0 || return 1 - else - save=$-; set +e - docker pull $1 2> /dev/null > /dev/null - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashWarning "Could not pull from '$1'. Docker image doesn't exist or is not accessible." - fi - return $out - fi -} - -# ViashDockerPush: push a Docker image -# -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was found -# examples: -# ViashDockerPush python:latest -# echo $? # returns '0' -# ViashDockerPush sdaizudceahifu -# echo $? # returns '1' -function ViashDockerPush { - ViashNotice "Pushing image to '$1'" - save=$-; set +e - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker push $1 - out=$? - else - docker push $1 2> /dev/null > /dev/null - out=$? - fi - [[ $save =~ e ]] && set -e - if [ $out -eq 0 ]; then - ViashNotice "Container '$VSHD_ID' push succeeded." - else - ViashError "Container '$VSHD_ID' push errored. You might not be logged in or have the necessary permissions." - fi - return $out -} - -# ViashDockerPullElseBuild: pull a Docker image, else build it -# -# $1 : image identifier with format `[registry/]image[:tag]` -# ViashDockerBuild : a Bash function which builds a docker image, takes image identifier as argument. -# examples: -# ViashDockerPullElseBuild mynewcomponent -function ViashDockerPullElseBuild { - save=$-; set +e - ViashDockerPull $1 - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashDockerBuild $@ - fi -} - -# ViashDockerSetup: create a Docker image, according to specified docker setup strategy -# -# $1 : image identifier with format `[registry/]image[:tag]` -# $2 : docker setup strategy, see DockerSetupStrategy.scala -# ViashDockerBuild : a Bash function which builds a docker image, takes image identifier as argument. -# examples: -# ViashDockerSetup mynewcomponent alwaysbuild -function ViashDockerSetup { - VSHD_ID="$1" - VSHD_STRAT="$2" - if [ "$VSHD_STRAT" == "alwaysbuild" -o "$VSHD_STRAT" == "build" -o "$VSHD_STRAT" == "b" ]; then - ViashDockerBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "alwayspull" -o "$VSHD_STRAT" == "pull" -o "$VSHD_STRAT" == "p" ]; then - ViashDockerPull $VSHD_ID - elif [ "$VSHD_STRAT" == "alwayspullelsebuild" -o "$VSHD_STRAT" == "pullelsebuild" ]; then - ViashDockerPullElseBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "alwayspullelsecachedbuild" -o "$VSHD_STRAT" == "pullelsecachedbuild" ]; then - ViashDockerPullElseBuild $VSHD_ID - elif [ "$VSHD_STRAT" == "alwayscachedbuild" -o "$VSHD_STRAT" == "cachedbuild" -o "$VSHD_STRAT" == "cb" ]; then - ViashDockerBuild $VSHD_ID - elif [[ "$VSHD_STRAT" =~ ^ifneedbe ]]; then - save=$-; set +e - ViashDockerLocalTagCheck $VSHD_ID - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -eq 0 ]; then - ViashInfo "Image $VSHD_ID already exists" - elif [ "$VSHD_STRAT" == "ifneedbebuild" ]; then - ViashDockerBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "ifneedbecachedbuild" ]; then - ViashDockerBuild $VSHD_ID - elif [ "$VSHD_STRAT" == "ifneedbepull" ]; then - ViashDockerPull $VSHD_ID - elif [ "$VSHD_STRAT" == "ifneedbepullelsebuild" ]; then - ViashDockerPullElseBuild $VSHD_ID --no-cache - elif [ "$VSHD_STRAT" == "ifneedbepullelsecachedbuild" ]; then - ViashDockerPullElseBuild $VSHD_ID - else - ViashError "Unrecognised Docker strategy: $VSHD_STRAT" - exit 1 - fi - elif [ "$VSHD_STRAT" == "push" -o "$VSHD_STRAT" == "forcepush" -o "$VSHD_STRAT" == "alwayspush" ]; then - ViashDockerPush "$VSHD_ID" - elif [ "$VSHD_STRAT" == "pushifnotpresent" -o "$VSHD_STRAT" == "gentlepush" -o "$VSHD_STRAT" == "maybepush" ]; then - save=$-; set +e - ViashDockerRemoteTagCheck $VSHD_ID - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -eq 0 ]; then - ViashNotice "Container '$VSHD_ID' exists, doing nothing." - else - ViashNotice "Container '$VSHD_ID' does not yet exist." - ViashDockerPush "$VSHD_ID" - fi - elif [ "$VSHD_STRAT" == "donothing" -o "$VSHD_STRAT" == "meh" ]; then - ViashNotice "Skipping setup." - else - ViashError "Unrecognised Docker strategy: $VSHD_STRAT" - exit 1 - fi -} - -# ViashDockerCheckCommands: Check whether a docker container has the required commands -# -# $1 : image identifier with format `[registry/]image[:tag]` -# $@ : commands to verify being present -# examples: -# ViashDockerCheckCommands bash:4.0 bash ps foo -function ViashDockerCheckCommands { - tag=$1 - shift 1 - commands="$@" - save=$-; set +e - missing=$(docker run --rm --entrypoint=sh $tag -c "for command in $commands; do command -v \$command >/dev/null 2>&1; if [ \$? -ne 0 ]; then echo \$command; exit 1; fi; done") - outCheck=$? - [[ $save =~ e ]] && set -e - if [ $outCheck -ne 0 ]; then - ViashError "Docker container '$tag' does not contain command '$missing'." - exit 1 - fi -} - - -######## End of helper functions for setting up Docker images for viash ######## - -# ViashDockerFile: print the dockerfile to stdout -# return : dockerfile required to run this component -# examples: -# ViashDockerFile -function ViashDockerfile { - cat << 'VIASHDOCKER' -FROM python:3.10-slim - -ENTRYPOINT [] - - -RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "pandas" - -RUN apt-get update && \ - DEBIAN_FRONTEND=noninteractive apt-get install -y procps && \ - rm -rf /var/lib/apt/lists/* - -LABEL org.opencontainers.image.description="Companion container for running component template take_column" -LABEL org.opencontainers.image.created="2024-01-16T14:48:47+01:00" -LABEL org.opencontainers.image.source="https://github.com/viash-io/viash_project_template" -LABEL org.opencontainers.image.revision="11b6278597bf22afbfb56a8e83065a55553c9dd0" -LABEL org.opencontainers.image.version="0.2.2" - -VIASHDOCKER -} - -# ViashDockerBuild: build a docker container -# $1 : image identifier with format `[registry/]image[:tag]` -# exit code $? : whether or not the image was built -function ViashDockerBuild { - # create temporary directory to store dockerfile & optional resources in - tmpdir=$(mktemp -d "$VIASH_META_TEMP_DIR/dockerbuild-take_column-XXXXXX") - dockerfile="$tmpdir/Dockerfile" - function clean_up { - rm -rf "$tmpdir" - } - trap clean_up EXIT - - # store dockerfile and resources - ViashDockerfile > $dockerfile - - # Build the container - ViashNotice "Building container '$1' with Dockerfile" - ViashInfo "Running 'docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile'" - save=$-; set +e - if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then - docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile - else - docker build -t $@ $VIASH_META_RESOURCES_DIR -f $dockerfile &> $tmpdir/docker_build.log - fi - out=$? - [[ $save =~ e ]] && set -e - if [ $out -ne 0 ]; then - ViashError "Error occurred while building container '$1'" - if [ $VIASH_VERBOSITY -lt $VIASH_LOGCODE_INFO ]; then - ViashError "Transcript: --------------------------------" - cat "$tmpdir/docker_build.log" - ViashError "End of transcript --------------------------" - fi - exit 1 - fi - ViashDockerCheckCommands "$1" 'bash' -} - -# ViashAbsolutePath: generate absolute path from relative path -# borrowed from https://stackoverflow.com/a/21951256 -# $1 : relative filename -# return : absolute path -# examples: -# ViashAbsolutePath some_file.txt # returns /path/to/some_file.txt -# ViashAbsolutePath /foo/bar/.. # returns /foo -function ViashAbsolutePath { - local thePath - if [[ ! "$1" =~ ^/ ]]; then - thePath="$PWD/$1" - else - thePath="$1" - fi - echo "$thePath" | ( - IFS=/ - read -a parr - declare -a outp - for i in "${parr[@]}"; do - case "$i" in - ''|.) continue ;; - ..) - len=${#outp[@]} - if ((len==0)); then - continue - else - unset outp[$((len-1))] - fi - ;; - *) - len=${#outp[@]} - outp[$len]="$i" - ;; - esac - done - echo /"${outp[*]}" - ) -} -# ViashAutodetectMount: auto configuring docker mounts from parameters -# $1 : The parameter value -# returns : New parameter -# $VIASH_EXTRA_MOUNTS : Added another parameter to be passed to docker -# examples: -# ViashAutodetectMount /path/to/bar # returns '/viash_automount/path/to/bar' -# ViashAutodetectMountArg /path/to/bar # returns '--volume="/path/to:/viash_automount/path/to"' -function ViashAutodetectMount { - abs_path=$(ViashAbsolutePath "$1") - if [ -d "$abs_path" ]; then - mount_source="$abs_path" - base_name="" - else - mount_source=`dirname "$abs_path"` - base_name=`basename "$abs_path"` - fi - mount_target="/viash_automount$mount_source" - echo "$mount_target/$base_name" -} -function ViashAutodetectMountArg { - abs_path=$(ViashAbsolutePath "$1") - if [ -d "$abs_path" ]; then - mount_source="$abs_path" - base_name="" - else - mount_source=`dirname "$abs_path"` - base_name=`basename "$abs_path"` - fi - mount_target="/viash_automount$mount_source" - ViashDebug "ViashAutodetectMountArg $1 -> $mount_source -> $mount_target" - echo "--volume=\"$mount_source:$mount_target\"" -} -function ViashStripAutomount { - abs_path=$(ViashAbsolutePath "$1") - echo "${abs_path#/viash_automount}" -} -# ViashExtractFlags: Retain leading flag -# $1 : string with a possible leading flag -# return : leading flag -# examples: -# ViashExtractFlags --foo=bar # returns --foo -function ViashExtractFlags { - echo $1 | sed 's/=.*//' -} -# initialise variables -VIASH_EXTRA_MOUNTS=() - -# initialise array -VIASH_POSITIONAL_ARGS='' -VIASH_MODE='run' - -while [[ $# -gt 0 ]]; do - case "$1" in - -h|--help) - ViashHelp - exit - ;; - ---v|---verbose) - let "VIASH_VERBOSITY=VIASH_VERBOSITY+1" - shift 1 - ;; - ---verbosity) - VIASH_VERBOSITY="$2" - shift 2 - ;; - ---verbosity=*) - VIASH_VERBOSITY="$(ViashRemoveFlags "$1")" - shift 1 - ;; - --version) - echo "take_column 0.2.2" - exit - ;; - --input) - [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'--input\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_INPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --input. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --input=*) - [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'--input=*\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_INPUT=$(ViashRemoveFlags "$1") - shift 1 - ;; - -i) - [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'-i\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_INPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to -i. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --output) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'--output\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --output. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --output=*) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'--output=*\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT=$(ViashRemoveFlags "$1") - shift 1 - ;; - -o) - [ -n "$VIASH_PAR_OUTPUT" ] && ViashError Bad arguments for option \'-o\': \'$VIASH_PAR_OUTPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OUTPUT="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to -o. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --column) - [ -n "$VIASH_PAR_COLUMN" ] && ViashError Bad arguments for option \'--column\': \'$VIASH_PAR_COLUMN\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_COLUMN="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --column. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --column=*) - [ -n "$VIASH_PAR_COLUMN" ] && ViashError Bad arguments for option \'--column=*\': \'$VIASH_PAR_COLUMN\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_COLUMN=$(ViashRemoveFlags "$1") - shift 1 - ;; - ---setup) - VIASH_MODE='docker_setup' - VIASH_DOCKER_SETUP_STRATEGY="$2" - shift 1 - ;; - ---setup=*) - VIASH_MODE='docker_setup' - VIASH_DOCKER_SETUP_STRATEGY="$(ViashRemoveFlags "$1")" - shift 2 - ;; - ---dockerfile) - ViashDockerfile - exit 0 - ;; - ---v|---volume) - VIASH_EXTRA_MOUNTS+=("--volume='$2'") - shift 2 - ;; - ---volume=*) - VIASH_EXTRA_MOUNTS+=("--volume='$(ViashRemoveFlags "$2")'") - shift 1 - ;; - ---debug) - VIASH_MODE='docker_debug' - shift 1 - ;; - ---cpus) - [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_CPUS="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to ---cpus. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - ---cpus=*) - [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus=*\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_CPUS=$(ViashRemoveFlags "$1") - shift 1 - ;; - ---memory) - [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_MEMORY="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to ---memory. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - ---memory=*) - [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory=*\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_META_MEMORY=$(ViashRemoveFlags "$1") - shift 1 - ;; - *) # positional arg or unknown option - # since the positional args will be eval'd, can we always quote, instead of using ViashQuote - VIASH_POSITIONAL_ARGS="$VIASH_POSITIONAL_ARGS '$1'" - [[ $1 == -* ]] && ViashWarning $1 looks like a parameter but is not a defined parameter and will instead be treated as a positional argument. Use "--help" to get more information on the parameters. - shift # past argument - ;; - esac -done - -# parse positional parameters -eval set -- $VIASH_POSITIONAL_ARGS - - -ViashDockerInstallationCheck - -if [ $VIASH_MODE == "docker_setup" ]; then - ViashDockerSetup 'ghcr.io/viash-io/viash_project_template/template/take_column:0.2.2' "$VIASH_DOCKER_SETUP_STRATEGY" - exit 0 -fi -ViashDockerSetup 'ghcr.io/viash-io/viash_project_template/template/take_column:0.2.2' ifneedbepullelsecachedbuild - -if [ $VIASH_MODE == "docker_debug" ]; then - ViashNotice "+ docker run --entrypoint=bash -i --rm -v "$(pwd)":/pwd --workdir /pwd -t 'ghcr.io/viash-io/viash_project_template/template/take_column:0.2.2'" - docker run --entrypoint=bash -i --rm -v "$(pwd)":/pwd --workdir /pwd -t 'ghcr.io/viash-io/viash_project_template/template/take_column:0.2.2' - exit 0 -fi - -# setting computational defaults - -# helper function for parsing memory strings -function ViashMemoryAsBytes { - local memory=`echo "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]'` - local memory_regex='^([0-9]+)([kmgtp]b?|b)$' - if [[ $memory =~ $memory_regex ]]; then - local number=${memory/[^0-9]*/} - local symbol=${memory/*[0-9]/} - - case $symbol in - b) memory_b=$number ;; - kb|k) memory_b=$(( $number * 1024 )) ;; - mb|m) memory_b=$(( $number * 1024 * 1024 )) ;; - gb|g) memory_b=$(( $number * 1024 * 1024 * 1024 )) ;; - tb|t) memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 )) ;; - pb|p) memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 * 1024 )) ;; - esac - echo "$memory_b" - fi -} -# compute memory in different units -if [ ! -z ${VIASH_META_MEMORY+x} ]; then - VIASH_META_MEMORY_B=`ViashMemoryAsBytes $VIASH_META_MEMORY` - # do not define other variables if memory_b is an empty string - if [ ! -z "$VIASH_META_MEMORY_B" ]; then - VIASH_META_MEMORY_KB=$(( ($VIASH_META_MEMORY_B+1023) / 1024 )) - VIASH_META_MEMORY_MB=$(( ($VIASH_META_MEMORY_KB+1023) / 1024 )) - VIASH_META_MEMORY_GB=$(( ($VIASH_META_MEMORY_MB+1023) / 1024 )) - VIASH_META_MEMORY_TB=$(( ($VIASH_META_MEMORY_GB+1023) / 1024 )) - VIASH_META_MEMORY_PB=$(( ($VIASH_META_MEMORY_TB+1023) / 1024 )) - else - # unset memory if string is empty - unset $VIASH_META_MEMORY_B - fi -fi -# unset nproc if string is empty -if [ -z "$VIASH_META_CPUS" ]; then - unset $VIASH_META_CPUS -fi - - -# check whether required parameters exist -if [ -z ${VIASH_PAR_INPUT+x} ]; then - ViashError '--input' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_PAR_OUTPUT+x} ]; then - ViashError '--output' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then - ViashError 'functionality_name' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_RESOURCES_DIR+x} ]; then - ViashError 'resources_dir' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_EXECUTABLE+x} ]; then - ViashError 'executable' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_CONFIG+x} ]; then - ViashError 'config' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi -if [ -z ${VIASH_META_TEMP_DIR+x} ]; then - ViashError 'temp_dir' is a required argument. Use "--help" to get more information on the parameters. - exit 1 -fi - -# filling in defaults -if [ -z ${VIASH_PAR_COLUMN+x} ]; then - VIASH_PAR_COLUMN="2" -fi - -# check whether required files exist -if [ ! -z "$VIASH_PAR_INPUT" ] && [ ! -e "$VIASH_PAR_INPUT" ]; then - ViashError "Input file '$VIASH_PAR_INPUT' does not exist." - exit 1 -fi - -# check whether parameters values are of the right type -if [[ -n "$VIASH_PAR_COLUMN" ]]; then - if ! [[ "$VIASH_PAR_COLUMN" =~ ^[-+]?[0-9]+$ ]]; then - ViashError '--column' has to be an integer. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_CPUS" ]]; then - if ! [[ "$VIASH_META_CPUS" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'cpus' has to be an integer. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_B" ]]; then - if ! [[ "$VIASH_META_MEMORY_B" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_b' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_KB" ]]; then - if ! [[ "$VIASH_META_MEMORY_KB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_kb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_MB" ]]; then - if ! [[ "$VIASH_META_MEMORY_MB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_mb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_GB" ]]; then - if ! [[ "$VIASH_META_MEMORY_GB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_gb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_TB" ]]; then - if ! [[ "$VIASH_META_MEMORY_TB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_tb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi -if [[ -n "$VIASH_META_MEMORY_PB" ]]; then - if ! [[ "$VIASH_META_MEMORY_PB" =~ ^[-+]?[0-9]+$ ]]; then - ViashError 'memory_pb' has to be a long. Use "--help" to get more information on the parameters. - exit 1 - fi -fi - -# create parent directories of output files, if so desired -if [ ! -z "$VIASH_PAR_OUTPUT" ] && [ ! -d "$(dirname "$VIASH_PAR_OUTPUT")" ]; then - mkdir -p "$(dirname "$VIASH_PAR_OUTPUT")" -fi - -# detect volumes from file arguments -VIASH_CHOWN_VARS=() -if [ ! -z "$VIASH_PAR_INPUT" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_PAR_INPUT")" ) - VIASH_PAR_INPUT=$(ViashAutodetectMount "$VIASH_PAR_INPUT") -fi -if [ ! -z "$VIASH_PAR_OUTPUT" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_PAR_OUTPUT")" ) - VIASH_PAR_OUTPUT=$(ViashAutodetectMount "$VIASH_PAR_OUTPUT") - VIASH_CHOWN_VARS+=( "$VIASH_PAR_OUTPUT" ) -fi -if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_RESOURCES_DIR")" ) - VIASH_META_RESOURCES_DIR=$(ViashAutodetectMount "$VIASH_META_RESOURCES_DIR") -fi -if [ ! -z "$VIASH_META_EXECUTABLE" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_EXECUTABLE")" ) - VIASH_META_EXECUTABLE=$(ViashAutodetectMount "$VIASH_META_EXECUTABLE") -fi -if [ ! -z "$VIASH_META_CONFIG" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_CONFIG")" ) - VIASH_META_CONFIG=$(ViashAutodetectMount "$VIASH_META_CONFIG") -fi -if [ ! -z "$VIASH_META_TEMP_DIR" ]; then - VIASH_EXTRA_MOUNTS+=( "$(ViashAutodetectMountArg "$VIASH_META_TEMP_DIR")" ) - VIASH_META_TEMP_DIR=$(ViashAutodetectMount "$VIASH_META_TEMP_DIR") -fi - -# get unique mounts -VIASH_UNIQUE_MOUNTS=($(for val in "${VIASH_EXTRA_MOUNTS[@]}"; do echo "$val"; done | sort -u)) - -# change file ownership -function ViashPerformChown { - if (( ${#VIASH_CHOWN_VARS[@]} )); then - set +e - eval docker run --entrypoint=chown -i --rm ${VIASH_UNIQUE_MOUNTS[@]} ghcr.io/viash-io/viash_project_template/template/take_column:0.2.2 "$(id -u):$(id -g)" --silent --recursive ${VIASH_CHOWN_VARS[@]} - set -e - fi -} -trap ViashPerformChown EXIT - -# helper function for filling in extra docker args -VIASH_EXTRA_DOCKER_ARGS="" -if [ ! -z "$VIASH_META_MEMORY_MB" ]; then - VIASH_EXTRA_DOCKER_ARGS="$VIASH_EXTRA_DOCKER_ARGS --memory=${VIASH_META_MEMORY_MB}m" -fi -if [ ! -z "$VIASH_META_CPUS" ]; then - VIASH_EXTRA_DOCKER_ARGS="$VIASH_EXTRA_DOCKER_ARGS --cpus=${VIASH_META_CPUS}" -fi - - -# set dependency paths - - -ViashDebug "Running command: $(echo docker run --entrypoint=bash -i --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_EXTRA_DOCKER_ARGS ghcr.io/viash-io/viash_project_template/template/take_column:0.2.2)" -cat << VIASHEOF | eval docker run --entrypoint=bash -i --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_EXTRA_DOCKER_ARGS ghcr.io/viash-io/viash_project_template/template/take_column:0.2.2 -set -e -tempscript=\$(mktemp "$VIASH_META_TEMP_DIR/viash-run-take_column-XXXXXX").py -function clean_up { - rm "\$tempscript" -} -function interrupt { - echo -e "\nCTRL-C Pressed..." - exit 1 -} -trap clean_up EXIT -trap interrupt INT SIGINT -cat > "\$tempscript" << 'VIASHMAIN' -import pandas as pd - -## VIASH START -# The following code has been auto-generated by Viash. -par = { - 'input': $( if [ ! -z ${VIASH_PAR_INPUT+x} ]; then echo "r'${VIASH_PAR_INPUT//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'output': $( if [ ! -z ${VIASH_PAR_OUTPUT+x} ]; then echo "r'${VIASH_PAR_OUTPUT//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'column': $( if [ ! -z ${VIASH_PAR_COLUMN+x} ]; then echo "int(r'${VIASH_PAR_COLUMN//\'/\'\"\'\"r\'}')"; else echo None; fi ) -} -meta = { - 'functionality_name': $( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo "r'${VIASH_META_FUNCTIONALITY_NAME//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'resources_dir': $( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo "r'${VIASH_META_RESOURCES_DIR//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'executable': $( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo "r'${VIASH_META_EXECUTABLE//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'config': $( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo "r'${VIASH_META_CONFIG//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'temp_dir': $( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo "r'${VIASH_META_TEMP_DIR//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'cpus': $( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo "int(r'${VIASH_META_CPUS//\'/\'\"\'\"r\'}')"; else echo None; fi ), - 'memory_b': $( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo "int(r'${VIASH_META_MEMORY_B//\'/\'\"\'\"r\'}')"; else echo None; fi ), - 'memory_kb': $( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo "int(r'${VIASH_META_MEMORY_KB//\'/\'\"\'\"r\'}')"; else echo None; fi ), - 'memory_mb': $( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo "int(r'${VIASH_META_MEMORY_MB//\'/\'\"\'\"r\'}')"; else echo None; fi ), - 'memory_gb': $( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo "int(r'${VIASH_META_MEMORY_GB//\'/\'\"\'\"r\'}')"; else echo None; fi ), - 'memory_tb': $( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo "int(r'${VIASH_META_MEMORY_TB//\'/\'\"\'\"r\'}')"; else echo None; fi ), - 'memory_pb': $( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo "int(r'${VIASH_META_MEMORY_PB//\'/\'\"\'\"r\'}')"; else echo None; fi ) -} -dep = { - -} - -## VIASH END - -# read the tsv file -tab = pd.read_csv(par["input"], sep="\\t", comment="#") - -# subset a column -tab_filt = tab.iloc[:, par["column"]-1] - -# write to file -tab_filt.to_csv(par["output"], index=False) -VIASHMAIN -python -B "\$tempscript" & -wait "\$!" - -VIASHEOF - - -# strip viash automount from file paths -if [ ! -z "$VIASH_PAR_INPUT" ]; then - VIASH_PAR_INPUT=$(ViashStripAutomount "$VIASH_PAR_INPUT") -fi -if [ ! -z "$VIASH_PAR_OUTPUT" ]; then - VIASH_PAR_OUTPUT=$(ViashStripAutomount "$VIASH_PAR_OUTPUT") -fi -if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then - VIASH_META_RESOURCES_DIR=$(ViashStripAutomount "$VIASH_META_RESOURCES_DIR") -fi -if [ ! -z "$VIASH_META_EXECUTABLE" ]; then - VIASH_META_EXECUTABLE=$(ViashStripAutomount "$VIASH_META_EXECUTABLE") -fi -if [ ! -z "$VIASH_META_CONFIG" ]; then - VIASH_META_CONFIG=$(ViashStripAutomount "$VIASH_META_CONFIG") -fi -if [ ! -z "$VIASH_META_TEMP_DIR" ]; then - VIASH_META_TEMP_DIR=$(ViashStripAutomount "$VIASH_META_TEMP_DIR") -fi - - -# check whether required files exist -if [ ! -z "$VIASH_PAR_OUTPUT" ] && [ ! -e "$VIASH_PAR_OUTPUT" ]; then - ViashError "Output file '$VIASH_PAR_OUTPUT' does not exist." - exit 1 -fi - - -exit 0 diff --git a/target/nextflow/template/combine_columns/.config.vsh.yaml b/target/nextflow/template/combine_columns/.config.vsh.yaml deleted file mode 100644 index 908ac75..0000000 --- a/target/nextflow/template/combine_columns/.config.vsh.yaml +++ /dev/null @@ -1,101 +0,0 @@ -functionality: - name: "combine_columns" - namespace: "template" - version: "0.2.2" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - info: null - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: true - multiple_sep: ":" - dest: "par" - - type: "file" - name: "--output" - alternatives: - - "-o" - info: null - must_exist: true - create_parent: true - required: true - direction: "output" - multiple: false - multiple_sep: ":" - dest: "par" - resources: - - type: "r_script" - path: "script.R" - is_executable: true - info: null - status: "enabled" - set_wd_to_resources_dir: false -platforms: -- type: "docker" - id: "docker" - image: "eddelbuettel/r2u:22.04" - target_organization: "viash-io/viash_project_template" - target_registry: "ghcr.io" - namespace_separator: "/" - resolve_volume: "Automatic" - chown: true - setup_strategy: "ifneedbepullelsecachedbuild" - target_image_source: "https://github.com/viash-io/viash_project_template" - entrypoint: [] - cmd: null -- type: "nextflow" - id: "nextflow" - directives: - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1.GB" - mem2gb: "memory = 2.GB" - mem4gb: "memory = 4.GB" - mem8gb: "memory = 8.GB" - mem16gb: "memory = 16.GB" - mem32gb: "memory = 32.GB" - mem64gb: "memory = 64.GB" - mem128gb: "memory = 128.GB" - mem256gb: "memory = 256.GB" - mem512gb: "memory = 512.GB" - mem1tb: "memory = 1.TB" - mem2tb: "memory = 2.TB" - mem4tb: "memory = 4.TB" - mem8tb: "memory = 8.TB" - mem16tb: "memory = 16.TB" - mem32tb: "memory = 32.TB" - mem64tb: "memory = 64.TB" - mem128tb: "memory = 128.TB" - mem256tb: "memory = 256.TB" - mem512tb: "memory = 512.TB" - cpu1: "cpus = 1" - cpu2: "cpus = 2" - cpu5: "cpus = 5" - cpu10: "cpus = 10" - cpu20: "cpus = 20" - cpu50: "cpus = 50" - cpu100: "cpus = 100" - cpu200: "cpus = 200" - cpu500: "cpus = 500" - cpu1000: "cpus = 1000" - debug: false - container: "docker" -info: - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/combine_columns/config.vsh.yaml" - platform: "nextflow" - output: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/combine_columns" - executable: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/combine_columns/combine_columns" - viash_version: "0.8.4" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - git_remote: "https://github.com/viash-io/viash_project_template" - git_tag: "v0.2.1" diff --git a/target/nextflow/template/combine_columns/main.nf b/target/nextflow/template/combine_columns/main.nf deleted file mode 100644 index 98b0942..0000000 --- a/target/nextflow/template/combine_columns/main.nf +++ /dev/null @@ -1,3410 +0,0 @@ -// combine_columns 0.2.2 -// -// This wrapper script is auto-generated by viash 0.8.4 and is thus a derivative -// work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data -// Intuitive. -// -// The component may contain files which fall under a different license. The -// authors of this component should specify the license in the header of such -// files, or include a separate license file detailing the licenses of all included -// files. - -//////////////////////////// -// VDSL3 helper functions // -//////////////////////////// - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_checkArgumentType.nf' -class UnexpectedArgumentTypeException extends Exception { - String errorIdentifier - String stage - String plainName - String expectedClass - String foundClass - - // ${key ? " in module '$key'" : ""}${id ? " id '$id'" : ""} - UnexpectedArgumentTypeException(String errorIdentifier, String stage, String plainName, String expectedClass, String foundClass) { - super("Error${errorIdentifier ? " $errorIdentifier" : ""}:${stage ? " $stage" : "" } argument '${plainName}' has the wrong type. " + - "Expected type: ${expectedClass}. Found type: ${foundClass}") - this.errorIdentifier = errorIdentifier - this.stage = stage - this.plainName = plainName - this.expectedClass = expectedClass - this.foundClass = foundClass - } -} - -/** - * Checks if the given value is of the expected type. If not, an exception is thrown. - * - * @param stage The stage of the argument (input or output) - * @param par The parameter definition - * @param value The value to check - * @param errorIdentifier The identifier to use in the error message - * @return The value, if it is of the expected type - * @throws UnexpectedArgumentTypeException If the value is not of the expected type -*/ -def _checkArgumentType(String stage, Map par, Object value, String errorIdentifier) { - // expectedClass will only be != null if value is not of the expected type - def expectedClass = null - def foundClass = null - - // todo: split if need be - - if (!par.required && value == null) { - expectedClass = null - } else if (par.multiple) { - if (value !instanceof Collection) { - value = [value] - } - - // split strings - value = value.collectMany{ val -> - if (val instanceof String) { - // collect() to ensure that the result is a List and not simply an array - val.split(par.multiple_sep).collect() - } else { - [val] - } - } - - // process globs - if (par.type == "file" && par.direction == "input") { - value = value.collect{ it instanceof String ? file(it, hidden: true) : it }.flatten() - } - - // check types of elements in list - try { - value = value.collect { listVal -> - _checkArgumentType(stage, par + [multiple: false], listVal, errorIdentifier) - } - } catch (UnexpectedArgumentTypeException e) { - expectedClass = "List[${e.expectedClass}]" - foundClass = "List[${e.foundClass}]" - } - } else if (par.type == "string") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else if (par.type == "integer") { - // cast to integer if need be - if (value instanceof String) { - try { - value = value.toInteger() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigInteger) { - value = value.intValue() - } - expectedClass = value instanceof Integer ? null : "Integer" - } else if (par.type == "long") { - // cast to long if need be - if (value instanceof String) { - try { - value = value.toLong() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof Integer) { - value = value.toLong() - } - expectedClass = value instanceof Long ? null : "Long" - } else if (par.type == "double") { - // cast to double if need be - if (value instanceof String) { - try { - value = value.toDouble() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigDecimal) { - value = value.doubleValue() - } - if (value instanceof Float) { - value = value.toDouble() - } - expectedClass = value instanceof Double ? null : "Double" - } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { - // cast to boolean if need ben - if (value instanceof String) { - def valueLower = value.toLowerCase() - if (valueLower == "true") { - value = true - } else if (valueLower == "false") { - value = false - } - } - expectedClass = value instanceof Boolean ? null : "Boolean" - } else if (par.type == "file" && (par.direction == "input" || stage == "output")) { - // cast to path if need be - if (value instanceof String) { - value = file(value, hidden: true) - } - if (value instanceof File) { - value = value.toPath() - } - expectedClass = value instanceof Path ? null : "Path" - } else if (par.type == "file" && stage == "input" && par.direction == "output") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else { - // didn't find a match for par.type - expectedClass = par.type - } - - if (expectedClass != null) { - if (foundClass == null) { - foundClass = value.getClass().getName() - } - throw new UnexpectedArgumentTypeException(errorIdentifier, stage, par.plainName, expectedClass, foundClass) - } - - return value -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processInputValues.nf' -Map _processInputValues(Map inputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.required) { - assert inputs.containsKey(arg.plainName) && inputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required input argument '${arg.plainName}' is missing" - } - } - - inputs = inputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid input argument" - - value = _checkArgumentType("input", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return inputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processOutputValues.nf' -Map _processOutputValues(Map outputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.direction == "output" && arg.required) { - assert outputs.containsKey(arg.plainName) && outputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required output argument '${arg.plainName}' is missing" - } - } - - outputs = outputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && it.direction == "output" } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid output argument" - - value = _checkArgumentType("output", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return outputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/IDChecker.nf' -class IDChecker { - final def items = [] as Set - - @groovy.transform.WithWriteLock - boolean observe(String item) { - if (items.contains(item)) { - return false - } else { - items << item - return true - } - } - - @groovy.transform.WithReadLock - boolean contains(String item) { - return items.contains(item) - } - - @groovy.transform.WithReadLock - Set getItems() { - return items.clone() - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_checkUniqueIds.nf' - -/** - * Check if the ids are unique across parameter sets - * - * @param parameterSets a list of parameter sets. - */ -private void _checkUniqueIds(List>> parameterSets) { - def ppIds = parameterSets.collect{it[0]} - assert ppIds.size() == ppIds.unique().size() : "All argument sets should have unique ids. Detected ids: $ppIds" -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_getChild.nf' - -// helper functions for reading params from file // -def _getChild(parent, child) { - if (child.contains("://") || java.nio.file.Paths.get(child).isAbsolute()) { - child - } else { - def parentAbsolute = java.nio.file.Paths.get(parent).toAbsolutePath().toString() - parentAbsolute.replaceAll('/[^/]*$', "/") + child - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_parseParamList.nf' -/** - * Figure out the param list format based on the file extension - * - * @param param_list A String containing the path to the parameter list file. - * - * @return A String containing the format of the parameter list file. - */ -def _paramListGuessFormat(param_list) { - if (param_list !instanceof String) { - "asis" - } else if (param_list.endsWith(".csv")) { - "csv" - } else if (param_list.endsWith(".json") || param_list.endsWith(".jsn")) { - "json" - } else if (param_list.endsWith(".yaml") || param_list.endsWith(".yml")) { - "yaml" - } else { - "yaml_blob" - } -} - - -/** - * Read the param list - * - * @param param_list One of the following: - * - A String containing the path to the parameter list file (csv, json or yaml), - * - A yaml blob of a list of maps (yaml_blob), - * - Or a groovy list of maps (asis). - * @param config A Map of the Viash configuration. - * - * @return A List of Maps containing the parameters. - */ -def _parseParamList(param_list, Map config) { - // first determine format by extension - def paramListFormat = _paramListGuessFormat(param_list) - - def paramListPath = (paramListFormat != "asis" && paramListFormat != "yaml_blob") ? - file(param_list, hidden: true) : - null - - // get the correct parser function for the detected params_list format - def paramSets = [] - if (paramListFormat == "asis") { - paramSets = param_list - } else if (paramListFormat == "yaml_blob") { - paramSets = readYamlBlob(param_list) - } else if (paramListFormat == "yaml") { - paramSets = readYaml(paramListPath) - } else if (paramListFormat == "json") { - paramSets = readJson(paramListPath) - } else if (paramListFormat == "csv") { - paramSets = readCsv(paramListPath) - } else { - error "Format of provided --param_list not recognised.\n" + - "Found: '$paramListFormat'.\n" + - "Expected: a csv file, a json file, a yaml file,\n" + - "a yaml blob or a groovy list of maps." - } - - // data checks - assert paramSets instanceof List: "--param_list should contain a list of maps" - for (value in paramSets) { - assert value instanceof Map: "--param_list should contain a list of maps" - } - - // id is argument - def idIsArgument = config.functionality.allArguments.any{it.plainName == "id"} - - // Reformat from List to List> by adding the ID as first element of a Tuple2 - paramSets = paramSets.collect({ data -> - def id = data.id - if (!idIsArgument) { - data = data.findAll{k, v -> k != "id"} - } - [id, data] - }) - - // Split parameters with 'multiple: true' - paramSets = paramSets.collect({ id, data -> - data = _splitParams(data, config) - [id, data] - }) - - // The paths of input files inside a param_list file may have been specified relatively to the - // location of the param_list file. These paths must be made absolute. - if (paramListPath) { - paramSets = paramSets.collect({ id, data -> - def new_data = data.collectEntries{ parName, parValue -> - def par = config.functionality.allArguments.find{it.plainName == parName} - if (par && par.type == "file" && par.direction == "input") { - if (parValue instanceof Collection) { - parValue = parValue.collectMany{path -> - def x = _resolveSiblingIfNotAbsolute(path, paramListPath) - x instanceof Collection ? x : [x] - } - } else { - parValue = _resolveSiblingIfNotAbsolute(parValue, paramListPath) - } - } - [parName, parValue] - } - [id, new_data] - }) - } - - return paramSets -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_splitParams.nf' -/** - * Split parameters for arguments that accept multiple values using their separator - * - * @param paramList A Map containing parameters to split. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A Map of parameters where the parameter values have been split into a list using - * their seperator. - */ -Map _splitParams(Map parValues, Map config){ - def parsedParamValues = parValues.collectEntries { parName, parValue -> - def parameterSettings = config.functionality.allArguments.find({it.plainName == parName}) - - if (!parameterSettings) { - // if argument is not found, do not alter - return [parName, parValue] - } - if (parameterSettings.multiple) { // Check if parameter can accept multiple values - if (parValue instanceof Collection) { - parValue = parValue.collect{it instanceof String ? it.split(parameterSettings.multiple_sep) : it } - } else if (parValue instanceof String) { - parValue = parValue.split(parameterSettings.multiple_sep) - } else if (parValue == null) { - parValue = [] - } else { - parValue = [ parValue ] - } - parValue = parValue.flatten() - } - // For all parameters check if multiple values are only passed for - // arguments that allow it. Quietly simplify lists of length 1. - if (!parameterSettings.multiple && parValue instanceof Collection) { - assert parValue.size() == 1 : - "Error: argument ${parName} has too many values.\n" + - " Expected amount: 1. Found: ${parValue.size()}" - parValue = parValue[0] - } - [parName, parValue] - } - return parsedParamValues -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/channelFromParams.nf' -/** - * Parse nextflow parameters based on settings defined in a viash config. - * Return a list of parameter sets, each parameter set corresponding to - * an event in a nextflow channel. The output from this function can be used - * with Channel.fromList to create a nextflow channel with Vdsl3 formatted - * events. - * - * This function performs: - * - A filtering of the params which can be found in the config file. - * - Process the params_list argument which allows a user to to initialise - * a Vsdl3 channel with multiple parameter sets. Possible formats are - * csv, json, yaml, or simply a yaml_blob. A csv should have column names - * which correspond to the different arguments of this pipeline. A json or a yaml - * file should be a list of maps, each of which has keys corresponding to the - * arguments of the pipeline. A yaml blob can also be passed directly as a parameter. - * When passing a csv, json or yaml, relative path names are relativized to the - * location of the parameter file. - * - Combine the parameter sets into a vdsl3 Channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A list of parameters with the first element of the event being - * the event ID and the second element containing a map of the parsed parameters. - */ - -private List>> _paramsToParamSets(Map params, Map config){ - // todo: fetch key from run args - def key_ = config.functionality.name - - /* parse regular parameters (not in param_list) */ - /*************************************************/ - def globalParams = config.functionality.allArguments - .findAll { params.containsKey(it.plainName) } - .collectEntries { [ it.plainName, params[it.plainName] ] } - def globalID = params.get("id", null) - - /* process params_list arguments */ - /*********************************/ - def paramList = params.containsKey("param_list") && params.param_list != null ? - params.param_list : [] - // if (paramList instanceof String) { - // paramList = [paramList] - // } - // def paramSets = paramList.collectMany{ _parseParamList(it, config) } - // TODO: be able to process param_list when it is a list of strings - def paramSets = _parseParamList(paramList, config) - if (paramSets.isEmpty()) { - paramSets = [[null, [:]]] - } - - /* combine arguments into channel */ - /**********************************/ - def processedParams = paramSets.indexed().collect{ index, tup -> - // Process ID - def id = tup[0] ?: globalID - - if (workflow.stubRun) { - // if stub run, explicitly add an id if missing - id = id ? id : "stub${index}" - } - assert id != null: "Each parameter set should have at least an 'id'" - - // Process params - def parValues = globalParams + tup[1] - // // Remove parameters which are null, if the default is also null - // parValues = parValues.collectEntries{paramName, paramValue -> - // parameterSettings = config.functionality.allArguments.find({it.plainName == paramName}) - // if ( paramValue != null || parameterSettings.get("default", null) != null ) { - // [paramName, paramValue] - // } - // } - parValues = parValues.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key_}' id '${id}': '${name}' is not a valid input argument" - - if (par == null) { - return [:] - } - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - - [ name, value ] - } - - [id, parValues] - } - - // Check if ids (first element of each list) is unique - _checkUniqueIds(processedParams) - return processedParams -} - -/** - * Parse nextflow parameters based on settings defined in a viash config - * and return a nextflow channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A nextflow Channel with events. Events are formatted as a tuple that contains - * first contains the ID of the event and as second element holds a parameter map. - * - * - */ -def channelFromParams(Map params, Map config) { - def processedParams = _paramsToParamSets(params, config) - return Channel.fromList(processedParams) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/checkUniqueIds.nf' -def checkUniqueIds(Map args) { - def stopOnError = args.stopOnError == null ? args.stopOnError : true - - def idChecker = new IDChecker() - - return filter { tup -> - if (!idChecker.observe(tup[0])) { - if (stopOnError) { - error "Duplicate id: ${tup[0]}" - } else { - log.warn "Duplicate id: ${tup[0]}, removing duplicate entry" - return false - } - } - return true - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/preprocessInputs.nf' -// This helper file will be deprecated soon -preprocessInputsDeprecationWarningPrinted = false - -def preprocessInputsDeprecationWarning() { - if (!preprocessInputsDeprecationWarningPrinted) { - preprocessInputsDeprecationWarningPrinted = true - System.err.println("Warning: preprocessInputs() is deprecated and will be removed in Viash 0.9.0.") - } -} - -/** - * Generate a nextflow Workflow that allows processing a channel of - * Vdsl3 formatted events and apply a Viash config to them: - * - Gather default parameters from the Viash config and make - * sure that they are correctly formatted (see applyConfig method). - * - Format the input parameters (also using the applyConfig method). - * - Apply the default parameter to the input parameters. - * - Do some assertions: - * ~ Check if the event IDs in the channel are unique. - * - * The events in the channel are formatted as tuples, with the - * first element of the tuples being a unique id of the parameter set, - * and the second element containg the the parameters themselves. - * Optional extra elements of the tuples will be passed to the output as is. - * - * @param args A map that must contain a 'config' key that points - * to a parsed config (see readConfig()). Optionally, a - * 'key' key can be provided which can be used to create a unique - * name for the workflow process. - * - * @return A workflow that allows processing a channel of Vdsl3 formatted events - * and apply a Viash config to them. - */ -def preprocessInputs(Map args) { - preprocessInputsDeprecationWarning() - - def config = args.config - assert config instanceof Map : - "Error in preprocessInputs: config must be a map. " + - "Expected class: Map. Found: config.getClass() is ${config.getClass()}" - def key_ = args.key ?: config.functionality.name - - // Get different parameter types (used throughout this function) - def defaultArgs = config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - map { tup -> - def id = tup[0] - def data = tup[1] - def passthrough = tup.drop(2) - - def new_data = (defaultArgs + data).collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - - if (par != null) { - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - } - - [ name, value ] - } - - [ id, new_data ] + passthrough - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runComponents.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component config. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component config. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component config. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component config. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runComponents(Map args) { - log.warn("runComponents is deprecated, use runEach instead") - assert args.components: "runComponents should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runComponents" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runComponentsWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def comp_config = comp_.config - - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_config) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - // def new_id = id_(tup[0], tup[1], comp_config) - def new_id = tup[0] - if (id_ instanceof String) { - new_id = id_ - } else if (id_ instanceof Closure) { - new_id = id_(new_id, tup[1], comp_config) - } - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_config) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_config) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runComponentsWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runEach.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component itself. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component itself. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component itself. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component itself. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runEach(Map args) { - assert args.components: "runEach should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runEach" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runEachWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - def new_id = id_ - if (new_id instanceof Closure) { - new_id = new_id(tup[0], tup[1], comp_) - } - assert new_id instanceof String : "Error in runEach: id should be a String or a Closure that returns a String. Expected: id instanceof String. Found: ${new_id.getClass()}" - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - def new_state = null - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runEachWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/safeJoin.nf' -/** - * Join sourceChannel to targetChannel - * - * This function joins the sourceChannel to the targetChannel. - * However, each id in the targetChannel must be present in the - * sourceChannel. If _meta.join_id exists in the targetChannel, that is - * used as an id instead. If the id doesn't match any id in the sourceChannel, - * an error is thrown. - */ - -def safeJoin(targetChannel, sourceChannel, key) { - def sourceIDs = new IDChecker() - - def sourceCheck = sourceChannel - | map { tup -> - sourceIDs.observe(tup[0]) - tup - } - def targetCheck = targetChannel - | map { tup -> - def id = tup[0] - - if (!sourceIDs.contains(id)) { - error ( - "Error in module '${key}' when merging output with original state.\n" + - " Reason: output with id '${id}' could not be joined with source channel.\n" + - " If the IDs in the output channel differ from the input channel,\n" + - " please set `tup[1]._meta.join_id to the original ID.\n" + - " Original IDs in input channel: ['${sourceIDs.getItems().join("', '")}'].\n" + - " Unexpected ID in the output channel: '${id}'.\n" + - " Example input event: [\"id\", [input: file(...)]],\n" + - " Example output event: [\"newid\", [output: file(...), _meta: [join_id: \"id\"]]]" - ) - } - // TODO: add link to our documentation on how to fix this - - tup - } - - sourceCheck.cross(targetChannel) - | map{ left, right -> - right + left.drop(1) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/_processArgument.nf' -def _processArgument(arg) { - arg.multiple = arg.multiple != null ? arg.multiple : false - arg.required = arg.required != null ? arg.required : false - arg.direction = arg.direction != null ? arg.direction : "input" - arg.multiple_sep = arg.multiple_sep != null ? arg.multiple_sep : ":" - arg.plainName = arg.name.replaceAll("^-*", "") - - if (arg.type == "file") { - arg.must_exist = arg.must_exist != null ? arg.must_exist : true - arg.create_parent = arg.create_parent != null ? arg.create_parent : true - } - - // add default values to output files which haven't already got a default - if (arg.type == "file" && arg.direction == "output" && arg.default == null) { - def mult = arg.multiple ? "_*" : "" - def extSearch = "" - if (arg.default != null) { - extSearch = arg.default - } else if (arg.example != null) { - extSearch = arg.example - } - if (extSearch instanceof List) { - extSearch = extSearch[0] - } - def extSearchResult = extSearch.find("\\.[^\\.]+\$") - def ext = extSearchResult != null ? extSearchResult : "" - arg.default = "\$id.\$key.${arg.plainName}${mult}${ext}" - if (arg.multiple) { - arg.default = [arg.default] - } - } - - if (!arg.multiple) { - if (arg.default != null && arg.default instanceof List) { - arg.default = arg.default[0] - } - if (arg.example != null && arg.example instanceof List) { - arg.example = arg.example[0] - } - } - - if (arg.type == "boolean_true") { - arg.default = false - } - if (arg.type == "boolean_false") { - arg.default = true - } - - arg -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/addGlobalParams.nf' -def addGlobalArguments(config) { - def localConfig = [ - "functionality" : [ - "argument_groups": [ - [ - "name": "Nextflow input-output arguments", - "description": "Input/output parameters for Nextflow itself. Please note that both publishDir and publish_dir are supported but at least one has to be configured.", - "arguments" : [ - [ - 'name': '--publish_dir', - 'required': true, - 'type': 'string', - 'description': 'Path to an output directory.', - 'example': 'output/', - 'multiple': false - ], - [ - 'name': '--param_list', - 'required': false, - 'type': 'string', - 'description': '''Allows inputting multiple parameter sets to initialise a Nextflow channel. A `param_list` can either be a list of maps, a csv file, a json file, a yaml file, or simply a yaml blob. - | - |* A list of maps (as-is) where the keys of each map corresponds to the arguments of the pipeline. Example: in a `nextflow.config` file: `param_list: [ ['id': 'foo', 'input': 'foo.txt'], ['id': 'bar', 'input': 'bar.txt'] ]`. - |* A csv file should have column names which correspond to the different arguments of this pipeline. Example: `--param_list data.csv` with columns `id,input`. - |* A json or a yaml file should be a list of maps, each of which has keys corresponding to the arguments of the pipeline. Example: `--param_list data.json` with contents `[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]`. - |* A yaml blob can also be passed directly as a string. Example: `--param_list "[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]"`. - | - |When passing a csv, json or yaml file, relative path names are relativized to the location of the parameter file. No relativation is performed when `param_list` is a list of maps (as-is) or a yaml blob.'''.stripMargin(), - 'example': 'my_params.yaml', - 'multiple': false, - 'hidden': true - ] - // TODO: allow multiple: true in param_list? - // TODO: allow to specify a --param_list_regex to filter the param_list? - // TODO: allow to specify a --param_list_from_state to remap entries in the param_list? - ] - ] - ] - ] - ] - - return processConfig(_mergeMap(config, localConfig)) -} - -def _mergeMap(Map lhs, Map rhs) { - return rhs.inject(lhs.clone()) { map, entry -> - if (map[entry.key] instanceof Map && entry.value instanceof Map) { - map[entry.key] = _mergeMap(map[entry.key], entry.value) - } else if (map[entry.key] instanceof Collection && entry.value instanceof Collection) { - map[entry.key] += entry.value - } else { - map[entry.key] = entry.value - } - return map - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/generateHelp.nf' -def _generateArgumentHelp(param) { - // alternatives are not supported - // def names = param.alternatives ::: List(param.name) - - def unnamedProps = [ - ["required parameter", param.required], - ["multiple values allowed", param.multiple], - ["output", param.direction.toLowerCase() == "output"], - ["file must exist", param.type == "file" && param.must_exist] - ].findAll{it[1]}.collect{it[0]} - - def dflt = null - if (param.default != null) { - if (param.default instanceof List) { - dflt = param.default.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - dflt = param.default.toString() - } - } - def example = null - if (param.example != null) { - if (param.example instanceof List) { - example = param.example.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - example = param.example.toString() - } - } - def min = param.min?.toString() - def max = param.max?.toString() - - def escapeChoice = { choice -> - def s1 = choice.replaceAll("\\n", "\\\\n") - def s2 = s1.replaceAll("\"", """\\\"""") - s2.contains(",") || s2 != choice ? "\"" + s2 + "\"" : s2 - } - def choices = param.choices == null ? - null : - "[ " + param.choices.collect{escapeChoice(it.toString())}.join(", ") + " ]" - - def namedPropsStr = [ - ["type", ([param.type] + unnamedProps).join(", ")], - ["default", dflt], - ["example", example], - ["choices", choices], - ["min", min], - ["max", max] - ] - .findAll{it[1]} - .collect{"\n " + it[0] + ": " + it[1].replaceAll("\n", "\\n")} - .join("") - - def descStr = param.description == null ? - "" : - _paragraphWrap("\n" + param.description.trim(), 80 - 8).join("\n ") - - "\n --" + param.plainName + - namedPropsStr + - descStr -} - -// Based on Helper.generateHelp() in Helper.scala -def _generateHelp(config) { - def fun = config.functionality - - // PART 1: NAME AND VERSION - def nameStr = fun.name + - (fun.version == null ? "" : " " + fun.version) - - // PART 2: DESCRIPTION - def descrStr = fun.description == null ? - "" : - "\n\n" + _paragraphWrap(fun.description.trim(), 80).join("\n") - - // PART 3: Usage - def usageStr = fun.usage == null ? - "" : - "\n\nUsage:\n" + fun.usage.trim() - - // PART 4: Options - def argGroupStrs = fun.allArgumentGroups.collect{argGroup -> - def name = argGroup.name - def descriptionStr = argGroup.description == null ? - "" : - "\n " + _paragraphWrap(argGroup.description.trim(), 80-4).join("\n ") + "\n" - def arguments = argGroup.arguments.collect{arg -> - arg instanceof String ? fun.allArguments.find{it.plainName == arg} : arg - }.findAll{it != null} - def argumentStrs = arguments.collect{param -> _generateArgumentHelp(param)} - - "\n\n$name:" + - descriptionStr + - argumentStrs.join("\n") - } - - // FINAL: combine - def out = nameStr + - descrStr + - usageStr + - argGroupStrs.join("") - - return out -} - -// based on Format._paragraphWrap -def _paragraphWrap(str, maxLength) { - def outLines = [] - str.split("\n").each{par -> - def words = par.split("\\s").toList() - - def word = null - def line = words.pop() - while(!words.isEmpty()) { - word = words.pop() - if (line.length() + word.length() + 1 <= maxLength) { - line = line + " " + word - } else { - outLines.add(line) - line = word - } - } - if (words.isEmpty()) { - outLines.add(line) - } - } - return outLines -} - -def helpMessage(config) { - if (params.containsKey("help") && params.help) { - def mergedConfig = addGlobalArguments(config) - def helpStr = _generateHelp(mergedConfig) - println(helpStr) - exit 0 - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/processConfig.nf' -def processConfig(config) { - // set defaults for arguments - config.functionality.arguments = - (config.functionality.arguments ?: []).collect{_processArgument(it)} - - // set defaults for argument_group arguments - config.functionality.argument_groups = - (config.functionality.argument_groups ?: []).collect{grp -> - grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} - grp - } - - // create combined arguments list - config.functionality.allArguments = - config.functionality.arguments + - config.functionality.argument_groups.collectMany{it.arguments} - - // add missing argument groups (based on Functionality::allArgumentGroups()) - def argGroups = config.functionality.argument_groups - if (argGroups.any{it.name.toLowerCase() == "arguments"}) { - argGroups = argGroups.collect{ grp -> - if (grp.name.toLowerCase() == "arguments") { - grp = grp + [ - arguments: grp.arguments + config.functionality.arguments - ] - } - grp - } - } else { - argGroups = argGroups + [ - name: "Arguments", - arguments: config.functionality.arguments - ] - } - config.functionality.allArgumentGroups = argGroups - - config -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/readConfig.nf' - -def readConfig(file) { - def config = readYaml(file ?: moduleDir.resolve("config.vsh.yaml")) - processConfig(config) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_resolveSiblingIfNotAbsolute.nf' -/** - * Resolve a path relative to the current file. - * - * @param str The path to resolve, as a String. - * @param parentPath The path to resolve relative to, as a Path. - * - * @return The path that may have been resovled, as a Path. - */ -def _resolveSiblingIfNotAbsolute(str, parentPath) { - if (str !instanceof String) { - return str - } - if (!_stringIsAbsolutePath(str)) { - return parentPath.resolveSibling(str) - } else { - return file(str, hidden: true) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_stringIsAbsolutePath.nf' -/** - * Check whether a path as a string is absolute. - * - * In the past, we tried using `file(., relative: true).isAbsolute()`, - * but the 'relative' option was added in 22.10.0. - * - * @param path The path to check, as a String. - * - * @return Whether the path is absolute, as a boolean. - */ -def _stringIsAbsolutePath(path) { - _resolve_URL_PROTOCOL = ~/^([a-zA-Z][a-zA-Z0-9]*:)?\\/.+/ - - assert path instanceof String - return _resolve_URL_PROTOCOL.matcher(path).matches() -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/collectTraces.nf' -class CustomTraceObserver implements nextflow.trace.TraceObserver { - List traces - - CustomTraceObserver(List traces) { - this.traces = traces - } - - @Override - void onProcessComplete(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } - - @Override - void onProcessCached(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } -} - -def collectTraces() { - def traces = Collections.synchronizedList([]) - - // add custom trace observer which stores traces in the traces object - session.observers.add(new CustomTraceObserver(traces)) - - traces -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/deepClone.nf' -/** - * Performs a deep clone of the given object. - * @param x an object - */ -def deepClone(x) { - iterateMap(x, {it instanceof Cloneable ? it.clone() : it}) -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getPublishDir.nf' -def getPublishDir() { - return params.containsKey("publish_dir") ? params.publish_dir : - params.containsKey("publishDir") ? params.publishDir : - null -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getRootDir.nf' - -// Recurse upwards until we find a '.build.yaml' file -def _findBuildYamlFile(pathPossiblySymlink) { - def path = pathPossiblySymlink.toRealPath() - def child = path.resolve(".build.yaml") - if (java.nio.file.Files.isDirectory(path) && java.nio.file.Files.exists(child)) { - return child - } else { - def parent = path.getParent() - if (parent == null) { - return null - } else { - return _findBuildYamlFile(parent) - } - } -} - -// get the root of the target folder -def getRootDir() { - def dir = _findBuildYamlFile(meta.resources_dir) - assert dir != null: "Could not find .build.yaml in the folder structure" - dir.getParent() -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/iterateMap.nf' -/** - * Recursively apply a function over the leaves of an object. - * @param obj The object to iterate over. - * @param fun The function to apply to each value. - * @return The object with the function applied to each value. - */ -def iterateMap(obj, fun) { - if (obj instanceof List && obj !instanceof String) { - return obj.collect{item -> - iterateMap(item, fun) - } - } else if (obj instanceof Map) { - return obj.collectEntries{key, item -> - [key.toString(), iterateMap(item, fun)] - } - } else { - return fun(obj) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/niceView.nf' -/** - * A view for printing the event of each channel as a YAML blob. - * This is useful for debugging. - */ -def niceView() { - workflow niceViewWf { - take: input - main: - output = input - | view{toYamlBlob(it)} - emit: output - } - return niceViewWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readCsv.nf' - -def readCsv(file_path) { - def output = [] - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - - // todo: allow escaped quotes in string - // todo: allow single quotes? - def splitRegex = java.util.regex.Pattern.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''') - def removeQuote = java.util.regex.Pattern.compile('''"(.*)"''') - - def br = java.nio.file.Files.newBufferedReader(inputFile) - - def row = -1 - def header = null - while (br.ready() && header == null) { - def line = br.readLine() - row++ - if (!line.startsWith("#")) { - header = splitRegex.split(line, -1).collect{field -> - m = removeQuote.matcher(field) - m.find() ? m.replaceFirst('$1') : field - } - } - } - assert header != null: "CSV file should contain a header" - - while (br.ready()) { - def line = br.readLine() - row++ - if (line == null) { - br.close() - break - } - - if (!line.startsWith("#")) { - def predata = splitRegex.split(line, -1) - def data = predata.collect{field -> - if (field == "") { - return null - } - m = removeQuote.matcher(field) - if (m.find()) { - return m.replaceFirst('$1') - } else { - return field - } - } - assert header.size() == data.size(): "Row $row should contain the same number as fields as the header" - - def dataMap = [header, data].transpose().collectEntries().findAll{it.value != null} - output.add(dataMap) - } - } - - output -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJson.nf' -def readJson(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parse(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJsonBlob.nf' -def readJsonBlob(str) { - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parseText(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readTaggedYaml.nf' -// Custom constructor to modify how certain objects are parsed from YAML -class CustomConstructor extends org.yaml.snakeyaml.constructor.Constructor { - Path root - - class ConstructPath extends org.yaml.snakeyaml.constructor.AbstractConstruct { - public Object construct(org.yaml.snakeyaml.nodes.Node node) { - String filename = (String) constructScalar(node); - if (root != null) { - return root.resolve(filename); - } - return java.nio.file.Paths.get(filename); - } - } - - CustomConstructor(org.yaml.snakeyaml.LoaderOptions options, Path root) { - super(options) - this.root = root - // Handling !file tag and parse it back to a File type - this.yamlConstructors.put(new org.yaml.snakeyaml.nodes.Tag("!file"), new ConstructPath()) - } -} - -def readTaggedYaml(Path path) { - def options = new org.yaml.snakeyaml.LoaderOptions() - def constructor = new CustomConstructor(options, path.getParent()) - def yaml = new org.yaml.snakeyaml.Yaml(constructor) - return yaml.load(path.text) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYaml.nf' -def readYaml(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYamlBlob.nf' -def readYamlBlob(str) { - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toJsonBlob.nf' -String toJsonBlob(data) { - return groovy.json.JsonOutput.toJson(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toTaggedYamlBlob.nf' -// Custom representer to modify how certain objects are represented in YAML -class CustomRepresenter extends org.yaml.snakeyaml.representer.Representer { - Path relativizer - - class RepresentPath implements org.yaml.snakeyaml.representer.Represent { - public String getFileName(Object obj) { - if (obj instanceof File) { - obj = ((File) obj).toPath(); - } - if (obj !instanceof Path) { - throw new IllegalArgumentException("Object: " + obj + " is not a Path or File"); - } - def path = (Path) obj; - - if (relativizer != null) { - return relativizer.relativize(path).toString() - } else { - return path.toString() - } - } - - public org.yaml.snakeyaml.nodes.Node representData(Object data) { - String filename = getFileName(data); - def tag = new org.yaml.snakeyaml.nodes.Tag("!file"); - return representScalar(tag, filename); - } - } - CustomRepresenter(org.yaml.snakeyaml.DumperOptions options, Path relativizer) { - super(options) - this.relativizer = relativizer - this.representers.put(sun.nio.fs.UnixPath, new RepresentPath()) - this.representers.put(Path, new RepresentPath()) - this.representers.put(File, new RepresentPath()) - } -} - -String toTaggedYamlBlob(data) { - return toRelativeTaggedYamlBlob(data, null) -} -String toRelativeTaggedYamlBlob(data, Path relativizer) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - def representer = new CustomRepresenter(options, relativizer) - def yaml = new org.yaml.snakeyaml.Yaml(representer, options) - return yaml.dump(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toYamlBlob.nf' -String toYamlBlob(data) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - options.setPrettyFlow(true) - def yaml = new org.yaml.snakeyaml.Yaml(options) - def cleanData = iterateMap(data, { it instanceof Path ? it.toString() : it }) - return yaml.dump(cleanData) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeJson.nf' -void writeJson(data, file) { - assert data: "writeJson: data should not be null" - assert file: "writeJson: file should not be null" - file.write(toJsonBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeYaml.nf' -void writeYaml(data, file) { - assert data: "writeYaml: data should not be null" - assert file: "writeYaml: file should not be null" - file.write(toYamlBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/findStates.nf' -def findStates(Map params, Map config) { - // TODO: do a deep clone of config - def auto_config = deepClone(config) - def auto_params = deepClone(params) - - auto_config = auto_config.clone() - // override arguments - auto_config.functionality.argument_groups = [] - auto_config.functionality.arguments = [ - [ - type: "string", - name: "--id", - description: "A dummy identifier", - required: false - ], - [ - type: "file", - name: "--input_states", - example: "/path/to/input/directory/**/state.yaml", - description: "Path to input directory containing the datasets to be integrated.", - required: true, - multiple: true, - multiple_sep: ";" - ], - [ - type: "string", - name: "--filter", - example: "foo/.*/state.yaml", - description: "Regex to filter state files by path.", - required: false - ], - // to do: make this a yaml blob? - [ - type: "string", - name: "--rename_keys", - example: ["newKey1:oldKey1", "newKey2:oldKey2"], - description: "Rename keys in the detected input files. This is useful if the input files do not match the set of input arguments of the workflow.", - required: false, - multiple: true, - multiple_sep: "," - ], - [ - type: "string", - name: "--settings", - example: '{"output_dataset": "dataset.h5ad", "k": 10}', - description: "Global arguments as a JSON glob to be passed to all components.", - required: false - ] - ] - if (!(auto_params.containsKey("id"))) { - auto_params["id"] = "auto" - } - - // run auto config through processConfig once more - auto_config = processConfig(auto_config) - - workflow findStatesWf { - helpMessage(auto_config) - - output_ch = - channelFromParams(auto_params, auto_config) - | flatMap { autoId, args -> - - def globalSettings = args.settings ? readYamlBlob(args.settings) : [:] - - // look for state files in input dir - def stateFiles = args.input_states - - // filter state files by regex - if (args.filter) { - stateFiles = stateFiles.findAll{ stateFile -> - def stateFileStr = stateFile.toString() - def matcher = stateFileStr =~ args.filter - matcher.matches()} - } - - // read in states - def states = stateFiles.collect { stateFile -> - def state_ = readTaggedYaml(stateFile) - [state_.id, state_] - } - - // construct renameMap - if (args.rename_keys) { - def renameMap = args.rename_keys.collectEntries{renameString -> - def split = renameString.split(":") - assert split.size() == 2: "Argument 'rename_keys' should be of the form 'newKey:oldKey,newKey:oldKey'" - split - } - - // rename keys in state, only let states through which have all keys - // also add global settings - states = states.collectMany{id, state -> - def newState = [:] - - for (key in renameMap.keySet()) { - def origKey = renameMap[key] - if (!(state.containsKey(origKey))) { - return [] - } - newState[key] = state[origKey] - } - - [[id, globalSettings + newState]] - } - } - - states - } - emit: - output_ch - } - - return findStatesWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/joinStates.nf' -def joinStates(Closure apply_) { - workflow joinStatesWf { - take: input_ch - main: - output_ch = input_ch - | toSortedList - | filter{ it.size() > 0 } - | map{ tups -> - def ids = tups.collect{it[0]} - def states = tups.collect{it[1]} - apply_(ids, states) - } - - emit: output_ch - } - return joinStatesWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/publishStates.nf' -def collectFiles(obj) { - if (obj instanceof java.io.File || obj instanceof Path) { - return [obj] - } else if (obj instanceof List && obj !instanceof String) { - return obj.collectMany{item -> - collectFiles(item) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectFiles(item) - } - } else { - return [] - } -} - -/** - * Recurse through a state and collect all input files and their target output filenames. - * @param obj The state to recurse through. - * @param prefix The prefix to prepend to the output filenames. - */ -def collectInputOutputPaths(obj, prefix) { - if (obj instanceof File || obj instanceof Path) { - def path = obj instanceof Path ? obj : obj.toPath() - def ext = path.getFileName().toString().find("\\.[^\\.]+\$") ?: "" - def newFilename = prefix + ext - return [[obj, newFilename]] - } else if (obj instanceof List && obj !instanceof String) { - return obj.withIndex().collectMany{item, ix -> - collectInputOutputPaths(item, prefix + "_" + ix) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectInputOutputPaths(item, prefix + "." + key) - } - } else { - return [] - } -} - -def publishStates(Map args) { - def key_ = args.get("key") - def yamlTemplate_ = args.get("output_state", args.get("outputState", '$id.$key.state.yaml')) - - assert key_ != null : "publishStates: key must be specified" - - workflow publishStatesWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] - - // the input files and the target output filenames - def inputOutputFiles_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() - def inputFiles_ = inputOutputFiles_[0] - def outputFiles_ = inputOutputFiles_[1] - - def yamlFilename = yamlTemplate_ - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - - // TODO: do the pathnames in state_ match up with the outputFiles_? - - // convert state to yaml blob - def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesWf -} -process publishStatesProc { - // todo: check publishpath? - publishDir path: "${getPublishDir()}/", mode: "copy" - tag "$id" - input: - tuple val(id), val(yamlBlob), val(yamlFile), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) - output: - tuple val(id), path{[yamlFile] + outputFiles} - script: - def copyCommands = [ - inputFiles instanceof List ? inputFiles : [inputFiles], - outputFiles instanceof List ? outputFiles : [outputFiles] - ] - .transpose() - .collectMany{infile, outfile -> - if (infile.toString() != outfile.toString()) { - [ - "[ -d \"\$(dirname '${outfile.toString()}')\" ] || mkdir -p \"\$(dirname '${outfile.toString()}')\"", - "cp -r '${infile.toString()}' '${outfile.toString()}'" - ] - } else { - // no need to copy if infile is the same as outfile - [] - } - } - """ - mkdir -p "\$(dirname '${yamlFile}')" - echo "Storing state as yaml" - echo '${yamlBlob}' > '${yamlFile}' - echo "Copying output files to destination folder" - ${copyCommands.join("\n ")} - """ -} - - -// this assumes that the state contains no other values other than those specified in the config -def publishStatesByConfig(Map args) { - def config = args.get("config") - assert config != null : "publishStatesByConfig: config must be specified" - - def key_ = args.get("key", config.functionality.name) - assert key_ != null : "publishStatesByConfig: key must be specified" - - workflow publishStatesSimpleWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] // e.g. [output: new File("myoutput.h5ad"), k: 10] - def origState_ = tup[2] // e.g. [output: '$id.$key.foo.h5ad'] - - // TODO: allow overriding the state.yaml template - // TODO TODO: if auto.publish == "state", add output_state as an argument - def yamlTemplate = params.containsKey("output_state") ? params.output_state : '$id.$key.state.yaml' - def yamlFilename = yamlTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() - - // the processed state is a list of [key, value, srcPath, destPath] tuples, where - // - key, value is part of the state to be saved to disk - // - srcPath and destPath are lists of files to be copied from src to dest - def processedState = - config.functionality.allArguments - .findAll { it.direction == "output" } - .collectMany { par -> - def plainName_ = par.plainName - // if the state does not contain the key, it's an - // optional argument for which the component did - // not generate any output - if (!state_.containsKey(plainName_)) { - return [] - } - def value = state_[plainName_] - // if the parameter is not a file, it should be stored - // in the state as-is, but is not something that needs - // to be copied from the source path to the dest path - if (par.type != "file") { - return [[key: plainName_, value: value, srcPath: [], destPath: []]] - } - // if the orig state does not contain this filename, - // it's an optional argument for which the user specified - // that it should not be returned as a state - if (!origState_.containsKey(plainName_)) { - return [] - } - def filenameTemplate = origState_[plainName_] - // if the pararameter is multiple: true, fetch the template - if (par.multiple && filenameTemplate instanceof List) { - filenameTemplate = filenameTemplate[0] - } - // instantiate the template - def filename = filenameTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - if (par.multiple) { - // if the parameter is multiple: true, the filename - // should contain a wildcard '*' that is replaced with - // the index of the file - assert filename.contains("*") : "Module '${key_}' id '${id_}': Multiple output files specified, but no wildcard '*' in the filename: ${filename}" - def outputPerFile = value.withIndex().collect{ val, ix -> - def value_ = java.nio.file.Paths.get(filename.replace("*", ix.toString())) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = val instanceof File ? val.toPath() : val - [value: value_, srcPath: srcPath, destPath: destPath] - } - def transposedOutputs = ["value", "srcPath", "destPath"].collectEntries{ key -> - [key, outputPerFile.collect{dic -> dic[key]}] - } - return [[key: plainName_] + transposedOutputs] - } else { - def value_ = java.nio.file.Paths.get(filename) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = value instanceof File ? value.toPath() : value - return [[key: plainName_, value: value_, srcPath: [srcPath], destPath: [filename]]] - } - } - - def updatedState_ = processedState.collectEntries{[it.key, it.value]} - def inputFiles_ = processedState.collectMany{it.srcPath} - def outputFiles_ = processedState.collectMany{it.destPath} - - // convert state to yaml blob - def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesSimpleWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/setState.nf' -def setState(fun) { - assert fun instanceof Closure || fun instanceof Map || fun instanceof List : - "Error in setState: Expected process argument to be a Closure, a Map, or a List. Found: class ${fun.getClass()}" - - // if fun is a List, convert to map - if (fun instanceof List) { - // check whether fun is a list[string] - assert fun.every{it instanceof CharSequence} : "Error in setState: argument is a List, but not all elements are Strings" - fun = fun.collectEntries{[it, it]} - } - - // if fun is a map, convert to closure - if (fun instanceof Map) { - // check whether fun is a map[string, string] - assert fun.values().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all values are Strings" - assert fun.keySet().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all keys are Strings" - def funMap = fun.clone() - // turn the map into a closure to be used later on - fun = { id_, state_ -> - assert state_ instanceof Map : "Error in setState: the state is not a Map" - funMap.collectMany{newkey, origkey -> - if (state_.containsKey(origkey)) { - [[newkey, state_[origkey]]] - } else { - [] - } - }.collectEntries() - } - } - - map { tup -> - def id = tup[0] - def state = tup[1] - def unfilteredState = fun(id, state) - def newState = unfilteredState.findAll{key, val -> val != null} - [id, newState] + tup.drop(2) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processAuto.nf' -// TODO: unit test processAuto -def processAuto(Map auto) { - // remove null values - auto = auto.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = ["simplifyInput", "simplifyOutput", "transcript", "publish"] - def unexpectedKeys = auto.keySet() - expectedKeys - assert unexpectedKeys.isEmpty(), "unexpected keys in auto: '${unexpectedKeys.join("', '")}'" - - // check auto.simplifyInput - assert auto.simplifyInput instanceof Boolean, "auto.simplifyInput must be a boolean" - - // check auto.simplifyOutput - assert auto.simplifyOutput instanceof Boolean, "auto.simplifyOutput must be a boolean" - - // check auto.transcript - assert auto.transcript instanceof Boolean, "auto.transcript must be a boolean" - - // check auto.publish - assert auto.publish instanceof Boolean || auto.publish == "state", "auto.publish must be a boolean or 'state'" - - return auto.subMap(expectedKeys) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processDirectives.nf' -def assertMapKeys(map, expectedKeys, requiredKeys, mapName) { - assert map instanceof Map : "Expected argument '$mapName' to be a Map. Found: class ${map.getClass()}" - map.forEach { key, val -> - assert key in expectedKeys : "Unexpected key '$key' in ${mapName ? mapName + " " : ""}map" - } - requiredKeys.forEach { requiredKey -> - assert map.containsKey(requiredKey) : "Missing required key '$key' in ${mapName ? mapName + " " : ""}map" - } -} - -// TODO: unit test processDirectives -def processDirectives(Map drctv) { - // remove null values - drctv = drctv.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = [ - "accelerator", "afterScript", "beforeScript", "cache", "conda", "container", "containerOptions", "cpus", "disk", "echo", "errorStrategy", "executor", "machineType", "maxErrors", "maxForks", "maxRetries", "memory", "module", "penv", "pod", "publishDir", "queue", "label", "scratch", "storeDir", "stageInMode", "stageOutMode", "tag", "time" - ] - def unexpectedKeys = drctv.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Unexpected keys in process directive: '${unexpectedKeys.join("', '")}'" - - /* DIRECTIVE accelerator - accepted examples: - - [ limit: 4, type: "nvidia-tesla-k80" ] - */ - if (drctv.containsKey("accelerator")) { - assertMapKeys(drctv["accelerator"], ["type", "limit", "request", "runtime"], [], "accelerator") - } - - /* DIRECTIVE afterScript - accepted examples: - - "source /cluster/bin/cleanup" - */ - if (drctv.containsKey("afterScript")) { - assert drctv["afterScript"] instanceof CharSequence - } - - /* DIRECTIVE beforeScript - accepted examples: - - "source /cluster/bin/setup" - */ - if (drctv.containsKey("beforeScript")) { - assert drctv["beforeScript"] instanceof CharSequence - } - - /* DIRECTIVE cache - accepted examples: - - true - - false - - "deep" - - "lenient" - */ - if (drctv.containsKey("cache")) { - assert drctv["cache"] instanceof CharSequence || drctv["cache"] instanceof Boolean - if (drctv["cache"] instanceof CharSequence) { - assert drctv["cache"] in ["deep", "lenient"] : "Unexpected value for cache" - } - } - - /* DIRECTIVE conda - accepted examples: - - "bwa=0.7.15" - - "bwa=0.7.15 fastqc=0.11.5" - - ["bwa=0.7.15", "fastqc=0.11.5"] - */ - if (drctv.containsKey("conda")) { - if (drctv["conda"] instanceof List) { - drctv["conda"] = drctv["conda"].join(" ") - } - assert drctv["conda"] instanceof CharSequence - } - - /* DIRECTIVE container - accepted examples: - - "foo/bar:tag" - - [ registry: "reg", image: "im", tag: "ta" ] - is transformed to "reg/im:ta" - - [ image: "im" ] - is transformed to "im:latest" - */ - if (drctv.containsKey("container")) { - assert drctv["container"] instanceof Map || drctv["container"] instanceof CharSequence - if (drctv["container"] instanceof Map) { - def m = drctv["container"] - assertMapKeys(m, [ "registry", "image", "tag" ], ["image"], "container") - def part1 = - System.getenv('OVERRIDE_CONTAINER_REGISTRY') ? System.getenv('OVERRIDE_CONTAINER_REGISTRY') + "/" : - params.containsKey("override_container_registry") ? params["override_container_registry"] + "/" : // todo: remove? - m.registry ? m.registry + "/" : - "" - def part2 = m.image - def part3 = m.tag ? ":" + m.tag : ":latest" - drctv["container"] = part1 + part2 + part3 - } - } - - /* DIRECTIVE containerOptions - accepted examples: - - "--foo bar" - - ["--foo bar", "-f b"] - */ - if (drctv.containsKey("containerOptions")) { - if (drctv["containerOptions"] instanceof List) { - drctv["containerOptions"] = drctv["containerOptions"].join(" ") - } - assert drctv["containerOptions"] instanceof CharSequence - } - - /* DIRECTIVE cpus - accepted examples: - - 1 - - 10 - */ - if (drctv.containsKey("cpus")) { - assert drctv["cpus"] instanceof Integer - } - - /* DIRECTIVE disk - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("disk")) { - assert drctv["disk"] instanceof CharSequence - // assert drctv["disk"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE echo - accepted examples: - - true - - false - */ - if (drctv.containsKey("echo")) { - assert drctv["echo"] instanceof Boolean - } - - /* DIRECTIVE errorStrategy - accepted examples: - - "terminate" - - "finish" - */ - if (drctv.containsKey("errorStrategy")) { - assert drctv["errorStrategy"] instanceof CharSequence - assert drctv["errorStrategy"] in ["terminate", "finish", "ignore", "retry"] : "Unexpected value for errorStrategy" - } - - /* DIRECTIVE executor - accepted examples: - - "local" - - "sge" - */ - if (drctv.containsKey("executor")) { - assert drctv["executor"] instanceof CharSequence - assert drctv["executor"] in ["local", "sge", "uge", "lsf", "slurm", "pbs", "pbspro", "moab", "condor", "nqsii", "ignite", "k8s", "awsbatch", "google-pipelines"] : "Unexpected value for executor" - } - - /* DIRECTIVE machineType - accepted examples: - - "n1-highmem-8" - */ - if (drctv.containsKey("machineType")) { - assert drctv["machineType"] instanceof CharSequence - } - - /* DIRECTIVE maxErrors - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxErrors")) { - assert drctv["maxErrors"] instanceof Integer - } - - /* DIRECTIVE maxForks - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxForks")) { - assert drctv["maxForks"] instanceof Integer - } - - /* DIRECTIVE maxRetries - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxRetries")) { - assert drctv["maxRetries"] instanceof Integer - } - - /* DIRECTIVE memory - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("memory")) { - assert drctv["memory"] instanceof CharSequence - // assert drctv["memory"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE module - accepted examples: - - "ncbi-blast/2.2.27" - - "ncbi-blast/2.2.27:t_coffee/10.0" - - ["ncbi-blast/2.2.27", "t_coffee/10.0"] - */ - if (drctv.containsKey("module")) { - if (drctv["module"] instanceof List) { - drctv["module"] = drctv["module"].join(":") - } - assert drctv["module"] instanceof CharSequence - } - - /* DIRECTIVE penv - accepted examples: - - "smp" - */ - if (drctv.containsKey("penv")) { - assert drctv["penv"] instanceof CharSequence - } - - /* DIRECTIVE pod - accepted examples: - - [ label: "key", value: "val" ] - - [ annotation: "key", value: "val" ] - - [ env: "key", value: "val" ] - - [ [label: "l", value: "v"], [env: "e", value: "v"]] - */ - if (drctv.containsKey("pod")) { - if (drctv["pod"] instanceof Map) { - drctv["pod"] = [ drctv["pod"] ] - } - assert drctv["pod"] instanceof List - drctv["pod"].forEach { pod -> - assert pod instanceof Map - // TODO: should more checks be added? - // See https://www.nextflow.io/docs/latest/process.html?highlight=directives#pod - // e.g. does it contain 'label' and 'value', or 'annotation' and 'value', or ...? - } - } - - /* DIRECTIVE publishDir - accepted examples: - - [] - - [ [ path: "foo", enabled: true ], [ path: "bar", enabled: false ] ] - - "/path/to/dir" - is transformed to [[ path: "/path/to/dir" ]] - - [ path: "/path/to/dir", mode: "cache" ] - is transformed to [[ path: "/path/to/dir", mode: "cache" ]] - */ - // TODO: should we also look at params["publishDir"]? - if (drctv.containsKey("publishDir")) { - def pblsh = drctv["publishDir"] - - // check different options - assert pblsh instanceof List || pblsh instanceof Map || pblsh instanceof CharSequence - - // turn into list if not already so - // for some reason, 'if (!pblsh instanceof List) pblsh = [ pblsh ]' doesn't work. - pblsh = pblsh instanceof List ? pblsh : [ pblsh ] - - // check elements of publishDir - pblsh = pblsh.collect{ elem -> - // turn into map if not already so - elem = elem instanceof CharSequence ? [ path: elem ] : elem - - // check types and keys - assert elem instanceof Map : "Expected publish argument '$elem' to be a String or a Map. Found: class ${elem.getClass()}" - assertMapKeys(elem, [ "path", "mode", "overwrite", "pattern", "saveAs", "enabled" ], ["path"], "publishDir") - - // check elements in map - assert elem.containsKey("path") - assert elem["path"] instanceof CharSequence - if (elem.containsKey("mode")) { - assert elem["mode"] instanceof CharSequence - assert elem["mode"] in [ "symlink", "rellink", "link", "copy", "copyNoFollow", "move" ] - } - if (elem.containsKey("overwrite")) { - assert elem["overwrite"] instanceof Boolean - } - if (elem.containsKey("pattern")) { - assert elem["pattern"] instanceof CharSequence - } - if (elem.containsKey("saveAs")) { - assert elem["saveAs"] instanceof CharSequence //: "saveAs as a Closure is currently not supported. Surround your closure with single quotes to get the desired effect. Example: '\{ foo \}'" - } - if (elem.containsKey("enabled")) { - assert elem["enabled"] instanceof Boolean - } - - // return final result - elem - } - // store final directive - drctv["publishDir"] = pblsh - } - - /* DIRECTIVE queue - accepted examples: - - "long" - - "short,long" - - ["short", "long"] - */ - if (drctv.containsKey("queue")) { - if (drctv["queue"] instanceof List) { - drctv["queue"] = drctv["queue"].join(",") - } - assert drctv["queue"] instanceof CharSequence - } - - /* DIRECTIVE label - accepted examples: - - "big_mem" - - "big_cpu" - - ["big_mem", "big_cpu"] - */ - if (drctv.containsKey("label")) { - if (drctv["label"] instanceof CharSequence) { - drctv["label"] = [ drctv["label"] ] - } - assert drctv["label"] instanceof List - drctv["label"].forEach { label -> - assert label instanceof CharSequence - // assert label.matches("[a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?") - // ^ does not allow closures - } - } - - /* DIRECTIVE scratch - accepted examples: - - true - - "/path/to/scratch" - - '$MY_PATH_TO_SCRATCH' - - "ram-disk" - */ - if (drctv.containsKey("scratch")) { - assert drctv["scratch"] == true || drctv["scratch"] instanceof CharSequence - } - - /* DIRECTIVE storeDir - accepted examples: - - "/path/to/storeDir" - */ - if (drctv.containsKey("storeDir")) { - assert drctv["storeDir"] instanceof CharSequence - } - - /* DIRECTIVE stageInMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageInMode")) { - assert drctv["stageInMode"] instanceof CharSequence - assert drctv["stageInMode"] in ["copy", "link", "symlink", "rellink"] - } - - /* DIRECTIVE stageOutMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageOutMode")) { - assert drctv["stageOutMode"] instanceof CharSequence - assert drctv["stageOutMode"] in ["copy", "move", "rsync"] - } - - /* DIRECTIVE tag - accepted examples: - - "foo" - - '$id' - */ - if (drctv.containsKey("tag")) { - assert drctv["tag"] instanceof CharSequence - } - - /* DIRECTIVE time - accepted examples: - - "1h" - - "2days" - - "1day 6hours 3minutes 30seconds" - */ - if (drctv.containsKey("time")) { - assert drctv["time"] instanceof CharSequence - // todo: validation regex? - } - - return drctv -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processWorkflowArgs.nf' -def processWorkflowArgs(Map args, Map defaultWfArgs, Map meta) { - // override defaults with args - def workflowArgs = defaultWfArgs + args - - // check whether 'key' exists - assert workflowArgs.containsKey("key") : "Error in module '${meta.config.functionality.name}': key is a required argument" - - // if 'key' is a closure, apply it to the original key - if (workflowArgs["key"] instanceof Closure) { - workflowArgs["key"] = workflowArgs["key"](meta.config.functionality.name) - } - def key = workflowArgs["key"] - assert key instanceof CharSequence : "Expected process argument 'key' to be a String. Found: class ${key.getClass()}" - assert key ==~ /^[a-zA-Z_]\w*$/ : "Error in module '$key': Expected process argument 'key' to consist of only letters, digits or underscores. Found: ${key}" - - // check for any unexpected keys - def expectedKeys = ["key", "directives", "auto", "map", "mapId", "mapData", "mapPassthrough", "filter", "runIf", "fromState", "toState", "args", "renameKeys", "debug"] - def unexpectedKeys = workflowArgs.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Error in module '$key': unexpected arguments to the '.run()' function: '${unexpectedKeys.join("', '")}'" - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("directives") : "Error in module '$key': directives is a required argument" - assert workflowArgs["directives"] instanceof Map : "Error in module '$key': Expected process argument 'directives' to be a Map. Found: class ${workflowArgs['directives'].getClass()}" - workflowArgs["directives"] = processDirectives(defaultWfArgs.directives + workflowArgs["directives"]) - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("auto") : "Error in module '$key': auto is a required argument" - assert workflowArgs["auto"] instanceof Map : "Error in module '$key': Expected process argument 'auto' to be a Map. Found: class ${workflowArgs['auto'].getClass()}" - workflowArgs["auto"] = processAuto(defaultWfArgs.auto + workflowArgs["auto"]) - - // auto define publish, if so desired - if (workflowArgs.auto.publish == true && (workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : [:]).isEmpty()) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.publish is true, params.publish_dir needs to be defined.\n" + - // " Example: params.publish_dir = \"./output/\"" - def publishDir = getPublishDir() - - if (publishDir != null) { - workflowArgs.directives.publishDir = [[ - path: publishDir, - saveAs: "{ it.startsWith('.') ? null : it }", // don't publish hidden files, by default - mode: "copy" - ]] - } - } - - // auto define transcript, if so desired - if (workflowArgs.auto.transcript == true) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("transcriptsDir") || params.containsKey("transcripts_dir") || params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.transcript is true, either params.transcripts_dir or params.publish_dir needs to be defined.\n" + - // " Example: params.transcripts_dir = \"./transcripts/\"" - def transcriptsDir = - params.containsKey("transcripts_dir") ? params.transcripts_dir : - params.containsKey("transcriptsDir") ? params.transcriptsDir : - params.containsKey("publish_dir") ? params.publish_dir + "/_transcripts" : - params.containsKey("publishDir") ? params.publishDir + "/_transcripts" : - null - if (transcriptsDir != null) { - def timestamp = nextflow.Nextflow.getSession().getWorkflowMetadata().start.format('yyyy-MM-dd_HH-mm-ss') - def transcriptsPublishDir = [ - path: "$transcriptsDir/$timestamp/\${task.process.replaceAll(':', '-')}/\${id}/", - saveAs: "{ it.startsWith('.') ? it.replaceAll('^.', '') : null }", - mode: "copy" - ] - def publishDirs = workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : null ? workflowArgs.directives.publishDir : [] - workflowArgs.directives.publishDir = publishDirs + transcriptsPublishDir - } - } - - // if this is a stubrun, remove certain directives? - if (workflow.stubRun) { - workflowArgs.directives.keySet().removeAll(["publishDir", "cpus", "memory", "label"]) - } - - for (nam in ["map", "mapId", "mapData", "mapPassthrough", "filter", "runIf"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam]) { - assert workflowArgs[nam] instanceof Closure : "Error in module '$key': Expected process argument '$nam' to be null or a Closure. Found: class ${workflowArgs[nam].getClass()}" - } - } - - // TODO: should functions like 'map', 'mapId', 'mapData', 'mapPassthrough' be deprecated as well? - for (nam in ["map", "mapData", "mapPassthrough", "renameKeys"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam] != null) { - log.warn "module '$key': workflow argument '$nam' is deprecated and will be removed in Viash 0.9.0. Please use 'fromState' and 'toState' instead." - } - } - - // check fromState - workflowArgs["fromState"] = _processFromState(workflowArgs.get("fromState"), key, meta.config) - - // check toState - workflowArgs["toState"] = _processToState(workflowArgs.get("toState"), key, meta.config) - - // return output - return workflowArgs -} - -def _processFromState(fromState, key_, config_) { - assert fromState == null || fromState instanceof Closure || fromState instanceof Map || fromState instanceof List : - "Error in module '$key_': Expected process argument 'fromState' to be null, a Closure, a Map, or a List. Found: class ${fromState.getClass()}" - if (fromState == null) { - return null - } - - // if fromState is a List, convert to map - if (fromState instanceof List) { - // check whether fromstate is a list[string] - assert fromState.every{it instanceof CharSequence} : "Error in module '$key_': fromState is a List, but not all elements are Strings" - fromState = fromState.collectEntries{[it, it]} - } - - // if fromState is a map, convert to closure - if (fromState instanceof Map) { - // check whether fromstate is a map[string, string] - assert fromState.values().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all values are Strings" - assert fromState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all keys are Strings" - def fromStateMap = fromState.clone() - def requiredInputNames = meta.config.functionality.allArguments.findAll{it.required && it.direction == "Input"}.collect{it.plainName} - // turn the map into a closure to be used later on - fromState = { it -> - def state = it[1] - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def data = fromStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (state.containsKey(origkey)) { - [[newkey, state[origkey]]] - } else if (!requiredInputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': fromState key '$origkey' not found in current state") - } - }.collectEntries() - data - } - } - - return fromState -} - -def _processToState(toState, key_, config_) { - if (toState == null) { - toState = { tup -> tup[1] } - } - - // toState should be a closure, map[string, string], or list[string] - assert toState instanceof Closure || toState instanceof Map || toState instanceof List : - "Error in module '$key_': Expected process argument 'toState' to be a Closure, a Map, or a List. Found: class ${toState.getClass()}" - - // if toState is a List, convert to map - if (toState instanceof List) { - // check whether toState is a list[string] - assert toState.every{it instanceof CharSequence} : "Error in module '$key_': toState is a List, but not all elements are Strings" - toState = toState.collectEntries{[it, it]} - } - - // if toState is a map, convert to closure - if (toState instanceof Map) { - // check whether toState is a map[string, string] - assert toState.values().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all values are Strings" - assert toState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all keys are Strings" - def toStateMap = toState.clone() - def requiredOutputNames = config_.functionality.allArguments.findAll{it.required && it.direction == "Output"}.collect{it.plainName} - // turn the map into a closure to be used later on - toState = { it -> - def output = it[1] - def state = it[2] - assert output instanceof Map : "Error in module '$key_': the output is not a Map" - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def extraEntries = toStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (output.containsKey(origkey)) { - [[newkey, output[origkey]]] - } else if (!requiredOutputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': toState key '$origkey' not found in current output") - } - }.collectEntries() - state + extraEntries - } - } - - return toState -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/workflowFactory.nf' -def _debug(workflowArgs, debugKey) { - if (workflowArgs.debug) { - view { "process '${workflowArgs.key}' $debugKey tuple: $it" } - } else { - map { it } - } -} - -// depends on: innerWorkflowFactory -def workflowFactory(Map args, Map defaultWfArgs, Map meta) { - def workflowArgs = processWorkflowArgs(args, defaultWfArgs, meta) - def key_ = workflowArgs["key"] - - workflow workflowInstance { - take: input_ - - main: - chModified = input_ - | checkUniqueIds([:]) - | _debug(workflowArgs, "input") - | map { tuple -> - tuple = deepClone(tuple) - - if (workflowArgs.map) { - tuple = workflowArgs.map(tuple) - } - if (workflowArgs.mapId) { - tuple[0] = workflowArgs.mapId(tuple[0]) - } - if (workflowArgs.mapData) { - tuple[1] = workflowArgs.mapData(tuple[1]) - } - if (workflowArgs.mapPassthrough) { - tuple = tuple.take(2) + workflowArgs.mapPassthrough(tuple.drop(2)) - } - - // check tuple - assert tuple instanceof List : - "Error in module '${key_}': element in channel should be a tuple [id, data, ...otherargs...]\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: List. Found: tuple.getClass() is ${tuple.getClass()}" - assert tuple.size() >= 2 : - "Error in module '${key_}': expected length of tuple in input channel to be two or greater.\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: tuple.size() == ${tuple.size()}" - - // check id field - assert tuple[0] instanceof CharSequence : - "Error in module '${key_}': first element of tuple in channel should be a String\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: ${tuple[0]}" - - // match file to input file - if (workflowArgs.auto.simplifyInput && (tuple[1] instanceof Path || tuple[1] instanceof List)) { - def inputFiles = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - - assert inputFiles.size() == 1 : - "Error in module '${key_}' id '${tuple[0]}'.\n" + - " Anonymous file inputs are only allowed when the process has exactly one file input.\n" + - " Expected: inputFiles.size() == 1. Found: inputFiles.size() is ${inputFiles.size()}" - - tuple[1] = [[ inputFiles[0].plainName, tuple[1] ]].collectEntries() - } - - // check data field - assert tuple[1] instanceof Map : - "Error in module '${key_}' id '${tuple[0]}': second element of tuple in channel should be a Map\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // rename keys of data field in tuple - if (workflowArgs.renameKeys) { - assert workflowArgs.renameKeys instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class: Map. Found: renameKeys.getClass() is ${workflowArgs.renameKeys.getClass()}" - assert tuple[1] instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // TODO: allow renameKeys to be a function? - workflowArgs.renameKeys.each { newKey, oldKey -> - assert newKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of newKey: String. Found: newKey.getClass() is ${newKey.getClass()}" - assert oldKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of oldKey: String. Found: oldKey.getClass() is ${oldKey.getClass()}" - assert tuple[1].containsKey(oldKey) : - "Error renaming data keys in module '${key}' id '${tuple[0]}'.\n" + - " Key '$oldKey' is missing in the data map. tuple[1].keySet() is '${tuple[1].keySet()}'" - tuple[1].put(newKey, tuple[1][oldKey]) - } - tuple[1].keySet().removeAll(workflowArgs.renameKeys.collect{ newKey, oldKey -> oldKey }) - } - tuple - } - - chModifiedFiltered = workflowArgs.filter ? - chModified | filter{workflowArgs.filter(it)} : - chModified - - if (workflowArgs.runIf) { - runIfBranch = chModifiedFiltered.branch{ tup -> - run: workflowArgs.runIf(tup[0], tup[1]) - passthrough: true - } - chRun = runIfBranch.run - chPassthrough = runIfBranch.passthrough - } else { - chRun = chModifiedFiltered - chPassthrough = Channel.empty() - } - - chArgs = workflowArgs.fromState ? - chRun | map{ - def new_data = workflowArgs.fromState(it.take(2)) - [it[0], new_data] - } : - chRun | map {tup -> tup.take(2)} - - // fill in defaults - chArgsWithDefaults = chArgs - | map { tuple -> - def id_ = tuple[0] - def data_ = tuple[1] - - // TODO: could move fromState to here - - // fetch default params from functionality - def defaultArgs = meta.config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - // fetch overrides in params - def paramArgs = meta.config.functionality.allArguments - .findAll { par -> - def argKey = key_ + "__" + par.plainName - params.containsKey(argKey) - } - .collectEntries { [ it.plainName, params[key_ + "__" + it.plainName] ] } - - // fetch overrides in data - def dataArgs = meta.config.functionality.allArguments - .findAll { data_.containsKey(it.plainName) } - .collectEntries { [ it.plainName, data_[it.plainName] ] } - - // combine params - def combinedArgs = defaultArgs + paramArgs + workflowArgs.args + dataArgs - - // remove arguments with explicit null values - combinedArgs - .removeAll{_, val -> val == null || val == "viash_no_value" || val == "force_null"} - - combinedArgs = _processInputValues(combinedArgs, meta.config, id_, key_) - - [id_, combinedArgs] + tuple.drop(2) - } - - // TODO: move some of the _meta.join_id wrangling to the safeJoin() function. - chInitialOutput = chArgsWithDefaults - | _debug(workflowArgs, "processed") - // run workflow - | innerWorkflowFactory(workflowArgs) - // check output tuple - | map { id_, output_ -> - - // see if output map contains metadata - def meta_ = - output_ instanceof Map && output_.containsKey("_meta") ? - output_["_meta"] : - [:] - def join_id = meta_.join_id ?: id_ - - // remove metadata - output_ = output_.findAll{k, v -> k != "_meta"} - - // check value types - output_ = _processOutputValues(output_, meta.config, id_, key_) - - // simplify output if need be - if (workflowArgs.auto.simplifyOutput && output_.size() == 1) { - output_ = output_.values()[0] - } - - [join_id, id_, output_] - } - // | view{"chInitialOutput: ${it.take(3)}"} - - // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] - chNewState = safeJoin(chInitialOutput, chModifiedFiltered, key_) - // input tuple format: [join_id, id, output, prev_state, ...] - // output tuple format: [join_id, id, new_state, ...] - | map{ tup -> - def new_state = workflowArgs.toState(tup.drop(1).take(3)) - tup.take(2) + [new_state] + tup.drop(4) - } - - if (workflowArgs.auto.publish == "state") { - chPublish = chNewState - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [join_id, id, new_state] - | map{ tup -> - tup.take(3) - } - - safeJoin(chPublish, chArgsWithDefaults, key_) - // input tuple format: [join_id, id, new_state, orig_state, ...] - // output tuple format: [id, new_state, orig_state] - | map { tup -> - tup.drop(1).take(3) - } - | publishStatesByConfig(key: key_, config: meta.config) - } - - // remove join_id and meta - chReturn = chNewState - | map { tup -> - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [id, new_state, ...] - tup.drop(1) - } - | _debug(workflowArgs, "output") - | concat(chPassthrough) - - emit: chReturn - } - - def wf = workflowInstance.cloneWithName(key_) - - // add factory function - wf.metaClass.run = { runArgs -> - workflowFactory(runArgs, workflowArgs, meta) - } - // add config to module for later introspection - wf.metaClass.config = meta.config - - return wf -} - -nextflow.enable.dsl=2 - -// START COMPONENT-SPECIFIC CODE - -// create meta object -meta = [ - "resources_dir": moduleDir.toRealPath().normalize(), - "config": processConfig(readJsonBlob('''{ - "functionality" : { - "name" : "combine_columns", - "namespace" : "template", - "version" : "0.2.2", - "arguments" : [ - { - "type" : "file", - "name" : "--input", - "alternatives" : [ - "-i" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "input", - "multiple" : true, - "multiple_sep" : ":", - "dest" : "par" - }, - { - "type" : "file", - "name" : "--output", - "alternatives" : [ - "-o" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "output", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - } - ], - "resources" : [ - { - "type" : "r_script", - "path" : "script.R", - "is_executable" : true, - "parent" : "file:/Users/toni/code/projects/viash/viash_project_template/src/template/combine_columns/" - } - ], - "status" : "enabled", - "set_wd_to_resources_dir" : false - }, - "platforms" : [ - { - "type" : "docker", - "id" : "docker", - "image" : "eddelbuettel/r2u:22.04", - "target_organization" : "viash-io/viash_project_template", - "target_registry" : "ghcr.io", - "namespace_separator" : "/", - "resolve_volume" : "Automatic", - "chown" : true, - "setup_strategy" : "ifneedbepullelsecachedbuild", - "target_image_source" : "https://github.com/viash-io/viash_project_template" - }, - { - "type" : "nextflow", - "id" : "nextflow", - "directives" : { - "tag" : "$id" - }, - "auto" : { - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false - }, - "config" : { - "labels" : { - "mem1gb" : "memory = 1.GB", - "mem2gb" : "memory = 2.GB", - "mem4gb" : "memory = 4.GB", - "mem8gb" : "memory = 8.GB", - "mem16gb" : "memory = 16.GB", - "mem32gb" : "memory = 32.GB", - "mem64gb" : "memory = 64.GB", - "mem128gb" : "memory = 128.GB", - "mem256gb" : "memory = 256.GB", - "mem512gb" : "memory = 512.GB", - "mem1tb" : "memory = 1.TB", - "mem2tb" : "memory = 2.TB", - "mem4tb" : "memory = 4.TB", - "mem8tb" : "memory = 8.TB", - "mem16tb" : "memory = 16.TB", - "mem32tb" : "memory = 32.TB", - "mem64tb" : "memory = 64.TB", - "mem128tb" : "memory = 128.TB", - "mem256tb" : "memory = 256.TB", - "mem512tb" : "memory = 512.TB", - "cpu1" : "cpus = 1", - "cpu2" : "cpus = 2", - "cpu5" : "cpus = 5", - "cpu10" : "cpus = 10", - "cpu20" : "cpus = 20", - "cpu50" : "cpus = 50", - "cpu100" : "cpus = 100", - "cpu200" : "cpus = 200", - "cpu500" : "cpus = 500", - "cpu1000" : "cpus = 1000" - } - }, - "debug" : false, - "container" : "docker" - } - ], - "info" : { - "config" : "/Users/toni/code/projects/viash/viash_project_template/src/template/combine_columns/config.vsh.yaml", - "platform" : "nextflow", - "output" : "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/combine_columns", - "viash_version" : "0.8.4", - "git_commit" : "11b6278597bf22afbfb56a8e83065a55553c9dd0", - "git_remote" : "https://github.com/viash-io/viash_project_template", - "git_tag" : "v0.2.1" - } -}''')) -] - -// resolve dependencies dependencies (if any) - - -// inner workflow -// inner workflow hook -def innerWorkflowFactory(args) { - def rawScript = '''set -e -tempscript=".viash_script.sh" -cat > "$tempscript" << VIASHMAIN - -## VIASH START -# The following code has been auto-generated by Viash. -# treat warnings as errors -.viash_orig_warn <- options(warn = 2) - -par <- list( - "input" = $( if [ ! -z ${VIASH_PAR_INPUT+x} ]; then echo -n "strsplit('"; echo -n "$VIASH_PAR_INPUT" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "', split = ':')[[1]]"; else echo NULL; fi ), - "output" = $( if [ ! -z ${VIASH_PAR_OUTPUT+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_OUTPUT" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "'"; else echo NULL; fi ) -) -meta <- list( - "functionality_name" = $( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo -n "'"; echo -n "$VIASH_META_FUNCTIONALITY_NAME" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "'"; else echo NULL; fi ), - "resources_dir" = $( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo -n "'"; echo -n "$VIASH_META_RESOURCES_DIR" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "'"; else echo NULL; fi ), - "executable" = $( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo -n "'"; echo -n "$VIASH_META_EXECUTABLE" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "'"; else echo NULL; fi ), - "config" = $( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo -n "'"; echo -n "$VIASH_META_CONFIG" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "'"; else echo NULL; fi ), - "temp_dir" = $( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo -n "'"; echo -n "$VIASH_META_TEMP_DIR" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "'"; else echo NULL; fi ), - "cpus" = $( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo -n "as.integer('"; echo -n "$VIASH_META_CPUS" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_b" = $( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_B" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_kb" = $( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_KB" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_mb" = $( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_MB" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_gb" = $( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_GB" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_tb" = $( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_TB" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "')"; else echo NULL; fi ), - "memory_pb" = $( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_PB" | sed "s#['\\\\]#\\\\\\\\&#g"; echo "')"; else echo NULL; fi ) -) -dep <- list( - -) - - -# restore original warn setting -options(.viash_orig_warn) -rm(.viash_orig_warn) - -## VIASH END - -outs <- lapply(par\\$input, function(file) { - read.delim(file, comment.char = "#", sep = "\\\\t", header = FALSE) -}) - -table <- do.call(cbind, outs) - -write.table(table, par\\$output, col.names = FALSE, sep = "\\\\t") -VIASHMAIN -Rscript "$tempscript" -''' - - return vdsl3WorkflowFactory(args, meta, rawScript) -} - - - -/** - * Generate a workflow for VDSL3 modules. - * - * This function is called by the workflowFactory() function. - * - * Input channel: [id, input_map] - * Output channel: [id, output_map] - * - * Internally, this workflow will convert the input channel - * to a format which the Nextflow module will be able to handle. - */ -def vdsl3WorkflowFactory(Map args, Map meta, String rawScript) { - def key = args["key"] - def processObj = null - - workflow processWf { - take: input_ - main: - - if (processObj == null) { - processObj = _vdsl3ProcessFactory(args, meta, rawScript) - } - - output_ = input_ - | map { tuple -> - def id = tuple[0] - def data_ = tuple[1] - - if (workflow.stubRun) { - // add id if missing - data_ = [id: 'stub'] + data_ - } - - // process input files separately - def inputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - .collect { par -> - def val = data_.containsKey(par.plainName) ? data_[par.plainName] : [] - def inputFiles = [] - if (val == null) { - inputFiles = [] - } else if (val instanceof List) { - inputFiles = val - } else if (val instanceof Path) { - inputFiles = [ val ] - } else { - inputFiles = [] - } - if (!workflow.stubRun) { - // throw error when an input file doesn't exist - inputFiles.each{ file -> - assert file.exists() : - "Error in module '${key}' id '${id}' argument '${par.plainName}'.\n" + - " Required input file does not exist.\n" + - " Path: '$file'.\n" + - " Expected input file to exist" - } - } - inputFiles - } - - // remove input files - def argsExclInputFiles = meta.config.functionality.allArguments - .findAll { (it.type != "file" || it.direction != "input") && data_.containsKey(it.plainName) } - .collectEntries { par -> - def parName = par.plainName - def val = data_[parName] - if (par.multiple && val instanceof Collection) { - val = val.join(par.multiple_sep) - } - if (par.direction == "output" && par.type == "file") { - val = val.replaceAll('\\$id', id).replaceAll('\\$key', key) - } - [parName, val] - } - - [ id ] + inputPaths + [ argsExclInputFiles, meta.resources_dir ] - } - | processObj - | map { output -> - def outputFiles = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .indexed() - .collectEntries{ index, par -> - out = output[index + 1] - // strip dummy '.exitcode' file from output (see nextflow-io/nextflow#2678) - if (!out instanceof List || out.size() <= 1) { - if (par.multiple) { - out = [] - } else { - assert !par.required : - "Error in module '${key}' id '${output[0]}' argument '${par.plainName}'.\n" + - " Required output file is missing" - out = null - } - } else if (out.size() == 2 && !par.multiple) { - out = out[1] - } else { - out = out.drop(1) - } - [ par.plainName, out ] - } - - // drop null outputs - outputFiles.removeAll{it.value == null} - - [ output[0], outputFiles ] - } - emit: output_ - } - - return processWf -} - -// depends on: session? -def _vdsl3ProcessFactory(Map workflowArgs, Map meta, String rawScript) { - // autodetect process key - def wfKey = workflowArgs["key"] - def procKeyPrefix = "${wfKey}_process" - def scriptMeta = nextflow.script.ScriptMeta.current() - def existing = scriptMeta.getProcessNames().findAll{it.startsWith(procKeyPrefix)} - def numbers = existing.collect{it.replace(procKeyPrefix, "0").toInteger()} - def newNumber = (numbers + [-1]).max() + 1 - - def procKey = newNumber == 0 ? procKeyPrefix : "$procKeyPrefix$newNumber" - - if (newNumber > 0) { - log.warn "Key for module '${wfKey}' is duplicated.\n", - "If you run a component multiple times in the same workflow,\n" + - "it's recommended you set a unique key for every call,\n" + - "for example: ${wfKey}.run(key: \"foo\")." - } - - // subset directives and convert to list of tuples - def drctv = workflowArgs.directives - - // TODO: unit test the two commands below - // convert publish array into tags - def valueToStr = { val -> - // ignore closures - if (val instanceof CharSequence) { - if (!val.matches('^[{].*[}]$')) { - '"' + val + '"' - } else { - val - } - } else if (val instanceof List) { - "[" + val.collect{valueToStr(it)}.join(", ") + "]" - } else if (val instanceof Map) { - "[" + val.collect{k, v -> k + ": " + valueToStr(v)}.join(", ") + "]" - } else { - val.inspect() - } - } - - // multiple entries allowed: label, publishdir - def drctvStrs = drctv.collect { key, value -> - if (key in ["label", "publishDir"]) { - value.collect{ val -> - if (val instanceof Map) { - "\n$key " + val.collect{ k, v -> k + ": " + valueToStr(v) }.join(", ") - } else if (val == null) { - "" - } else { - "\n$key " + valueToStr(val) - } - }.join() - } else if (value instanceof Map) { - "\n$key " + value.collect{ k, v -> k + ": " + valueToStr(v) }.join(", ") - } else { - "\n$key " + valueToStr(value) - } - }.join() - - def inputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - .collect { ', path(viash_par_' + it.plainName + ', stageAs: "_viash_par/' + it.plainName + '_?/*")' } - .join() - - def outputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .collect { par -> - // insert dummy into every output (see nextflow-io/nextflow#2678) - if (!par.multiple) { - ', path{[".exitcode", args.' + par.plainName + ']}' - } else { - ', path{[".exitcode"] + args.' + par.plainName + '}' - } - } - .join() - - // TODO: move this functionality somewhere else? - if (workflowArgs.auto.transcript) { - outputPaths = outputPaths + ', path{[".exitcode", ".command*"]}' - } else { - outputPaths = outputPaths + ', path{[".exitcode"]}' - } - - // create dirs for output files (based on BashWrapper.createParentFiles) - def createParentStr = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" && it.create_parent } - .collect { par -> - "\${ args.containsKey(\"${par.plainName}\") ? \"mkdir_parent \\\"\" + (args[\"${par.plainName}\"] instanceof String ? args[\"${par.plainName}\"] : args[\"${par.plainName}\"].join('\" \"')) + \"\\\"\" : \"\" }" - } - .join("\n") - - // construct inputFileExports - def inputFileExports = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction.toLowerCase() == "input" } - .collect { par -> - viash_par_contents = "(viash_par_${par.plainName} instanceof List ? viash_par_${par.plainName}.join(\"${par.multiple_sep}\") : viash_par_${par.plainName})" - "\n\${viash_par_${par.plainName}.empty ? \"\" : \"export VIASH_PAR_${par.plainName.toUpperCase()}=\\\"\" + ${viash_par_contents} + \"\\\"\"}" - } - - // NOTE: if using docker, use /tmp instead of tmpDir! - def tmpDir = java.nio.file.Paths.get( - System.getenv('NXF_TEMP') ?: - System.getenv('VIASH_TEMP') ?: - System.getenv('VIASH_TMPDIR') ?: - System.getenv('VIASH_TEMPDIR') ?: - System.getenv('VIASH_TMP') ?: - System.getenv('TEMP') ?: - System.getenv('TMPDIR') ?: - System.getenv('TEMPDIR') ?: - System.getenv('TMP') ?: - '/tmp' - ).toAbsolutePath() - - // construct stub - def stub = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .collect { par -> - "\${ args.containsKey(\"${par.plainName}\") ? \"touch2 \\\"\" + (args[\"${par.plainName}\"] instanceof String ? args[\"${par.plainName}\"].replace(\"_*\", \"_0\") : args[\"${par.plainName}\"].join('\" \"')) + \"\\\"\" : \"\" }" - } - .join("\n") - - // escape script - def escapedScript = rawScript.replace('\\', '\\\\').replace('$', '\\$').replace('"""', '\\"\\"\\"') - - // publishdir assert - def assertStr = (workflowArgs.auto.publish == true) || workflowArgs.auto.transcript ? - """\nassert task.publishDir.size() > 0: "if auto.publish is true, params.publish_dir needs to be defined.\\n Example: --publish_dir './output/'" """ : - "" - - // generate process string - def procStr = - """nextflow.enable.dsl=2 - | - |process $procKey {$drctvStrs - |input: - | tuple val(id)$inputPaths, val(args), path(resourcesDir, stageAs: ".viash_meta_resources") - |output: - | tuple val("\$id")$outputPaths, optional: true - |stub: - |\"\"\" - |touch2() { mkdir -p "\\\$(dirname "\\\$1")" && touch "\\\$1" ; } - |$stub - |\"\"\" - |script:$assertStr - |def escapeText = { s -> s.toString().replaceAll('([`"])', '\\\\\\\\\$1') } - |def parInject = args - | .findAll{key, value -> value != null} - | .collect{key, value -> "export VIASH_PAR_\${key.toUpperCase()}=\\\"\${escapeText(value)}\\\""} - | .join("\\n") - |\"\"\" - |# meta exports - |# export VIASH_META_RESOURCES_DIR="\${resourcesDir.toRealPath().toAbsolutePath()}" - |export VIASH_META_RESOURCES_DIR="\${resourcesDir}" - |export VIASH_META_TEMP_DIR="${['docker', 'podman', 'charliecloud'].any{ it == workflow.containerEngine } ? '/tmp' : tmpDir}" - |export VIASH_META_FUNCTIONALITY_NAME="${meta.config.functionality.name}" - |# export VIASH_META_EXECUTABLE="\\\$VIASH_META_RESOURCES_DIR/\\\$VIASH_META_FUNCTIONALITY_NAME" - |export VIASH_META_CONFIG="\\\$VIASH_META_RESOURCES_DIR/.config.vsh.yaml" - |\${task.cpus ? "export VIASH_META_CPUS=\$task.cpus" : "" } - |\${task.memory?.bytes != null ? "export VIASH_META_MEMORY_B=\$task.memory.bytes" : "" } - |if [ ! -z \\\${VIASH_META_MEMORY_B+x} ]; then - | export VIASH_META_MEMORY_KB=\\\$(( (\\\$VIASH_META_MEMORY_B+1023) / 1024 )) - | export VIASH_META_MEMORY_MB=\\\$(( (\\\$VIASH_META_MEMORY_KB+1023) / 1024 )) - | export VIASH_META_MEMORY_GB=\\\$(( (\\\$VIASH_META_MEMORY_MB+1023) / 1024 )) - | export VIASH_META_MEMORY_TB=\\\$(( (\\\$VIASH_META_MEMORY_GB+1023) / 1024 )) - | export VIASH_META_MEMORY_PB=\\\$(( (\\\$VIASH_META_MEMORY_TB+1023) / 1024 )) - |fi - | - |# meta synonyms - |export VIASH_TEMP="\\\$VIASH_META_TEMP_DIR" - |export TEMP_DIR="\\\$VIASH_META_TEMP_DIR" - | - |# create output dirs if need be - |function mkdir_parent { - | for file in "\\\$@"; do - | mkdir -p "\\\$(dirname "\\\$file")" - | done - |} - |$createParentStr - | - |# argument exports${inputFileExports.join()} - |\$parInject - | - |# process script - |${escapedScript} - |\"\"\" - |} - |""".stripMargin() - - // TODO: print on debug - // if (workflowArgs.debug == true) { - // println("######################\n$procStr\n######################") - // } - - // create runtime process - def ownerParams = new nextflow.script.ScriptBinding.ParamsMap() - def binding = new nextflow.script.ScriptBinding().setParams(ownerParams) - def module = new nextflow.script.IncludeDef.Module(name: procKey) - def session = nextflow.Nextflow.getSession() - def scriptParser = new nextflow.script.ScriptParser(session) - .setModule(true) - .setBinding(binding) - scriptParser.scriptPath = scriptMeta.getScriptPath() - def moduleScript = scriptParser.runScript(procStr) - .getScript() - - // register module in meta - scriptMeta.addModule(moduleScript, module.name, module.alias) - - // retrieve and return process from meta - return scriptMeta.getProcess(procKey) -} - -// defaults -meta["defaults"] = [ - // key to be used to trace the process and determine output names - key: null, - - // fixed arguments to be passed to script - args: [:], - - // default directives - directives: readJsonBlob('''{ - "container" : { - "registry" : "ghcr.io", - "image" : "viash-io/viash_project_template/template/combine_columns", - "tag" : "0.2.2" - }, - "tag" : "$id" -}'''), - - // auto settings - auto: readJsonBlob('''{ - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false -}'''), - - // Apply a map over the incoming tuple - // Example: `{ tup -> [ tup[0], [input: tup[1].output] ] + tup.drop(2) }` - map: null, - - // Apply a map over the ID element of a tuple (i.e. the first element) - // Example: `{ id -> id + "_foo" }` - mapId: null, - - // Apply a map over the data element of a tuple (i.e. the second element) - // Example: `{ data -> [ input: data.output ] }` - mapData: null, - - // Apply a map over the passthrough elements of a tuple (i.e. the tuple excl. the first two elements) - // Example: `{ pt -> pt.drop(1) }` - mapPassthrough: null, - - // Filter the channel - // Example: `{ tup -> tup[0] == "foo" }` - filter: null, - - // Choose whether or not to run the component on the tuple if the condition is true. - // Otherwise, the tuple will be passed through. - // Example: `{ tup -> tup[0] != "skip_this" }` - runIf: null, - - // Rename keys in the data field of the tuple (i.e. the second element) - // Will likely be deprecated in favour of `fromState`. - // Example: `[ "new_key": "old_key" ]` - renameKeys: null, - - // Fetch data from the state and pass it to the module without altering the current state. - // - // `fromState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be passed to the module as is. - // - If it is a `List[String]`, the data will be the values of the state at the given keys. - // - If it is a `Map[String, String]`, the data will be the values of the state at the given keys, with the keys renamed according to the map. - // - If it is a function, the tuple (`[id, state]`) in the channel will be passed to the function, and the result will be used as the data. - // - // Example: `{ id, state -> [input: state.fastq_file] }` - // Default: `null` - fromState: null, - - // Determine how the state should be updated after the module has been run. - // - // `toState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be replaced with the output of the module. - // - If it is a `List[String]`, the state will be updated with the values of the data at the given keys. - // - If it is a `Map[String, String]`, the state will be updated with the values of the data at the given keys, with the keys renamed according to the map. - // - If it is a function, a tuple (`[id, output, state]`) will be passed to the function, and the result will be used as the new state. - // - // Example: `{ id, output, state -> state + [counts: state.output] }` - // Default: `{ id, output, state -> output }` - toState: null, - - // Whether or not to print debug messages - // Default: `false` - debug: false -] - -// initialise default workflow -meta["workflow"] = workflowFactory([key: meta.config.functionality.name], meta.defaults, meta) - -// add workflow to environment -nextflow.script.ScriptMeta.current().addDefinition(meta.workflow) - -// anonymous workflow for running this module as a standalone -workflow { - // add id argument if it's not already in the config - // TODO: deep copy - def newConfig = deepClone(meta.config) - def newParams = deepClone(params) - - def argsContainsId = newConfig.functionality.allArguments.any{it.plainName == "id"} - if (!argsContainsId) { - def idArg = [ - 'name': '--id', - 'required': false, - 'type': 'string', - 'description': 'A unique id for every entry.', - 'multiple': false - ] - newConfig.functionality.arguments.add(0, idArg) - newConfig = processConfig(newConfig) - } - if (!newParams.containsKey("id")) { - newParams.id = "run" - } - - helpMessage(newConfig) - - channelFromParams(newParams, newConfig) - // make sure id is not in the state if id is not in the args - | map {id, state -> - if (!argsContainsId) { - [id, state.findAll{k, v -> k != "id"}] - } else { - [id, state] - } - } - | meta.workflow.run( - auto: [ publish: "state" ] - ) -} - -// END COMPONENT-SPECIFIC CODE diff --git a/target/nextflow/template/combine_columns/nextflow.config b/target/nextflow/template/combine_columns/nextflow.config deleted file mode 100644 index 12884ec..0000000 --- a/target/nextflow/template/combine_columns/nextflow.config +++ /dev/null @@ -1,106 +0,0 @@ -manifest { - name = 'template/combine_columns' - mainScript = 'main.nf' - nextflowVersion = '!>=20.12.1-edge' - version = '0.2.2' -} - -process.container = 'nextflow/bash:latest' - -// detect tempdir -tempDir = java.nio.file.Paths.get( - System.getenv('NXF_TEMP') ?: - System.getenv('VIASH_TEMP') ?: - System.getenv('TEMPDIR') ?: - System.getenv('TMPDIR') ?: - '/tmp' -).toAbsolutePath() - -profiles { - no_publish { - process { - withName: '.*' { - publishDir = [ - enabled: false - ] - } - } - } - mount_temp { - docker.temp = tempDir - podman.temp = tempDir - charliecloud.temp = tempDir - } - docker { - docker.enabled = true - // docker.userEmulation = true - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - singularity { - singularity.enabled = true - singularity.autoMounts = true - docker.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - podman { - podman.enabled = true - docker.enabled = false - singularity.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - shifter { - shifter.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - charliecloud.enabled = false - } - charliecloud { - charliecloud.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - } -} - -process{ - withLabel: mem1gb { memory = 1.GB } - withLabel: mem2gb { memory = 2.GB } - withLabel: mem4gb { memory = 4.GB } - withLabel: mem8gb { memory = 8.GB } - withLabel: mem16gb { memory = 16.GB } - withLabel: mem32gb { memory = 32.GB } - withLabel: mem64gb { memory = 64.GB } - withLabel: mem128gb { memory = 128.GB } - withLabel: mem256gb { memory = 256.GB } - withLabel: mem512gb { memory = 512.GB } - withLabel: mem1tb { memory = 1.TB } - withLabel: mem2tb { memory = 2.TB } - withLabel: mem4tb { memory = 4.TB } - withLabel: mem8tb { memory = 8.TB } - withLabel: mem16tb { memory = 16.TB } - withLabel: mem32tb { memory = 32.TB } - withLabel: mem64tb { memory = 64.TB } - withLabel: mem128tb { memory = 128.TB } - withLabel: mem256tb { memory = 256.TB } - withLabel: mem512tb { memory = 512.TB } - withLabel: cpu1 { cpus = 1 } - withLabel: cpu2 { cpus = 2 } - withLabel: cpu5 { cpus = 5 } - withLabel: cpu10 { cpus = 10 } - withLabel: cpu20 { cpus = 20 } - withLabel: cpu50 { cpus = 50 } - withLabel: cpu100 { cpus = 100 } - withLabel: cpu200 { cpus = 200 } - withLabel: cpu500 { cpus = 500 } - withLabel: cpu1000 { cpus = 1000 } -} - - diff --git a/target/nextflow/template/remove_comments/.config.vsh.yaml b/target/nextflow/template/remove_comments/.config.vsh.yaml deleted file mode 100644 index d94d8a2..0000000 --- a/target/nextflow/template/remove_comments/.config.vsh.yaml +++ /dev/null @@ -1,109 +0,0 @@ -functionality: - name: "remove_comments" - namespace: "template" - version: "0.2.2" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - info: null - example: - - "file.tsv" - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "file" - name: "--output" - alternatives: - - "-o" - info: null - example: - - "file.tsv" - must_exist: true - create_parent: true - required: true - direction: "output" - multiple: false - multiple_sep: ":" - dest: "par" - resources: - - type: "bash_script" - path: "script.sh" - is_executable: true - test_resources: - - type: "bash_script" - path: "test.sh" - is_executable: true - info: null - status: "enabled" - set_wd_to_resources_dir: false -platforms: -- type: "docker" - id: "docker" - image: "ubuntu:20.04" - target_organization: "viash-io/viash_project_template" - target_registry: "ghcr.io" - namespace_separator: "/" - resolve_volume: "Automatic" - chown: true - setup_strategy: "ifneedbepullelsecachedbuild" - target_image_source: "https://github.com/viash-io/viash_project_template" - entrypoint: [] - cmd: null -- type: "nextflow" - id: "nextflow" - directives: - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1.GB" - mem2gb: "memory = 2.GB" - mem4gb: "memory = 4.GB" - mem8gb: "memory = 8.GB" - mem16gb: "memory = 16.GB" - mem32gb: "memory = 32.GB" - mem64gb: "memory = 64.GB" - mem128gb: "memory = 128.GB" - mem256gb: "memory = 256.GB" - mem512gb: "memory = 512.GB" - mem1tb: "memory = 1.TB" - mem2tb: "memory = 2.TB" - mem4tb: "memory = 4.TB" - mem8tb: "memory = 8.TB" - mem16tb: "memory = 16.TB" - mem32tb: "memory = 32.TB" - mem64tb: "memory = 64.TB" - mem128tb: "memory = 128.TB" - mem256tb: "memory = 256.TB" - mem512tb: "memory = 512.TB" - cpu1: "cpus = 1" - cpu2: "cpus = 2" - cpu5: "cpus = 5" - cpu10: "cpus = 10" - cpu20: "cpus = 20" - cpu50: "cpus = 50" - cpu100: "cpus = 100" - cpu200: "cpus = 200" - cpu500: "cpus = 500" - cpu1000: "cpus = 1000" - debug: false - container: "docker" -info: - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/config.vsh.yaml" - platform: "nextflow" - output: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/remove_comments" - executable: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/remove_comments/remove_comments" - viash_version: "0.8.4" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - git_remote: "https://github.com/viash-io/viash_project_template" - git_tag: "v0.2.1" diff --git a/target/nextflow/template/remove_comments/main.nf b/target/nextflow/template/remove_comments/main.nf deleted file mode 100644 index fe94089..0000000 --- a/target/nextflow/template/remove_comments/main.nf +++ /dev/null @@ -1,3403 +0,0 @@ -// remove_comments 0.2.2 -// -// This wrapper script is auto-generated by viash 0.8.4 and is thus a derivative -// work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data -// Intuitive. -// -// The component may contain files which fall under a different license. The -// authors of this component should specify the license in the header of such -// files, or include a separate license file detailing the licenses of all included -// files. - -//////////////////////////// -// VDSL3 helper functions // -//////////////////////////// - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_checkArgumentType.nf' -class UnexpectedArgumentTypeException extends Exception { - String errorIdentifier - String stage - String plainName - String expectedClass - String foundClass - - // ${key ? " in module '$key'" : ""}${id ? " id '$id'" : ""} - UnexpectedArgumentTypeException(String errorIdentifier, String stage, String plainName, String expectedClass, String foundClass) { - super("Error${errorIdentifier ? " $errorIdentifier" : ""}:${stage ? " $stage" : "" } argument '${plainName}' has the wrong type. " + - "Expected type: ${expectedClass}. Found type: ${foundClass}") - this.errorIdentifier = errorIdentifier - this.stage = stage - this.plainName = plainName - this.expectedClass = expectedClass - this.foundClass = foundClass - } -} - -/** - * Checks if the given value is of the expected type. If not, an exception is thrown. - * - * @param stage The stage of the argument (input or output) - * @param par The parameter definition - * @param value The value to check - * @param errorIdentifier The identifier to use in the error message - * @return The value, if it is of the expected type - * @throws UnexpectedArgumentTypeException If the value is not of the expected type -*/ -def _checkArgumentType(String stage, Map par, Object value, String errorIdentifier) { - // expectedClass will only be != null if value is not of the expected type - def expectedClass = null - def foundClass = null - - // todo: split if need be - - if (!par.required && value == null) { - expectedClass = null - } else if (par.multiple) { - if (value !instanceof Collection) { - value = [value] - } - - // split strings - value = value.collectMany{ val -> - if (val instanceof String) { - // collect() to ensure that the result is a List and not simply an array - val.split(par.multiple_sep).collect() - } else { - [val] - } - } - - // process globs - if (par.type == "file" && par.direction == "input") { - value = value.collect{ it instanceof String ? file(it, hidden: true) : it }.flatten() - } - - // check types of elements in list - try { - value = value.collect { listVal -> - _checkArgumentType(stage, par + [multiple: false], listVal, errorIdentifier) - } - } catch (UnexpectedArgumentTypeException e) { - expectedClass = "List[${e.expectedClass}]" - foundClass = "List[${e.foundClass}]" - } - } else if (par.type == "string") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else if (par.type == "integer") { - // cast to integer if need be - if (value instanceof String) { - try { - value = value.toInteger() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigInteger) { - value = value.intValue() - } - expectedClass = value instanceof Integer ? null : "Integer" - } else if (par.type == "long") { - // cast to long if need be - if (value instanceof String) { - try { - value = value.toLong() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof Integer) { - value = value.toLong() - } - expectedClass = value instanceof Long ? null : "Long" - } else if (par.type == "double") { - // cast to double if need be - if (value instanceof String) { - try { - value = value.toDouble() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigDecimal) { - value = value.doubleValue() - } - if (value instanceof Float) { - value = value.toDouble() - } - expectedClass = value instanceof Double ? null : "Double" - } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { - // cast to boolean if need ben - if (value instanceof String) { - def valueLower = value.toLowerCase() - if (valueLower == "true") { - value = true - } else if (valueLower == "false") { - value = false - } - } - expectedClass = value instanceof Boolean ? null : "Boolean" - } else if (par.type == "file" && (par.direction == "input" || stage == "output")) { - // cast to path if need be - if (value instanceof String) { - value = file(value, hidden: true) - } - if (value instanceof File) { - value = value.toPath() - } - expectedClass = value instanceof Path ? null : "Path" - } else if (par.type == "file" && stage == "input" && par.direction == "output") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else { - // didn't find a match for par.type - expectedClass = par.type - } - - if (expectedClass != null) { - if (foundClass == null) { - foundClass = value.getClass().getName() - } - throw new UnexpectedArgumentTypeException(errorIdentifier, stage, par.plainName, expectedClass, foundClass) - } - - return value -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processInputValues.nf' -Map _processInputValues(Map inputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.required) { - assert inputs.containsKey(arg.plainName) && inputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required input argument '${arg.plainName}' is missing" - } - } - - inputs = inputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid input argument" - - value = _checkArgumentType("input", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return inputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processOutputValues.nf' -Map _processOutputValues(Map outputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.direction == "output" && arg.required) { - assert outputs.containsKey(arg.plainName) && outputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required output argument '${arg.plainName}' is missing" - } - } - - outputs = outputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && it.direction == "output" } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid output argument" - - value = _checkArgumentType("output", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return outputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/IDChecker.nf' -class IDChecker { - final def items = [] as Set - - @groovy.transform.WithWriteLock - boolean observe(String item) { - if (items.contains(item)) { - return false - } else { - items << item - return true - } - } - - @groovy.transform.WithReadLock - boolean contains(String item) { - return items.contains(item) - } - - @groovy.transform.WithReadLock - Set getItems() { - return items.clone() - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_checkUniqueIds.nf' - -/** - * Check if the ids are unique across parameter sets - * - * @param parameterSets a list of parameter sets. - */ -private void _checkUniqueIds(List>> parameterSets) { - def ppIds = parameterSets.collect{it[0]} - assert ppIds.size() == ppIds.unique().size() : "All argument sets should have unique ids. Detected ids: $ppIds" -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_getChild.nf' - -// helper functions for reading params from file // -def _getChild(parent, child) { - if (child.contains("://") || java.nio.file.Paths.get(child).isAbsolute()) { - child - } else { - def parentAbsolute = java.nio.file.Paths.get(parent).toAbsolutePath().toString() - parentAbsolute.replaceAll('/[^/]*$', "/") + child - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_parseParamList.nf' -/** - * Figure out the param list format based on the file extension - * - * @param param_list A String containing the path to the parameter list file. - * - * @return A String containing the format of the parameter list file. - */ -def _paramListGuessFormat(param_list) { - if (param_list !instanceof String) { - "asis" - } else if (param_list.endsWith(".csv")) { - "csv" - } else if (param_list.endsWith(".json") || param_list.endsWith(".jsn")) { - "json" - } else if (param_list.endsWith(".yaml") || param_list.endsWith(".yml")) { - "yaml" - } else { - "yaml_blob" - } -} - - -/** - * Read the param list - * - * @param param_list One of the following: - * - A String containing the path to the parameter list file (csv, json or yaml), - * - A yaml blob of a list of maps (yaml_blob), - * - Or a groovy list of maps (asis). - * @param config A Map of the Viash configuration. - * - * @return A List of Maps containing the parameters. - */ -def _parseParamList(param_list, Map config) { - // first determine format by extension - def paramListFormat = _paramListGuessFormat(param_list) - - def paramListPath = (paramListFormat != "asis" && paramListFormat != "yaml_blob") ? - file(param_list, hidden: true) : - null - - // get the correct parser function for the detected params_list format - def paramSets = [] - if (paramListFormat == "asis") { - paramSets = param_list - } else if (paramListFormat == "yaml_blob") { - paramSets = readYamlBlob(param_list) - } else if (paramListFormat == "yaml") { - paramSets = readYaml(paramListPath) - } else if (paramListFormat == "json") { - paramSets = readJson(paramListPath) - } else if (paramListFormat == "csv") { - paramSets = readCsv(paramListPath) - } else { - error "Format of provided --param_list not recognised.\n" + - "Found: '$paramListFormat'.\n" + - "Expected: a csv file, a json file, a yaml file,\n" + - "a yaml blob or a groovy list of maps." - } - - // data checks - assert paramSets instanceof List: "--param_list should contain a list of maps" - for (value in paramSets) { - assert value instanceof Map: "--param_list should contain a list of maps" - } - - // id is argument - def idIsArgument = config.functionality.allArguments.any{it.plainName == "id"} - - // Reformat from List to List> by adding the ID as first element of a Tuple2 - paramSets = paramSets.collect({ data -> - def id = data.id - if (!idIsArgument) { - data = data.findAll{k, v -> k != "id"} - } - [id, data] - }) - - // Split parameters with 'multiple: true' - paramSets = paramSets.collect({ id, data -> - data = _splitParams(data, config) - [id, data] - }) - - // The paths of input files inside a param_list file may have been specified relatively to the - // location of the param_list file. These paths must be made absolute. - if (paramListPath) { - paramSets = paramSets.collect({ id, data -> - def new_data = data.collectEntries{ parName, parValue -> - def par = config.functionality.allArguments.find{it.plainName == parName} - if (par && par.type == "file" && par.direction == "input") { - if (parValue instanceof Collection) { - parValue = parValue.collectMany{path -> - def x = _resolveSiblingIfNotAbsolute(path, paramListPath) - x instanceof Collection ? x : [x] - } - } else { - parValue = _resolveSiblingIfNotAbsolute(parValue, paramListPath) - } - } - [parName, parValue] - } - [id, new_data] - }) - } - - return paramSets -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_splitParams.nf' -/** - * Split parameters for arguments that accept multiple values using their separator - * - * @param paramList A Map containing parameters to split. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A Map of parameters where the parameter values have been split into a list using - * their seperator. - */ -Map _splitParams(Map parValues, Map config){ - def parsedParamValues = parValues.collectEntries { parName, parValue -> - def parameterSettings = config.functionality.allArguments.find({it.plainName == parName}) - - if (!parameterSettings) { - // if argument is not found, do not alter - return [parName, parValue] - } - if (parameterSettings.multiple) { // Check if parameter can accept multiple values - if (parValue instanceof Collection) { - parValue = parValue.collect{it instanceof String ? it.split(parameterSettings.multiple_sep) : it } - } else if (parValue instanceof String) { - parValue = parValue.split(parameterSettings.multiple_sep) - } else if (parValue == null) { - parValue = [] - } else { - parValue = [ parValue ] - } - parValue = parValue.flatten() - } - // For all parameters check if multiple values are only passed for - // arguments that allow it. Quietly simplify lists of length 1. - if (!parameterSettings.multiple && parValue instanceof Collection) { - assert parValue.size() == 1 : - "Error: argument ${parName} has too many values.\n" + - " Expected amount: 1. Found: ${parValue.size()}" - parValue = parValue[0] - } - [parName, parValue] - } - return parsedParamValues -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/channelFromParams.nf' -/** - * Parse nextflow parameters based on settings defined in a viash config. - * Return a list of parameter sets, each parameter set corresponding to - * an event in a nextflow channel. The output from this function can be used - * with Channel.fromList to create a nextflow channel with Vdsl3 formatted - * events. - * - * This function performs: - * - A filtering of the params which can be found in the config file. - * - Process the params_list argument which allows a user to to initialise - * a Vsdl3 channel with multiple parameter sets. Possible formats are - * csv, json, yaml, or simply a yaml_blob. A csv should have column names - * which correspond to the different arguments of this pipeline. A json or a yaml - * file should be a list of maps, each of which has keys corresponding to the - * arguments of the pipeline. A yaml blob can also be passed directly as a parameter. - * When passing a csv, json or yaml, relative path names are relativized to the - * location of the parameter file. - * - Combine the parameter sets into a vdsl3 Channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A list of parameters with the first element of the event being - * the event ID and the second element containing a map of the parsed parameters. - */ - -private List>> _paramsToParamSets(Map params, Map config){ - // todo: fetch key from run args - def key_ = config.functionality.name - - /* parse regular parameters (not in param_list) */ - /*************************************************/ - def globalParams = config.functionality.allArguments - .findAll { params.containsKey(it.plainName) } - .collectEntries { [ it.plainName, params[it.plainName] ] } - def globalID = params.get("id", null) - - /* process params_list arguments */ - /*********************************/ - def paramList = params.containsKey("param_list") && params.param_list != null ? - params.param_list : [] - // if (paramList instanceof String) { - // paramList = [paramList] - // } - // def paramSets = paramList.collectMany{ _parseParamList(it, config) } - // TODO: be able to process param_list when it is a list of strings - def paramSets = _parseParamList(paramList, config) - if (paramSets.isEmpty()) { - paramSets = [[null, [:]]] - } - - /* combine arguments into channel */ - /**********************************/ - def processedParams = paramSets.indexed().collect{ index, tup -> - // Process ID - def id = tup[0] ?: globalID - - if (workflow.stubRun) { - // if stub run, explicitly add an id if missing - id = id ? id : "stub${index}" - } - assert id != null: "Each parameter set should have at least an 'id'" - - // Process params - def parValues = globalParams + tup[1] - // // Remove parameters which are null, if the default is also null - // parValues = parValues.collectEntries{paramName, paramValue -> - // parameterSettings = config.functionality.allArguments.find({it.plainName == paramName}) - // if ( paramValue != null || parameterSettings.get("default", null) != null ) { - // [paramName, paramValue] - // } - // } - parValues = parValues.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key_}' id '${id}': '${name}' is not a valid input argument" - - if (par == null) { - return [:] - } - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - - [ name, value ] - } - - [id, parValues] - } - - // Check if ids (first element of each list) is unique - _checkUniqueIds(processedParams) - return processedParams -} - -/** - * Parse nextflow parameters based on settings defined in a viash config - * and return a nextflow channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A nextflow Channel with events. Events are formatted as a tuple that contains - * first contains the ID of the event and as second element holds a parameter map. - * - * - */ -def channelFromParams(Map params, Map config) { - def processedParams = _paramsToParamSets(params, config) - return Channel.fromList(processedParams) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/checkUniqueIds.nf' -def checkUniqueIds(Map args) { - def stopOnError = args.stopOnError == null ? args.stopOnError : true - - def idChecker = new IDChecker() - - return filter { tup -> - if (!idChecker.observe(tup[0])) { - if (stopOnError) { - error "Duplicate id: ${tup[0]}" - } else { - log.warn "Duplicate id: ${tup[0]}, removing duplicate entry" - return false - } - } - return true - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/preprocessInputs.nf' -// This helper file will be deprecated soon -preprocessInputsDeprecationWarningPrinted = false - -def preprocessInputsDeprecationWarning() { - if (!preprocessInputsDeprecationWarningPrinted) { - preprocessInputsDeprecationWarningPrinted = true - System.err.println("Warning: preprocessInputs() is deprecated and will be removed in Viash 0.9.0.") - } -} - -/** - * Generate a nextflow Workflow that allows processing a channel of - * Vdsl3 formatted events and apply a Viash config to them: - * - Gather default parameters from the Viash config and make - * sure that they are correctly formatted (see applyConfig method). - * - Format the input parameters (also using the applyConfig method). - * - Apply the default parameter to the input parameters. - * - Do some assertions: - * ~ Check if the event IDs in the channel are unique. - * - * The events in the channel are formatted as tuples, with the - * first element of the tuples being a unique id of the parameter set, - * and the second element containg the the parameters themselves. - * Optional extra elements of the tuples will be passed to the output as is. - * - * @param args A map that must contain a 'config' key that points - * to a parsed config (see readConfig()). Optionally, a - * 'key' key can be provided which can be used to create a unique - * name for the workflow process. - * - * @return A workflow that allows processing a channel of Vdsl3 formatted events - * and apply a Viash config to them. - */ -def preprocessInputs(Map args) { - preprocessInputsDeprecationWarning() - - def config = args.config - assert config instanceof Map : - "Error in preprocessInputs: config must be a map. " + - "Expected class: Map. Found: config.getClass() is ${config.getClass()}" - def key_ = args.key ?: config.functionality.name - - // Get different parameter types (used throughout this function) - def defaultArgs = config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - map { tup -> - def id = tup[0] - def data = tup[1] - def passthrough = tup.drop(2) - - def new_data = (defaultArgs + data).collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - - if (par != null) { - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - } - - [ name, value ] - } - - [ id, new_data ] + passthrough - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runComponents.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component config. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component config. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component config. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component config. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runComponents(Map args) { - log.warn("runComponents is deprecated, use runEach instead") - assert args.components: "runComponents should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runComponents" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runComponentsWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def comp_config = comp_.config - - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_config) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - // def new_id = id_(tup[0], tup[1], comp_config) - def new_id = tup[0] - if (id_ instanceof String) { - new_id = id_ - } else if (id_ instanceof Closure) { - new_id = id_(new_id, tup[1], comp_config) - } - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_config) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_config) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runComponentsWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runEach.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component itself. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component itself. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component itself. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component itself. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runEach(Map args) { - assert args.components: "runEach should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runEach" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runEachWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - def new_id = id_ - if (new_id instanceof Closure) { - new_id = new_id(tup[0], tup[1], comp_) - } - assert new_id instanceof String : "Error in runEach: id should be a String or a Closure that returns a String. Expected: id instanceof String. Found: ${new_id.getClass()}" - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - def new_state = null - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runEachWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/safeJoin.nf' -/** - * Join sourceChannel to targetChannel - * - * This function joins the sourceChannel to the targetChannel. - * However, each id in the targetChannel must be present in the - * sourceChannel. If _meta.join_id exists in the targetChannel, that is - * used as an id instead. If the id doesn't match any id in the sourceChannel, - * an error is thrown. - */ - -def safeJoin(targetChannel, sourceChannel, key) { - def sourceIDs = new IDChecker() - - def sourceCheck = sourceChannel - | map { tup -> - sourceIDs.observe(tup[0]) - tup - } - def targetCheck = targetChannel - | map { tup -> - def id = tup[0] - - if (!sourceIDs.contains(id)) { - error ( - "Error in module '${key}' when merging output with original state.\n" + - " Reason: output with id '${id}' could not be joined with source channel.\n" + - " If the IDs in the output channel differ from the input channel,\n" + - " please set `tup[1]._meta.join_id to the original ID.\n" + - " Original IDs in input channel: ['${sourceIDs.getItems().join("', '")}'].\n" + - " Unexpected ID in the output channel: '${id}'.\n" + - " Example input event: [\"id\", [input: file(...)]],\n" + - " Example output event: [\"newid\", [output: file(...), _meta: [join_id: \"id\"]]]" - ) - } - // TODO: add link to our documentation on how to fix this - - tup - } - - sourceCheck.cross(targetChannel) - | map{ left, right -> - right + left.drop(1) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/_processArgument.nf' -def _processArgument(arg) { - arg.multiple = arg.multiple != null ? arg.multiple : false - arg.required = arg.required != null ? arg.required : false - arg.direction = arg.direction != null ? arg.direction : "input" - arg.multiple_sep = arg.multiple_sep != null ? arg.multiple_sep : ":" - arg.plainName = arg.name.replaceAll("^-*", "") - - if (arg.type == "file") { - arg.must_exist = arg.must_exist != null ? arg.must_exist : true - arg.create_parent = arg.create_parent != null ? arg.create_parent : true - } - - // add default values to output files which haven't already got a default - if (arg.type == "file" && arg.direction == "output" && arg.default == null) { - def mult = arg.multiple ? "_*" : "" - def extSearch = "" - if (arg.default != null) { - extSearch = arg.default - } else if (arg.example != null) { - extSearch = arg.example - } - if (extSearch instanceof List) { - extSearch = extSearch[0] - } - def extSearchResult = extSearch.find("\\.[^\\.]+\$") - def ext = extSearchResult != null ? extSearchResult : "" - arg.default = "\$id.\$key.${arg.plainName}${mult}${ext}" - if (arg.multiple) { - arg.default = [arg.default] - } - } - - if (!arg.multiple) { - if (arg.default != null && arg.default instanceof List) { - arg.default = arg.default[0] - } - if (arg.example != null && arg.example instanceof List) { - arg.example = arg.example[0] - } - } - - if (arg.type == "boolean_true") { - arg.default = false - } - if (arg.type == "boolean_false") { - arg.default = true - } - - arg -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/addGlobalParams.nf' -def addGlobalArguments(config) { - def localConfig = [ - "functionality" : [ - "argument_groups": [ - [ - "name": "Nextflow input-output arguments", - "description": "Input/output parameters for Nextflow itself. Please note that both publishDir and publish_dir are supported but at least one has to be configured.", - "arguments" : [ - [ - 'name': '--publish_dir', - 'required': true, - 'type': 'string', - 'description': 'Path to an output directory.', - 'example': 'output/', - 'multiple': false - ], - [ - 'name': '--param_list', - 'required': false, - 'type': 'string', - 'description': '''Allows inputting multiple parameter sets to initialise a Nextflow channel. A `param_list` can either be a list of maps, a csv file, a json file, a yaml file, or simply a yaml blob. - | - |* A list of maps (as-is) where the keys of each map corresponds to the arguments of the pipeline. Example: in a `nextflow.config` file: `param_list: [ ['id': 'foo', 'input': 'foo.txt'], ['id': 'bar', 'input': 'bar.txt'] ]`. - |* A csv file should have column names which correspond to the different arguments of this pipeline. Example: `--param_list data.csv` with columns `id,input`. - |* A json or a yaml file should be a list of maps, each of which has keys corresponding to the arguments of the pipeline. Example: `--param_list data.json` with contents `[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]`. - |* A yaml blob can also be passed directly as a string. Example: `--param_list "[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]"`. - | - |When passing a csv, json or yaml file, relative path names are relativized to the location of the parameter file. No relativation is performed when `param_list` is a list of maps (as-is) or a yaml blob.'''.stripMargin(), - 'example': 'my_params.yaml', - 'multiple': false, - 'hidden': true - ] - // TODO: allow multiple: true in param_list? - // TODO: allow to specify a --param_list_regex to filter the param_list? - // TODO: allow to specify a --param_list_from_state to remap entries in the param_list? - ] - ] - ] - ] - ] - - return processConfig(_mergeMap(config, localConfig)) -} - -def _mergeMap(Map lhs, Map rhs) { - return rhs.inject(lhs.clone()) { map, entry -> - if (map[entry.key] instanceof Map && entry.value instanceof Map) { - map[entry.key] = _mergeMap(map[entry.key], entry.value) - } else if (map[entry.key] instanceof Collection && entry.value instanceof Collection) { - map[entry.key] += entry.value - } else { - map[entry.key] = entry.value - } - return map - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/generateHelp.nf' -def _generateArgumentHelp(param) { - // alternatives are not supported - // def names = param.alternatives ::: List(param.name) - - def unnamedProps = [ - ["required parameter", param.required], - ["multiple values allowed", param.multiple], - ["output", param.direction.toLowerCase() == "output"], - ["file must exist", param.type == "file" && param.must_exist] - ].findAll{it[1]}.collect{it[0]} - - def dflt = null - if (param.default != null) { - if (param.default instanceof List) { - dflt = param.default.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - dflt = param.default.toString() - } - } - def example = null - if (param.example != null) { - if (param.example instanceof List) { - example = param.example.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - example = param.example.toString() - } - } - def min = param.min?.toString() - def max = param.max?.toString() - - def escapeChoice = { choice -> - def s1 = choice.replaceAll("\\n", "\\\\n") - def s2 = s1.replaceAll("\"", """\\\"""") - s2.contains(",") || s2 != choice ? "\"" + s2 + "\"" : s2 - } - def choices = param.choices == null ? - null : - "[ " + param.choices.collect{escapeChoice(it.toString())}.join(", ") + " ]" - - def namedPropsStr = [ - ["type", ([param.type] + unnamedProps).join(", ")], - ["default", dflt], - ["example", example], - ["choices", choices], - ["min", min], - ["max", max] - ] - .findAll{it[1]} - .collect{"\n " + it[0] + ": " + it[1].replaceAll("\n", "\\n")} - .join("") - - def descStr = param.description == null ? - "" : - _paragraphWrap("\n" + param.description.trim(), 80 - 8).join("\n ") - - "\n --" + param.plainName + - namedPropsStr + - descStr -} - -// Based on Helper.generateHelp() in Helper.scala -def _generateHelp(config) { - def fun = config.functionality - - // PART 1: NAME AND VERSION - def nameStr = fun.name + - (fun.version == null ? "" : " " + fun.version) - - // PART 2: DESCRIPTION - def descrStr = fun.description == null ? - "" : - "\n\n" + _paragraphWrap(fun.description.trim(), 80).join("\n") - - // PART 3: Usage - def usageStr = fun.usage == null ? - "" : - "\n\nUsage:\n" + fun.usage.trim() - - // PART 4: Options - def argGroupStrs = fun.allArgumentGroups.collect{argGroup -> - def name = argGroup.name - def descriptionStr = argGroup.description == null ? - "" : - "\n " + _paragraphWrap(argGroup.description.trim(), 80-4).join("\n ") + "\n" - def arguments = argGroup.arguments.collect{arg -> - arg instanceof String ? fun.allArguments.find{it.plainName == arg} : arg - }.findAll{it != null} - def argumentStrs = arguments.collect{param -> _generateArgumentHelp(param)} - - "\n\n$name:" + - descriptionStr + - argumentStrs.join("\n") - } - - // FINAL: combine - def out = nameStr + - descrStr + - usageStr + - argGroupStrs.join("") - - return out -} - -// based on Format._paragraphWrap -def _paragraphWrap(str, maxLength) { - def outLines = [] - str.split("\n").each{par -> - def words = par.split("\\s").toList() - - def word = null - def line = words.pop() - while(!words.isEmpty()) { - word = words.pop() - if (line.length() + word.length() + 1 <= maxLength) { - line = line + " " + word - } else { - outLines.add(line) - line = word - } - } - if (words.isEmpty()) { - outLines.add(line) - } - } - return outLines -} - -def helpMessage(config) { - if (params.containsKey("help") && params.help) { - def mergedConfig = addGlobalArguments(config) - def helpStr = _generateHelp(mergedConfig) - println(helpStr) - exit 0 - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/processConfig.nf' -def processConfig(config) { - // set defaults for arguments - config.functionality.arguments = - (config.functionality.arguments ?: []).collect{_processArgument(it)} - - // set defaults for argument_group arguments - config.functionality.argument_groups = - (config.functionality.argument_groups ?: []).collect{grp -> - grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} - grp - } - - // create combined arguments list - config.functionality.allArguments = - config.functionality.arguments + - config.functionality.argument_groups.collectMany{it.arguments} - - // add missing argument groups (based on Functionality::allArgumentGroups()) - def argGroups = config.functionality.argument_groups - if (argGroups.any{it.name.toLowerCase() == "arguments"}) { - argGroups = argGroups.collect{ grp -> - if (grp.name.toLowerCase() == "arguments") { - grp = grp + [ - arguments: grp.arguments + config.functionality.arguments - ] - } - grp - } - } else { - argGroups = argGroups + [ - name: "Arguments", - arguments: config.functionality.arguments - ] - } - config.functionality.allArgumentGroups = argGroups - - config -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/readConfig.nf' - -def readConfig(file) { - def config = readYaml(file ?: moduleDir.resolve("config.vsh.yaml")) - processConfig(config) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_resolveSiblingIfNotAbsolute.nf' -/** - * Resolve a path relative to the current file. - * - * @param str The path to resolve, as a String. - * @param parentPath The path to resolve relative to, as a Path. - * - * @return The path that may have been resovled, as a Path. - */ -def _resolveSiblingIfNotAbsolute(str, parentPath) { - if (str !instanceof String) { - return str - } - if (!_stringIsAbsolutePath(str)) { - return parentPath.resolveSibling(str) - } else { - return file(str, hidden: true) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_stringIsAbsolutePath.nf' -/** - * Check whether a path as a string is absolute. - * - * In the past, we tried using `file(., relative: true).isAbsolute()`, - * but the 'relative' option was added in 22.10.0. - * - * @param path The path to check, as a String. - * - * @return Whether the path is absolute, as a boolean. - */ -def _stringIsAbsolutePath(path) { - _resolve_URL_PROTOCOL = ~/^([a-zA-Z][a-zA-Z0-9]*:)?\\/.+/ - - assert path instanceof String - return _resolve_URL_PROTOCOL.matcher(path).matches() -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/collectTraces.nf' -class CustomTraceObserver implements nextflow.trace.TraceObserver { - List traces - - CustomTraceObserver(List traces) { - this.traces = traces - } - - @Override - void onProcessComplete(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } - - @Override - void onProcessCached(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } -} - -def collectTraces() { - def traces = Collections.synchronizedList([]) - - // add custom trace observer which stores traces in the traces object - session.observers.add(new CustomTraceObserver(traces)) - - traces -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/deepClone.nf' -/** - * Performs a deep clone of the given object. - * @param x an object - */ -def deepClone(x) { - iterateMap(x, {it instanceof Cloneable ? it.clone() : it}) -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getPublishDir.nf' -def getPublishDir() { - return params.containsKey("publish_dir") ? params.publish_dir : - params.containsKey("publishDir") ? params.publishDir : - null -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getRootDir.nf' - -// Recurse upwards until we find a '.build.yaml' file -def _findBuildYamlFile(pathPossiblySymlink) { - def path = pathPossiblySymlink.toRealPath() - def child = path.resolve(".build.yaml") - if (java.nio.file.Files.isDirectory(path) && java.nio.file.Files.exists(child)) { - return child - } else { - def parent = path.getParent() - if (parent == null) { - return null - } else { - return _findBuildYamlFile(parent) - } - } -} - -// get the root of the target folder -def getRootDir() { - def dir = _findBuildYamlFile(meta.resources_dir) - assert dir != null: "Could not find .build.yaml in the folder structure" - dir.getParent() -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/iterateMap.nf' -/** - * Recursively apply a function over the leaves of an object. - * @param obj The object to iterate over. - * @param fun The function to apply to each value. - * @return The object with the function applied to each value. - */ -def iterateMap(obj, fun) { - if (obj instanceof List && obj !instanceof String) { - return obj.collect{item -> - iterateMap(item, fun) - } - } else if (obj instanceof Map) { - return obj.collectEntries{key, item -> - [key.toString(), iterateMap(item, fun)] - } - } else { - return fun(obj) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/niceView.nf' -/** - * A view for printing the event of each channel as a YAML blob. - * This is useful for debugging. - */ -def niceView() { - workflow niceViewWf { - take: input - main: - output = input - | view{toYamlBlob(it)} - emit: output - } - return niceViewWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readCsv.nf' - -def readCsv(file_path) { - def output = [] - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - - // todo: allow escaped quotes in string - // todo: allow single quotes? - def splitRegex = java.util.regex.Pattern.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''') - def removeQuote = java.util.regex.Pattern.compile('''"(.*)"''') - - def br = java.nio.file.Files.newBufferedReader(inputFile) - - def row = -1 - def header = null - while (br.ready() && header == null) { - def line = br.readLine() - row++ - if (!line.startsWith("#")) { - header = splitRegex.split(line, -1).collect{field -> - m = removeQuote.matcher(field) - m.find() ? m.replaceFirst('$1') : field - } - } - } - assert header != null: "CSV file should contain a header" - - while (br.ready()) { - def line = br.readLine() - row++ - if (line == null) { - br.close() - break - } - - if (!line.startsWith("#")) { - def predata = splitRegex.split(line, -1) - def data = predata.collect{field -> - if (field == "") { - return null - } - m = removeQuote.matcher(field) - if (m.find()) { - return m.replaceFirst('$1') - } else { - return field - } - } - assert header.size() == data.size(): "Row $row should contain the same number as fields as the header" - - def dataMap = [header, data].transpose().collectEntries().findAll{it.value != null} - output.add(dataMap) - } - } - - output -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJson.nf' -def readJson(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parse(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJsonBlob.nf' -def readJsonBlob(str) { - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parseText(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readTaggedYaml.nf' -// Custom constructor to modify how certain objects are parsed from YAML -class CustomConstructor extends org.yaml.snakeyaml.constructor.Constructor { - Path root - - class ConstructPath extends org.yaml.snakeyaml.constructor.AbstractConstruct { - public Object construct(org.yaml.snakeyaml.nodes.Node node) { - String filename = (String) constructScalar(node); - if (root != null) { - return root.resolve(filename); - } - return java.nio.file.Paths.get(filename); - } - } - - CustomConstructor(org.yaml.snakeyaml.LoaderOptions options, Path root) { - super(options) - this.root = root - // Handling !file tag and parse it back to a File type - this.yamlConstructors.put(new org.yaml.snakeyaml.nodes.Tag("!file"), new ConstructPath()) - } -} - -def readTaggedYaml(Path path) { - def options = new org.yaml.snakeyaml.LoaderOptions() - def constructor = new CustomConstructor(options, path.getParent()) - def yaml = new org.yaml.snakeyaml.Yaml(constructor) - return yaml.load(path.text) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYaml.nf' -def readYaml(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYamlBlob.nf' -def readYamlBlob(str) { - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toJsonBlob.nf' -String toJsonBlob(data) { - return groovy.json.JsonOutput.toJson(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toTaggedYamlBlob.nf' -// Custom representer to modify how certain objects are represented in YAML -class CustomRepresenter extends org.yaml.snakeyaml.representer.Representer { - Path relativizer - - class RepresentPath implements org.yaml.snakeyaml.representer.Represent { - public String getFileName(Object obj) { - if (obj instanceof File) { - obj = ((File) obj).toPath(); - } - if (obj !instanceof Path) { - throw new IllegalArgumentException("Object: " + obj + " is not a Path or File"); - } - def path = (Path) obj; - - if (relativizer != null) { - return relativizer.relativize(path).toString() - } else { - return path.toString() - } - } - - public org.yaml.snakeyaml.nodes.Node representData(Object data) { - String filename = getFileName(data); - def tag = new org.yaml.snakeyaml.nodes.Tag("!file"); - return representScalar(tag, filename); - } - } - CustomRepresenter(org.yaml.snakeyaml.DumperOptions options, Path relativizer) { - super(options) - this.relativizer = relativizer - this.representers.put(sun.nio.fs.UnixPath, new RepresentPath()) - this.representers.put(Path, new RepresentPath()) - this.representers.put(File, new RepresentPath()) - } -} - -String toTaggedYamlBlob(data) { - return toRelativeTaggedYamlBlob(data, null) -} -String toRelativeTaggedYamlBlob(data, Path relativizer) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - def representer = new CustomRepresenter(options, relativizer) - def yaml = new org.yaml.snakeyaml.Yaml(representer, options) - return yaml.dump(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toYamlBlob.nf' -String toYamlBlob(data) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - options.setPrettyFlow(true) - def yaml = new org.yaml.snakeyaml.Yaml(options) - def cleanData = iterateMap(data, { it instanceof Path ? it.toString() : it }) - return yaml.dump(cleanData) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeJson.nf' -void writeJson(data, file) { - assert data: "writeJson: data should not be null" - assert file: "writeJson: file should not be null" - file.write(toJsonBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeYaml.nf' -void writeYaml(data, file) { - assert data: "writeYaml: data should not be null" - assert file: "writeYaml: file should not be null" - file.write(toYamlBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/findStates.nf' -def findStates(Map params, Map config) { - // TODO: do a deep clone of config - def auto_config = deepClone(config) - def auto_params = deepClone(params) - - auto_config = auto_config.clone() - // override arguments - auto_config.functionality.argument_groups = [] - auto_config.functionality.arguments = [ - [ - type: "string", - name: "--id", - description: "A dummy identifier", - required: false - ], - [ - type: "file", - name: "--input_states", - example: "/path/to/input/directory/**/state.yaml", - description: "Path to input directory containing the datasets to be integrated.", - required: true, - multiple: true, - multiple_sep: ";" - ], - [ - type: "string", - name: "--filter", - example: "foo/.*/state.yaml", - description: "Regex to filter state files by path.", - required: false - ], - // to do: make this a yaml blob? - [ - type: "string", - name: "--rename_keys", - example: ["newKey1:oldKey1", "newKey2:oldKey2"], - description: "Rename keys in the detected input files. This is useful if the input files do not match the set of input arguments of the workflow.", - required: false, - multiple: true, - multiple_sep: "," - ], - [ - type: "string", - name: "--settings", - example: '{"output_dataset": "dataset.h5ad", "k": 10}', - description: "Global arguments as a JSON glob to be passed to all components.", - required: false - ] - ] - if (!(auto_params.containsKey("id"))) { - auto_params["id"] = "auto" - } - - // run auto config through processConfig once more - auto_config = processConfig(auto_config) - - workflow findStatesWf { - helpMessage(auto_config) - - output_ch = - channelFromParams(auto_params, auto_config) - | flatMap { autoId, args -> - - def globalSettings = args.settings ? readYamlBlob(args.settings) : [:] - - // look for state files in input dir - def stateFiles = args.input_states - - // filter state files by regex - if (args.filter) { - stateFiles = stateFiles.findAll{ stateFile -> - def stateFileStr = stateFile.toString() - def matcher = stateFileStr =~ args.filter - matcher.matches()} - } - - // read in states - def states = stateFiles.collect { stateFile -> - def state_ = readTaggedYaml(stateFile) - [state_.id, state_] - } - - // construct renameMap - if (args.rename_keys) { - def renameMap = args.rename_keys.collectEntries{renameString -> - def split = renameString.split(":") - assert split.size() == 2: "Argument 'rename_keys' should be of the form 'newKey:oldKey,newKey:oldKey'" - split - } - - // rename keys in state, only let states through which have all keys - // also add global settings - states = states.collectMany{id, state -> - def newState = [:] - - for (key in renameMap.keySet()) { - def origKey = renameMap[key] - if (!(state.containsKey(origKey))) { - return [] - } - newState[key] = state[origKey] - } - - [[id, globalSettings + newState]] - } - } - - states - } - emit: - output_ch - } - - return findStatesWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/joinStates.nf' -def joinStates(Closure apply_) { - workflow joinStatesWf { - take: input_ch - main: - output_ch = input_ch - | toSortedList - | filter{ it.size() > 0 } - | map{ tups -> - def ids = tups.collect{it[0]} - def states = tups.collect{it[1]} - apply_(ids, states) - } - - emit: output_ch - } - return joinStatesWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/publishStates.nf' -def collectFiles(obj) { - if (obj instanceof java.io.File || obj instanceof Path) { - return [obj] - } else if (obj instanceof List && obj !instanceof String) { - return obj.collectMany{item -> - collectFiles(item) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectFiles(item) - } - } else { - return [] - } -} - -/** - * Recurse through a state and collect all input files and their target output filenames. - * @param obj The state to recurse through. - * @param prefix The prefix to prepend to the output filenames. - */ -def collectInputOutputPaths(obj, prefix) { - if (obj instanceof File || obj instanceof Path) { - def path = obj instanceof Path ? obj : obj.toPath() - def ext = path.getFileName().toString().find("\\.[^\\.]+\$") ?: "" - def newFilename = prefix + ext - return [[obj, newFilename]] - } else if (obj instanceof List && obj !instanceof String) { - return obj.withIndex().collectMany{item, ix -> - collectInputOutputPaths(item, prefix + "_" + ix) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectInputOutputPaths(item, prefix + "." + key) - } - } else { - return [] - } -} - -def publishStates(Map args) { - def key_ = args.get("key") - def yamlTemplate_ = args.get("output_state", args.get("outputState", '$id.$key.state.yaml')) - - assert key_ != null : "publishStates: key must be specified" - - workflow publishStatesWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] - - // the input files and the target output filenames - def inputOutputFiles_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() - def inputFiles_ = inputOutputFiles_[0] - def outputFiles_ = inputOutputFiles_[1] - - def yamlFilename = yamlTemplate_ - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - - // TODO: do the pathnames in state_ match up with the outputFiles_? - - // convert state to yaml blob - def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesWf -} -process publishStatesProc { - // todo: check publishpath? - publishDir path: "${getPublishDir()}/", mode: "copy" - tag "$id" - input: - tuple val(id), val(yamlBlob), val(yamlFile), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) - output: - tuple val(id), path{[yamlFile] + outputFiles} - script: - def copyCommands = [ - inputFiles instanceof List ? inputFiles : [inputFiles], - outputFiles instanceof List ? outputFiles : [outputFiles] - ] - .transpose() - .collectMany{infile, outfile -> - if (infile.toString() != outfile.toString()) { - [ - "[ -d \"\$(dirname '${outfile.toString()}')\" ] || mkdir -p \"\$(dirname '${outfile.toString()}')\"", - "cp -r '${infile.toString()}' '${outfile.toString()}'" - ] - } else { - // no need to copy if infile is the same as outfile - [] - } - } - """ - mkdir -p "\$(dirname '${yamlFile}')" - echo "Storing state as yaml" - echo '${yamlBlob}' > '${yamlFile}' - echo "Copying output files to destination folder" - ${copyCommands.join("\n ")} - """ -} - - -// this assumes that the state contains no other values other than those specified in the config -def publishStatesByConfig(Map args) { - def config = args.get("config") - assert config != null : "publishStatesByConfig: config must be specified" - - def key_ = args.get("key", config.functionality.name) - assert key_ != null : "publishStatesByConfig: key must be specified" - - workflow publishStatesSimpleWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] // e.g. [output: new File("myoutput.h5ad"), k: 10] - def origState_ = tup[2] // e.g. [output: '$id.$key.foo.h5ad'] - - // TODO: allow overriding the state.yaml template - // TODO TODO: if auto.publish == "state", add output_state as an argument - def yamlTemplate = params.containsKey("output_state") ? params.output_state : '$id.$key.state.yaml' - def yamlFilename = yamlTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() - - // the processed state is a list of [key, value, srcPath, destPath] tuples, where - // - key, value is part of the state to be saved to disk - // - srcPath and destPath are lists of files to be copied from src to dest - def processedState = - config.functionality.allArguments - .findAll { it.direction == "output" } - .collectMany { par -> - def plainName_ = par.plainName - // if the state does not contain the key, it's an - // optional argument for which the component did - // not generate any output - if (!state_.containsKey(plainName_)) { - return [] - } - def value = state_[plainName_] - // if the parameter is not a file, it should be stored - // in the state as-is, but is not something that needs - // to be copied from the source path to the dest path - if (par.type != "file") { - return [[key: plainName_, value: value, srcPath: [], destPath: []]] - } - // if the orig state does not contain this filename, - // it's an optional argument for which the user specified - // that it should not be returned as a state - if (!origState_.containsKey(plainName_)) { - return [] - } - def filenameTemplate = origState_[plainName_] - // if the pararameter is multiple: true, fetch the template - if (par.multiple && filenameTemplate instanceof List) { - filenameTemplate = filenameTemplate[0] - } - // instantiate the template - def filename = filenameTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - if (par.multiple) { - // if the parameter is multiple: true, the filename - // should contain a wildcard '*' that is replaced with - // the index of the file - assert filename.contains("*") : "Module '${key_}' id '${id_}': Multiple output files specified, but no wildcard '*' in the filename: ${filename}" - def outputPerFile = value.withIndex().collect{ val, ix -> - def value_ = java.nio.file.Paths.get(filename.replace("*", ix.toString())) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = val instanceof File ? val.toPath() : val - [value: value_, srcPath: srcPath, destPath: destPath] - } - def transposedOutputs = ["value", "srcPath", "destPath"].collectEntries{ key -> - [key, outputPerFile.collect{dic -> dic[key]}] - } - return [[key: plainName_] + transposedOutputs] - } else { - def value_ = java.nio.file.Paths.get(filename) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = value instanceof File ? value.toPath() : value - return [[key: plainName_, value: value_, srcPath: [srcPath], destPath: [filename]]] - } - } - - def updatedState_ = processedState.collectEntries{[it.key, it.value]} - def inputFiles_ = processedState.collectMany{it.srcPath} - def outputFiles_ = processedState.collectMany{it.destPath} - - // convert state to yaml blob - def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesSimpleWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/setState.nf' -def setState(fun) { - assert fun instanceof Closure || fun instanceof Map || fun instanceof List : - "Error in setState: Expected process argument to be a Closure, a Map, or a List. Found: class ${fun.getClass()}" - - // if fun is a List, convert to map - if (fun instanceof List) { - // check whether fun is a list[string] - assert fun.every{it instanceof CharSequence} : "Error in setState: argument is a List, but not all elements are Strings" - fun = fun.collectEntries{[it, it]} - } - - // if fun is a map, convert to closure - if (fun instanceof Map) { - // check whether fun is a map[string, string] - assert fun.values().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all values are Strings" - assert fun.keySet().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all keys are Strings" - def funMap = fun.clone() - // turn the map into a closure to be used later on - fun = { id_, state_ -> - assert state_ instanceof Map : "Error in setState: the state is not a Map" - funMap.collectMany{newkey, origkey -> - if (state_.containsKey(origkey)) { - [[newkey, state_[origkey]]] - } else { - [] - } - }.collectEntries() - } - } - - map { tup -> - def id = tup[0] - def state = tup[1] - def unfilteredState = fun(id, state) - def newState = unfilteredState.findAll{key, val -> val != null} - [id, newState] + tup.drop(2) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processAuto.nf' -// TODO: unit test processAuto -def processAuto(Map auto) { - // remove null values - auto = auto.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = ["simplifyInput", "simplifyOutput", "transcript", "publish"] - def unexpectedKeys = auto.keySet() - expectedKeys - assert unexpectedKeys.isEmpty(), "unexpected keys in auto: '${unexpectedKeys.join("', '")}'" - - // check auto.simplifyInput - assert auto.simplifyInput instanceof Boolean, "auto.simplifyInput must be a boolean" - - // check auto.simplifyOutput - assert auto.simplifyOutput instanceof Boolean, "auto.simplifyOutput must be a boolean" - - // check auto.transcript - assert auto.transcript instanceof Boolean, "auto.transcript must be a boolean" - - // check auto.publish - assert auto.publish instanceof Boolean || auto.publish == "state", "auto.publish must be a boolean or 'state'" - - return auto.subMap(expectedKeys) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processDirectives.nf' -def assertMapKeys(map, expectedKeys, requiredKeys, mapName) { - assert map instanceof Map : "Expected argument '$mapName' to be a Map. Found: class ${map.getClass()}" - map.forEach { key, val -> - assert key in expectedKeys : "Unexpected key '$key' in ${mapName ? mapName + " " : ""}map" - } - requiredKeys.forEach { requiredKey -> - assert map.containsKey(requiredKey) : "Missing required key '$key' in ${mapName ? mapName + " " : ""}map" - } -} - -// TODO: unit test processDirectives -def processDirectives(Map drctv) { - // remove null values - drctv = drctv.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = [ - "accelerator", "afterScript", "beforeScript", "cache", "conda", "container", "containerOptions", "cpus", "disk", "echo", "errorStrategy", "executor", "machineType", "maxErrors", "maxForks", "maxRetries", "memory", "module", "penv", "pod", "publishDir", "queue", "label", "scratch", "storeDir", "stageInMode", "stageOutMode", "tag", "time" - ] - def unexpectedKeys = drctv.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Unexpected keys in process directive: '${unexpectedKeys.join("', '")}'" - - /* DIRECTIVE accelerator - accepted examples: - - [ limit: 4, type: "nvidia-tesla-k80" ] - */ - if (drctv.containsKey("accelerator")) { - assertMapKeys(drctv["accelerator"], ["type", "limit", "request", "runtime"], [], "accelerator") - } - - /* DIRECTIVE afterScript - accepted examples: - - "source /cluster/bin/cleanup" - */ - if (drctv.containsKey("afterScript")) { - assert drctv["afterScript"] instanceof CharSequence - } - - /* DIRECTIVE beforeScript - accepted examples: - - "source /cluster/bin/setup" - */ - if (drctv.containsKey("beforeScript")) { - assert drctv["beforeScript"] instanceof CharSequence - } - - /* DIRECTIVE cache - accepted examples: - - true - - false - - "deep" - - "lenient" - */ - if (drctv.containsKey("cache")) { - assert drctv["cache"] instanceof CharSequence || drctv["cache"] instanceof Boolean - if (drctv["cache"] instanceof CharSequence) { - assert drctv["cache"] in ["deep", "lenient"] : "Unexpected value for cache" - } - } - - /* DIRECTIVE conda - accepted examples: - - "bwa=0.7.15" - - "bwa=0.7.15 fastqc=0.11.5" - - ["bwa=0.7.15", "fastqc=0.11.5"] - */ - if (drctv.containsKey("conda")) { - if (drctv["conda"] instanceof List) { - drctv["conda"] = drctv["conda"].join(" ") - } - assert drctv["conda"] instanceof CharSequence - } - - /* DIRECTIVE container - accepted examples: - - "foo/bar:tag" - - [ registry: "reg", image: "im", tag: "ta" ] - is transformed to "reg/im:ta" - - [ image: "im" ] - is transformed to "im:latest" - */ - if (drctv.containsKey("container")) { - assert drctv["container"] instanceof Map || drctv["container"] instanceof CharSequence - if (drctv["container"] instanceof Map) { - def m = drctv["container"] - assertMapKeys(m, [ "registry", "image", "tag" ], ["image"], "container") - def part1 = - System.getenv('OVERRIDE_CONTAINER_REGISTRY') ? System.getenv('OVERRIDE_CONTAINER_REGISTRY') + "/" : - params.containsKey("override_container_registry") ? params["override_container_registry"] + "/" : // todo: remove? - m.registry ? m.registry + "/" : - "" - def part2 = m.image - def part3 = m.tag ? ":" + m.tag : ":latest" - drctv["container"] = part1 + part2 + part3 - } - } - - /* DIRECTIVE containerOptions - accepted examples: - - "--foo bar" - - ["--foo bar", "-f b"] - */ - if (drctv.containsKey("containerOptions")) { - if (drctv["containerOptions"] instanceof List) { - drctv["containerOptions"] = drctv["containerOptions"].join(" ") - } - assert drctv["containerOptions"] instanceof CharSequence - } - - /* DIRECTIVE cpus - accepted examples: - - 1 - - 10 - */ - if (drctv.containsKey("cpus")) { - assert drctv["cpus"] instanceof Integer - } - - /* DIRECTIVE disk - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("disk")) { - assert drctv["disk"] instanceof CharSequence - // assert drctv["disk"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE echo - accepted examples: - - true - - false - */ - if (drctv.containsKey("echo")) { - assert drctv["echo"] instanceof Boolean - } - - /* DIRECTIVE errorStrategy - accepted examples: - - "terminate" - - "finish" - */ - if (drctv.containsKey("errorStrategy")) { - assert drctv["errorStrategy"] instanceof CharSequence - assert drctv["errorStrategy"] in ["terminate", "finish", "ignore", "retry"] : "Unexpected value for errorStrategy" - } - - /* DIRECTIVE executor - accepted examples: - - "local" - - "sge" - */ - if (drctv.containsKey("executor")) { - assert drctv["executor"] instanceof CharSequence - assert drctv["executor"] in ["local", "sge", "uge", "lsf", "slurm", "pbs", "pbspro", "moab", "condor", "nqsii", "ignite", "k8s", "awsbatch", "google-pipelines"] : "Unexpected value for executor" - } - - /* DIRECTIVE machineType - accepted examples: - - "n1-highmem-8" - */ - if (drctv.containsKey("machineType")) { - assert drctv["machineType"] instanceof CharSequence - } - - /* DIRECTIVE maxErrors - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxErrors")) { - assert drctv["maxErrors"] instanceof Integer - } - - /* DIRECTIVE maxForks - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxForks")) { - assert drctv["maxForks"] instanceof Integer - } - - /* DIRECTIVE maxRetries - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxRetries")) { - assert drctv["maxRetries"] instanceof Integer - } - - /* DIRECTIVE memory - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("memory")) { - assert drctv["memory"] instanceof CharSequence - // assert drctv["memory"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE module - accepted examples: - - "ncbi-blast/2.2.27" - - "ncbi-blast/2.2.27:t_coffee/10.0" - - ["ncbi-blast/2.2.27", "t_coffee/10.0"] - */ - if (drctv.containsKey("module")) { - if (drctv["module"] instanceof List) { - drctv["module"] = drctv["module"].join(":") - } - assert drctv["module"] instanceof CharSequence - } - - /* DIRECTIVE penv - accepted examples: - - "smp" - */ - if (drctv.containsKey("penv")) { - assert drctv["penv"] instanceof CharSequence - } - - /* DIRECTIVE pod - accepted examples: - - [ label: "key", value: "val" ] - - [ annotation: "key", value: "val" ] - - [ env: "key", value: "val" ] - - [ [label: "l", value: "v"], [env: "e", value: "v"]] - */ - if (drctv.containsKey("pod")) { - if (drctv["pod"] instanceof Map) { - drctv["pod"] = [ drctv["pod"] ] - } - assert drctv["pod"] instanceof List - drctv["pod"].forEach { pod -> - assert pod instanceof Map - // TODO: should more checks be added? - // See https://www.nextflow.io/docs/latest/process.html?highlight=directives#pod - // e.g. does it contain 'label' and 'value', or 'annotation' and 'value', or ...? - } - } - - /* DIRECTIVE publishDir - accepted examples: - - [] - - [ [ path: "foo", enabled: true ], [ path: "bar", enabled: false ] ] - - "/path/to/dir" - is transformed to [[ path: "/path/to/dir" ]] - - [ path: "/path/to/dir", mode: "cache" ] - is transformed to [[ path: "/path/to/dir", mode: "cache" ]] - */ - // TODO: should we also look at params["publishDir"]? - if (drctv.containsKey("publishDir")) { - def pblsh = drctv["publishDir"] - - // check different options - assert pblsh instanceof List || pblsh instanceof Map || pblsh instanceof CharSequence - - // turn into list if not already so - // for some reason, 'if (!pblsh instanceof List) pblsh = [ pblsh ]' doesn't work. - pblsh = pblsh instanceof List ? pblsh : [ pblsh ] - - // check elements of publishDir - pblsh = pblsh.collect{ elem -> - // turn into map if not already so - elem = elem instanceof CharSequence ? [ path: elem ] : elem - - // check types and keys - assert elem instanceof Map : "Expected publish argument '$elem' to be a String or a Map. Found: class ${elem.getClass()}" - assertMapKeys(elem, [ "path", "mode", "overwrite", "pattern", "saveAs", "enabled" ], ["path"], "publishDir") - - // check elements in map - assert elem.containsKey("path") - assert elem["path"] instanceof CharSequence - if (elem.containsKey("mode")) { - assert elem["mode"] instanceof CharSequence - assert elem["mode"] in [ "symlink", "rellink", "link", "copy", "copyNoFollow", "move" ] - } - if (elem.containsKey("overwrite")) { - assert elem["overwrite"] instanceof Boolean - } - if (elem.containsKey("pattern")) { - assert elem["pattern"] instanceof CharSequence - } - if (elem.containsKey("saveAs")) { - assert elem["saveAs"] instanceof CharSequence //: "saveAs as a Closure is currently not supported. Surround your closure with single quotes to get the desired effect. Example: '\{ foo \}'" - } - if (elem.containsKey("enabled")) { - assert elem["enabled"] instanceof Boolean - } - - // return final result - elem - } - // store final directive - drctv["publishDir"] = pblsh - } - - /* DIRECTIVE queue - accepted examples: - - "long" - - "short,long" - - ["short", "long"] - */ - if (drctv.containsKey("queue")) { - if (drctv["queue"] instanceof List) { - drctv["queue"] = drctv["queue"].join(",") - } - assert drctv["queue"] instanceof CharSequence - } - - /* DIRECTIVE label - accepted examples: - - "big_mem" - - "big_cpu" - - ["big_mem", "big_cpu"] - */ - if (drctv.containsKey("label")) { - if (drctv["label"] instanceof CharSequence) { - drctv["label"] = [ drctv["label"] ] - } - assert drctv["label"] instanceof List - drctv["label"].forEach { label -> - assert label instanceof CharSequence - // assert label.matches("[a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?") - // ^ does not allow closures - } - } - - /* DIRECTIVE scratch - accepted examples: - - true - - "/path/to/scratch" - - '$MY_PATH_TO_SCRATCH' - - "ram-disk" - */ - if (drctv.containsKey("scratch")) { - assert drctv["scratch"] == true || drctv["scratch"] instanceof CharSequence - } - - /* DIRECTIVE storeDir - accepted examples: - - "/path/to/storeDir" - */ - if (drctv.containsKey("storeDir")) { - assert drctv["storeDir"] instanceof CharSequence - } - - /* DIRECTIVE stageInMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageInMode")) { - assert drctv["stageInMode"] instanceof CharSequence - assert drctv["stageInMode"] in ["copy", "link", "symlink", "rellink"] - } - - /* DIRECTIVE stageOutMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageOutMode")) { - assert drctv["stageOutMode"] instanceof CharSequence - assert drctv["stageOutMode"] in ["copy", "move", "rsync"] - } - - /* DIRECTIVE tag - accepted examples: - - "foo" - - '$id' - */ - if (drctv.containsKey("tag")) { - assert drctv["tag"] instanceof CharSequence - } - - /* DIRECTIVE time - accepted examples: - - "1h" - - "2days" - - "1day 6hours 3minutes 30seconds" - */ - if (drctv.containsKey("time")) { - assert drctv["time"] instanceof CharSequence - // todo: validation regex? - } - - return drctv -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processWorkflowArgs.nf' -def processWorkflowArgs(Map args, Map defaultWfArgs, Map meta) { - // override defaults with args - def workflowArgs = defaultWfArgs + args - - // check whether 'key' exists - assert workflowArgs.containsKey("key") : "Error in module '${meta.config.functionality.name}': key is a required argument" - - // if 'key' is a closure, apply it to the original key - if (workflowArgs["key"] instanceof Closure) { - workflowArgs["key"] = workflowArgs["key"](meta.config.functionality.name) - } - def key = workflowArgs["key"] - assert key instanceof CharSequence : "Expected process argument 'key' to be a String. Found: class ${key.getClass()}" - assert key ==~ /^[a-zA-Z_]\w*$/ : "Error in module '$key': Expected process argument 'key' to consist of only letters, digits or underscores. Found: ${key}" - - // check for any unexpected keys - def expectedKeys = ["key", "directives", "auto", "map", "mapId", "mapData", "mapPassthrough", "filter", "runIf", "fromState", "toState", "args", "renameKeys", "debug"] - def unexpectedKeys = workflowArgs.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Error in module '$key': unexpected arguments to the '.run()' function: '${unexpectedKeys.join("', '")}'" - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("directives") : "Error in module '$key': directives is a required argument" - assert workflowArgs["directives"] instanceof Map : "Error in module '$key': Expected process argument 'directives' to be a Map. Found: class ${workflowArgs['directives'].getClass()}" - workflowArgs["directives"] = processDirectives(defaultWfArgs.directives + workflowArgs["directives"]) - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("auto") : "Error in module '$key': auto is a required argument" - assert workflowArgs["auto"] instanceof Map : "Error in module '$key': Expected process argument 'auto' to be a Map. Found: class ${workflowArgs['auto'].getClass()}" - workflowArgs["auto"] = processAuto(defaultWfArgs.auto + workflowArgs["auto"]) - - // auto define publish, if so desired - if (workflowArgs.auto.publish == true && (workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : [:]).isEmpty()) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.publish is true, params.publish_dir needs to be defined.\n" + - // " Example: params.publish_dir = \"./output/\"" - def publishDir = getPublishDir() - - if (publishDir != null) { - workflowArgs.directives.publishDir = [[ - path: publishDir, - saveAs: "{ it.startsWith('.') ? null : it }", // don't publish hidden files, by default - mode: "copy" - ]] - } - } - - // auto define transcript, if so desired - if (workflowArgs.auto.transcript == true) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("transcriptsDir") || params.containsKey("transcripts_dir") || params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.transcript is true, either params.transcripts_dir or params.publish_dir needs to be defined.\n" + - // " Example: params.transcripts_dir = \"./transcripts/\"" - def transcriptsDir = - params.containsKey("transcripts_dir") ? params.transcripts_dir : - params.containsKey("transcriptsDir") ? params.transcriptsDir : - params.containsKey("publish_dir") ? params.publish_dir + "/_transcripts" : - params.containsKey("publishDir") ? params.publishDir + "/_transcripts" : - null - if (transcriptsDir != null) { - def timestamp = nextflow.Nextflow.getSession().getWorkflowMetadata().start.format('yyyy-MM-dd_HH-mm-ss') - def transcriptsPublishDir = [ - path: "$transcriptsDir/$timestamp/\${task.process.replaceAll(':', '-')}/\${id}/", - saveAs: "{ it.startsWith('.') ? it.replaceAll('^.', '') : null }", - mode: "copy" - ] - def publishDirs = workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : null ? workflowArgs.directives.publishDir : [] - workflowArgs.directives.publishDir = publishDirs + transcriptsPublishDir - } - } - - // if this is a stubrun, remove certain directives? - if (workflow.stubRun) { - workflowArgs.directives.keySet().removeAll(["publishDir", "cpus", "memory", "label"]) - } - - for (nam in ["map", "mapId", "mapData", "mapPassthrough", "filter", "runIf"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam]) { - assert workflowArgs[nam] instanceof Closure : "Error in module '$key': Expected process argument '$nam' to be null or a Closure. Found: class ${workflowArgs[nam].getClass()}" - } - } - - // TODO: should functions like 'map', 'mapId', 'mapData', 'mapPassthrough' be deprecated as well? - for (nam in ["map", "mapData", "mapPassthrough", "renameKeys"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam] != null) { - log.warn "module '$key': workflow argument '$nam' is deprecated and will be removed in Viash 0.9.0. Please use 'fromState' and 'toState' instead." - } - } - - // check fromState - workflowArgs["fromState"] = _processFromState(workflowArgs.get("fromState"), key, meta.config) - - // check toState - workflowArgs["toState"] = _processToState(workflowArgs.get("toState"), key, meta.config) - - // return output - return workflowArgs -} - -def _processFromState(fromState, key_, config_) { - assert fromState == null || fromState instanceof Closure || fromState instanceof Map || fromState instanceof List : - "Error in module '$key_': Expected process argument 'fromState' to be null, a Closure, a Map, or a List. Found: class ${fromState.getClass()}" - if (fromState == null) { - return null - } - - // if fromState is a List, convert to map - if (fromState instanceof List) { - // check whether fromstate is a list[string] - assert fromState.every{it instanceof CharSequence} : "Error in module '$key_': fromState is a List, but not all elements are Strings" - fromState = fromState.collectEntries{[it, it]} - } - - // if fromState is a map, convert to closure - if (fromState instanceof Map) { - // check whether fromstate is a map[string, string] - assert fromState.values().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all values are Strings" - assert fromState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all keys are Strings" - def fromStateMap = fromState.clone() - def requiredInputNames = meta.config.functionality.allArguments.findAll{it.required && it.direction == "Input"}.collect{it.plainName} - // turn the map into a closure to be used later on - fromState = { it -> - def state = it[1] - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def data = fromStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (state.containsKey(origkey)) { - [[newkey, state[origkey]]] - } else if (!requiredInputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': fromState key '$origkey' not found in current state") - } - }.collectEntries() - data - } - } - - return fromState -} - -def _processToState(toState, key_, config_) { - if (toState == null) { - toState = { tup -> tup[1] } - } - - // toState should be a closure, map[string, string], or list[string] - assert toState instanceof Closure || toState instanceof Map || toState instanceof List : - "Error in module '$key_': Expected process argument 'toState' to be a Closure, a Map, or a List. Found: class ${toState.getClass()}" - - // if toState is a List, convert to map - if (toState instanceof List) { - // check whether toState is a list[string] - assert toState.every{it instanceof CharSequence} : "Error in module '$key_': toState is a List, but not all elements are Strings" - toState = toState.collectEntries{[it, it]} - } - - // if toState is a map, convert to closure - if (toState instanceof Map) { - // check whether toState is a map[string, string] - assert toState.values().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all values are Strings" - assert toState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all keys are Strings" - def toStateMap = toState.clone() - def requiredOutputNames = config_.functionality.allArguments.findAll{it.required && it.direction == "Output"}.collect{it.plainName} - // turn the map into a closure to be used later on - toState = { it -> - def output = it[1] - def state = it[2] - assert output instanceof Map : "Error in module '$key_': the output is not a Map" - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def extraEntries = toStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (output.containsKey(origkey)) { - [[newkey, output[origkey]]] - } else if (!requiredOutputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': toState key '$origkey' not found in current output") - } - }.collectEntries() - state + extraEntries - } - } - - return toState -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/workflowFactory.nf' -def _debug(workflowArgs, debugKey) { - if (workflowArgs.debug) { - view { "process '${workflowArgs.key}' $debugKey tuple: $it" } - } else { - map { it } - } -} - -// depends on: innerWorkflowFactory -def workflowFactory(Map args, Map defaultWfArgs, Map meta) { - def workflowArgs = processWorkflowArgs(args, defaultWfArgs, meta) - def key_ = workflowArgs["key"] - - workflow workflowInstance { - take: input_ - - main: - chModified = input_ - | checkUniqueIds([:]) - | _debug(workflowArgs, "input") - | map { tuple -> - tuple = deepClone(tuple) - - if (workflowArgs.map) { - tuple = workflowArgs.map(tuple) - } - if (workflowArgs.mapId) { - tuple[0] = workflowArgs.mapId(tuple[0]) - } - if (workflowArgs.mapData) { - tuple[1] = workflowArgs.mapData(tuple[1]) - } - if (workflowArgs.mapPassthrough) { - tuple = tuple.take(2) + workflowArgs.mapPassthrough(tuple.drop(2)) - } - - // check tuple - assert tuple instanceof List : - "Error in module '${key_}': element in channel should be a tuple [id, data, ...otherargs...]\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: List. Found: tuple.getClass() is ${tuple.getClass()}" - assert tuple.size() >= 2 : - "Error in module '${key_}': expected length of tuple in input channel to be two or greater.\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: tuple.size() == ${tuple.size()}" - - // check id field - assert tuple[0] instanceof CharSequence : - "Error in module '${key_}': first element of tuple in channel should be a String\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: ${tuple[0]}" - - // match file to input file - if (workflowArgs.auto.simplifyInput && (tuple[1] instanceof Path || tuple[1] instanceof List)) { - def inputFiles = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - - assert inputFiles.size() == 1 : - "Error in module '${key_}' id '${tuple[0]}'.\n" + - " Anonymous file inputs are only allowed when the process has exactly one file input.\n" + - " Expected: inputFiles.size() == 1. Found: inputFiles.size() is ${inputFiles.size()}" - - tuple[1] = [[ inputFiles[0].plainName, tuple[1] ]].collectEntries() - } - - // check data field - assert tuple[1] instanceof Map : - "Error in module '${key_}' id '${tuple[0]}': second element of tuple in channel should be a Map\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // rename keys of data field in tuple - if (workflowArgs.renameKeys) { - assert workflowArgs.renameKeys instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class: Map. Found: renameKeys.getClass() is ${workflowArgs.renameKeys.getClass()}" - assert tuple[1] instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // TODO: allow renameKeys to be a function? - workflowArgs.renameKeys.each { newKey, oldKey -> - assert newKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of newKey: String. Found: newKey.getClass() is ${newKey.getClass()}" - assert oldKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of oldKey: String. Found: oldKey.getClass() is ${oldKey.getClass()}" - assert tuple[1].containsKey(oldKey) : - "Error renaming data keys in module '${key}' id '${tuple[0]}'.\n" + - " Key '$oldKey' is missing in the data map. tuple[1].keySet() is '${tuple[1].keySet()}'" - tuple[1].put(newKey, tuple[1][oldKey]) - } - tuple[1].keySet().removeAll(workflowArgs.renameKeys.collect{ newKey, oldKey -> oldKey }) - } - tuple - } - - chModifiedFiltered = workflowArgs.filter ? - chModified | filter{workflowArgs.filter(it)} : - chModified - - if (workflowArgs.runIf) { - runIfBranch = chModifiedFiltered.branch{ tup -> - run: workflowArgs.runIf(tup[0], tup[1]) - passthrough: true - } - chRun = runIfBranch.run - chPassthrough = runIfBranch.passthrough - } else { - chRun = chModifiedFiltered - chPassthrough = Channel.empty() - } - - chArgs = workflowArgs.fromState ? - chRun | map{ - def new_data = workflowArgs.fromState(it.take(2)) - [it[0], new_data] - } : - chRun | map {tup -> tup.take(2)} - - // fill in defaults - chArgsWithDefaults = chArgs - | map { tuple -> - def id_ = tuple[0] - def data_ = tuple[1] - - // TODO: could move fromState to here - - // fetch default params from functionality - def defaultArgs = meta.config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - // fetch overrides in params - def paramArgs = meta.config.functionality.allArguments - .findAll { par -> - def argKey = key_ + "__" + par.plainName - params.containsKey(argKey) - } - .collectEntries { [ it.plainName, params[key_ + "__" + it.plainName] ] } - - // fetch overrides in data - def dataArgs = meta.config.functionality.allArguments - .findAll { data_.containsKey(it.plainName) } - .collectEntries { [ it.plainName, data_[it.plainName] ] } - - // combine params - def combinedArgs = defaultArgs + paramArgs + workflowArgs.args + dataArgs - - // remove arguments with explicit null values - combinedArgs - .removeAll{_, val -> val == null || val == "viash_no_value" || val == "force_null"} - - combinedArgs = _processInputValues(combinedArgs, meta.config, id_, key_) - - [id_, combinedArgs] + tuple.drop(2) - } - - // TODO: move some of the _meta.join_id wrangling to the safeJoin() function. - chInitialOutput = chArgsWithDefaults - | _debug(workflowArgs, "processed") - // run workflow - | innerWorkflowFactory(workflowArgs) - // check output tuple - | map { id_, output_ -> - - // see if output map contains metadata - def meta_ = - output_ instanceof Map && output_.containsKey("_meta") ? - output_["_meta"] : - [:] - def join_id = meta_.join_id ?: id_ - - // remove metadata - output_ = output_.findAll{k, v -> k != "_meta"} - - // check value types - output_ = _processOutputValues(output_, meta.config, id_, key_) - - // simplify output if need be - if (workflowArgs.auto.simplifyOutput && output_.size() == 1) { - output_ = output_.values()[0] - } - - [join_id, id_, output_] - } - // | view{"chInitialOutput: ${it.take(3)}"} - - // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] - chNewState = safeJoin(chInitialOutput, chModifiedFiltered, key_) - // input tuple format: [join_id, id, output, prev_state, ...] - // output tuple format: [join_id, id, new_state, ...] - | map{ tup -> - def new_state = workflowArgs.toState(tup.drop(1).take(3)) - tup.take(2) + [new_state] + tup.drop(4) - } - - if (workflowArgs.auto.publish == "state") { - chPublish = chNewState - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [join_id, id, new_state] - | map{ tup -> - tup.take(3) - } - - safeJoin(chPublish, chArgsWithDefaults, key_) - // input tuple format: [join_id, id, new_state, orig_state, ...] - // output tuple format: [id, new_state, orig_state] - | map { tup -> - tup.drop(1).take(3) - } - | publishStatesByConfig(key: key_, config: meta.config) - } - - // remove join_id and meta - chReturn = chNewState - | map { tup -> - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [id, new_state, ...] - tup.drop(1) - } - | _debug(workflowArgs, "output") - | concat(chPassthrough) - - emit: chReturn - } - - def wf = workflowInstance.cloneWithName(key_) - - // add factory function - wf.metaClass.run = { runArgs -> - workflowFactory(runArgs, workflowArgs, meta) - } - // add config to module for later introspection - wf.metaClass.config = meta.config - - return wf -} - -nextflow.enable.dsl=2 - -// START COMPONENT-SPECIFIC CODE - -// create meta object -meta = [ - "resources_dir": moduleDir.toRealPath().normalize(), - "config": processConfig(readJsonBlob('''{ - "functionality" : { - "name" : "remove_comments", - "namespace" : "template", - "version" : "0.2.2", - "arguments" : [ - { - "type" : "file", - "name" : "--input", - "alternatives" : [ - "-i" - ], - "example" : [ - "file.tsv" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "input", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - }, - { - "type" : "file", - "name" : "--output", - "alternatives" : [ - "-o" - ], - "example" : [ - "file.tsv" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "output", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - } - ], - "resources" : [ - { - "type" : "bash_script", - "path" : "script.sh", - "is_executable" : true, - "parent" : "file:/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/" - } - ], - "test_resources" : [ - { - "type" : "bash_script", - "path" : "test.sh", - "is_executable" : true, - "parent" : "file:/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/" - } - ], - "status" : "enabled", - "set_wd_to_resources_dir" : false - }, - "platforms" : [ - { - "type" : "docker", - "id" : "docker", - "image" : "ubuntu:20.04", - "target_organization" : "viash-io/viash_project_template", - "target_registry" : "ghcr.io", - "namespace_separator" : "/", - "resolve_volume" : "Automatic", - "chown" : true, - "setup_strategy" : "ifneedbepullelsecachedbuild", - "target_image_source" : "https://github.com/viash-io/viash_project_template" - }, - { - "type" : "nextflow", - "id" : "nextflow", - "directives" : { - "tag" : "$id" - }, - "auto" : { - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false - }, - "config" : { - "labels" : { - "mem1gb" : "memory = 1.GB", - "mem2gb" : "memory = 2.GB", - "mem4gb" : "memory = 4.GB", - "mem8gb" : "memory = 8.GB", - "mem16gb" : "memory = 16.GB", - "mem32gb" : "memory = 32.GB", - "mem64gb" : "memory = 64.GB", - "mem128gb" : "memory = 128.GB", - "mem256gb" : "memory = 256.GB", - "mem512gb" : "memory = 512.GB", - "mem1tb" : "memory = 1.TB", - "mem2tb" : "memory = 2.TB", - "mem4tb" : "memory = 4.TB", - "mem8tb" : "memory = 8.TB", - "mem16tb" : "memory = 16.TB", - "mem32tb" : "memory = 32.TB", - "mem64tb" : "memory = 64.TB", - "mem128tb" : "memory = 128.TB", - "mem256tb" : "memory = 256.TB", - "mem512tb" : "memory = 512.TB", - "cpu1" : "cpus = 1", - "cpu2" : "cpus = 2", - "cpu5" : "cpus = 5", - "cpu10" : "cpus = 10", - "cpu20" : "cpus = 20", - "cpu50" : "cpus = 50", - "cpu100" : "cpus = 100", - "cpu200" : "cpus = 200", - "cpu500" : "cpus = 500", - "cpu1000" : "cpus = 1000" - } - }, - "debug" : false, - "container" : "docker" - } - ], - "info" : { - "config" : "/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/config.vsh.yaml", - "platform" : "nextflow", - "output" : "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/remove_comments", - "viash_version" : "0.8.4", - "git_commit" : "11b6278597bf22afbfb56a8e83065a55553c9dd0", - "git_remote" : "https://github.com/viash-io/viash_project_template", - "git_tag" : "v0.2.1" - } -}''')) -] - -// resolve dependencies dependencies (if any) - - -// inner workflow -// inner workflow hook -def innerWorkflowFactory(args) { - def rawScript = '''set -e -tempscript=".viash_script.sh" -cat > "$tempscript" << VIASHMAIN -## VIASH START -# The following code has been auto-generated by Viash. -$( if [ ! -z ${VIASH_PAR_INPUT+x} ]; then echo "${VIASH_PAR_INPUT}" | sed "s#'#'\\"'\\"'#g;s#.*#par_input='&'#" ; else echo "# par_input="; fi ) -$( if [ ! -z ${VIASH_PAR_OUTPUT+x} ]; then echo "${VIASH_PAR_OUTPUT}" | sed "s#'#'\\"'\\"'#g;s#.*#par_output='&'#" ; else echo "# par_output="; fi ) -$( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo "${VIASH_META_FUNCTIONALITY_NAME}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_functionality_name='&'#" ; else echo "# meta_functionality_name="; fi ) -$( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo "${VIASH_META_RESOURCES_DIR}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_resources_dir='&'#" ; else echo "# meta_resources_dir="; fi ) -$( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo "${VIASH_META_EXECUTABLE}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_executable='&'#" ; else echo "# meta_executable="; fi ) -$( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo "${VIASH_META_CONFIG}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_config='&'#" ; else echo "# meta_config="; fi ) -$( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo "${VIASH_META_TEMP_DIR}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_temp_dir='&'#" ; else echo "# meta_temp_dir="; fi ) -$( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo "${VIASH_META_CPUS}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_cpus='&'#" ; else echo "# meta_cpus="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo "${VIASH_META_MEMORY_B}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_memory_b='&'#" ; else echo "# meta_memory_b="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo "${VIASH_META_MEMORY_KB}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_memory_kb='&'#" ; else echo "# meta_memory_kb="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo "${VIASH_META_MEMORY_MB}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_memory_mb='&'#" ; else echo "# meta_memory_mb="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo "${VIASH_META_MEMORY_GB}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_memory_gb='&'#" ; else echo "# meta_memory_gb="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo "${VIASH_META_MEMORY_TB}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_memory_tb='&'#" ; else echo "# meta_memory_tb="; fi ) -$( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo "${VIASH_META_MEMORY_PB}" | sed "s#'#'\\"'\\"'#g;s#.*#meta_memory_pb='&'#" ; else echo "# meta_memory_pb="; fi ) - -## VIASH END -#!/bin/bash - -grep -v '^#' "\\$par_input" > "\\$par_output" -VIASHMAIN -bash "$tempscript" -''' - - return vdsl3WorkflowFactory(args, meta, rawScript) -} - - - -/** - * Generate a workflow for VDSL3 modules. - * - * This function is called by the workflowFactory() function. - * - * Input channel: [id, input_map] - * Output channel: [id, output_map] - * - * Internally, this workflow will convert the input channel - * to a format which the Nextflow module will be able to handle. - */ -def vdsl3WorkflowFactory(Map args, Map meta, String rawScript) { - def key = args["key"] - def processObj = null - - workflow processWf { - take: input_ - main: - - if (processObj == null) { - processObj = _vdsl3ProcessFactory(args, meta, rawScript) - } - - output_ = input_ - | map { tuple -> - def id = tuple[0] - def data_ = tuple[1] - - if (workflow.stubRun) { - // add id if missing - data_ = [id: 'stub'] + data_ - } - - // process input files separately - def inputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - .collect { par -> - def val = data_.containsKey(par.plainName) ? data_[par.plainName] : [] - def inputFiles = [] - if (val == null) { - inputFiles = [] - } else if (val instanceof List) { - inputFiles = val - } else if (val instanceof Path) { - inputFiles = [ val ] - } else { - inputFiles = [] - } - if (!workflow.stubRun) { - // throw error when an input file doesn't exist - inputFiles.each{ file -> - assert file.exists() : - "Error in module '${key}' id '${id}' argument '${par.plainName}'.\n" + - " Required input file does not exist.\n" + - " Path: '$file'.\n" + - " Expected input file to exist" - } - } - inputFiles - } - - // remove input files - def argsExclInputFiles = meta.config.functionality.allArguments - .findAll { (it.type != "file" || it.direction != "input") && data_.containsKey(it.plainName) } - .collectEntries { par -> - def parName = par.plainName - def val = data_[parName] - if (par.multiple && val instanceof Collection) { - val = val.join(par.multiple_sep) - } - if (par.direction == "output" && par.type == "file") { - val = val.replaceAll('\\$id', id).replaceAll('\\$key', key) - } - [parName, val] - } - - [ id ] + inputPaths + [ argsExclInputFiles, meta.resources_dir ] - } - | processObj - | map { output -> - def outputFiles = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .indexed() - .collectEntries{ index, par -> - out = output[index + 1] - // strip dummy '.exitcode' file from output (see nextflow-io/nextflow#2678) - if (!out instanceof List || out.size() <= 1) { - if (par.multiple) { - out = [] - } else { - assert !par.required : - "Error in module '${key}' id '${output[0]}' argument '${par.plainName}'.\n" + - " Required output file is missing" - out = null - } - } else if (out.size() == 2 && !par.multiple) { - out = out[1] - } else { - out = out.drop(1) - } - [ par.plainName, out ] - } - - // drop null outputs - outputFiles.removeAll{it.value == null} - - [ output[0], outputFiles ] - } - emit: output_ - } - - return processWf -} - -// depends on: session? -def _vdsl3ProcessFactory(Map workflowArgs, Map meta, String rawScript) { - // autodetect process key - def wfKey = workflowArgs["key"] - def procKeyPrefix = "${wfKey}_process" - def scriptMeta = nextflow.script.ScriptMeta.current() - def existing = scriptMeta.getProcessNames().findAll{it.startsWith(procKeyPrefix)} - def numbers = existing.collect{it.replace(procKeyPrefix, "0").toInteger()} - def newNumber = (numbers + [-1]).max() + 1 - - def procKey = newNumber == 0 ? procKeyPrefix : "$procKeyPrefix$newNumber" - - if (newNumber > 0) { - log.warn "Key for module '${wfKey}' is duplicated.\n", - "If you run a component multiple times in the same workflow,\n" + - "it's recommended you set a unique key for every call,\n" + - "for example: ${wfKey}.run(key: \"foo\")." - } - - // subset directives and convert to list of tuples - def drctv = workflowArgs.directives - - // TODO: unit test the two commands below - // convert publish array into tags - def valueToStr = { val -> - // ignore closures - if (val instanceof CharSequence) { - if (!val.matches('^[{].*[}]$')) { - '"' + val + '"' - } else { - val - } - } else if (val instanceof List) { - "[" + val.collect{valueToStr(it)}.join(", ") + "]" - } else if (val instanceof Map) { - "[" + val.collect{k, v -> k + ": " + valueToStr(v)}.join(", ") + "]" - } else { - val.inspect() - } - } - - // multiple entries allowed: label, publishdir - def drctvStrs = drctv.collect { key, value -> - if (key in ["label", "publishDir"]) { - value.collect{ val -> - if (val instanceof Map) { - "\n$key " + val.collect{ k, v -> k + ": " + valueToStr(v) }.join(", ") - } else if (val == null) { - "" - } else { - "\n$key " + valueToStr(val) - } - }.join() - } else if (value instanceof Map) { - "\n$key " + value.collect{ k, v -> k + ": " + valueToStr(v) }.join(", ") - } else { - "\n$key " + valueToStr(value) - } - }.join() - - def inputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - .collect { ', path(viash_par_' + it.plainName + ', stageAs: "_viash_par/' + it.plainName + '_?/*")' } - .join() - - def outputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .collect { par -> - // insert dummy into every output (see nextflow-io/nextflow#2678) - if (!par.multiple) { - ', path{[".exitcode", args.' + par.plainName + ']}' - } else { - ', path{[".exitcode"] + args.' + par.plainName + '}' - } - } - .join() - - // TODO: move this functionality somewhere else? - if (workflowArgs.auto.transcript) { - outputPaths = outputPaths + ', path{[".exitcode", ".command*"]}' - } else { - outputPaths = outputPaths + ', path{[".exitcode"]}' - } - - // create dirs for output files (based on BashWrapper.createParentFiles) - def createParentStr = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" && it.create_parent } - .collect { par -> - "\${ args.containsKey(\"${par.plainName}\") ? \"mkdir_parent \\\"\" + (args[\"${par.plainName}\"] instanceof String ? args[\"${par.plainName}\"] : args[\"${par.plainName}\"].join('\" \"')) + \"\\\"\" : \"\" }" - } - .join("\n") - - // construct inputFileExports - def inputFileExports = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction.toLowerCase() == "input" } - .collect { par -> - viash_par_contents = "(viash_par_${par.plainName} instanceof List ? viash_par_${par.plainName}.join(\"${par.multiple_sep}\") : viash_par_${par.plainName})" - "\n\${viash_par_${par.plainName}.empty ? \"\" : \"export VIASH_PAR_${par.plainName.toUpperCase()}=\\\"\" + ${viash_par_contents} + \"\\\"\"}" - } - - // NOTE: if using docker, use /tmp instead of tmpDir! - def tmpDir = java.nio.file.Paths.get( - System.getenv('NXF_TEMP') ?: - System.getenv('VIASH_TEMP') ?: - System.getenv('VIASH_TMPDIR') ?: - System.getenv('VIASH_TEMPDIR') ?: - System.getenv('VIASH_TMP') ?: - System.getenv('TEMP') ?: - System.getenv('TMPDIR') ?: - System.getenv('TEMPDIR') ?: - System.getenv('TMP') ?: - '/tmp' - ).toAbsolutePath() - - // construct stub - def stub = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .collect { par -> - "\${ args.containsKey(\"${par.plainName}\") ? \"touch2 \\\"\" + (args[\"${par.plainName}\"] instanceof String ? args[\"${par.plainName}\"].replace(\"_*\", \"_0\") : args[\"${par.plainName}\"].join('\" \"')) + \"\\\"\" : \"\" }" - } - .join("\n") - - // escape script - def escapedScript = rawScript.replace('\\', '\\\\').replace('$', '\\$').replace('"""', '\\"\\"\\"') - - // publishdir assert - def assertStr = (workflowArgs.auto.publish == true) || workflowArgs.auto.transcript ? - """\nassert task.publishDir.size() > 0: "if auto.publish is true, params.publish_dir needs to be defined.\\n Example: --publish_dir './output/'" """ : - "" - - // generate process string - def procStr = - """nextflow.enable.dsl=2 - | - |process $procKey {$drctvStrs - |input: - | tuple val(id)$inputPaths, val(args), path(resourcesDir, stageAs: ".viash_meta_resources") - |output: - | tuple val("\$id")$outputPaths, optional: true - |stub: - |\"\"\" - |touch2() { mkdir -p "\\\$(dirname "\\\$1")" && touch "\\\$1" ; } - |$stub - |\"\"\" - |script:$assertStr - |def escapeText = { s -> s.toString().replaceAll('([`"])', '\\\\\\\\\$1') } - |def parInject = args - | .findAll{key, value -> value != null} - | .collect{key, value -> "export VIASH_PAR_\${key.toUpperCase()}=\\\"\${escapeText(value)}\\\""} - | .join("\\n") - |\"\"\" - |# meta exports - |# export VIASH_META_RESOURCES_DIR="\${resourcesDir.toRealPath().toAbsolutePath()}" - |export VIASH_META_RESOURCES_DIR="\${resourcesDir}" - |export VIASH_META_TEMP_DIR="${['docker', 'podman', 'charliecloud'].any{ it == workflow.containerEngine } ? '/tmp' : tmpDir}" - |export VIASH_META_FUNCTIONALITY_NAME="${meta.config.functionality.name}" - |# export VIASH_META_EXECUTABLE="\\\$VIASH_META_RESOURCES_DIR/\\\$VIASH_META_FUNCTIONALITY_NAME" - |export VIASH_META_CONFIG="\\\$VIASH_META_RESOURCES_DIR/.config.vsh.yaml" - |\${task.cpus ? "export VIASH_META_CPUS=\$task.cpus" : "" } - |\${task.memory?.bytes != null ? "export VIASH_META_MEMORY_B=\$task.memory.bytes" : "" } - |if [ ! -z \\\${VIASH_META_MEMORY_B+x} ]; then - | export VIASH_META_MEMORY_KB=\\\$(( (\\\$VIASH_META_MEMORY_B+1023) / 1024 )) - | export VIASH_META_MEMORY_MB=\\\$(( (\\\$VIASH_META_MEMORY_KB+1023) / 1024 )) - | export VIASH_META_MEMORY_GB=\\\$(( (\\\$VIASH_META_MEMORY_MB+1023) / 1024 )) - | export VIASH_META_MEMORY_TB=\\\$(( (\\\$VIASH_META_MEMORY_GB+1023) / 1024 )) - | export VIASH_META_MEMORY_PB=\\\$(( (\\\$VIASH_META_MEMORY_TB+1023) / 1024 )) - |fi - | - |# meta synonyms - |export VIASH_TEMP="\\\$VIASH_META_TEMP_DIR" - |export TEMP_DIR="\\\$VIASH_META_TEMP_DIR" - | - |# create output dirs if need be - |function mkdir_parent { - | for file in "\\\$@"; do - | mkdir -p "\\\$(dirname "\\\$file")" - | done - |} - |$createParentStr - | - |# argument exports${inputFileExports.join()} - |\$parInject - | - |# process script - |${escapedScript} - |\"\"\" - |} - |""".stripMargin() - - // TODO: print on debug - // if (workflowArgs.debug == true) { - // println("######################\n$procStr\n######################") - // } - - // create runtime process - def ownerParams = new nextflow.script.ScriptBinding.ParamsMap() - def binding = new nextflow.script.ScriptBinding().setParams(ownerParams) - def module = new nextflow.script.IncludeDef.Module(name: procKey) - def session = nextflow.Nextflow.getSession() - def scriptParser = new nextflow.script.ScriptParser(session) - .setModule(true) - .setBinding(binding) - scriptParser.scriptPath = scriptMeta.getScriptPath() - def moduleScript = scriptParser.runScript(procStr) - .getScript() - - // register module in meta - scriptMeta.addModule(moduleScript, module.name, module.alias) - - // retrieve and return process from meta - return scriptMeta.getProcess(procKey) -} - -// defaults -meta["defaults"] = [ - // key to be used to trace the process and determine output names - key: null, - - // fixed arguments to be passed to script - args: [:], - - // default directives - directives: readJsonBlob('''{ - "container" : { - "registry" : "ghcr.io", - "image" : "viash-io/viash_project_template/template/remove_comments", - "tag" : "0.2.2" - }, - "tag" : "$id" -}'''), - - // auto settings - auto: readJsonBlob('''{ - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false -}'''), - - // Apply a map over the incoming tuple - // Example: `{ tup -> [ tup[0], [input: tup[1].output] ] + tup.drop(2) }` - map: null, - - // Apply a map over the ID element of a tuple (i.e. the first element) - // Example: `{ id -> id + "_foo" }` - mapId: null, - - // Apply a map over the data element of a tuple (i.e. the second element) - // Example: `{ data -> [ input: data.output ] }` - mapData: null, - - // Apply a map over the passthrough elements of a tuple (i.e. the tuple excl. the first two elements) - // Example: `{ pt -> pt.drop(1) }` - mapPassthrough: null, - - // Filter the channel - // Example: `{ tup -> tup[0] == "foo" }` - filter: null, - - // Choose whether or not to run the component on the tuple if the condition is true. - // Otherwise, the tuple will be passed through. - // Example: `{ tup -> tup[0] != "skip_this" }` - runIf: null, - - // Rename keys in the data field of the tuple (i.e. the second element) - // Will likely be deprecated in favour of `fromState`. - // Example: `[ "new_key": "old_key" ]` - renameKeys: null, - - // Fetch data from the state and pass it to the module without altering the current state. - // - // `fromState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be passed to the module as is. - // - If it is a `List[String]`, the data will be the values of the state at the given keys. - // - If it is a `Map[String, String]`, the data will be the values of the state at the given keys, with the keys renamed according to the map. - // - If it is a function, the tuple (`[id, state]`) in the channel will be passed to the function, and the result will be used as the data. - // - // Example: `{ id, state -> [input: state.fastq_file] }` - // Default: `null` - fromState: null, - - // Determine how the state should be updated after the module has been run. - // - // `toState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be replaced with the output of the module. - // - If it is a `List[String]`, the state will be updated with the values of the data at the given keys. - // - If it is a `Map[String, String]`, the state will be updated with the values of the data at the given keys, with the keys renamed according to the map. - // - If it is a function, a tuple (`[id, output, state]`) will be passed to the function, and the result will be used as the new state. - // - // Example: `{ id, output, state -> state + [counts: state.output] }` - // Default: `{ id, output, state -> output }` - toState: null, - - // Whether or not to print debug messages - // Default: `false` - debug: false -] - -// initialise default workflow -meta["workflow"] = workflowFactory([key: meta.config.functionality.name], meta.defaults, meta) - -// add workflow to environment -nextflow.script.ScriptMeta.current().addDefinition(meta.workflow) - -// anonymous workflow for running this module as a standalone -workflow { - // add id argument if it's not already in the config - // TODO: deep copy - def newConfig = deepClone(meta.config) - def newParams = deepClone(params) - - def argsContainsId = newConfig.functionality.allArguments.any{it.plainName == "id"} - if (!argsContainsId) { - def idArg = [ - 'name': '--id', - 'required': false, - 'type': 'string', - 'description': 'A unique id for every entry.', - 'multiple': false - ] - newConfig.functionality.arguments.add(0, idArg) - newConfig = processConfig(newConfig) - } - if (!newParams.containsKey("id")) { - newParams.id = "run" - } - - helpMessage(newConfig) - - channelFromParams(newParams, newConfig) - // make sure id is not in the state if id is not in the args - | map {id, state -> - if (!argsContainsId) { - [id, state.findAll{k, v -> k != "id"}] - } else { - [id, state] - } - } - | meta.workflow.run( - auto: [ publish: "state" ] - ) -} - -// END COMPONENT-SPECIFIC CODE diff --git a/target/nextflow/template/remove_comments/nextflow.config b/target/nextflow/template/remove_comments/nextflow.config deleted file mode 100644 index 15f0d95..0000000 --- a/target/nextflow/template/remove_comments/nextflow.config +++ /dev/null @@ -1,106 +0,0 @@ -manifest { - name = 'template/remove_comments' - mainScript = 'main.nf' - nextflowVersion = '!>=20.12.1-edge' - version = '0.2.2' -} - -process.container = 'nextflow/bash:latest' - -// detect tempdir -tempDir = java.nio.file.Paths.get( - System.getenv('NXF_TEMP') ?: - System.getenv('VIASH_TEMP') ?: - System.getenv('TEMPDIR') ?: - System.getenv('TMPDIR') ?: - '/tmp' -).toAbsolutePath() - -profiles { - no_publish { - process { - withName: '.*' { - publishDir = [ - enabled: false - ] - } - } - } - mount_temp { - docker.temp = tempDir - podman.temp = tempDir - charliecloud.temp = tempDir - } - docker { - docker.enabled = true - // docker.userEmulation = true - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - singularity { - singularity.enabled = true - singularity.autoMounts = true - docker.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - podman { - podman.enabled = true - docker.enabled = false - singularity.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - shifter { - shifter.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - charliecloud.enabled = false - } - charliecloud { - charliecloud.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - } -} - -process{ - withLabel: mem1gb { memory = 1.GB } - withLabel: mem2gb { memory = 2.GB } - withLabel: mem4gb { memory = 4.GB } - withLabel: mem8gb { memory = 8.GB } - withLabel: mem16gb { memory = 16.GB } - withLabel: mem32gb { memory = 32.GB } - withLabel: mem64gb { memory = 64.GB } - withLabel: mem128gb { memory = 128.GB } - withLabel: mem256gb { memory = 256.GB } - withLabel: mem512gb { memory = 512.GB } - withLabel: mem1tb { memory = 1.TB } - withLabel: mem2tb { memory = 2.TB } - withLabel: mem4tb { memory = 4.TB } - withLabel: mem8tb { memory = 8.TB } - withLabel: mem16tb { memory = 16.TB } - withLabel: mem32tb { memory = 32.TB } - withLabel: mem64tb { memory = 64.TB } - withLabel: mem128tb { memory = 128.TB } - withLabel: mem256tb { memory = 256.TB } - withLabel: mem512tb { memory = 512.TB } - withLabel: cpu1 { cpus = 1 } - withLabel: cpu2 { cpus = 2 } - withLabel: cpu5 { cpus = 5 } - withLabel: cpu10 { cpus = 10 } - withLabel: cpu20 { cpus = 20 } - withLabel: cpu50 { cpus = 50 } - withLabel: cpu100 { cpus = 100 } - withLabel: cpu200 { cpus = 200 } - withLabel: cpu500 { cpus = 500 } - withLabel: cpu1000 { cpus = 1000 } -} - - diff --git a/target/nextflow/template/take_column/.config.vsh.yaml b/target/nextflow/template/take_column/.config.vsh.yaml deleted file mode 100644 index d944309..0000000 --- a/target/nextflow/template/take_column/.config.vsh.yaml +++ /dev/null @@ -1,121 +0,0 @@ -functionality: - name: "take_column" - namespace: "template" - version: "0.2.2" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - info: null - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "file" - name: "--output" - alternatives: - - "-o" - info: null - must_exist: true - create_parent: true - required: true - direction: "output" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "integer" - name: "--column" - info: null - default: - - 2 - required: false - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - resources: - - type: "python_script" - path: "script.py" - is_executable: true - info: null - status: "enabled" - set_wd_to_resources_dir: false -platforms: -- type: "docker" - id: "docker" - image: "python:3.10-slim" - target_organization: "viash-io/viash_project_template" - target_registry: "ghcr.io" - namespace_separator: "/" - resolve_volume: "Automatic" - chown: true - setup_strategy: "ifneedbepullelsecachedbuild" - target_image_source: "https://github.com/viash-io/viash_project_template" - setup: - - type: "python" - user: false - packages: - - "pandas" - upgrade: true - - type: "apt" - packages: - - "procps" - interactive: false - entrypoint: [] - cmd: null -- type: "nextflow" - id: "nextflow" - directives: - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1.GB" - mem2gb: "memory = 2.GB" - mem4gb: "memory = 4.GB" - mem8gb: "memory = 8.GB" - mem16gb: "memory = 16.GB" - mem32gb: "memory = 32.GB" - mem64gb: "memory = 64.GB" - mem128gb: "memory = 128.GB" - mem256gb: "memory = 256.GB" - mem512gb: "memory = 512.GB" - mem1tb: "memory = 1.TB" - mem2tb: "memory = 2.TB" - mem4tb: "memory = 4.TB" - mem8tb: "memory = 8.TB" - mem16tb: "memory = 16.TB" - mem32tb: "memory = 32.TB" - mem64tb: "memory = 64.TB" - mem128tb: "memory = 128.TB" - mem256tb: "memory = 256.TB" - mem512tb: "memory = 512.TB" - cpu1: "cpus = 1" - cpu2: "cpus = 2" - cpu5: "cpus = 5" - cpu10: "cpus = 10" - cpu20: "cpus = 20" - cpu50: "cpus = 50" - cpu100: "cpus = 100" - cpu200: "cpus = 200" - cpu500: "cpus = 500" - cpu1000: "cpus = 1000" - debug: false - container: "docker" -info: - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/take_column/config.vsh.yaml" - platform: "nextflow" - output: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/take_column" - executable: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/take_column/take_column" - viash_version: "0.8.4" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - git_remote: "https://github.com/viash-io/viash_project_template" - git_tag: "v0.2.1" diff --git a/target/nextflow/template/take_column/main.nf b/target/nextflow/template/take_column/main.nf deleted file mode 100644 index 600e6cd..0000000 --- a/target/nextflow/template/take_column/main.nf +++ /dev/null @@ -1,3434 +0,0 @@ -// take_column 0.2.2 -// -// This wrapper script is auto-generated by viash 0.8.4 and is thus a derivative -// work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data -// Intuitive. -// -// The component may contain files which fall under a different license. The -// authors of this component should specify the license in the header of such -// files, or include a separate license file detailing the licenses of all included -// files. - -//////////////////////////// -// VDSL3 helper functions // -//////////////////////////// - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_checkArgumentType.nf' -class UnexpectedArgumentTypeException extends Exception { - String errorIdentifier - String stage - String plainName - String expectedClass - String foundClass - - // ${key ? " in module '$key'" : ""}${id ? " id '$id'" : ""} - UnexpectedArgumentTypeException(String errorIdentifier, String stage, String plainName, String expectedClass, String foundClass) { - super("Error${errorIdentifier ? " $errorIdentifier" : ""}:${stage ? " $stage" : "" } argument '${plainName}' has the wrong type. " + - "Expected type: ${expectedClass}. Found type: ${foundClass}") - this.errorIdentifier = errorIdentifier - this.stage = stage - this.plainName = plainName - this.expectedClass = expectedClass - this.foundClass = foundClass - } -} - -/** - * Checks if the given value is of the expected type. If not, an exception is thrown. - * - * @param stage The stage of the argument (input or output) - * @param par The parameter definition - * @param value The value to check - * @param errorIdentifier The identifier to use in the error message - * @return The value, if it is of the expected type - * @throws UnexpectedArgumentTypeException If the value is not of the expected type -*/ -def _checkArgumentType(String stage, Map par, Object value, String errorIdentifier) { - // expectedClass will only be != null if value is not of the expected type - def expectedClass = null - def foundClass = null - - // todo: split if need be - - if (!par.required && value == null) { - expectedClass = null - } else if (par.multiple) { - if (value !instanceof Collection) { - value = [value] - } - - // split strings - value = value.collectMany{ val -> - if (val instanceof String) { - // collect() to ensure that the result is a List and not simply an array - val.split(par.multiple_sep).collect() - } else { - [val] - } - } - - // process globs - if (par.type == "file" && par.direction == "input") { - value = value.collect{ it instanceof String ? file(it, hidden: true) : it }.flatten() - } - - // check types of elements in list - try { - value = value.collect { listVal -> - _checkArgumentType(stage, par + [multiple: false], listVal, errorIdentifier) - } - } catch (UnexpectedArgumentTypeException e) { - expectedClass = "List[${e.expectedClass}]" - foundClass = "List[${e.foundClass}]" - } - } else if (par.type == "string") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else if (par.type == "integer") { - // cast to integer if need be - if (value instanceof String) { - try { - value = value.toInteger() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigInteger) { - value = value.intValue() - } - expectedClass = value instanceof Integer ? null : "Integer" - } else if (par.type == "long") { - // cast to long if need be - if (value instanceof String) { - try { - value = value.toLong() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof Integer) { - value = value.toLong() - } - expectedClass = value instanceof Long ? null : "Long" - } else if (par.type == "double") { - // cast to double if need be - if (value instanceof String) { - try { - value = value.toDouble() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigDecimal) { - value = value.doubleValue() - } - if (value instanceof Float) { - value = value.toDouble() - } - expectedClass = value instanceof Double ? null : "Double" - } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { - // cast to boolean if need ben - if (value instanceof String) { - def valueLower = value.toLowerCase() - if (valueLower == "true") { - value = true - } else if (valueLower == "false") { - value = false - } - } - expectedClass = value instanceof Boolean ? null : "Boolean" - } else if (par.type == "file" && (par.direction == "input" || stage == "output")) { - // cast to path if need be - if (value instanceof String) { - value = file(value, hidden: true) - } - if (value instanceof File) { - value = value.toPath() - } - expectedClass = value instanceof Path ? null : "Path" - } else if (par.type == "file" && stage == "input" && par.direction == "output") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else { - // didn't find a match for par.type - expectedClass = par.type - } - - if (expectedClass != null) { - if (foundClass == null) { - foundClass = value.getClass().getName() - } - throw new UnexpectedArgumentTypeException(errorIdentifier, stage, par.plainName, expectedClass, foundClass) - } - - return value -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processInputValues.nf' -Map _processInputValues(Map inputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.required) { - assert inputs.containsKey(arg.plainName) && inputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required input argument '${arg.plainName}' is missing" - } - } - - inputs = inputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid input argument" - - value = _checkArgumentType("input", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return inputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processOutputValues.nf' -Map _processOutputValues(Map outputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.direction == "output" && arg.required) { - assert outputs.containsKey(arg.plainName) && outputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required output argument '${arg.plainName}' is missing" - } - } - - outputs = outputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && it.direction == "output" } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid output argument" - - value = _checkArgumentType("output", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return outputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/IDChecker.nf' -class IDChecker { - final def items = [] as Set - - @groovy.transform.WithWriteLock - boolean observe(String item) { - if (items.contains(item)) { - return false - } else { - items << item - return true - } - } - - @groovy.transform.WithReadLock - boolean contains(String item) { - return items.contains(item) - } - - @groovy.transform.WithReadLock - Set getItems() { - return items.clone() - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_checkUniqueIds.nf' - -/** - * Check if the ids are unique across parameter sets - * - * @param parameterSets a list of parameter sets. - */ -private void _checkUniqueIds(List>> parameterSets) { - def ppIds = parameterSets.collect{it[0]} - assert ppIds.size() == ppIds.unique().size() : "All argument sets should have unique ids. Detected ids: $ppIds" -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_getChild.nf' - -// helper functions for reading params from file // -def _getChild(parent, child) { - if (child.contains("://") || java.nio.file.Paths.get(child).isAbsolute()) { - child - } else { - def parentAbsolute = java.nio.file.Paths.get(parent).toAbsolutePath().toString() - parentAbsolute.replaceAll('/[^/]*$', "/") + child - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_parseParamList.nf' -/** - * Figure out the param list format based on the file extension - * - * @param param_list A String containing the path to the parameter list file. - * - * @return A String containing the format of the parameter list file. - */ -def _paramListGuessFormat(param_list) { - if (param_list !instanceof String) { - "asis" - } else if (param_list.endsWith(".csv")) { - "csv" - } else if (param_list.endsWith(".json") || param_list.endsWith(".jsn")) { - "json" - } else if (param_list.endsWith(".yaml") || param_list.endsWith(".yml")) { - "yaml" - } else { - "yaml_blob" - } -} - - -/** - * Read the param list - * - * @param param_list One of the following: - * - A String containing the path to the parameter list file (csv, json or yaml), - * - A yaml blob of a list of maps (yaml_blob), - * - Or a groovy list of maps (asis). - * @param config A Map of the Viash configuration. - * - * @return A List of Maps containing the parameters. - */ -def _parseParamList(param_list, Map config) { - // first determine format by extension - def paramListFormat = _paramListGuessFormat(param_list) - - def paramListPath = (paramListFormat != "asis" && paramListFormat != "yaml_blob") ? - file(param_list, hidden: true) : - null - - // get the correct parser function for the detected params_list format - def paramSets = [] - if (paramListFormat == "asis") { - paramSets = param_list - } else if (paramListFormat == "yaml_blob") { - paramSets = readYamlBlob(param_list) - } else if (paramListFormat == "yaml") { - paramSets = readYaml(paramListPath) - } else if (paramListFormat == "json") { - paramSets = readJson(paramListPath) - } else if (paramListFormat == "csv") { - paramSets = readCsv(paramListPath) - } else { - error "Format of provided --param_list not recognised.\n" + - "Found: '$paramListFormat'.\n" + - "Expected: a csv file, a json file, a yaml file,\n" + - "a yaml blob or a groovy list of maps." - } - - // data checks - assert paramSets instanceof List: "--param_list should contain a list of maps" - for (value in paramSets) { - assert value instanceof Map: "--param_list should contain a list of maps" - } - - // id is argument - def idIsArgument = config.functionality.allArguments.any{it.plainName == "id"} - - // Reformat from List to List> by adding the ID as first element of a Tuple2 - paramSets = paramSets.collect({ data -> - def id = data.id - if (!idIsArgument) { - data = data.findAll{k, v -> k != "id"} - } - [id, data] - }) - - // Split parameters with 'multiple: true' - paramSets = paramSets.collect({ id, data -> - data = _splitParams(data, config) - [id, data] - }) - - // The paths of input files inside a param_list file may have been specified relatively to the - // location of the param_list file. These paths must be made absolute. - if (paramListPath) { - paramSets = paramSets.collect({ id, data -> - def new_data = data.collectEntries{ parName, parValue -> - def par = config.functionality.allArguments.find{it.plainName == parName} - if (par && par.type == "file" && par.direction == "input") { - if (parValue instanceof Collection) { - parValue = parValue.collectMany{path -> - def x = _resolveSiblingIfNotAbsolute(path, paramListPath) - x instanceof Collection ? x : [x] - } - } else { - parValue = _resolveSiblingIfNotAbsolute(parValue, paramListPath) - } - } - [parName, parValue] - } - [id, new_data] - }) - } - - return paramSets -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_splitParams.nf' -/** - * Split parameters for arguments that accept multiple values using their separator - * - * @param paramList A Map containing parameters to split. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A Map of parameters where the parameter values have been split into a list using - * their seperator. - */ -Map _splitParams(Map parValues, Map config){ - def parsedParamValues = parValues.collectEntries { parName, parValue -> - def parameterSettings = config.functionality.allArguments.find({it.plainName == parName}) - - if (!parameterSettings) { - // if argument is not found, do not alter - return [parName, parValue] - } - if (parameterSettings.multiple) { // Check if parameter can accept multiple values - if (parValue instanceof Collection) { - parValue = parValue.collect{it instanceof String ? it.split(parameterSettings.multiple_sep) : it } - } else if (parValue instanceof String) { - parValue = parValue.split(parameterSettings.multiple_sep) - } else if (parValue == null) { - parValue = [] - } else { - parValue = [ parValue ] - } - parValue = parValue.flatten() - } - // For all parameters check if multiple values are only passed for - // arguments that allow it. Quietly simplify lists of length 1. - if (!parameterSettings.multiple && parValue instanceof Collection) { - assert parValue.size() == 1 : - "Error: argument ${parName} has too many values.\n" + - " Expected amount: 1. Found: ${parValue.size()}" - parValue = parValue[0] - } - [parName, parValue] - } - return parsedParamValues -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/channelFromParams.nf' -/** - * Parse nextflow parameters based on settings defined in a viash config. - * Return a list of parameter sets, each parameter set corresponding to - * an event in a nextflow channel. The output from this function can be used - * with Channel.fromList to create a nextflow channel with Vdsl3 formatted - * events. - * - * This function performs: - * - A filtering of the params which can be found in the config file. - * - Process the params_list argument which allows a user to to initialise - * a Vsdl3 channel with multiple parameter sets. Possible formats are - * csv, json, yaml, or simply a yaml_blob. A csv should have column names - * which correspond to the different arguments of this pipeline. A json or a yaml - * file should be a list of maps, each of which has keys corresponding to the - * arguments of the pipeline. A yaml blob can also be passed directly as a parameter. - * When passing a csv, json or yaml, relative path names are relativized to the - * location of the parameter file. - * - Combine the parameter sets into a vdsl3 Channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A list of parameters with the first element of the event being - * the event ID and the second element containing a map of the parsed parameters. - */ - -private List>> _paramsToParamSets(Map params, Map config){ - // todo: fetch key from run args - def key_ = config.functionality.name - - /* parse regular parameters (not in param_list) */ - /*************************************************/ - def globalParams = config.functionality.allArguments - .findAll { params.containsKey(it.plainName) } - .collectEntries { [ it.plainName, params[it.plainName] ] } - def globalID = params.get("id", null) - - /* process params_list arguments */ - /*********************************/ - def paramList = params.containsKey("param_list") && params.param_list != null ? - params.param_list : [] - // if (paramList instanceof String) { - // paramList = [paramList] - // } - // def paramSets = paramList.collectMany{ _parseParamList(it, config) } - // TODO: be able to process param_list when it is a list of strings - def paramSets = _parseParamList(paramList, config) - if (paramSets.isEmpty()) { - paramSets = [[null, [:]]] - } - - /* combine arguments into channel */ - /**********************************/ - def processedParams = paramSets.indexed().collect{ index, tup -> - // Process ID - def id = tup[0] ?: globalID - - if (workflow.stubRun) { - // if stub run, explicitly add an id if missing - id = id ? id : "stub${index}" - } - assert id != null: "Each parameter set should have at least an 'id'" - - // Process params - def parValues = globalParams + tup[1] - // // Remove parameters which are null, if the default is also null - // parValues = parValues.collectEntries{paramName, paramValue -> - // parameterSettings = config.functionality.allArguments.find({it.plainName == paramName}) - // if ( paramValue != null || parameterSettings.get("default", null) != null ) { - // [paramName, paramValue] - // } - // } - parValues = parValues.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key_}' id '${id}': '${name}' is not a valid input argument" - - if (par == null) { - return [:] - } - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - - [ name, value ] - } - - [id, parValues] - } - - // Check if ids (first element of each list) is unique - _checkUniqueIds(processedParams) - return processedParams -} - -/** - * Parse nextflow parameters based on settings defined in a viash config - * and return a nextflow channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A nextflow Channel with events. Events are formatted as a tuple that contains - * first contains the ID of the event and as second element holds a parameter map. - * - * - */ -def channelFromParams(Map params, Map config) { - def processedParams = _paramsToParamSets(params, config) - return Channel.fromList(processedParams) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/checkUniqueIds.nf' -def checkUniqueIds(Map args) { - def stopOnError = args.stopOnError == null ? args.stopOnError : true - - def idChecker = new IDChecker() - - return filter { tup -> - if (!idChecker.observe(tup[0])) { - if (stopOnError) { - error "Duplicate id: ${tup[0]}" - } else { - log.warn "Duplicate id: ${tup[0]}, removing duplicate entry" - return false - } - } - return true - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/preprocessInputs.nf' -// This helper file will be deprecated soon -preprocessInputsDeprecationWarningPrinted = false - -def preprocessInputsDeprecationWarning() { - if (!preprocessInputsDeprecationWarningPrinted) { - preprocessInputsDeprecationWarningPrinted = true - System.err.println("Warning: preprocessInputs() is deprecated and will be removed in Viash 0.9.0.") - } -} - -/** - * Generate a nextflow Workflow that allows processing a channel of - * Vdsl3 formatted events and apply a Viash config to them: - * - Gather default parameters from the Viash config and make - * sure that they are correctly formatted (see applyConfig method). - * - Format the input parameters (also using the applyConfig method). - * - Apply the default parameter to the input parameters. - * - Do some assertions: - * ~ Check if the event IDs in the channel are unique. - * - * The events in the channel are formatted as tuples, with the - * first element of the tuples being a unique id of the parameter set, - * and the second element containg the the parameters themselves. - * Optional extra elements of the tuples will be passed to the output as is. - * - * @param args A map that must contain a 'config' key that points - * to a parsed config (see readConfig()). Optionally, a - * 'key' key can be provided which can be used to create a unique - * name for the workflow process. - * - * @return A workflow that allows processing a channel of Vdsl3 formatted events - * and apply a Viash config to them. - */ -def preprocessInputs(Map args) { - preprocessInputsDeprecationWarning() - - def config = args.config - assert config instanceof Map : - "Error in preprocessInputs: config must be a map. " + - "Expected class: Map. Found: config.getClass() is ${config.getClass()}" - def key_ = args.key ?: config.functionality.name - - // Get different parameter types (used throughout this function) - def defaultArgs = config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - map { tup -> - def id = tup[0] - def data = tup[1] - def passthrough = tup.drop(2) - - def new_data = (defaultArgs + data).collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - - if (par != null) { - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - } - - [ name, value ] - } - - [ id, new_data ] + passthrough - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runComponents.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component config. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component config. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component config. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component config. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runComponents(Map args) { - log.warn("runComponents is deprecated, use runEach instead") - assert args.components: "runComponents should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runComponents" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runComponentsWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def comp_config = comp_.config - - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_config) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - // def new_id = id_(tup[0], tup[1], comp_config) - def new_id = tup[0] - if (id_ instanceof String) { - new_id = id_ - } else if (id_ instanceof Closure) { - new_id = id_(new_id, tup[1], comp_config) - } - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_config) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_config) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runComponentsWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runEach.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component itself. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component itself. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component itself. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component itself. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runEach(Map args) { - assert args.components: "runEach should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runEach" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runEachWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - def new_id = id_ - if (new_id instanceof Closure) { - new_id = new_id(tup[0], tup[1], comp_) - } - assert new_id instanceof String : "Error in runEach: id should be a String or a Closure that returns a String. Expected: id instanceof String. Found: ${new_id.getClass()}" - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - def new_state = null - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runEachWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/safeJoin.nf' -/** - * Join sourceChannel to targetChannel - * - * This function joins the sourceChannel to the targetChannel. - * However, each id in the targetChannel must be present in the - * sourceChannel. If _meta.join_id exists in the targetChannel, that is - * used as an id instead. If the id doesn't match any id in the sourceChannel, - * an error is thrown. - */ - -def safeJoin(targetChannel, sourceChannel, key) { - def sourceIDs = new IDChecker() - - def sourceCheck = sourceChannel - | map { tup -> - sourceIDs.observe(tup[0]) - tup - } - def targetCheck = targetChannel - | map { tup -> - def id = tup[0] - - if (!sourceIDs.contains(id)) { - error ( - "Error in module '${key}' when merging output with original state.\n" + - " Reason: output with id '${id}' could not be joined with source channel.\n" + - " If the IDs in the output channel differ from the input channel,\n" + - " please set `tup[1]._meta.join_id to the original ID.\n" + - " Original IDs in input channel: ['${sourceIDs.getItems().join("', '")}'].\n" + - " Unexpected ID in the output channel: '${id}'.\n" + - " Example input event: [\"id\", [input: file(...)]],\n" + - " Example output event: [\"newid\", [output: file(...), _meta: [join_id: \"id\"]]]" - ) - } - // TODO: add link to our documentation on how to fix this - - tup - } - - sourceCheck.cross(targetChannel) - | map{ left, right -> - right + left.drop(1) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/_processArgument.nf' -def _processArgument(arg) { - arg.multiple = arg.multiple != null ? arg.multiple : false - arg.required = arg.required != null ? arg.required : false - arg.direction = arg.direction != null ? arg.direction : "input" - arg.multiple_sep = arg.multiple_sep != null ? arg.multiple_sep : ":" - arg.plainName = arg.name.replaceAll("^-*", "") - - if (arg.type == "file") { - arg.must_exist = arg.must_exist != null ? arg.must_exist : true - arg.create_parent = arg.create_parent != null ? arg.create_parent : true - } - - // add default values to output files which haven't already got a default - if (arg.type == "file" && arg.direction == "output" && arg.default == null) { - def mult = arg.multiple ? "_*" : "" - def extSearch = "" - if (arg.default != null) { - extSearch = arg.default - } else if (arg.example != null) { - extSearch = arg.example - } - if (extSearch instanceof List) { - extSearch = extSearch[0] - } - def extSearchResult = extSearch.find("\\.[^\\.]+\$") - def ext = extSearchResult != null ? extSearchResult : "" - arg.default = "\$id.\$key.${arg.plainName}${mult}${ext}" - if (arg.multiple) { - arg.default = [arg.default] - } - } - - if (!arg.multiple) { - if (arg.default != null && arg.default instanceof List) { - arg.default = arg.default[0] - } - if (arg.example != null && arg.example instanceof List) { - arg.example = arg.example[0] - } - } - - if (arg.type == "boolean_true") { - arg.default = false - } - if (arg.type == "boolean_false") { - arg.default = true - } - - arg -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/addGlobalParams.nf' -def addGlobalArguments(config) { - def localConfig = [ - "functionality" : [ - "argument_groups": [ - [ - "name": "Nextflow input-output arguments", - "description": "Input/output parameters for Nextflow itself. Please note that both publishDir and publish_dir are supported but at least one has to be configured.", - "arguments" : [ - [ - 'name': '--publish_dir', - 'required': true, - 'type': 'string', - 'description': 'Path to an output directory.', - 'example': 'output/', - 'multiple': false - ], - [ - 'name': '--param_list', - 'required': false, - 'type': 'string', - 'description': '''Allows inputting multiple parameter sets to initialise a Nextflow channel. A `param_list` can either be a list of maps, a csv file, a json file, a yaml file, or simply a yaml blob. - | - |* A list of maps (as-is) where the keys of each map corresponds to the arguments of the pipeline. Example: in a `nextflow.config` file: `param_list: [ ['id': 'foo', 'input': 'foo.txt'], ['id': 'bar', 'input': 'bar.txt'] ]`. - |* A csv file should have column names which correspond to the different arguments of this pipeline. Example: `--param_list data.csv` with columns `id,input`. - |* A json or a yaml file should be a list of maps, each of which has keys corresponding to the arguments of the pipeline. Example: `--param_list data.json` with contents `[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]`. - |* A yaml blob can also be passed directly as a string. Example: `--param_list "[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]"`. - | - |When passing a csv, json or yaml file, relative path names are relativized to the location of the parameter file. No relativation is performed when `param_list` is a list of maps (as-is) or a yaml blob.'''.stripMargin(), - 'example': 'my_params.yaml', - 'multiple': false, - 'hidden': true - ] - // TODO: allow multiple: true in param_list? - // TODO: allow to specify a --param_list_regex to filter the param_list? - // TODO: allow to specify a --param_list_from_state to remap entries in the param_list? - ] - ] - ] - ] - ] - - return processConfig(_mergeMap(config, localConfig)) -} - -def _mergeMap(Map lhs, Map rhs) { - return rhs.inject(lhs.clone()) { map, entry -> - if (map[entry.key] instanceof Map && entry.value instanceof Map) { - map[entry.key] = _mergeMap(map[entry.key], entry.value) - } else if (map[entry.key] instanceof Collection && entry.value instanceof Collection) { - map[entry.key] += entry.value - } else { - map[entry.key] = entry.value - } - return map - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/generateHelp.nf' -def _generateArgumentHelp(param) { - // alternatives are not supported - // def names = param.alternatives ::: List(param.name) - - def unnamedProps = [ - ["required parameter", param.required], - ["multiple values allowed", param.multiple], - ["output", param.direction.toLowerCase() == "output"], - ["file must exist", param.type == "file" && param.must_exist] - ].findAll{it[1]}.collect{it[0]} - - def dflt = null - if (param.default != null) { - if (param.default instanceof List) { - dflt = param.default.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - dflt = param.default.toString() - } - } - def example = null - if (param.example != null) { - if (param.example instanceof List) { - example = param.example.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - example = param.example.toString() - } - } - def min = param.min?.toString() - def max = param.max?.toString() - - def escapeChoice = { choice -> - def s1 = choice.replaceAll("\\n", "\\\\n") - def s2 = s1.replaceAll("\"", """\\\"""") - s2.contains(",") || s2 != choice ? "\"" + s2 + "\"" : s2 - } - def choices = param.choices == null ? - null : - "[ " + param.choices.collect{escapeChoice(it.toString())}.join(", ") + " ]" - - def namedPropsStr = [ - ["type", ([param.type] + unnamedProps).join(", ")], - ["default", dflt], - ["example", example], - ["choices", choices], - ["min", min], - ["max", max] - ] - .findAll{it[1]} - .collect{"\n " + it[0] + ": " + it[1].replaceAll("\n", "\\n")} - .join("") - - def descStr = param.description == null ? - "" : - _paragraphWrap("\n" + param.description.trim(), 80 - 8).join("\n ") - - "\n --" + param.plainName + - namedPropsStr + - descStr -} - -// Based on Helper.generateHelp() in Helper.scala -def _generateHelp(config) { - def fun = config.functionality - - // PART 1: NAME AND VERSION - def nameStr = fun.name + - (fun.version == null ? "" : " " + fun.version) - - // PART 2: DESCRIPTION - def descrStr = fun.description == null ? - "" : - "\n\n" + _paragraphWrap(fun.description.trim(), 80).join("\n") - - // PART 3: Usage - def usageStr = fun.usage == null ? - "" : - "\n\nUsage:\n" + fun.usage.trim() - - // PART 4: Options - def argGroupStrs = fun.allArgumentGroups.collect{argGroup -> - def name = argGroup.name - def descriptionStr = argGroup.description == null ? - "" : - "\n " + _paragraphWrap(argGroup.description.trim(), 80-4).join("\n ") + "\n" - def arguments = argGroup.arguments.collect{arg -> - arg instanceof String ? fun.allArguments.find{it.plainName == arg} : arg - }.findAll{it != null} - def argumentStrs = arguments.collect{param -> _generateArgumentHelp(param)} - - "\n\n$name:" + - descriptionStr + - argumentStrs.join("\n") - } - - // FINAL: combine - def out = nameStr + - descrStr + - usageStr + - argGroupStrs.join("") - - return out -} - -// based on Format._paragraphWrap -def _paragraphWrap(str, maxLength) { - def outLines = [] - str.split("\n").each{par -> - def words = par.split("\\s").toList() - - def word = null - def line = words.pop() - while(!words.isEmpty()) { - word = words.pop() - if (line.length() + word.length() + 1 <= maxLength) { - line = line + " " + word - } else { - outLines.add(line) - line = word - } - } - if (words.isEmpty()) { - outLines.add(line) - } - } - return outLines -} - -def helpMessage(config) { - if (params.containsKey("help") && params.help) { - def mergedConfig = addGlobalArguments(config) - def helpStr = _generateHelp(mergedConfig) - println(helpStr) - exit 0 - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/processConfig.nf' -def processConfig(config) { - // set defaults for arguments - config.functionality.arguments = - (config.functionality.arguments ?: []).collect{_processArgument(it)} - - // set defaults for argument_group arguments - config.functionality.argument_groups = - (config.functionality.argument_groups ?: []).collect{grp -> - grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} - grp - } - - // create combined arguments list - config.functionality.allArguments = - config.functionality.arguments + - config.functionality.argument_groups.collectMany{it.arguments} - - // add missing argument groups (based on Functionality::allArgumentGroups()) - def argGroups = config.functionality.argument_groups - if (argGroups.any{it.name.toLowerCase() == "arguments"}) { - argGroups = argGroups.collect{ grp -> - if (grp.name.toLowerCase() == "arguments") { - grp = grp + [ - arguments: grp.arguments + config.functionality.arguments - ] - } - grp - } - } else { - argGroups = argGroups + [ - name: "Arguments", - arguments: config.functionality.arguments - ] - } - config.functionality.allArgumentGroups = argGroups - - config -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/readConfig.nf' - -def readConfig(file) { - def config = readYaml(file ?: moduleDir.resolve("config.vsh.yaml")) - processConfig(config) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_resolveSiblingIfNotAbsolute.nf' -/** - * Resolve a path relative to the current file. - * - * @param str The path to resolve, as a String. - * @param parentPath The path to resolve relative to, as a Path. - * - * @return The path that may have been resovled, as a Path. - */ -def _resolveSiblingIfNotAbsolute(str, parentPath) { - if (str !instanceof String) { - return str - } - if (!_stringIsAbsolutePath(str)) { - return parentPath.resolveSibling(str) - } else { - return file(str, hidden: true) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_stringIsAbsolutePath.nf' -/** - * Check whether a path as a string is absolute. - * - * In the past, we tried using `file(., relative: true).isAbsolute()`, - * but the 'relative' option was added in 22.10.0. - * - * @param path The path to check, as a String. - * - * @return Whether the path is absolute, as a boolean. - */ -def _stringIsAbsolutePath(path) { - _resolve_URL_PROTOCOL = ~/^([a-zA-Z][a-zA-Z0-9]*:)?\\/.+/ - - assert path instanceof String - return _resolve_URL_PROTOCOL.matcher(path).matches() -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/collectTraces.nf' -class CustomTraceObserver implements nextflow.trace.TraceObserver { - List traces - - CustomTraceObserver(List traces) { - this.traces = traces - } - - @Override - void onProcessComplete(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } - - @Override - void onProcessCached(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } -} - -def collectTraces() { - def traces = Collections.synchronizedList([]) - - // add custom trace observer which stores traces in the traces object - session.observers.add(new CustomTraceObserver(traces)) - - traces -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/deepClone.nf' -/** - * Performs a deep clone of the given object. - * @param x an object - */ -def deepClone(x) { - iterateMap(x, {it instanceof Cloneable ? it.clone() : it}) -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getPublishDir.nf' -def getPublishDir() { - return params.containsKey("publish_dir") ? params.publish_dir : - params.containsKey("publishDir") ? params.publishDir : - null -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getRootDir.nf' - -// Recurse upwards until we find a '.build.yaml' file -def _findBuildYamlFile(pathPossiblySymlink) { - def path = pathPossiblySymlink.toRealPath() - def child = path.resolve(".build.yaml") - if (java.nio.file.Files.isDirectory(path) && java.nio.file.Files.exists(child)) { - return child - } else { - def parent = path.getParent() - if (parent == null) { - return null - } else { - return _findBuildYamlFile(parent) - } - } -} - -// get the root of the target folder -def getRootDir() { - def dir = _findBuildYamlFile(meta.resources_dir) - assert dir != null: "Could not find .build.yaml in the folder structure" - dir.getParent() -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/iterateMap.nf' -/** - * Recursively apply a function over the leaves of an object. - * @param obj The object to iterate over. - * @param fun The function to apply to each value. - * @return The object with the function applied to each value. - */ -def iterateMap(obj, fun) { - if (obj instanceof List && obj !instanceof String) { - return obj.collect{item -> - iterateMap(item, fun) - } - } else if (obj instanceof Map) { - return obj.collectEntries{key, item -> - [key.toString(), iterateMap(item, fun)] - } - } else { - return fun(obj) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/niceView.nf' -/** - * A view for printing the event of each channel as a YAML blob. - * This is useful for debugging. - */ -def niceView() { - workflow niceViewWf { - take: input - main: - output = input - | view{toYamlBlob(it)} - emit: output - } - return niceViewWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readCsv.nf' - -def readCsv(file_path) { - def output = [] - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - - // todo: allow escaped quotes in string - // todo: allow single quotes? - def splitRegex = java.util.regex.Pattern.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''') - def removeQuote = java.util.regex.Pattern.compile('''"(.*)"''') - - def br = java.nio.file.Files.newBufferedReader(inputFile) - - def row = -1 - def header = null - while (br.ready() && header == null) { - def line = br.readLine() - row++ - if (!line.startsWith("#")) { - header = splitRegex.split(line, -1).collect{field -> - m = removeQuote.matcher(field) - m.find() ? m.replaceFirst('$1') : field - } - } - } - assert header != null: "CSV file should contain a header" - - while (br.ready()) { - def line = br.readLine() - row++ - if (line == null) { - br.close() - break - } - - if (!line.startsWith("#")) { - def predata = splitRegex.split(line, -1) - def data = predata.collect{field -> - if (field == "") { - return null - } - m = removeQuote.matcher(field) - if (m.find()) { - return m.replaceFirst('$1') - } else { - return field - } - } - assert header.size() == data.size(): "Row $row should contain the same number as fields as the header" - - def dataMap = [header, data].transpose().collectEntries().findAll{it.value != null} - output.add(dataMap) - } - } - - output -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJson.nf' -def readJson(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parse(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJsonBlob.nf' -def readJsonBlob(str) { - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parseText(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readTaggedYaml.nf' -// Custom constructor to modify how certain objects are parsed from YAML -class CustomConstructor extends org.yaml.snakeyaml.constructor.Constructor { - Path root - - class ConstructPath extends org.yaml.snakeyaml.constructor.AbstractConstruct { - public Object construct(org.yaml.snakeyaml.nodes.Node node) { - String filename = (String) constructScalar(node); - if (root != null) { - return root.resolve(filename); - } - return java.nio.file.Paths.get(filename); - } - } - - CustomConstructor(org.yaml.snakeyaml.LoaderOptions options, Path root) { - super(options) - this.root = root - // Handling !file tag and parse it back to a File type - this.yamlConstructors.put(new org.yaml.snakeyaml.nodes.Tag("!file"), new ConstructPath()) - } -} - -def readTaggedYaml(Path path) { - def options = new org.yaml.snakeyaml.LoaderOptions() - def constructor = new CustomConstructor(options, path.getParent()) - def yaml = new org.yaml.snakeyaml.Yaml(constructor) - return yaml.load(path.text) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYaml.nf' -def readYaml(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYamlBlob.nf' -def readYamlBlob(str) { - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toJsonBlob.nf' -String toJsonBlob(data) { - return groovy.json.JsonOutput.toJson(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toTaggedYamlBlob.nf' -// Custom representer to modify how certain objects are represented in YAML -class CustomRepresenter extends org.yaml.snakeyaml.representer.Representer { - Path relativizer - - class RepresentPath implements org.yaml.snakeyaml.representer.Represent { - public String getFileName(Object obj) { - if (obj instanceof File) { - obj = ((File) obj).toPath(); - } - if (obj !instanceof Path) { - throw new IllegalArgumentException("Object: " + obj + " is not a Path or File"); - } - def path = (Path) obj; - - if (relativizer != null) { - return relativizer.relativize(path).toString() - } else { - return path.toString() - } - } - - public org.yaml.snakeyaml.nodes.Node representData(Object data) { - String filename = getFileName(data); - def tag = new org.yaml.snakeyaml.nodes.Tag("!file"); - return representScalar(tag, filename); - } - } - CustomRepresenter(org.yaml.snakeyaml.DumperOptions options, Path relativizer) { - super(options) - this.relativizer = relativizer - this.representers.put(sun.nio.fs.UnixPath, new RepresentPath()) - this.representers.put(Path, new RepresentPath()) - this.representers.put(File, new RepresentPath()) - } -} - -String toTaggedYamlBlob(data) { - return toRelativeTaggedYamlBlob(data, null) -} -String toRelativeTaggedYamlBlob(data, Path relativizer) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - def representer = new CustomRepresenter(options, relativizer) - def yaml = new org.yaml.snakeyaml.Yaml(representer, options) - return yaml.dump(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toYamlBlob.nf' -String toYamlBlob(data) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - options.setPrettyFlow(true) - def yaml = new org.yaml.snakeyaml.Yaml(options) - def cleanData = iterateMap(data, { it instanceof Path ? it.toString() : it }) - return yaml.dump(cleanData) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeJson.nf' -void writeJson(data, file) { - assert data: "writeJson: data should not be null" - assert file: "writeJson: file should not be null" - file.write(toJsonBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeYaml.nf' -void writeYaml(data, file) { - assert data: "writeYaml: data should not be null" - assert file: "writeYaml: file should not be null" - file.write(toYamlBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/findStates.nf' -def findStates(Map params, Map config) { - // TODO: do a deep clone of config - def auto_config = deepClone(config) - def auto_params = deepClone(params) - - auto_config = auto_config.clone() - // override arguments - auto_config.functionality.argument_groups = [] - auto_config.functionality.arguments = [ - [ - type: "string", - name: "--id", - description: "A dummy identifier", - required: false - ], - [ - type: "file", - name: "--input_states", - example: "/path/to/input/directory/**/state.yaml", - description: "Path to input directory containing the datasets to be integrated.", - required: true, - multiple: true, - multiple_sep: ";" - ], - [ - type: "string", - name: "--filter", - example: "foo/.*/state.yaml", - description: "Regex to filter state files by path.", - required: false - ], - // to do: make this a yaml blob? - [ - type: "string", - name: "--rename_keys", - example: ["newKey1:oldKey1", "newKey2:oldKey2"], - description: "Rename keys in the detected input files. This is useful if the input files do not match the set of input arguments of the workflow.", - required: false, - multiple: true, - multiple_sep: "," - ], - [ - type: "string", - name: "--settings", - example: '{"output_dataset": "dataset.h5ad", "k": 10}', - description: "Global arguments as a JSON glob to be passed to all components.", - required: false - ] - ] - if (!(auto_params.containsKey("id"))) { - auto_params["id"] = "auto" - } - - // run auto config through processConfig once more - auto_config = processConfig(auto_config) - - workflow findStatesWf { - helpMessage(auto_config) - - output_ch = - channelFromParams(auto_params, auto_config) - | flatMap { autoId, args -> - - def globalSettings = args.settings ? readYamlBlob(args.settings) : [:] - - // look for state files in input dir - def stateFiles = args.input_states - - // filter state files by regex - if (args.filter) { - stateFiles = stateFiles.findAll{ stateFile -> - def stateFileStr = stateFile.toString() - def matcher = stateFileStr =~ args.filter - matcher.matches()} - } - - // read in states - def states = stateFiles.collect { stateFile -> - def state_ = readTaggedYaml(stateFile) - [state_.id, state_] - } - - // construct renameMap - if (args.rename_keys) { - def renameMap = args.rename_keys.collectEntries{renameString -> - def split = renameString.split(":") - assert split.size() == 2: "Argument 'rename_keys' should be of the form 'newKey:oldKey,newKey:oldKey'" - split - } - - // rename keys in state, only let states through which have all keys - // also add global settings - states = states.collectMany{id, state -> - def newState = [:] - - for (key in renameMap.keySet()) { - def origKey = renameMap[key] - if (!(state.containsKey(origKey))) { - return [] - } - newState[key] = state[origKey] - } - - [[id, globalSettings + newState]] - } - } - - states - } - emit: - output_ch - } - - return findStatesWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/joinStates.nf' -def joinStates(Closure apply_) { - workflow joinStatesWf { - take: input_ch - main: - output_ch = input_ch - | toSortedList - | filter{ it.size() > 0 } - | map{ tups -> - def ids = tups.collect{it[0]} - def states = tups.collect{it[1]} - apply_(ids, states) - } - - emit: output_ch - } - return joinStatesWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/publishStates.nf' -def collectFiles(obj) { - if (obj instanceof java.io.File || obj instanceof Path) { - return [obj] - } else if (obj instanceof List && obj !instanceof String) { - return obj.collectMany{item -> - collectFiles(item) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectFiles(item) - } - } else { - return [] - } -} - -/** - * Recurse through a state and collect all input files and their target output filenames. - * @param obj The state to recurse through. - * @param prefix The prefix to prepend to the output filenames. - */ -def collectInputOutputPaths(obj, prefix) { - if (obj instanceof File || obj instanceof Path) { - def path = obj instanceof Path ? obj : obj.toPath() - def ext = path.getFileName().toString().find("\\.[^\\.]+\$") ?: "" - def newFilename = prefix + ext - return [[obj, newFilename]] - } else if (obj instanceof List && obj !instanceof String) { - return obj.withIndex().collectMany{item, ix -> - collectInputOutputPaths(item, prefix + "_" + ix) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectInputOutputPaths(item, prefix + "." + key) - } - } else { - return [] - } -} - -def publishStates(Map args) { - def key_ = args.get("key") - def yamlTemplate_ = args.get("output_state", args.get("outputState", '$id.$key.state.yaml')) - - assert key_ != null : "publishStates: key must be specified" - - workflow publishStatesWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] - - // the input files and the target output filenames - def inputOutputFiles_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() - def inputFiles_ = inputOutputFiles_[0] - def outputFiles_ = inputOutputFiles_[1] - - def yamlFilename = yamlTemplate_ - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - - // TODO: do the pathnames in state_ match up with the outputFiles_? - - // convert state to yaml blob - def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesWf -} -process publishStatesProc { - // todo: check publishpath? - publishDir path: "${getPublishDir()}/", mode: "copy" - tag "$id" - input: - tuple val(id), val(yamlBlob), val(yamlFile), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) - output: - tuple val(id), path{[yamlFile] + outputFiles} - script: - def copyCommands = [ - inputFiles instanceof List ? inputFiles : [inputFiles], - outputFiles instanceof List ? outputFiles : [outputFiles] - ] - .transpose() - .collectMany{infile, outfile -> - if (infile.toString() != outfile.toString()) { - [ - "[ -d \"\$(dirname '${outfile.toString()}')\" ] || mkdir -p \"\$(dirname '${outfile.toString()}')\"", - "cp -r '${infile.toString()}' '${outfile.toString()}'" - ] - } else { - // no need to copy if infile is the same as outfile - [] - } - } - """ - mkdir -p "\$(dirname '${yamlFile}')" - echo "Storing state as yaml" - echo '${yamlBlob}' > '${yamlFile}' - echo "Copying output files to destination folder" - ${copyCommands.join("\n ")} - """ -} - - -// this assumes that the state contains no other values other than those specified in the config -def publishStatesByConfig(Map args) { - def config = args.get("config") - assert config != null : "publishStatesByConfig: config must be specified" - - def key_ = args.get("key", config.functionality.name) - assert key_ != null : "publishStatesByConfig: key must be specified" - - workflow publishStatesSimpleWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] // e.g. [output: new File("myoutput.h5ad"), k: 10] - def origState_ = tup[2] // e.g. [output: '$id.$key.foo.h5ad'] - - // TODO: allow overriding the state.yaml template - // TODO TODO: if auto.publish == "state", add output_state as an argument - def yamlTemplate = params.containsKey("output_state") ? params.output_state : '$id.$key.state.yaml' - def yamlFilename = yamlTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() - - // the processed state is a list of [key, value, srcPath, destPath] tuples, where - // - key, value is part of the state to be saved to disk - // - srcPath and destPath are lists of files to be copied from src to dest - def processedState = - config.functionality.allArguments - .findAll { it.direction == "output" } - .collectMany { par -> - def plainName_ = par.plainName - // if the state does not contain the key, it's an - // optional argument for which the component did - // not generate any output - if (!state_.containsKey(plainName_)) { - return [] - } - def value = state_[plainName_] - // if the parameter is not a file, it should be stored - // in the state as-is, but is not something that needs - // to be copied from the source path to the dest path - if (par.type != "file") { - return [[key: plainName_, value: value, srcPath: [], destPath: []]] - } - // if the orig state does not contain this filename, - // it's an optional argument for which the user specified - // that it should not be returned as a state - if (!origState_.containsKey(plainName_)) { - return [] - } - def filenameTemplate = origState_[plainName_] - // if the pararameter is multiple: true, fetch the template - if (par.multiple && filenameTemplate instanceof List) { - filenameTemplate = filenameTemplate[0] - } - // instantiate the template - def filename = filenameTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - if (par.multiple) { - // if the parameter is multiple: true, the filename - // should contain a wildcard '*' that is replaced with - // the index of the file - assert filename.contains("*") : "Module '${key_}' id '${id_}': Multiple output files specified, but no wildcard '*' in the filename: ${filename}" - def outputPerFile = value.withIndex().collect{ val, ix -> - def value_ = java.nio.file.Paths.get(filename.replace("*", ix.toString())) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = val instanceof File ? val.toPath() : val - [value: value_, srcPath: srcPath, destPath: destPath] - } - def transposedOutputs = ["value", "srcPath", "destPath"].collectEntries{ key -> - [key, outputPerFile.collect{dic -> dic[key]}] - } - return [[key: plainName_] + transposedOutputs] - } else { - def value_ = java.nio.file.Paths.get(filename) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = value instanceof File ? value.toPath() : value - return [[key: plainName_, value: value_, srcPath: [srcPath], destPath: [filename]]] - } - } - - def updatedState_ = processedState.collectEntries{[it.key, it.value]} - def inputFiles_ = processedState.collectMany{it.srcPath} - def outputFiles_ = processedState.collectMany{it.destPath} - - // convert state to yaml blob - def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesSimpleWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/setState.nf' -def setState(fun) { - assert fun instanceof Closure || fun instanceof Map || fun instanceof List : - "Error in setState: Expected process argument to be a Closure, a Map, or a List. Found: class ${fun.getClass()}" - - // if fun is a List, convert to map - if (fun instanceof List) { - // check whether fun is a list[string] - assert fun.every{it instanceof CharSequence} : "Error in setState: argument is a List, but not all elements are Strings" - fun = fun.collectEntries{[it, it]} - } - - // if fun is a map, convert to closure - if (fun instanceof Map) { - // check whether fun is a map[string, string] - assert fun.values().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all values are Strings" - assert fun.keySet().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all keys are Strings" - def funMap = fun.clone() - // turn the map into a closure to be used later on - fun = { id_, state_ -> - assert state_ instanceof Map : "Error in setState: the state is not a Map" - funMap.collectMany{newkey, origkey -> - if (state_.containsKey(origkey)) { - [[newkey, state_[origkey]]] - } else { - [] - } - }.collectEntries() - } - } - - map { tup -> - def id = tup[0] - def state = tup[1] - def unfilteredState = fun(id, state) - def newState = unfilteredState.findAll{key, val -> val != null} - [id, newState] + tup.drop(2) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processAuto.nf' -// TODO: unit test processAuto -def processAuto(Map auto) { - // remove null values - auto = auto.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = ["simplifyInput", "simplifyOutput", "transcript", "publish"] - def unexpectedKeys = auto.keySet() - expectedKeys - assert unexpectedKeys.isEmpty(), "unexpected keys in auto: '${unexpectedKeys.join("', '")}'" - - // check auto.simplifyInput - assert auto.simplifyInput instanceof Boolean, "auto.simplifyInput must be a boolean" - - // check auto.simplifyOutput - assert auto.simplifyOutput instanceof Boolean, "auto.simplifyOutput must be a boolean" - - // check auto.transcript - assert auto.transcript instanceof Boolean, "auto.transcript must be a boolean" - - // check auto.publish - assert auto.publish instanceof Boolean || auto.publish == "state", "auto.publish must be a boolean or 'state'" - - return auto.subMap(expectedKeys) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processDirectives.nf' -def assertMapKeys(map, expectedKeys, requiredKeys, mapName) { - assert map instanceof Map : "Expected argument '$mapName' to be a Map. Found: class ${map.getClass()}" - map.forEach { key, val -> - assert key in expectedKeys : "Unexpected key '$key' in ${mapName ? mapName + " " : ""}map" - } - requiredKeys.forEach { requiredKey -> - assert map.containsKey(requiredKey) : "Missing required key '$key' in ${mapName ? mapName + " " : ""}map" - } -} - -// TODO: unit test processDirectives -def processDirectives(Map drctv) { - // remove null values - drctv = drctv.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = [ - "accelerator", "afterScript", "beforeScript", "cache", "conda", "container", "containerOptions", "cpus", "disk", "echo", "errorStrategy", "executor", "machineType", "maxErrors", "maxForks", "maxRetries", "memory", "module", "penv", "pod", "publishDir", "queue", "label", "scratch", "storeDir", "stageInMode", "stageOutMode", "tag", "time" - ] - def unexpectedKeys = drctv.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Unexpected keys in process directive: '${unexpectedKeys.join("', '")}'" - - /* DIRECTIVE accelerator - accepted examples: - - [ limit: 4, type: "nvidia-tesla-k80" ] - */ - if (drctv.containsKey("accelerator")) { - assertMapKeys(drctv["accelerator"], ["type", "limit", "request", "runtime"], [], "accelerator") - } - - /* DIRECTIVE afterScript - accepted examples: - - "source /cluster/bin/cleanup" - */ - if (drctv.containsKey("afterScript")) { - assert drctv["afterScript"] instanceof CharSequence - } - - /* DIRECTIVE beforeScript - accepted examples: - - "source /cluster/bin/setup" - */ - if (drctv.containsKey("beforeScript")) { - assert drctv["beforeScript"] instanceof CharSequence - } - - /* DIRECTIVE cache - accepted examples: - - true - - false - - "deep" - - "lenient" - */ - if (drctv.containsKey("cache")) { - assert drctv["cache"] instanceof CharSequence || drctv["cache"] instanceof Boolean - if (drctv["cache"] instanceof CharSequence) { - assert drctv["cache"] in ["deep", "lenient"] : "Unexpected value for cache" - } - } - - /* DIRECTIVE conda - accepted examples: - - "bwa=0.7.15" - - "bwa=0.7.15 fastqc=0.11.5" - - ["bwa=0.7.15", "fastqc=0.11.5"] - */ - if (drctv.containsKey("conda")) { - if (drctv["conda"] instanceof List) { - drctv["conda"] = drctv["conda"].join(" ") - } - assert drctv["conda"] instanceof CharSequence - } - - /* DIRECTIVE container - accepted examples: - - "foo/bar:tag" - - [ registry: "reg", image: "im", tag: "ta" ] - is transformed to "reg/im:ta" - - [ image: "im" ] - is transformed to "im:latest" - */ - if (drctv.containsKey("container")) { - assert drctv["container"] instanceof Map || drctv["container"] instanceof CharSequence - if (drctv["container"] instanceof Map) { - def m = drctv["container"] - assertMapKeys(m, [ "registry", "image", "tag" ], ["image"], "container") - def part1 = - System.getenv('OVERRIDE_CONTAINER_REGISTRY') ? System.getenv('OVERRIDE_CONTAINER_REGISTRY') + "/" : - params.containsKey("override_container_registry") ? params["override_container_registry"] + "/" : // todo: remove? - m.registry ? m.registry + "/" : - "" - def part2 = m.image - def part3 = m.tag ? ":" + m.tag : ":latest" - drctv["container"] = part1 + part2 + part3 - } - } - - /* DIRECTIVE containerOptions - accepted examples: - - "--foo bar" - - ["--foo bar", "-f b"] - */ - if (drctv.containsKey("containerOptions")) { - if (drctv["containerOptions"] instanceof List) { - drctv["containerOptions"] = drctv["containerOptions"].join(" ") - } - assert drctv["containerOptions"] instanceof CharSequence - } - - /* DIRECTIVE cpus - accepted examples: - - 1 - - 10 - */ - if (drctv.containsKey("cpus")) { - assert drctv["cpus"] instanceof Integer - } - - /* DIRECTIVE disk - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("disk")) { - assert drctv["disk"] instanceof CharSequence - // assert drctv["disk"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE echo - accepted examples: - - true - - false - */ - if (drctv.containsKey("echo")) { - assert drctv["echo"] instanceof Boolean - } - - /* DIRECTIVE errorStrategy - accepted examples: - - "terminate" - - "finish" - */ - if (drctv.containsKey("errorStrategy")) { - assert drctv["errorStrategy"] instanceof CharSequence - assert drctv["errorStrategy"] in ["terminate", "finish", "ignore", "retry"] : "Unexpected value for errorStrategy" - } - - /* DIRECTIVE executor - accepted examples: - - "local" - - "sge" - */ - if (drctv.containsKey("executor")) { - assert drctv["executor"] instanceof CharSequence - assert drctv["executor"] in ["local", "sge", "uge", "lsf", "slurm", "pbs", "pbspro", "moab", "condor", "nqsii", "ignite", "k8s", "awsbatch", "google-pipelines"] : "Unexpected value for executor" - } - - /* DIRECTIVE machineType - accepted examples: - - "n1-highmem-8" - */ - if (drctv.containsKey("machineType")) { - assert drctv["machineType"] instanceof CharSequence - } - - /* DIRECTIVE maxErrors - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxErrors")) { - assert drctv["maxErrors"] instanceof Integer - } - - /* DIRECTIVE maxForks - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxForks")) { - assert drctv["maxForks"] instanceof Integer - } - - /* DIRECTIVE maxRetries - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxRetries")) { - assert drctv["maxRetries"] instanceof Integer - } - - /* DIRECTIVE memory - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("memory")) { - assert drctv["memory"] instanceof CharSequence - // assert drctv["memory"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE module - accepted examples: - - "ncbi-blast/2.2.27" - - "ncbi-blast/2.2.27:t_coffee/10.0" - - ["ncbi-blast/2.2.27", "t_coffee/10.0"] - */ - if (drctv.containsKey("module")) { - if (drctv["module"] instanceof List) { - drctv["module"] = drctv["module"].join(":") - } - assert drctv["module"] instanceof CharSequence - } - - /* DIRECTIVE penv - accepted examples: - - "smp" - */ - if (drctv.containsKey("penv")) { - assert drctv["penv"] instanceof CharSequence - } - - /* DIRECTIVE pod - accepted examples: - - [ label: "key", value: "val" ] - - [ annotation: "key", value: "val" ] - - [ env: "key", value: "val" ] - - [ [label: "l", value: "v"], [env: "e", value: "v"]] - */ - if (drctv.containsKey("pod")) { - if (drctv["pod"] instanceof Map) { - drctv["pod"] = [ drctv["pod"] ] - } - assert drctv["pod"] instanceof List - drctv["pod"].forEach { pod -> - assert pod instanceof Map - // TODO: should more checks be added? - // See https://www.nextflow.io/docs/latest/process.html?highlight=directives#pod - // e.g. does it contain 'label' and 'value', or 'annotation' and 'value', or ...? - } - } - - /* DIRECTIVE publishDir - accepted examples: - - [] - - [ [ path: "foo", enabled: true ], [ path: "bar", enabled: false ] ] - - "/path/to/dir" - is transformed to [[ path: "/path/to/dir" ]] - - [ path: "/path/to/dir", mode: "cache" ] - is transformed to [[ path: "/path/to/dir", mode: "cache" ]] - */ - // TODO: should we also look at params["publishDir"]? - if (drctv.containsKey("publishDir")) { - def pblsh = drctv["publishDir"] - - // check different options - assert pblsh instanceof List || pblsh instanceof Map || pblsh instanceof CharSequence - - // turn into list if not already so - // for some reason, 'if (!pblsh instanceof List) pblsh = [ pblsh ]' doesn't work. - pblsh = pblsh instanceof List ? pblsh : [ pblsh ] - - // check elements of publishDir - pblsh = pblsh.collect{ elem -> - // turn into map if not already so - elem = elem instanceof CharSequence ? [ path: elem ] : elem - - // check types and keys - assert elem instanceof Map : "Expected publish argument '$elem' to be a String or a Map. Found: class ${elem.getClass()}" - assertMapKeys(elem, [ "path", "mode", "overwrite", "pattern", "saveAs", "enabled" ], ["path"], "publishDir") - - // check elements in map - assert elem.containsKey("path") - assert elem["path"] instanceof CharSequence - if (elem.containsKey("mode")) { - assert elem["mode"] instanceof CharSequence - assert elem["mode"] in [ "symlink", "rellink", "link", "copy", "copyNoFollow", "move" ] - } - if (elem.containsKey("overwrite")) { - assert elem["overwrite"] instanceof Boolean - } - if (elem.containsKey("pattern")) { - assert elem["pattern"] instanceof CharSequence - } - if (elem.containsKey("saveAs")) { - assert elem["saveAs"] instanceof CharSequence //: "saveAs as a Closure is currently not supported. Surround your closure with single quotes to get the desired effect. Example: '\{ foo \}'" - } - if (elem.containsKey("enabled")) { - assert elem["enabled"] instanceof Boolean - } - - // return final result - elem - } - // store final directive - drctv["publishDir"] = pblsh - } - - /* DIRECTIVE queue - accepted examples: - - "long" - - "short,long" - - ["short", "long"] - */ - if (drctv.containsKey("queue")) { - if (drctv["queue"] instanceof List) { - drctv["queue"] = drctv["queue"].join(",") - } - assert drctv["queue"] instanceof CharSequence - } - - /* DIRECTIVE label - accepted examples: - - "big_mem" - - "big_cpu" - - ["big_mem", "big_cpu"] - */ - if (drctv.containsKey("label")) { - if (drctv["label"] instanceof CharSequence) { - drctv["label"] = [ drctv["label"] ] - } - assert drctv["label"] instanceof List - drctv["label"].forEach { label -> - assert label instanceof CharSequence - // assert label.matches("[a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?") - // ^ does not allow closures - } - } - - /* DIRECTIVE scratch - accepted examples: - - true - - "/path/to/scratch" - - '$MY_PATH_TO_SCRATCH' - - "ram-disk" - */ - if (drctv.containsKey("scratch")) { - assert drctv["scratch"] == true || drctv["scratch"] instanceof CharSequence - } - - /* DIRECTIVE storeDir - accepted examples: - - "/path/to/storeDir" - */ - if (drctv.containsKey("storeDir")) { - assert drctv["storeDir"] instanceof CharSequence - } - - /* DIRECTIVE stageInMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageInMode")) { - assert drctv["stageInMode"] instanceof CharSequence - assert drctv["stageInMode"] in ["copy", "link", "symlink", "rellink"] - } - - /* DIRECTIVE stageOutMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageOutMode")) { - assert drctv["stageOutMode"] instanceof CharSequence - assert drctv["stageOutMode"] in ["copy", "move", "rsync"] - } - - /* DIRECTIVE tag - accepted examples: - - "foo" - - '$id' - */ - if (drctv.containsKey("tag")) { - assert drctv["tag"] instanceof CharSequence - } - - /* DIRECTIVE time - accepted examples: - - "1h" - - "2days" - - "1day 6hours 3minutes 30seconds" - */ - if (drctv.containsKey("time")) { - assert drctv["time"] instanceof CharSequence - // todo: validation regex? - } - - return drctv -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processWorkflowArgs.nf' -def processWorkflowArgs(Map args, Map defaultWfArgs, Map meta) { - // override defaults with args - def workflowArgs = defaultWfArgs + args - - // check whether 'key' exists - assert workflowArgs.containsKey("key") : "Error in module '${meta.config.functionality.name}': key is a required argument" - - // if 'key' is a closure, apply it to the original key - if (workflowArgs["key"] instanceof Closure) { - workflowArgs["key"] = workflowArgs["key"](meta.config.functionality.name) - } - def key = workflowArgs["key"] - assert key instanceof CharSequence : "Expected process argument 'key' to be a String. Found: class ${key.getClass()}" - assert key ==~ /^[a-zA-Z_]\w*$/ : "Error in module '$key': Expected process argument 'key' to consist of only letters, digits or underscores. Found: ${key}" - - // check for any unexpected keys - def expectedKeys = ["key", "directives", "auto", "map", "mapId", "mapData", "mapPassthrough", "filter", "runIf", "fromState", "toState", "args", "renameKeys", "debug"] - def unexpectedKeys = workflowArgs.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Error in module '$key': unexpected arguments to the '.run()' function: '${unexpectedKeys.join("', '")}'" - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("directives") : "Error in module '$key': directives is a required argument" - assert workflowArgs["directives"] instanceof Map : "Error in module '$key': Expected process argument 'directives' to be a Map. Found: class ${workflowArgs['directives'].getClass()}" - workflowArgs["directives"] = processDirectives(defaultWfArgs.directives + workflowArgs["directives"]) - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("auto") : "Error in module '$key': auto is a required argument" - assert workflowArgs["auto"] instanceof Map : "Error in module '$key': Expected process argument 'auto' to be a Map. Found: class ${workflowArgs['auto'].getClass()}" - workflowArgs["auto"] = processAuto(defaultWfArgs.auto + workflowArgs["auto"]) - - // auto define publish, if so desired - if (workflowArgs.auto.publish == true && (workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : [:]).isEmpty()) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.publish is true, params.publish_dir needs to be defined.\n" + - // " Example: params.publish_dir = \"./output/\"" - def publishDir = getPublishDir() - - if (publishDir != null) { - workflowArgs.directives.publishDir = [[ - path: publishDir, - saveAs: "{ it.startsWith('.') ? null : it }", // don't publish hidden files, by default - mode: "copy" - ]] - } - } - - // auto define transcript, if so desired - if (workflowArgs.auto.transcript == true) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("transcriptsDir") || params.containsKey("transcripts_dir") || params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.transcript is true, either params.transcripts_dir or params.publish_dir needs to be defined.\n" + - // " Example: params.transcripts_dir = \"./transcripts/\"" - def transcriptsDir = - params.containsKey("transcripts_dir") ? params.transcripts_dir : - params.containsKey("transcriptsDir") ? params.transcriptsDir : - params.containsKey("publish_dir") ? params.publish_dir + "/_transcripts" : - params.containsKey("publishDir") ? params.publishDir + "/_transcripts" : - null - if (transcriptsDir != null) { - def timestamp = nextflow.Nextflow.getSession().getWorkflowMetadata().start.format('yyyy-MM-dd_HH-mm-ss') - def transcriptsPublishDir = [ - path: "$transcriptsDir/$timestamp/\${task.process.replaceAll(':', '-')}/\${id}/", - saveAs: "{ it.startsWith('.') ? it.replaceAll('^.', '') : null }", - mode: "copy" - ] - def publishDirs = workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : null ? workflowArgs.directives.publishDir : [] - workflowArgs.directives.publishDir = publishDirs + transcriptsPublishDir - } - } - - // if this is a stubrun, remove certain directives? - if (workflow.stubRun) { - workflowArgs.directives.keySet().removeAll(["publishDir", "cpus", "memory", "label"]) - } - - for (nam in ["map", "mapId", "mapData", "mapPassthrough", "filter", "runIf"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam]) { - assert workflowArgs[nam] instanceof Closure : "Error in module '$key': Expected process argument '$nam' to be null or a Closure. Found: class ${workflowArgs[nam].getClass()}" - } - } - - // TODO: should functions like 'map', 'mapId', 'mapData', 'mapPassthrough' be deprecated as well? - for (nam in ["map", "mapData", "mapPassthrough", "renameKeys"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam] != null) { - log.warn "module '$key': workflow argument '$nam' is deprecated and will be removed in Viash 0.9.0. Please use 'fromState' and 'toState' instead." - } - } - - // check fromState - workflowArgs["fromState"] = _processFromState(workflowArgs.get("fromState"), key, meta.config) - - // check toState - workflowArgs["toState"] = _processToState(workflowArgs.get("toState"), key, meta.config) - - // return output - return workflowArgs -} - -def _processFromState(fromState, key_, config_) { - assert fromState == null || fromState instanceof Closure || fromState instanceof Map || fromState instanceof List : - "Error in module '$key_': Expected process argument 'fromState' to be null, a Closure, a Map, or a List. Found: class ${fromState.getClass()}" - if (fromState == null) { - return null - } - - // if fromState is a List, convert to map - if (fromState instanceof List) { - // check whether fromstate is a list[string] - assert fromState.every{it instanceof CharSequence} : "Error in module '$key_': fromState is a List, but not all elements are Strings" - fromState = fromState.collectEntries{[it, it]} - } - - // if fromState is a map, convert to closure - if (fromState instanceof Map) { - // check whether fromstate is a map[string, string] - assert fromState.values().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all values are Strings" - assert fromState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all keys are Strings" - def fromStateMap = fromState.clone() - def requiredInputNames = meta.config.functionality.allArguments.findAll{it.required && it.direction == "Input"}.collect{it.plainName} - // turn the map into a closure to be used later on - fromState = { it -> - def state = it[1] - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def data = fromStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (state.containsKey(origkey)) { - [[newkey, state[origkey]]] - } else if (!requiredInputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': fromState key '$origkey' not found in current state") - } - }.collectEntries() - data - } - } - - return fromState -} - -def _processToState(toState, key_, config_) { - if (toState == null) { - toState = { tup -> tup[1] } - } - - // toState should be a closure, map[string, string], or list[string] - assert toState instanceof Closure || toState instanceof Map || toState instanceof List : - "Error in module '$key_': Expected process argument 'toState' to be a Closure, a Map, or a List. Found: class ${toState.getClass()}" - - // if toState is a List, convert to map - if (toState instanceof List) { - // check whether toState is a list[string] - assert toState.every{it instanceof CharSequence} : "Error in module '$key_': toState is a List, but not all elements are Strings" - toState = toState.collectEntries{[it, it]} - } - - // if toState is a map, convert to closure - if (toState instanceof Map) { - // check whether toState is a map[string, string] - assert toState.values().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all values are Strings" - assert toState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all keys are Strings" - def toStateMap = toState.clone() - def requiredOutputNames = config_.functionality.allArguments.findAll{it.required && it.direction == "Output"}.collect{it.plainName} - // turn the map into a closure to be used later on - toState = { it -> - def output = it[1] - def state = it[2] - assert output instanceof Map : "Error in module '$key_': the output is not a Map" - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def extraEntries = toStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (output.containsKey(origkey)) { - [[newkey, output[origkey]]] - } else if (!requiredOutputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': toState key '$origkey' not found in current output") - } - }.collectEntries() - state + extraEntries - } - } - - return toState -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/workflowFactory.nf' -def _debug(workflowArgs, debugKey) { - if (workflowArgs.debug) { - view { "process '${workflowArgs.key}' $debugKey tuple: $it" } - } else { - map { it } - } -} - -// depends on: innerWorkflowFactory -def workflowFactory(Map args, Map defaultWfArgs, Map meta) { - def workflowArgs = processWorkflowArgs(args, defaultWfArgs, meta) - def key_ = workflowArgs["key"] - - workflow workflowInstance { - take: input_ - - main: - chModified = input_ - | checkUniqueIds([:]) - | _debug(workflowArgs, "input") - | map { tuple -> - tuple = deepClone(tuple) - - if (workflowArgs.map) { - tuple = workflowArgs.map(tuple) - } - if (workflowArgs.mapId) { - tuple[0] = workflowArgs.mapId(tuple[0]) - } - if (workflowArgs.mapData) { - tuple[1] = workflowArgs.mapData(tuple[1]) - } - if (workflowArgs.mapPassthrough) { - tuple = tuple.take(2) + workflowArgs.mapPassthrough(tuple.drop(2)) - } - - // check tuple - assert tuple instanceof List : - "Error in module '${key_}': element in channel should be a tuple [id, data, ...otherargs...]\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: List. Found: tuple.getClass() is ${tuple.getClass()}" - assert tuple.size() >= 2 : - "Error in module '${key_}': expected length of tuple in input channel to be two or greater.\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: tuple.size() == ${tuple.size()}" - - // check id field - assert tuple[0] instanceof CharSequence : - "Error in module '${key_}': first element of tuple in channel should be a String\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: ${tuple[0]}" - - // match file to input file - if (workflowArgs.auto.simplifyInput && (tuple[1] instanceof Path || tuple[1] instanceof List)) { - def inputFiles = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - - assert inputFiles.size() == 1 : - "Error in module '${key_}' id '${tuple[0]}'.\n" + - " Anonymous file inputs are only allowed when the process has exactly one file input.\n" + - " Expected: inputFiles.size() == 1. Found: inputFiles.size() is ${inputFiles.size()}" - - tuple[1] = [[ inputFiles[0].plainName, tuple[1] ]].collectEntries() - } - - // check data field - assert tuple[1] instanceof Map : - "Error in module '${key_}' id '${tuple[0]}': second element of tuple in channel should be a Map\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // rename keys of data field in tuple - if (workflowArgs.renameKeys) { - assert workflowArgs.renameKeys instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class: Map. Found: renameKeys.getClass() is ${workflowArgs.renameKeys.getClass()}" - assert tuple[1] instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // TODO: allow renameKeys to be a function? - workflowArgs.renameKeys.each { newKey, oldKey -> - assert newKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of newKey: String. Found: newKey.getClass() is ${newKey.getClass()}" - assert oldKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of oldKey: String. Found: oldKey.getClass() is ${oldKey.getClass()}" - assert tuple[1].containsKey(oldKey) : - "Error renaming data keys in module '${key}' id '${tuple[0]}'.\n" + - " Key '$oldKey' is missing in the data map. tuple[1].keySet() is '${tuple[1].keySet()}'" - tuple[1].put(newKey, tuple[1][oldKey]) - } - tuple[1].keySet().removeAll(workflowArgs.renameKeys.collect{ newKey, oldKey -> oldKey }) - } - tuple - } - - chModifiedFiltered = workflowArgs.filter ? - chModified | filter{workflowArgs.filter(it)} : - chModified - - if (workflowArgs.runIf) { - runIfBranch = chModifiedFiltered.branch{ tup -> - run: workflowArgs.runIf(tup[0], tup[1]) - passthrough: true - } - chRun = runIfBranch.run - chPassthrough = runIfBranch.passthrough - } else { - chRun = chModifiedFiltered - chPassthrough = Channel.empty() - } - - chArgs = workflowArgs.fromState ? - chRun | map{ - def new_data = workflowArgs.fromState(it.take(2)) - [it[0], new_data] - } : - chRun | map {tup -> tup.take(2)} - - // fill in defaults - chArgsWithDefaults = chArgs - | map { tuple -> - def id_ = tuple[0] - def data_ = tuple[1] - - // TODO: could move fromState to here - - // fetch default params from functionality - def defaultArgs = meta.config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - // fetch overrides in params - def paramArgs = meta.config.functionality.allArguments - .findAll { par -> - def argKey = key_ + "__" + par.plainName - params.containsKey(argKey) - } - .collectEntries { [ it.plainName, params[key_ + "__" + it.plainName] ] } - - // fetch overrides in data - def dataArgs = meta.config.functionality.allArguments - .findAll { data_.containsKey(it.plainName) } - .collectEntries { [ it.plainName, data_[it.plainName] ] } - - // combine params - def combinedArgs = defaultArgs + paramArgs + workflowArgs.args + dataArgs - - // remove arguments with explicit null values - combinedArgs - .removeAll{_, val -> val == null || val == "viash_no_value" || val == "force_null"} - - combinedArgs = _processInputValues(combinedArgs, meta.config, id_, key_) - - [id_, combinedArgs] + tuple.drop(2) - } - - // TODO: move some of the _meta.join_id wrangling to the safeJoin() function. - chInitialOutput = chArgsWithDefaults - | _debug(workflowArgs, "processed") - // run workflow - | innerWorkflowFactory(workflowArgs) - // check output tuple - | map { id_, output_ -> - - // see if output map contains metadata - def meta_ = - output_ instanceof Map && output_.containsKey("_meta") ? - output_["_meta"] : - [:] - def join_id = meta_.join_id ?: id_ - - // remove metadata - output_ = output_.findAll{k, v -> k != "_meta"} - - // check value types - output_ = _processOutputValues(output_, meta.config, id_, key_) - - // simplify output if need be - if (workflowArgs.auto.simplifyOutput && output_.size() == 1) { - output_ = output_.values()[0] - } - - [join_id, id_, output_] - } - // | view{"chInitialOutput: ${it.take(3)}"} - - // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] - chNewState = safeJoin(chInitialOutput, chModifiedFiltered, key_) - // input tuple format: [join_id, id, output, prev_state, ...] - // output tuple format: [join_id, id, new_state, ...] - | map{ tup -> - def new_state = workflowArgs.toState(tup.drop(1).take(3)) - tup.take(2) + [new_state] + tup.drop(4) - } - - if (workflowArgs.auto.publish == "state") { - chPublish = chNewState - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [join_id, id, new_state] - | map{ tup -> - tup.take(3) - } - - safeJoin(chPublish, chArgsWithDefaults, key_) - // input tuple format: [join_id, id, new_state, orig_state, ...] - // output tuple format: [id, new_state, orig_state] - | map { tup -> - tup.drop(1).take(3) - } - | publishStatesByConfig(key: key_, config: meta.config) - } - - // remove join_id and meta - chReturn = chNewState - | map { tup -> - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [id, new_state, ...] - tup.drop(1) - } - | _debug(workflowArgs, "output") - | concat(chPassthrough) - - emit: chReturn - } - - def wf = workflowInstance.cloneWithName(key_) - - // add factory function - wf.metaClass.run = { runArgs -> - workflowFactory(runArgs, workflowArgs, meta) - } - // add config to module for later introspection - wf.metaClass.config = meta.config - - return wf -} - -nextflow.enable.dsl=2 - -// START COMPONENT-SPECIFIC CODE - -// create meta object -meta = [ - "resources_dir": moduleDir.toRealPath().normalize(), - "config": processConfig(readJsonBlob('''{ - "functionality" : { - "name" : "take_column", - "namespace" : "template", - "version" : "0.2.2", - "arguments" : [ - { - "type" : "file", - "name" : "--input", - "alternatives" : [ - "-i" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "input", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - }, - { - "type" : "file", - "name" : "--output", - "alternatives" : [ - "-o" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "output", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - }, - { - "type" : "integer", - "name" : "--column", - "default" : [ - 2 - ], - "required" : false, - "direction" : "input", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - } - ], - "resources" : [ - { - "type" : "python_script", - "path" : "script.py", - "is_executable" : true, - "parent" : "file:/Users/toni/code/projects/viash/viash_project_template/src/template/take_column/" - } - ], - "status" : "enabled", - "set_wd_to_resources_dir" : false - }, - "platforms" : [ - { - "type" : "docker", - "id" : "docker", - "image" : "python:3.10-slim", - "target_organization" : "viash-io/viash_project_template", - "target_registry" : "ghcr.io", - "namespace_separator" : "/", - "resolve_volume" : "Automatic", - "chown" : true, - "setup_strategy" : "ifneedbepullelsecachedbuild", - "target_image_source" : "https://github.com/viash-io/viash_project_template", - "setup" : [ - { - "type" : "python", - "user" : false, - "packages" : [ - "pandas" - ], - "upgrade" : true - }, - { - "type" : "apt", - "packages" : [ - "procps" - ], - "interactive" : false - } - ] - }, - { - "type" : "nextflow", - "id" : "nextflow", - "directives" : { - "tag" : "$id" - }, - "auto" : { - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false - }, - "config" : { - "labels" : { - "mem1gb" : "memory = 1.GB", - "mem2gb" : "memory = 2.GB", - "mem4gb" : "memory = 4.GB", - "mem8gb" : "memory = 8.GB", - "mem16gb" : "memory = 16.GB", - "mem32gb" : "memory = 32.GB", - "mem64gb" : "memory = 64.GB", - "mem128gb" : "memory = 128.GB", - "mem256gb" : "memory = 256.GB", - "mem512gb" : "memory = 512.GB", - "mem1tb" : "memory = 1.TB", - "mem2tb" : "memory = 2.TB", - "mem4tb" : "memory = 4.TB", - "mem8tb" : "memory = 8.TB", - "mem16tb" : "memory = 16.TB", - "mem32tb" : "memory = 32.TB", - "mem64tb" : "memory = 64.TB", - "mem128tb" : "memory = 128.TB", - "mem256tb" : "memory = 256.TB", - "mem512tb" : "memory = 512.TB", - "cpu1" : "cpus = 1", - "cpu2" : "cpus = 2", - "cpu5" : "cpus = 5", - "cpu10" : "cpus = 10", - "cpu20" : "cpus = 20", - "cpu50" : "cpus = 50", - "cpu100" : "cpus = 100", - "cpu200" : "cpus = 200", - "cpu500" : "cpus = 500", - "cpu1000" : "cpus = 1000" - } - }, - "debug" : false, - "container" : "docker" - } - ], - "info" : { - "config" : "/Users/toni/code/projects/viash/viash_project_template/src/template/take_column/config.vsh.yaml", - "platform" : "nextflow", - "output" : "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/take_column", - "viash_version" : "0.8.4", - "git_commit" : "11b6278597bf22afbfb56a8e83065a55553c9dd0", - "git_remote" : "https://github.com/viash-io/viash_project_template", - "git_tag" : "v0.2.1" - } -}''')) -] - -// resolve dependencies dependencies (if any) - - -// inner workflow -// inner workflow hook -def innerWorkflowFactory(args) { - def rawScript = '''set -e -tempscript=".viash_script.sh" -cat > "$tempscript" << VIASHMAIN -import pandas as pd - -## VIASH START -# The following code has been auto-generated by Viash. -par = { - 'input': $( if [ ! -z ${VIASH_PAR_INPUT+x} ]; then echo "r'${VIASH_PAR_INPUT//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'output': $( if [ ! -z ${VIASH_PAR_OUTPUT+x} ]; then echo "r'${VIASH_PAR_OUTPUT//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'column': $( if [ ! -z ${VIASH_PAR_COLUMN+x} ]; then echo "int(r'${VIASH_PAR_COLUMN//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ) -} -meta = { - 'functionality_name': $( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo "r'${VIASH_META_FUNCTIONALITY_NAME//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'resources_dir': $( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo "r'${VIASH_META_RESOURCES_DIR//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'executable': $( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo "r'${VIASH_META_EXECUTABLE//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'config': $( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo "r'${VIASH_META_CONFIG//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'temp_dir': $( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo "r'${VIASH_META_TEMP_DIR//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'cpus': $( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo "int(r'${VIASH_META_CPUS//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_b': $( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo "int(r'${VIASH_META_MEMORY_B//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_kb': $( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo "int(r'${VIASH_META_MEMORY_KB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_mb': $( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo "int(r'${VIASH_META_MEMORY_MB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_gb': $( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo "int(r'${VIASH_META_MEMORY_GB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_tb': $( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo "int(r'${VIASH_META_MEMORY_TB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_pb': $( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo "int(r'${VIASH_META_MEMORY_PB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ) -} -dep = { - -} - -## VIASH END - -# read the tsv file -tab = pd.read_csv(par["input"], sep="\\\\t", comment="#") - -# subset a column -tab_filt = tab.iloc[:, par["column"]-1] - -# write to file -tab_filt.to_csv(par["output"], index=False) -VIASHMAIN -python -B "$tempscript" -''' - - return vdsl3WorkflowFactory(args, meta, rawScript) -} - - - -/** - * Generate a workflow for VDSL3 modules. - * - * This function is called by the workflowFactory() function. - * - * Input channel: [id, input_map] - * Output channel: [id, output_map] - * - * Internally, this workflow will convert the input channel - * to a format which the Nextflow module will be able to handle. - */ -def vdsl3WorkflowFactory(Map args, Map meta, String rawScript) { - def key = args["key"] - def processObj = null - - workflow processWf { - take: input_ - main: - - if (processObj == null) { - processObj = _vdsl3ProcessFactory(args, meta, rawScript) - } - - output_ = input_ - | map { tuple -> - def id = tuple[0] - def data_ = tuple[1] - - if (workflow.stubRun) { - // add id if missing - data_ = [id: 'stub'] + data_ - } - - // process input files separately - def inputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - .collect { par -> - def val = data_.containsKey(par.plainName) ? data_[par.plainName] : [] - def inputFiles = [] - if (val == null) { - inputFiles = [] - } else if (val instanceof List) { - inputFiles = val - } else if (val instanceof Path) { - inputFiles = [ val ] - } else { - inputFiles = [] - } - if (!workflow.stubRun) { - // throw error when an input file doesn't exist - inputFiles.each{ file -> - assert file.exists() : - "Error in module '${key}' id '${id}' argument '${par.plainName}'.\n" + - " Required input file does not exist.\n" + - " Path: '$file'.\n" + - " Expected input file to exist" - } - } - inputFiles - } - - // remove input files - def argsExclInputFiles = meta.config.functionality.allArguments - .findAll { (it.type != "file" || it.direction != "input") && data_.containsKey(it.plainName) } - .collectEntries { par -> - def parName = par.plainName - def val = data_[parName] - if (par.multiple && val instanceof Collection) { - val = val.join(par.multiple_sep) - } - if (par.direction == "output" && par.type == "file") { - val = val.replaceAll('\\$id', id).replaceAll('\\$key', key) - } - [parName, val] - } - - [ id ] + inputPaths + [ argsExclInputFiles, meta.resources_dir ] - } - | processObj - | map { output -> - def outputFiles = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .indexed() - .collectEntries{ index, par -> - out = output[index + 1] - // strip dummy '.exitcode' file from output (see nextflow-io/nextflow#2678) - if (!out instanceof List || out.size() <= 1) { - if (par.multiple) { - out = [] - } else { - assert !par.required : - "Error in module '${key}' id '${output[0]}' argument '${par.plainName}'.\n" + - " Required output file is missing" - out = null - } - } else if (out.size() == 2 && !par.multiple) { - out = out[1] - } else { - out = out.drop(1) - } - [ par.plainName, out ] - } - - // drop null outputs - outputFiles.removeAll{it.value == null} - - [ output[0], outputFiles ] - } - emit: output_ - } - - return processWf -} - -// depends on: session? -def _vdsl3ProcessFactory(Map workflowArgs, Map meta, String rawScript) { - // autodetect process key - def wfKey = workflowArgs["key"] - def procKeyPrefix = "${wfKey}_process" - def scriptMeta = nextflow.script.ScriptMeta.current() - def existing = scriptMeta.getProcessNames().findAll{it.startsWith(procKeyPrefix)} - def numbers = existing.collect{it.replace(procKeyPrefix, "0").toInteger()} - def newNumber = (numbers + [-1]).max() + 1 - - def procKey = newNumber == 0 ? procKeyPrefix : "$procKeyPrefix$newNumber" - - if (newNumber > 0) { - log.warn "Key for module '${wfKey}' is duplicated.\n", - "If you run a component multiple times in the same workflow,\n" + - "it's recommended you set a unique key for every call,\n" + - "for example: ${wfKey}.run(key: \"foo\")." - } - - // subset directives and convert to list of tuples - def drctv = workflowArgs.directives - - // TODO: unit test the two commands below - // convert publish array into tags - def valueToStr = { val -> - // ignore closures - if (val instanceof CharSequence) { - if (!val.matches('^[{].*[}]$')) { - '"' + val + '"' - } else { - val - } - } else if (val instanceof List) { - "[" + val.collect{valueToStr(it)}.join(", ") + "]" - } else if (val instanceof Map) { - "[" + val.collect{k, v -> k + ": " + valueToStr(v)}.join(", ") + "]" - } else { - val.inspect() - } - } - - // multiple entries allowed: label, publishdir - def drctvStrs = drctv.collect { key, value -> - if (key in ["label", "publishDir"]) { - value.collect{ val -> - if (val instanceof Map) { - "\n$key " + val.collect{ k, v -> k + ": " + valueToStr(v) }.join(", ") - } else if (val == null) { - "" - } else { - "\n$key " + valueToStr(val) - } - }.join() - } else if (value instanceof Map) { - "\n$key " + value.collect{ k, v -> k + ": " + valueToStr(v) }.join(", ") - } else { - "\n$key " + valueToStr(value) - } - }.join() - - def inputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - .collect { ', path(viash_par_' + it.plainName + ', stageAs: "_viash_par/' + it.plainName + '_?/*")' } - .join() - - def outputPaths = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .collect { par -> - // insert dummy into every output (see nextflow-io/nextflow#2678) - if (!par.multiple) { - ', path{[".exitcode", args.' + par.plainName + ']}' - } else { - ', path{[".exitcode"] + args.' + par.plainName + '}' - } - } - .join() - - // TODO: move this functionality somewhere else? - if (workflowArgs.auto.transcript) { - outputPaths = outputPaths + ', path{[".exitcode", ".command*"]}' - } else { - outputPaths = outputPaths + ', path{[".exitcode"]}' - } - - // create dirs for output files (based on BashWrapper.createParentFiles) - def createParentStr = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" && it.create_parent } - .collect { par -> - "\${ args.containsKey(\"${par.plainName}\") ? \"mkdir_parent \\\"\" + (args[\"${par.plainName}\"] instanceof String ? args[\"${par.plainName}\"] : args[\"${par.plainName}\"].join('\" \"')) + \"\\\"\" : \"\" }" - } - .join("\n") - - // construct inputFileExports - def inputFileExports = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction.toLowerCase() == "input" } - .collect { par -> - viash_par_contents = "(viash_par_${par.plainName} instanceof List ? viash_par_${par.plainName}.join(\"${par.multiple_sep}\") : viash_par_${par.plainName})" - "\n\${viash_par_${par.plainName}.empty ? \"\" : \"export VIASH_PAR_${par.plainName.toUpperCase()}=\\\"\" + ${viash_par_contents} + \"\\\"\"}" - } - - // NOTE: if using docker, use /tmp instead of tmpDir! - def tmpDir = java.nio.file.Paths.get( - System.getenv('NXF_TEMP') ?: - System.getenv('VIASH_TEMP') ?: - System.getenv('VIASH_TMPDIR') ?: - System.getenv('VIASH_TEMPDIR') ?: - System.getenv('VIASH_TMP') ?: - System.getenv('TEMP') ?: - System.getenv('TMPDIR') ?: - System.getenv('TEMPDIR') ?: - System.getenv('TMP') ?: - '/tmp' - ).toAbsolutePath() - - // construct stub - def stub = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .collect { par -> - "\${ args.containsKey(\"${par.plainName}\") ? \"touch2 \\\"\" + (args[\"${par.plainName}\"] instanceof String ? args[\"${par.plainName}\"].replace(\"_*\", \"_0\") : args[\"${par.plainName}\"].join('\" \"')) + \"\\\"\" : \"\" }" - } - .join("\n") - - // escape script - def escapedScript = rawScript.replace('\\', '\\\\').replace('$', '\\$').replace('"""', '\\"\\"\\"') - - // publishdir assert - def assertStr = (workflowArgs.auto.publish == true) || workflowArgs.auto.transcript ? - """\nassert task.publishDir.size() > 0: "if auto.publish is true, params.publish_dir needs to be defined.\\n Example: --publish_dir './output/'" """ : - "" - - // generate process string - def procStr = - """nextflow.enable.dsl=2 - | - |process $procKey {$drctvStrs - |input: - | tuple val(id)$inputPaths, val(args), path(resourcesDir, stageAs: ".viash_meta_resources") - |output: - | tuple val("\$id")$outputPaths, optional: true - |stub: - |\"\"\" - |touch2() { mkdir -p "\\\$(dirname "\\\$1")" && touch "\\\$1" ; } - |$stub - |\"\"\" - |script:$assertStr - |def escapeText = { s -> s.toString().replaceAll('([`"])', '\\\\\\\\\$1') } - |def parInject = args - | .findAll{key, value -> value != null} - | .collect{key, value -> "export VIASH_PAR_\${key.toUpperCase()}=\\\"\${escapeText(value)}\\\""} - | .join("\\n") - |\"\"\" - |# meta exports - |# export VIASH_META_RESOURCES_DIR="\${resourcesDir.toRealPath().toAbsolutePath()}" - |export VIASH_META_RESOURCES_DIR="\${resourcesDir}" - |export VIASH_META_TEMP_DIR="${['docker', 'podman', 'charliecloud'].any{ it == workflow.containerEngine } ? '/tmp' : tmpDir}" - |export VIASH_META_FUNCTIONALITY_NAME="${meta.config.functionality.name}" - |# export VIASH_META_EXECUTABLE="\\\$VIASH_META_RESOURCES_DIR/\\\$VIASH_META_FUNCTIONALITY_NAME" - |export VIASH_META_CONFIG="\\\$VIASH_META_RESOURCES_DIR/.config.vsh.yaml" - |\${task.cpus ? "export VIASH_META_CPUS=\$task.cpus" : "" } - |\${task.memory?.bytes != null ? "export VIASH_META_MEMORY_B=\$task.memory.bytes" : "" } - |if [ ! -z \\\${VIASH_META_MEMORY_B+x} ]; then - | export VIASH_META_MEMORY_KB=\\\$(( (\\\$VIASH_META_MEMORY_B+1023) / 1024 )) - | export VIASH_META_MEMORY_MB=\\\$(( (\\\$VIASH_META_MEMORY_KB+1023) / 1024 )) - | export VIASH_META_MEMORY_GB=\\\$(( (\\\$VIASH_META_MEMORY_MB+1023) / 1024 )) - | export VIASH_META_MEMORY_TB=\\\$(( (\\\$VIASH_META_MEMORY_GB+1023) / 1024 )) - | export VIASH_META_MEMORY_PB=\\\$(( (\\\$VIASH_META_MEMORY_TB+1023) / 1024 )) - |fi - | - |# meta synonyms - |export VIASH_TEMP="\\\$VIASH_META_TEMP_DIR" - |export TEMP_DIR="\\\$VIASH_META_TEMP_DIR" - | - |# create output dirs if need be - |function mkdir_parent { - | for file in "\\\$@"; do - | mkdir -p "\\\$(dirname "\\\$file")" - | done - |} - |$createParentStr - | - |# argument exports${inputFileExports.join()} - |\$parInject - | - |# process script - |${escapedScript} - |\"\"\" - |} - |""".stripMargin() - - // TODO: print on debug - // if (workflowArgs.debug == true) { - // println("######################\n$procStr\n######################") - // } - - // create runtime process - def ownerParams = new nextflow.script.ScriptBinding.ParamsMap() - def binding = new nextflow.script.ScriptBinding().setParams(ownerParams) - def module = new nextflow.script.IncludeDef.Module(name: procKey) - def session = nextflow.Nextflow.getSession() - def scriptParser = new nextflow.script.ScriptParser(session) - .setModule(true) - .setBinding(binding) - scriptParser.scriptPath = scriptMeta.getScriptPath() - def moduleScript = scriptParser.runScript(procStr) - .getScript() - - // register module in meta - scriptMeta.addModule(moduleScript, module.name, module.alias) - - // retrieve and return process from meta - return scriptMeta.getProcess(procKey) -} - -// defaults -meta["defaults"] = [ - // key to be used to trace the process and determine output names - key: null, - - // fixed arguments to be passed to script - args: [:], - - // default directives - directives: readJsonBlob('''{ - "container" : { - "registry" : "ghcr.io", - "image" : "viash-io/viash_project_template/template/take_column", - "tag" : "0.2.2" - }, - "tag" : "$id" -}'''), - - // auto settings - auto: readJsonBlob('''{ - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false -}'''), - - // Apply a map over the incoming tuple - // Example: `{ tup -> [ tup[0], [input: tup[1].output] ] + tup.drop(2) }` - map: null, - - // Apply a map over the ID element of a tuple (i.e. the first element) - // Example: `{ id -> id + "_foo" }` - mapId: null, - - // Apply a map over the data element of a tuple (i.e. the second element) - // Example: `{ data -> [ input: data.output ] }` - mapData: null, - - // Apply a map over the passthrough elements of a tuple (i.e. the tuple excl. the first two elements) - // Example: `{ pt -> pt.drop(1) }` - mapPassthrough: null, - - // Filter the channel - // Example: `{ tup -> tup[0] == "foo" }` - filter: null, - - // Choose whether or not to run the component on the tuple if the condition is true. - // Otherwise, the tuple will be passed through. - // Example: `{ tup -> tup[0] != "skip_this" }` - runIf: null, - - // Rename keys in the data field of the tuple (i.e. the second element) - // Will likely be deprecated in favour of `fromState`. - // Example: `[ "new_key": "old_key" ]` - renameKeys: null, - - // Fetch data from the state and pass it to the module without altering the current state. - // - // `fromState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be passed to the module as is. - // - If it is a `List[String]`, the data will be the values of the state at the given keys. - // - If it is a `Map[String, String]`, the data will be the values of the state at the given keys, with the keys renamed according to the map. - // - If it is a function, the tuple (`[id, state]`) in the channel will be passed to the function, and the result will be used as the data. - // - // Example: `{ id, state -> [input: state.fastq_file] }` - // Default: `null` - fromState: null, - - // Determine how the state should be updated after the module has been run. - // - // `toState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be replaced with the output of the module. - // - If it is a `List[String]`, the state will be updated with the values of the data at the given keys. - // - If it is a `Map[String, String]`, the state will be updated with the values of the data at the given keys, with the keys renamed according to the map. - // - If it is a function, a tuple (`[id, output, state]`) will be passed to the function, and the result will be used as the new state. - // - // Example: `{ id, output, state -> state + [counts: state.output] }` - // Default: `{ id, output, state -> output }` - toState: null, - - // Whether or not to print debug messages - // Default: `false` - debug: false -] - -// initialise default workflow -meta["workflow"] = workflowFactory([key: meta.config.functionality.name], meta.defaults, meta) - -// add workflow to environment -nextflow.script.ScriptMeta.current().addDefinition(meta.workflow) - -// anonymous workflow for running this module as a standalone -workflow { - // add id argument if it's not already in the config - // TODO: deep copy - def newConfig = deepClone(meta.config) - def newParams = deepClone(params) - - def argsContainsId = newConfig.functionality.allArguments.any{it.plainName == "id"} - if (!argsContainsId) { - def idArg = [ - 'name': '--id', - 'required': false, - 'type': 'string', - 'description': 'A unique id for every entry.', - 'multiple': false - ] - newConfig.functionality.arguments.add(0, idArg) - newConfig = processConfig(newConfig) - } - if (!newParams.containsKey("id")) { - newParams.id = "run" - } - - helpMessage(newConfig) - - channelFromParams(newParams, newConfig) - // make sure id is not in the state if id is not in the args - | map {id, state -> - if (!argsContainsId) { - [id, state.findAll{k, v -> k != "id"}] - } else { - [id, state] - } - } - | meta.workflow.run( - auto: [ publish: "state" ] - ) -} - -// END COMPONENT-SPECIFIC CODE diff --git a/target/nextflow/template/take_column/nextflow.config b/target/nextflow/template/take_column/nextflow.config deleted file mode 100644 index 50e6a06..0000000 --- a/target/nextflow/template/take_column/nextflow.config +++ /dev/null @@ -1,106 +0,0 @@ -manifest { - name = 'template/take_column' - mainScript = 'main.nf' - nextflowVersion = '!>=20.12.1-edge' - version = '0.2.2' -} - -process.container = 'nextflow/bash:latest' - -// detect tempdir -tempDir = java.nio.file.Paths.get( - System.getenv('NXF_TEMP') ?: - System.getenv('VIASH_TEMP') ?: - System.getenv('TEMPDIR') ?: - System.getenv('TMPDIR') ?: - '/tmp' -).toAbsolutePath() - -profiles { - no_publish { - process { - withName: '.*' { - publishDir = [ - enabled: false - ] - } - } - } - mount_temp { - docker.temp = tempDir - podman.temp = tempDir - charliecloud.temp = tempDir - } - docker { - docker.enabled = true - // docker.userEmulation = true - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - singularity { - singularity.enabled = true - singularity.autoMounts = true - docker.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - podman { - podman.enabled = true - docker.enabled = false - singularity.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - shifter { - shifter.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - charliecloud.enabled = false - } - charliecloud { - charliecloud.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - } -} - -process{ - withLabel: mem1gb { memory = 1.GB } - withLabel: mem2gb { memory = 2.GB } - withLabel: mem4gb { memory = 4.GB } - withLabel: mem8gb { memory = 8.GB } - withLabel: mem16gb { memory = 16.GB } - withLabel: mem32gb { memory = 32.GB } - withLabel: mem64gb { memory = 64.GB } - withLabel: mem128gb { memory = 128.GB } - withLabel: mem256gb { memory = 256.GB } - withLabel: mem512gb { memory = 512.GB } - withLabel: mem1tb { memory = 1.TB } - withLabel: mem2tb { memory = 2.TB } - withLabel: mem4tb { memory = 4.TB } - withLabel: mem8tb { memory = 8.TB } - withLabel: mem16tb { memory = 16.TB } - withLabel: mem32tb { memory = 32.TB } - withLabel: mem64tb { memory = 64.TB } - withLabel: mem128tb { memory = 128.TB } - withLabel: mem256tb { memory = 256.TB } - withLabel: mem512tb { memory = 512.TB } - withLabel: cpu1 { cpus = 1 } - withLabel: cpu2 { cpus = 2 } - withLabel: cpu5 { cpus = 5 } - withLabel: cpu10 { cpus = 10 } - withLabel: cpu20 { cpus = 20 } - withLabel: cpu50 { cpus = 50 } - withLabel: cpu100 { cpus = 100 } - withLabel: cpu200 { cpus = 200 } - withLabel: cpu500 { cpus = 500 } - withLabel: cpu1000 { cpus = 1000 } -} - - diff --git a/target/nextflow/template/workflow/.config.vsh.yaml b/target/nextflow/template/workflow/.config.vsh.yaml deleted file mode 100644 index 371d2f0..0000000 --- a/target/nextflow/template/workflow/.config.vsh.yaml +++ /dev/null @@ -1,190 +0,0 @@ -functionality: - name: "workflow" - namespace: "template" - version: "0.2.2" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - description: "Input TSV file" - info: null - example: - - "file1.tar.gz" - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "integer" - name: "--column" - description: "The column index to extract from the TSV input file" - info: null - default: - - 2 - required: false - direction: "input" - multiple: false - multiple_sep: ":" - dest: "par" - - type: "file" - name: "--output" - alternatives: - - "-o" - description: "Output TSV file" - info: null - example: - - "output.tsv" - must_exist: true - create_parent: true - required: true - direction: "output" - multiple: false - multiple_sep: ":" - dest: "par" - resources: - - type: "nextflow_script" - path: "main.nf" - is_executable: true - entrypoint: "run_wf" - description: "An example pipeline and project template.\n\nMultiple TSV files can\ - \ be input, each with a 'column' identifier that\nshould be extracted. All extracted\ - \ columns are then collated again.\n" - info: null - status: "enabled" - dependencies: - - name: "template/combine_columns" - repository: - type: "local" - localPath: "" - foundConfigPath: "/Users/toni/code/projects/viash/viash_project_template/src/template/combine_columns/config.vsh.yaml" - configInfo: - functionalityName: "combine_columns" - git_tag: "v0.2.1" - git_remote: "https://github.com/viash-io/viash_project_template" - viash_version: "0.8.4" - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/combine_columns/config.vsh.yaml" - functionalityNamespace: "template" - output: "" - platform: "" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - executable: "/nextflow/template/combine_columns/main.nf" - writtenPath: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/combine_columns" - - name: "template/remove_comments" - repository: - type: "local" - localPath: "" - foundConfigPath: "/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/config.vsh.yaml" - configInfo: - functionalityName: "remove_comments" - git_tag: "v0.2.1" - git_remote: "https://github.com/viash-io/viash_project_template" - viash_version: "0.8.4" - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/config.vsh.yaml" - functionalityNamespace: "template" - output: "" - platform: "" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - executable: "/nextflow/template/remove_comments/main.nf" - writtenPath: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/remove_comments" - - name: "template/take_column" - repository: - type: "local" - localPath: "" - foundConfigPath: "/Users/toni/code/projects/viash/viash_project_template/src/template/take_column/config.vsh.yaml" - configInfo: - functionalityName: "take_column" - git_tag: "v0.2.1" - git_remote: "https://github.com/viash-io/viash_project_template" - viash_version: "0.8.4" - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/take_column/config.vsh.yaml" - functionalityNamespace: "template" - output: "" - platform: "" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - executable: "/nextflow/template/take_column/main.nf" - writtenPath: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/take_column" - - name: "join/vsh_toList" - repository: - type: "vsh" - name: "" - repo: "data-intuitive/vsh-pipeline-operators" - tag: "v0.2.0" - localPath: "/tmp/viash_hub_repo2163324410061546398" - foundConfigPath: "/tmp/viash_hub_repo2163324410061546398/target/nextflow/join/vsh_toList/.config.vsh.yaml" - configInfo: - functionalityName: "vsh_toList" - git_remote: "git@viash-hub.com:data-intuitive/vsh-pipeline-operators.git" - viash_version: "0.8.3" - config: "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/src/join/vsh_toList/config.vsh.yaml" - functionalityNamespace: "join" - output: "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/target/nextflow/join/vsh_toList" - platform: "nextflow" - git_commit: "05a5bfa4eaa2c04ba473671e4d30c6c18aceec6e" - executable: "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/target/nextflow/join/vsh_toList/main.nf" - writtenPath: "/Users/toni/code/projects/viash/viash_project_template/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList" - repositories: - - type: "local" - name: "local" - localPath: "" - - type: "vsh" - name: "vsh-pipeline-operators" - repo: "data-intuitive/vsh-pipeline-operators" - tag: "v0.2.0" - localPath: "" - set_wd_to_resources_dir: false -platforms: -- type: "nextflow" - id: "nextflow" - directives: - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1.GB" - mem2gb: "memory = 2.GB" - mem4gb: "memory = 4.GB" - mem8gb: "memory = 8.GB" - mem16gb: "memory = 16.GB" - mem32gb: "memory = 32.GB" - mem64gb: "memory = 64.GB" - mem128gb: "memory = 128.GB" - mem256gb: "memory = 256.GB" - mem512gb: "memory = 512.GB" - mem1tb: "memory = 1.TB" - mem2tb: "memory = 2.TB" - mem4tb: "memory = 4.TB" - mem8tb: "memory = 8.TB" - mem16tb: "memory = 16.TB" - mem32tb: "memory = 32.TB" - mem64tb: "memory = 64.TB" - mem128tb: "memory = 128.TB" - mem256tb: "memory = 256.TB" - mem512tb: "memory = 512.TB" - cpu1: "cpus = 1" - cpu2: "cpus = 2" - cpu5: "cpus = 5" - cpu10: "cpus = 10" - cpu20: "cpus = 20" - cpu50: "cpus = 50" - cpu100: "cpus = 100" - cpu200: "cpus = 200" - cpu500: "cpus = 500" - cpu1000: "cpus = 1000" - debug: false - container: "docker" -info: - config: "/Users/toni/code/projects/viash/viash_project_template/src/template/workflow/config.vsh.yaml" - platform: "nextflow" - output: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/workflow" - executable: "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/workflow/main.nf" - viash_version: "0.8.4" - git_commit: "11b6278597bf22afbfb56a8e83065a55553c9dd0" - git_remote: "https://github.com/viash-io/viash_project_template" - git_tag: "v0.2.1" diff --git a/target/nextflow/template/workflow/main.nf b/target/nextflow/template/workflow/main.nf deleted file mode 100644 index 56269c9..0000000 --- a/target/nextflow/template/workflow/main.nf +++ /dev/null @@ -1,3199 +0,0 @@ -// workflow 0.2.2 -// -// This wrapper script is auto-generated by viash 0.8.4 and is thus a derivative -// work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data -// Intuitive. -// -// The component may contain files which fall under a different license. The -// authors of this component should specify the license in the header of such -// files, or include a separate license file detailing the licenses of all included -// files. - -//////////////////////////// -// VDSL3 helper functions // -//////////////////////////// - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_checkArgumentType.nf' -class UnexpectedArgumentTypeException extends Exception { - String errorIdentifier - String stage - String plainName - String expectedClass - String foundClass - - // ${key ? " in module '$key'" : ""}${id ? " id '$id'" : ""} - UnexpectedArgumentTypeException(String errorIdentifier, String stage, String plainName, String expectedClass, String foundClass) { - super("Error${errorIdentifier ? " $errorIdentifier" : ""}:${stage ? " $stage" : "" } argument '${plainName}' has the wrong type. " + - "Expected type: ${expectedClass}. Found type: ${foundClass}") - this.errorIdentifier = errorIdentifier - this.stage = stage - this.plainName = plainName - this.expectedClass = expectedClass - this.foundClass = foundClass - } -} - -/** - * Checks if the given value is of the expected type. If not, an exception is thrown. - * - * @param stage The stage of the argument (input or output) - * @param par The parameter definition - * @param value The value to check - * @param errorIdentifier The identifier to use in the error message - * @return The value, if it is of the expected type - * @throws UnexpectedArgumentTypeException If the value is not of the expected type -*/ -def _checkArgumentType(String stage, Map par, Object value, String errorIdentifier) { - // expectedClass will only be != null if value is not of the expected type - def expectedClass = null - def foundClass = null - - // todo: split if need be - - if (!par.required && value == null) { - expectedClass = null - } else if (par.multiple) { - if (value !instanceof Collection) { - value = [value] - } - - // split strings - value = value.collectMany{ val -> - if (val instanceof String) { - // collect() to ensure that the result is a List and not simply an array - val.split(par.multiple_sep).collect() - } else { - [val] - } - } - - // process globs - if (par.type == "file" && par.direction == "input") { - value = value.collect{ it instanceof String ? file(it, hidden: true) : it }.flatten() - } - - // check types of elements in list - try { - value = value.collect { listVal -> - _checkArgumentType(stage, par + [multiple: false], listVal, errorIdentifier) - } - } catch (UnexpectedArgumentTypeException e) { - expectedClass = "List[${e.expectedClass}]" - foundClass = "List[${e.foundClass}]" - } - } else if (par.type == "string") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else if (par.type == "integer") { - // cast to integer if need be - if (value instanceof String) { - try { - value = value.toInteger() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigInteger) { - value = value.intValue() - } - expectedClass = value instanceof Integer ? null : "Integer" - } else if (par.type == "long") { - // cast to long if need be - if (value instanceof String) { - try { - value = value.toLong() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof Integer) { - value = value.toLong() - } - expectedClass = value instanceof Long ? null : "Long" - } else if (par.type == "double") { - // cast to double if need be - if (value instanceof String) { - try { - value = value.toDouble() - } catch (NumberFormatException e) { - // do nothing - } - } - if (value instanceof java.math.BigDecimal) { - value = value.doubleValue() - } - if (value instanceof Float) { - value = value.toDouble() - } - expectedClass = value instanceof Double ? null : "Double" - } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { - // cast to boolean if need ben - if (value instanceof String) { - def valueLower = value.toLowerCase() - if (valueLower == "true") { - value = true - } else if (valueLower == "false") { - value = false - } - } - expectedClass = value instanceof Boolean ? null : "Boolean" - } else if (par.type == "file" && (par.direction == "input" || stage == "output")) { - // cast to path if need be - if (value instanceof String) { - value = file(value, hidden: true) - } - if (value instanceof File) { - value = value.toPath() - } - expectedClass = value instanceof Path ? null : "Path" - } else if (par.type == "file" && stage == "input" && par.direction == "output") { - // cast to string if need be - if (value instanceof GString) { - value = value.toString() - } - expectedClass = value instanceof String ? null : "String" - } else { - // didn't find a match for par.type - expectedClass = par.type - } - - if (expectedClass != null) { - if (foundClass == null) { - foundClass = value.getClass().getName() - } - throw new UnexpectedArgumentTypeException(errorIdentifier, stage, par.plainName, expectedClass, foundClass) - } - - return value -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processInputValues.nf' -Map _processInputValues(Map inputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.required) { - assert inputs.containsKey(arg.plainName) && inputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required input argument '${arg.plainName}' is missing" - } - } - - inputs = inputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid input argument" - - value = _checkArgumentType("input", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return inputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/arguments/_processOutputValues.nf' -Map _processOutputValues(Map outputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.functionality.allArguments.each { arg -> - if (arg.direction == "output" && arg.required) { - assert outputs.containsKey(arg.plainName) && outputs.get(arg.plainName) != null : - "Error in module '${key}' id '${id}': required output argument '${arg.plainName}' is missing" - } - } - - outputs = outputs.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && it.direction == "output" } - assert par != null : "Error in module '${key}' id '${id}': '${name}' is not a valid output argument" - - value = _checkArgumentType("output", par, value, "in module '$key' id '$id'") - - [ name, value ] - } - } - return outputs -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/IDChecker.nf' -class IDChecker { - final def items = [] as Set - - @groovy.transform.WithWriteLock - boolean observe(String item) { - if (items.contains(item)) { - return false - } else { - items << item - return true - } - } - - @groovy.transform.WithReadLock - boolean contains(String item) { - return items.contains(item) - } - - @groovy.transform.WithReadLock - Set getItems() { - return items.clone() - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_checkUniqueIds.nf' - -/** - * Check if the ids are unique across parameter sets - * - * @param parameterSets a list of parameter sets. - */ -private void _checkUniqueIds(List>> parameterSets) { - def ppIds = parameterSets.collect{it[0]} - assert ppIds.size() == ppIds.unique().size() : "All argument sets should have unique ids. Detected ids: $ppIds" -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_getChild.nf' - -// helper functions for reading params from file // -def _getChild(parent, child) { - if (child.contains("://") || java.nio.file.Paths.get(child).isAbsolute()) { - child - } else { - def parentAbsolute = java.nio.file.Paths.get(parent).toAbsolutePath().toString() - parentAbsolute.replaceAll('/[^/]*$', "/") + child - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_parseParamList.nf' -/** - * Figure out the param list format based on the file extension - * - * @param param_list A String containing the path to the parameter list file. - * - * @return A String containing the format of the parameter list file. - */ -def _paramListGuessFormat(param_list) { - if (param_list !instanceof String) { - "asis" - } else if (param_list.endsWith(".csv")) { - "csv" - } else if (param_list.endsWith(".json") || param_list.endsWith(".jsn")) { - "json" - } else if (param_list.endsWith(".yaml") || param_list.endsWith(".yml")) { - "yaml" - } else { - "yaml_blob" - } -} - - -/** - * Read the param list - * - * @param param_list One of the following: - * - A String containing the path to the parameter list file (csv, json or yaml), - * - A yaml blob of a list of maps (yaml_blob), - * - Or a groovy list of maps (asis). - * @param config A Map of the Viash configuration. - * - * @return A List of Maps containing the parameters. - */ -def _parseParamList(param_list, Map config) { - // first determine format by extension - def paramListFormat = _paramListGuessFormat(param_list) - - def paramListPath = (paramListFormat != "asis" && paramListFormat != "yaml_blob") ? - file(param_list, hidden: true) : - null - - // get the correct parser function for the detected params_list format - def paramSets = [] - if (paramListFormat == "asis") { - paramSets = param_list - } else if (paramListFormat == "yaml_blob") { - paramSets = readYamlBlob(param_list) - } else if (paramListFormat == "yaml") { - paramSets = readYaml(paramListPath) - } else if (paramListFormat == "json") { - paramSets = readJson(paramListPath) - } else if (paramListFormat == "csv") { - paramSets = readCsv(paramListPath) - } else { - error "Format of provided --param_list not recognised.\n" + - "Found: '$paramListFormat'.\n" + - "Expected: a csv file, a json file, a yaml file,\n" + - "a yaml blob or a groovy list of maps." - } - - // data checks - assert paramSets instanceof List: "--param_list should contain a list of maps" - for (value in paramSets) { - assert value instanceof Map: "--param_list should contain a list of maps" - } - - // id is argument - def idIsArgument = config.functionality.allArguments.any{it.plainName == "id"} - - // Reformat from List to List> by adding the ID as first element of a Tuple2 - paramSets = paramSets.collect({ data -> - def id = data.id - if (!idIsArgument) { - data = data.findAll{k, v -> k != "id"} - } - [id, data] - }) - - // Split parameters with 'multiple: true' - paramSets = paramSets.collect({ id, data -> - data = _splitParams(data, config) - [id, data] - }) - - // The paths of input files inside a param_list file may have been specified relatively to the - // location of the param_list file. These paths must be made absolute. - if (paramListPath) { - paramSets = paramSets.collect({ id, data -> - def new_data = data.collectEntries{ parName, parValue -> - def par = config.functionality.allArguments.find{it.plainName == parName} - if (par && par.type == "file" && par.direction == "input") { - if (parValue instanceof Collection) { - parValue = parValue.collectMany{path -> - def x = _resolveSiblingIfNotAbsolute(path, paramListPath) - x instanceof Collection ? x : [x] - } - } else { - parValue = _resolveSiblingIfNotAbsolute(parValue, paramListPath) - } - } - [parName, parValue] - } - [id, new_data] - }) - } - - return paramSets -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/_splitParams.nf' -/** - * Split parameters for arguments that accept multiple values using their separator - * - * @param paramList A Map containing parameters to split. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A Map of parameters where the parameter values have been split into a list using - * their seperator. - */ -Map _splitParams(Map parValues, Map config){ - def parsedParamValues = parValues.collectEntries { parName, parValue -> - def parameterSettings = config.functionality.allArguments.find({it.plainName == parName}) - - if (!parameterSettings) { - // if argument is not found, do not alter - return [parName, parValue] - } - if (parameterSettings.multiple) { // Check if parameter can accept multiple values - if (parValue instanceof Collection) { - parValue = parValue.collect{it instanceof String ? it.split(parameterSettings.multiple_sep) : it } - } else if (parValue instanceof String) { - parValue = parValue.split(parameterSettings.multiple_sep) - } else if (parValue == null) { - parValue = [] - } else { - parValue = [ parValue ] - } - parValue = parValue.flatten() - } - // For all parameters check if multiple values are only passed for - // arguments that allow it. Quietly simplify lists of length 1. - if (!parameterSettings.multiple && parValue instanceof Collection) { - assert parValue.size() == 1 : - "Error: argument ${parName} has too many values.\n" + - " Expected amount: 1. Found: ${parValue.size()}" - parValue = parValue[0] - } - [parName, parValue] - } - return parsedParamValues -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/channelFromParams.nf' -/** - * Parse nextflow parameters based on settings defined in a viash config. - * Return a list of parameter sets, each parameter set corresponding to - * an event in a nextflow channel. The output from this function can be used - * with Channel.fromList to create a nextflow channel with Vdsl3 formatted - * events. - * - * This function performs: - * - A filtering of the params which can be found in the config file. - * - Process the params_list argument which allows a user to to initialise - * a Vsdl3 channel with multiple parameter sets. Possible formats are - * csv, json, yaml, or simply a yaml_blob. A csv should have column names - * which correspond to the different arguments of this pipeline. A json or a yaml - * file should be a list of maps, each of which has keys corresponding to the - * arguments of the pipeline. A yaml blob can also be passed directly as a parameter. - * When passing a csv, json or yaml, relative path names are relativized to the - * location of the parameter file. - * - Combine the parameter sets into a vdsl3 Channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A list of parameters with the first element of the event being - * the event ID and the second element containing a map of the parsed parameters. - */ - -private List>> _paramsToParamSets(Map params, Map config){ - // todo: fetch key from run args - def key_ = config.functionality.name - - /* parse regular parameters (not in param_list) */ - /*************************************************/ - def globalParams = config.functionality.allArguments - .findAll { params.containsKey(it.plainName) } - .collectEntries { [ it.plainName, params[it.plainName] ] } - def globalID = params.get("id", null) - - /* process params_list arguments */ - /*********************************/ - def paramList = params.containsKey("param_list") && params.param_list != null ? - params.param_list : [] - // if (paramList instanceof String) { - // paramList = [paramList] - // } - // def paramSets = paramList.collectMany{ _parseParamList(it, config) } - // TODO: be able to process param_list when it is a list of strings - def paramSets = _parseParamList(paramList, config) - if (paramSets.isEmpty()) { - paramSets = [[null, [:]]] - } - - /* combine arguments into channel */ - /**********************************/ - def processedParams = paramSets.indexed().collect{ index, tup -> - // Process ID - def id = tup[0] ?: globalID - - if (workflow.stubRun) { - // if stub run, explicitly add an id if missing - id = id ? id : "stub${index}" - } - assert id != null: "Each parameter set should have at least an 'id'" - - // Process params - def parValues = globalParams + tup[1] - // // Remove parameters which are null, if the default is also null - // parValues = parValues.collectEntries{paramName, paramValue -> - // parameterSettings = config.functionality.allArguments.find({it.plainName == paramName}) - // if ( paramValue != null || parameterSettings.get("default", null) != null ) { - // [paramName, paramValue] - // } - // } - parValues = parValues.collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - assert par != null : "Error in module '${key_}' id '${id}': '${name}' is not a valid input argument" - - if (par == null) { - return [:] - } - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - - [ name, value ] - } - - [id, parValues] - } - - // Check if ids (first element of each list) is unique - _checkUniqueIds(processedParams) - return processedParams -} - -/** - * Parse nextflow parameters based on settings defined in a viash config - * and return a nextflow channel. - * - * @param params Input parameters. Can optionaly contain a 'param_list' key that - * provides a list of arguments that can be split up into multiple events - * in the output channel possible formats of param_lists are: a csv file, - * json file, a yaml file or a yaml blob. Each parameters set (event) must - * have a unique ID. - * @param config A Map of the Viash configuration. This Map can be generated from the config file - * using the readConfig() function. - * - * @return A nextflow Channel with events. Events are formatted as a tuple that contains - * first contains the ID of the event and as second element holds a parameter map. - * - * - */ -def channelFromParams(Map params, Map config) { - def processedParams = _paramsToParamSets(params, config) - return Channel.fromList(processedParams) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/checkUniqueIds.nf' -def checkUniqueIds(Map args) { - def stopOnError = args.stopOnError == null ? args.stopOnError : true - - def idChecker = new IDChecker() - - return filter { tup -> - if (!idChecker.observe(tup[0])) { - if (stopOnError) { - error "Duplicate id: ${tup[0]}" - } else { - log.warn "Duplicate id: ${tup[0]}, removing duplicate entry" - return false - } - } - return true - } -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/preprocessInputs.nf' -// This helper file will be deprecated soon -preprocessInputsDeprecationWarningPrinted = false - -def preprocessInputsDeprecationWarning() { - if (!preprocessInputsDeprecationWarningPrinted) { - preprocessInputsDeprecationWarningPrinted = true - System.err.println("Warning: preprocessInputs() is deprecated and will be removed in Viash 0.9.0.") - } -} - -/** - * Generate a nextflow Workflow that allows processing a channel of - * Vdsl3 formatted events and apply a Viash config to them: - * - Gather default parameters from the Viash config and make - * sure that they are correctly formatted (see applyConfig method). - * - Format the input parameters (also using the applyConfig method). - * - Apply the default parameter to the input parameters. - * - Do some assertions: - * ~ Check if the event IDs in the channel are unique. - * - * The events in the channel are formatted as tuples, with the - * first element of the tuples being a unique id of the parameter set, - * and the second element containg the the parameters themselves. - * Optional extra elements of the tuples will be passed to the output as is. - * - * @param args A map that must contain a 'config' key that points - * to a parsed config (see readConfig()). Optionally, a - * 'key' key can be provided which can be used to create a unique - * name for the workflow process. - * - * @return A workflow that allows processing a channel of Vdsl3 formatted events - * and apply a Viash config to them. - */ -def preprocessInputs(Map args) { - preprocessInputsDeprecationWarning() - - def config = args.config - assert config instanceof Map : - "Error in preprocessInputs: config must be a map. " + - "Expected class: Map. Found: config.getClass() is ${config.getClass()}" - def key_ = args.key ?: config.functionality.name - - // Get different parameter types (used throughout this function) - def defaultArgs = config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - map { tup -> - def id = tup[0] - def data = tup[1] - def passthrough = tup.drop(2) - - def new_data = (defaultArgs + data).collectEntries { name, value -> - def par = config.functionality.allArguments.find { it.plainName == name && (it.direction == "input" || it.type == "file") } - - if (par != null) { - value = _checkArgumentType("input", par, value, "in module '$key_' id '$id'") - } - - [ name, value ] - } - - [ id, new_data ] + passthrough - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runComponents.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component config. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component config. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component config. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component config. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runComponents(Map args) { - log.warn("runComponents is deprecated, use runEach instead") - assert args.components: "runComponents should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runComponents" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runComponentsWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def comp_config = comp_.config - - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_config) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - // def new_id = id_(tup[0], tup[1], comp_config) - def new_id = tup[0] - if (id_ instanceof String) { - new_id = id_ - } else if (id_ instanceof Closure) { - new_id = id_(new_id, tup[1], comp_config) - } - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_config) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_config) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runComponentsWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/runEach.nf' -/** - * Run a list of components on a stream of data. - * - * @param components: list of Viash VDSL3 modules to run - * @param fromState: a closure, a map or a list of keys to extract from the input data. - * If a closure, it will be called with the id, the data and the component itself. - * @param toState: a closure, a map or a list of keys to extract from the output data - * If a closure, it will be called with the id, the output data, the old state and the component itself. - * @param filter: filter function to apply to the input. - * It will be called with the id, the data and the component itself. - * @param id: id to use for the output data - * If a closure, it will be called with the id, the data and the component itself. - * @param auto: auto options to pass to the components - * - * @return: a workflow that runs the components - **/ -def runEach(Map args) { - assert args.components: "runEach should be passed a list of components to run" - - def components_ = args.components - if (components_ !instanceof List) { - components_ = [ components_ ] - } - assert components_.size() > 0: "pass at least one component to runEach" - - def fromState_ = args.fromState - def toState_ = args.toState - def filter_ = args.filter - def id_ = args.id - - workflow runEachWf { - take: input_ch - main: - - // generate one channel per method - out_chs = components_.collect{ comp_ -> - def filter_ch = filter_ - ? input_ch | filter{tup -> - filter_(tup[0], tup[1], comp_) - } - : input_ch - def id_ch = id_ - ? filter_ch | map{tup -> - def new_id = id_ - if (new_id instanceof Closure) { - new_id = new_id(tup[0], tup[1], comp_) - } - assert new_id instanceof String : "Error in runEach: id should be a String or a Closure that returns a String. Expected: id instanceof String. Found: ${new_id.getClass()}" - [new_id] + tup.drop(1) - } - : filter_ch - def data_ch = id_ch | map{tup -> - def new_data = tup[1] - if (fromState_ instanceof Map) { - new_data = fromState_.collectEntries{ key0, key1 -> - [key0, new_data[key1]] - } - } else if (fromState_ instanceof List) { - new_data = fromState_.collectEntries{ key -> - [key, new_data[key]] - } - } else if (fromState_ instanceof Closure) { - new_data = fromState_(tup[0], new_data, comp_) - } - tup.take(1) + [new_data] + tup.drop(1) - } - def out_ch = data_ch - | comp_.run( - auto: (args.auto ?: [:]) + [simplifyInput: false, simplifyOutput: false] - ) - def post_ch = toState_ - ? out_ch | map{tup -> - def output = tup[1] - def old_state = tup[2] - def new_state = null - if (toState_ instanceof Map) { - new_state = old_state + toState_.collectEntries{ key0, key1 -> - [key0, output[key1]] - } - } else if (toState_ instanceof List) { - new_state = old_state + toState_.collectEntries{ key -> - [key, output[key]] - } - } else if (toState_ instanceof Closure) { - new_state = toState_(tup[0], output, old_state, comp_) - } - [tup[0], new_state] + tup.drop(3) - } - : out_ch - - post_ch - } - - // mix all results - output_ch = - (out_chs.size == 1) - ? out_chs[0] - : out_chs[0].mix(*out_chs.drop(1)) - - emit: output_ch - } - - return runEachWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/channel/safeJoin.nf' -/** - * Join sourceChannel to targetChannel - * - * This function joins the sourceChannel to the targetChannel. - * However, each id in the targetChannel must be present in the - * sourceChannel. If _meta.join_id exists in the targetChannel, that is - * used as an id instead. If the id doesn't match any id in the sourceChannel, - * an error is thrown. - */ - -def safeJoin(targetChannel, sourceChannel, key) { - def sourceIDs = new IDChecker() - - def sourceCheck = sourceChannel - | map { tup -> - sourceIDs.observe(tup[0]) - tup - } - def targetCheck = targetChannel - | map { tup -> - def id = tup[0] - - if (!sourceIDs.contains(id)) { - error ( - "Error in module '${key}' when merging output with original state.\n" + - " Reason: output with id '${id}' could not be joined with source channel.\n" + - " If the IDs in the output channel differ from the input channel,\n" + - " please set `tup[1]._meta.join_id to the original ID.\n" + - " Original IDs in input channel: ['${sourceIDs.getItems().join("', '")}'].\n" + - " Unexpected ID in the output channel: '${id}'.\n" + - " Example input event: [\"id\", [input: file(...)]],\n" + - " Example output event: [\"newid\", [output: file(...), _meta: [join_id: \"id\"]]]" - ) - } - // TODO: add link to our documentation on how to fix this - - tup - } - - sourceCheck.cross(targetChannel) - | map{ left, right -> - right + left.drop(1) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/_processArgument.nf' -def _processArgument(arg) { - arg.multiple = arg.multiple != null ? arg.multiple : false - arg.required = arg.required != null ? arg.required : false - arg.direction = arg.direction != null ? arg.direction : "input" - arg.multiple_sep = arg.multiple_sep != null ? arg.multiple_sep : ":" - arg.plainName = arg.name.replaceAll("^-*", "") - - if (arg.type == "file") { - arg.must_exist = arg.must_exist != null ? arg.must_exist : true - arg.create_parent = arg.create_parent != null ? arg.create_parent : true - } - - // add default values to output files which haven't already got a default - if (arg.type == "file" && arg.direction == "output" && arg.default == null) { - def mult = arg.multiple ? "_*" : "" - def extSearch = "" - if (arg.default != null) { - extSearch = arg.default - } else if (arg.example != null) { - extSearch = arg.example - } - if (extSearch instanceof List) { - extSearch = extSearch[0] - } - def extSearchResult = extSearch.find("\\.[^\\.]+\$") - def ext = extSearchResult != null ? extSearchResult : "" - arg.default = "\$id.\$key.${arg.plainName}${mult}${ext}" - if (arg.multiple) { - arg.default = [arg.default] - } - } - - if (!arg.multiple) { - if (arg.default != null && arg.default instanceof List) { - arg.default = arg.default[0] - } - if (arg.example != null && arg.example instanceof List) { - arg.example = arg.example[0] - } - } - - if (arg.type == "boolean_true") { - arg.default = false - } - if (arg.type == "boolean_false") { - arg.default = true - } - - arg -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/addGlobalParams.nf' -def addGlobalArguments(config) { - def localConfig = [ - "functionality" : [ - "argument_groups": [ - [ - "name": "Nextflow input-output arguments", - "description": "Input/output parameters for Nextflow itself. Please note that both publishDir and publish_dir are supported but at least one has to be configured.", - "arguments" : [ - [ - 'name': '--publish_dir', - 'required': true, - 'type': 'string', - 'description': 'Path to an output directory.', - 'example': 'output/', - 'multiple': false - ], - [ - 'name': '--param_list', - 'required': false, - 'type': 'string', - 'description': '''Allows inputting multiple parameter sets to initialise a Nextflow channel. A `param_list` can either be a list of maps, a csv file, a json file, a yaml file, or simply a yaml blob. - | - |* A list of maps (as-is) where the keys of each map corresponds to the arguments of the pipeline. Example: in a `nextflow.config` file: `param_list: [ ['id': 'foo', 'input': 'foo.txt'], ['id': 'bar', 'input': 'bar.txt'] ]`. - |* A csv file should have column names which correspond to the different arguments of this pipeline. Example: `--param_list data.csv` with columns `id,input`. - |* A json or a yaml file should be a list of maps, each of which has keys corresponding to the arguments of the pipeline. Example: `--param_list data.json` with contents `[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]`. - |* A yaml blob can also be passed directly as a string. Example: `--param_list "[ {'id': 'foo', 'input': 'foo.txt'}, {'id': 'bar', 'input': 'bar.txt'} ]"`. - | - |When passing a csv, json or yaml file, relative path names are relativized to the location of the parameter file. No relativation is performed when `param_list` is a list of maps (as-is) or a yaml blob.'''.stripMargin(), - 'example': 'my_params.yaml', - 'multiple': false, - 'hidden': true - ] - // TODO: allow multiple: true in param_list? - // TODO: allow to specify a --param_list_regex to filter the param_list? - // TODO: allow to specify a --param_list_from_state to remap entries in the param_list? - ] - ] - ] - ] - ] - - return processConfig(_mergeMap(config, localConfig)) -} - -def _mergeMap(Map lhs, Map rhs) { - return rhs.inject(lhs.clone()) { map, entry -> - if (map[entry.key] instanceof Map && entry.value instanceof Map) { - map[entry.key] = _mergeMap(map[entry.key], entry.value) - } else if (map[entry.key] instanceof Collection && entry.value instanceof Collection) { - map[entry.key] += entry.value - } else { - map[entry.key] = entry.value - } - return map - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/generateHelp.nf' -def _generateArgumentHelp(param) { - // alternatives are not supported - // def names = param.alternatives ::: List(param.name) - - def unnamedProps = [ - ["required parameter", param.required], - ["multiple values allowed", param.multiple], - ["output", param.direction.toLowerCase() == "output"], - ["file must exist", param.type == "file" && param.must_exist] - ].findAll{it[1]}.collect{it[0]} - - def dflt = null - if (param.default != null) { - if (param.default instanceof List) { - dflt = param.default.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - dflt = param.default.toString() - } - } - def example = null - if (param.example != null) { - if (param.example instanceof List) { - example = param.example.join(param.multiple_sep != null ? param.multiple_sep : ", ") - } else { - example = param.example.toString() - } - } - def min = param.min?.toString() - def max = param.max?.toString() - - def escapeChoice = { choice -> - def s1 = choice.replaceAll("\\n", "\\\\n") - def s2 = s1.replaceAll("\"", """\\\"""") - s2.contains(",") || s2 != choice ? "\"" + s2 + "\"" : s2 - } - def choices = param.choices == null ? - null : - "[ " + param.choices.collect{escapeChoice(it.toString())}.join(", ") + " ]" - - def namedPropsStr = [ - ["type", ([param.type] + unnamedProps).join(", ")], - ["default", dflt], - ["example", example], - ["choices", choices], - ["min", min], - ["max", max] - ] - .findAll{it[1]} - .collect{"\n " + it[0] + ": " + it[1].replaceAll("\n", "\\n")} - .join("") - - def descStr = param.description == null ? - "" : - _paragraphWrap("\n" + param.description.trim(), 80 - 8).join("\n ") - - "\n --" + param.plainName + - namedPropsStr + - descStr -} - -// Based on Helper.generateHelp() in Helper.scala -def _generateHelp(config) { - def fun = config.functionality - - // PART 1: NAME AND VERSION - def nameStr = fun.name + - (fun.version == null ? "" : " " + fun.version) - - // PART 2: DESCRIPTION - def descrStr = fun.description == null ? - "" : - "\n\n" + _paragraphWrap(fun.description.trim(), 80).join("\n") - - // PART 3: Usage - def usageStr = fun.usage == null ? - "" : - "\n\nUsage:\n" + fun.usage.trim() - - // PART 4: Options - def argGroupStrs = fun.allArgumentGroups.collect{argGroup -> - def name = argGroup.name - def descriptionStr = argGroup.description == null ? - "" : - "\n " + _paragraphWrap(argGroup.description.trim(), 80-4).join("\n ") + "\n" - def arguments = argGroup.arguments.collect{arg -> - arg instanceof String ? fun.allArguments.find{it.plainName == arg} : arg - }.findAll{it != null} - def argumentStrs = arguments.collect{param -> _generateArgumentHelp(param)} - - "\n\n$name:" + - descriptionStr + - argumentStrs.join("\n") - } - - // FINAL: combine - def out = nameStr + - descrStr + - usageStr + - argGroupStrs.join("") - - return out -} - -// based on Format._paragraphWrap -def _paragraphWrap(str, maxLength) { - def outLines = [] - str.split("\n").each{par -> - def words = par.split("\\s").toList() - - def word = null - def line = words.pop() - while(!words.isEmpty()) { - word = words.pop() - if (line.length() + word.length() + 1 <= maxLength) { - line = line + " " + word - } else { - outLines.add(line) - line = word - } - } - if (words.isEmpty()) { - outLines.add(line) - } - } - return outLines -} - -def helpMessage(config) { - if (params.containsKey("help") && params.help) { - def mergedConfig = addGlobalArguments(config) - def helpStr = _generateHelp(mergedConfig) - println(helpStr) - exit 0 - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/processConfig.nf' -def processConfig(config) { - // set defaults for arguments - config.functionality.arguments = - (config.functionality.arguments ?: []).collect{_processArgument(it)} - - // set defaults for argument_group arguments - config.functionality.argument_groups = - (config.functionality.argument_groups ?: []).collect{grp -> - grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} - grp - } - - // create combined arguments list - config.functionality.allArguments = - config.functionality.arguments + - config.functionality.argument_groups.collectMany{it.arguments} - - // add missing argument groups (based on Functionality::allArgumentGroups()) - def argGroups = config.functionality.argument_groups - if (argGroups.any{it.name.toLowerCase() == "arguments"}) { - argGroups = argGroups.collect{ grp -> - if (grp.name.toLowerCase() == "arguments") { - grp = grp + [ - arguments: grp.arguments + config.functionality.arguments - ] - } - grp - } - } else { - argGroups = argGroups + [ - name: "Arguments", - arguments: config.functionality.arguments - ] - } - config.functionality.allArgumentGroups = argGroups - - config -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/config/readConfig.nf' - -def readConfig(file) { - def config = readYaml(file ?: moduleDir.resolve("config.vsh.yaml")) - processConfig(config) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_resolveSiblingIfNotAbsolute.nf' -/** - * Resolve a path relative to the current file. - * - * @param str The path to resolve, as a String. - * @param parentPath The path to resolve relative to, as a Path. - * - * @return The path that may have been resovled, as a Path. - */ -def _resolveSiblingIfNotAbsolute(str, parentPath) { - if (str !instanceof String) { - return str - } - if (!_stringIsAbsolutePath(str)) { - return parentPath.resolveSibling(str) - } else { - return file(str, hidden: true) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/_stringIsAbsolutePath.nf' -/** - * Check whether a path as a string is absolute. - * - * In the past, we tried using `file(., relative: true).isAbsolute()`, - * but the 'relative' option was added in 22.10.0. - * - * @param path The path to check, as a String. - * - * @return Whether the path is absolute, as a boolean. - */ -def _stringIsAbsolutePath(path) { - _resolve_URL_PROTOCOL = ~/^([a-zA-Z][a-zA-Z0-9]*:)?\\/.+/ - - assert path instanceof String - return _resolve_URL_PROTOCOL.matcher(path).matches() -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/collectTraces.nf' -class CustomTraceObserver implements nextflow.trace.TraceObserver { - List traces - - CustomTraceObserver(List traces) { - this.traces = traces - } - - @Override - void onProcessComplete(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } - - @Override - void onProcessCached(nextflow.processor.TaskHandler handler, nextflow.trace.TraceRecord trace) { - def trace2 = trace.store.clone() - trace2.script = null - traces.add(trace2) - } -} - -def collectTraces() { - def traces = Collections.synchronizedList([]) - - // add custom trace observer which stores traces in the traces object - session.observers.add(new CustomTraceObserver(traces)) - - traces -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/deepClone.nf' -/** - * Performs a deep clone of the given object. - * @param x an object - */ -def deepClone(x) { - iterateMap(x, {it instanceof Cloneable ? it.clone() : it}) -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getPublishDir.nf' -def getPublishDir() { - return params.containsKey("publish_dir") ? params.publish_dir : - params.containsKey("publishDir") ? params.publishDir : - null -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/getRootDir.nf' - -// Recurse upwards until we find a '.build.yaml' file -def _findBuildYamlFile(pathPossiblySymlink) { - def path = pathPossiblySymlink.toRealPath() - def child = path.resolve(".build.yaml") - if (java.nio.file.Files.isDirectory(path) && java.nio.file.Files.exists(child)) { - return child - } else { - def parent = path.getParent() - if (parent == null) { - return null - } else { - return _findBuildYamlFile(parent) - } - } -} - -// get the root of the target folder -def getRootDir() { - def dir = _findBuildYamlFile(meta.resources_dir) - assert dir != null: "Could not find .build.yaml in the folder structure" - dir.getParent() -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/iterateMap.nf' -/** - * Recursively apply a function over the leaves of an object. - * @param obj The object to iterate over. - * @param fun The function to apply to each value. - * @return The object with the function applied to each value. - */ -def iterateMap(obj, fun) { - if (obj instanceof List && obj !instanceof String) { - return obj.collect{item -> - iterateMap(item, fun) - } - } else if (obj instanceof Map) { - return obj.collectEntries{key, item -> - [key.toString(), iterateMap(item, fun)] - } - } else { - return fun(obj) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/functions/niceView.nf' -/** - * A view for printing the event of each channel as a YAML blob. - * This is useful for debugging. - */ -def niceView() { - workflow niceViewWf { - take: input - main: - output = input - | view{toYamlBlob(it)} - emit: output - } - return niceViewWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readCsv.nf' - -def readCsv(file_path) { - def output = [] - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - - // todo: allow escaped quotes in string - // todo: allow single quotes? - def splitRegex = java.util.regex.Pattern.compile(''',(?=(?:[^"]*"[^"]*")*[^"]*$)''') - def removeQuote = java.util.regex.Pattern.compile('''"(.*)"''') - - def br = java.nio.file.Files.newBufferedReader(inputFile) - - def row = -1 - def header = null - while (br.ready() && header == null) { - def line = br.readLine() - row++ - if (!line.startsWith("#")) { - header = splitRegex.split(line, -1).collect{field -> - m = removeQuote.matcher(field) - m.find() ? m.replaceFirst('$1') : field - } - } - } - assert header != null: "CSV file should contain a header" - - while (br.ready()) { - def line = br.readLine() - row++ - if (line == null) { - br.close() - break - } - - if (!line.startsWith("#")) { - def predata = splitRegex.split(line, -1) - def data = predata.collect{field -> - if (field == "") { - return null - } - m = removeQuote.matcher(field) - if (m.find()) { - return m.replaceFirst('$1') - } else { - return field - } - } - assert header.size() == data.size(): "Row $row should contain the same number as fields as the header" - - def dataMap = [header, data].transpose().collectEntries().findAll{it.value != null} - output.add(dataMap) - } - } - - output -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJson.nf' -def readJson(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parse(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readJsonBlob.nf' -def readJsonBlob(str) { - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parseText(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readTaggedYaml.nf' -// Custom constructor to modify how certain objects are parsed from YAML -class CustomConstructor extends org.yaml.snakeyaml.constructor.Constructor { - Path root - - class ConstructPath extends org.yaml.snakeyaml.constructor.AbstractConstruct { - public Object construct(org.yaml.snakeyaml.nodes.Node node) { - String filename = (String) constructScalar(node); - if (root != null) { - return root.resolve(filename); - } - return java.nio.file.Paths.get(filename); - } - } - - CustomConstructor(org.yaml.snakeyaml.LoaderOptions options, Path root) { - super(options) - this.root = root - // Handling !file tag and parse it back to a File type - this.yamlConstructors.put(new org.yaml.snakeyaml.nodes.Tag("!file"), new ConstructPath()) - } -} - -def readTaggedYaml(Path path) { - def options = new org.yaml.snakeyaml.LoaderOptions() - def constructor = new CustomConstructor(options, path.getParent()) - def yaml = new org.yaml.snakeyaml.Yaml(constructor) - return yaml.load(path.text) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYaml.nf' -def readYaml(file_path) { - def inputFile = file_path !instanceof Path ? file(file_path, hidden: true) : file_path - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(inputFile) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/readYamlBlob.nf' -def readYamlBlob(str) { - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(str) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toJsonBlob.nf' -String toJsonBlob(data) { - return groovy.json.JsonOutput.toJson(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toTaggedYamlBlob.nf' -// Custom representer to modify how certain objects are represented in YAML -class CustomRepresenter extends org.yaml.snakeyaml.representer.Representer { - Path relativizer - - class RepresentPath implements org.yaml.snakeyaml.representer.Represent { - public String getFileName(Object obj) { - if (obj instanceof File) { - obj = ((File) obj).toPath(); - } - if (obj !instanceof Path) { - throw new IllegalArgumentException("Object: " + obj + " is not a Path or File"); - } - def path = (Path) obj; - - if (relativizer != null) { - return relativizer.relativize(path).toString() - } else { - return path.toString() - } - } - - public org.yaml.snakeyaml.nodes.Node representData(Object data) { - String filename = getFileName(data); - def tag = new org.yaml.snakeyaml.nodes.Tag("!file"); - return representScalar(tag, filename); - } - } - CustomRepresenter(org.yaml.snakeyaml.DumperOptions options, Path relativizer) { - super(options) - this.relativizer = relativizer - this.representers.put(sun.nio.fs.UnixPath, new RepresentPath()) - this.representers.put(Path, new RepresentPath()) - this.representers.put(File, new RepresentPath()) - } -} - -String toTaggedYamlBlob(data) { - return toRelativeTaggedYamlBlob(data, null) -} -String toRelativeTaggedYamlBlob(data, Path relativizer) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - def representer = new CustomRepresenter(options, relativizer) - def yaml = new org.yaml.snakeyaml.Yaml(representer, options) - return yaml.dump(data) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/toYamlBlob.nf' -String toYamlBlob(data) { - def options = new org.yaml.snakeyaml.DumperOptions() - options.setDefaultFlowStyle(org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) - options.setPrettyFlow(true) - def yaml = new org.yaml.snakeyaml.Yaml(options) - def cleanData = iterateMap(data, { it instanceof Path ? it.toString() : it }) - return yaml.dump(cleanData) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeJson.nf' -void writeJson(data, file) { - assert data: "writeJson: data should not be null" - assert file: "writeJson: file should not be null" - file.write(toJsonBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/readwrite/writeYaml.nf' -void writeYaml(data, file) { - assert data: "writeYaml: data should not be null" - assert file: "writeYaml: file should not be null" - file.write(toYamlBlob(data)) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/findStates.nf' -def findStates(Map params, Map config) { - // TODO: do a deep clone of config - def auto_config = deepClone(config) - def auto_params = deepClone(params) - - auto_config = auto_config.clone() - // override arguments - auto_config.functionality.argument_groups = [] - auto_config.functionality.arguments = [ - [ - type: "string", - name: "--id", - description: "A dummy identifier", - required: false - ], - [ - type: "file", - name: "--input_states", - example: "/path/to/input/directory/**/state.yaml", - description: "Path to input directory containing the datasets to be integrated.", - required: true, - multiple: true, - multiple_sep: ";" - ], - [ - type: "string", - name: "--filter", - example: "foo/.*/state.yaml", - description: "Regex to filter state files by path.", - required: false - ], - // to do: make this a yaml blob? - [ - type: "string", - name: "--rename_keys", - example: ["newKey1:oldKey1", "newKey2:oldKey2"], - description: "Rename keys in the detected input files. This is useful if the input files do not match the set of input arguments of the workflow.", - required: false, - multiple: true, - multiple_sep: "," - ], - [ - type: "string", - name: "--settings", - example: '{"output_dataset": "dataset.h5ad", "k": 10}', - description: "Global arguments as a JSON glob to be passed to all components.", - required: false - ] - ] - if (!(auto_params.containsKey("id"))) { - auto_params["id"] = "auto" - } - - // run auto config through processConfig once more - auto_config = processConfig(auto_config) - - workflow findStatesWf { - helpMessage(auto_config) - - output_ch = - channelFromParams(auto_params, auto_config) - | flatMap { autoId, args -> - - def globalSettings = args.settings ? readYamlBlob(args.settings) : [:] - - // look for state files in input dir - def stateFiles = args.input_states - - // filter state files by regex - if (args.filter) { - stateFiles = stateFiles.findAll{ stateFile -> - def stateFileStr = stateFile.toString() - def matcher = stateFileStr =~ args.filter - matcher.matches()} - } - - // read in states - def states = stateFiles.collect { stateFile -> - def state_ = readTaggedYaml(stateFile) - [state_.id, state_] - } - - // construct renameMap - if (args.rename_keys) { - def renameMap = args.rename_keys.collectEntries{renameString -> - def split = renameString.split(":") - assert split.size() == 2: "Argument 'rename_keys' should be of the form 'newKey:oldKey,newKey:oldKey'" - split - } - - // rename keys in state, only let states through which have all keys - // also add global settings - states = states.collectMany{id, state -> - def newState = [:] - - for (key in renameMap.keySet()) { - def origKey = renameMap[key] - if (!(state.containsKey(origKey))) { - return [] - } - newState[key] = state[origKey] - } - - [[id, globalSettings + newState]] - } - } - - states - } - emit: - output_ch - } - - return findStatesWf -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/joinStates.nf' -def joinStates(Closure apply_) { - workflow joinStatesWf { - take: input_ch - main: - output_ch = input_ch - | toSortedList - | filter{ it.size() > 0 } - | map{ tups -> - def ids = tups.collect{it[0]} - def states = tups.collect{it[1]} - apply_(ids, states) - } - - emit: output_ch - } - return joinStatesWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/publishStates.nf' -def collectFiles(obj) { - if (obj instanceof java.io.File || obj instanceof Path) { - return [obj] - } else if (obj instanceof List && obj !instanceof String) { - return obj.collectMany{item -> - collectFiles(item) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectFiles(item) - } - } else { - return [] - } -} - -/** - * Recurse through a state and collect all input files and their target output filenames. - * @param obj The state to recurse through. - * @param prefix The prefix to prepend to the output filenames. - */ -def collectInputOutputPaths(obj, prefix) { - if (obj instanceof File || obj instanceof Path) { - def path = obj instanceof Path ? obj : obj.toPath() - def ext = path.getFileName().toString().find("\\.[^\\.]+\$") ?: "" - def newFilename = prefix + ext - return [[obj, newFilename]] - } else if (obj instanceof List && obj !instanceof String) { - return obj.withIndex().collectMany{item, ix -> - collectInputOutputPaths(item, prefix + "_" + ix) - } - } else if (obj instanceof Map) { - return obj.collectMany{key, item -> - collectInputOutputPaths(item, prefix + "." + key) - } - } else { - return [] - } -} - -def publishStates(Map args) { - def key_ = args.get("key") - def yamlTemplate_ = args.get("output_state", args.get("outputState", '$id.$key.state.yaml')) - - assert key_ != null : "publishStates: key must be specified" - - workflow publishStatesWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] - - // the input files and the target output filenames - def inputOutputFiles_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() - def inputFiles_ = inputOutputFiles_[0] - def outputFiles_ = inputOutputFiles_[1] - - def yamlFilename = yamlTemplate_ - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - - // TODO: do the pathnames in state_ match up with the outputFiles_? - - // convert state to yaml blob - def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesWf -} -process publishStatesProc { - // todo: check publishpath? - publishDir path: "${getPublishDir()}/", mode: "copy" - tag "$id" - input: - tuple val(id), val(yamlBlob), val(yamlFile), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) - output: - tuple val(id), path{[yamlFile] + outputFiles} - script: - def copyCommands = [ - inputFiles instanceof List ? inputFiles : [inputFiles], - outputFiles instanceof List ? outputFiles : [outputFiles] - ] - .transpose() - .collectMany{infile, outfile -> - if (infile.toString() != outfile.toString()) { - [ - "[ -d \"\$(dirname '${outfile.toString()}')\" ] || mkdir -p \"\$(dirname '${outfile.toString()}')\"", - "cp -r '${infile.toString()}' '${outfile.toString()}'" - ] - } else { - // no need to copy if infile is the same as outfile - [] - } - } - """ - mkdir -p "\$(dirname '${yamlFile}')" - echo "Storing state as yaml" - echo '${yamlBlob}' > '${yamlFile}' - echo "Copying output files to destination folder" - ${copyCommands.join("\n ")} - """ -} - - -// this assumes that the state contains no other values other than those specified in the config -def publishStatesByConfig(Map args) { - def config = args.get("config") - assert config != null : "publishStatesByConfig: config must be specified" - - def key_ = args.get("key", config.functionality.name) - assert key_ != null : "publishStatesByConfig: key must be specified" - - workflow publishStatesSimpleWf { - take: input_ch - main: - input_ch - | map { tup -> - def id_ = tup[0] - def state_ = tup[1] // e.g. [output: new File("myoutput.h5ad"), k: 10] - def origState_ = tup[2] // e.g. [output: '$id.$key.foo.h5ad'] - - // TODO: allow overriding the state.yaml template - // TODO TODO: if auto.publish == "state", add output_state as an argument - def yamlTemplate = params.containsKey("output_state") ? params.output_state : '$id.$key.state.yaml' - def yamlFilename = yamlTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() - - // the processed state is a list of [key, value, srcPath, destPath] tuples, where - // - key, value is part of the state to be saved to disk - // - srcPath and destPath are lists of files to be copied from src to dest - def processedState = - config.functionality.allArguments - .findAll { it.direction == "output" } - .collectMany { par -> - def plainName_ = par.plainName - // if the state does not contain the key, it's an - // optional argument for which the component did - // not generate any output - if (!state_.containsKey(plainName_)) { - return [] - } - def value = state_[plainName_] - // if the parameter is not a file, it should be stored - // in the state as-is, but is not something that needs - // to be copied from the source path to the dest path - if (par.type != "file") { - return [[key: plainName_, value: value, srcPath: [], destPath: []]] - } - // if the orig state does not contain this filename, - // it's an optional argument for which the user specified - // that it should not be returned as a state - if (!origState_.containsKey(plainName_)) { - return [] - } - def filenameTemplate = origState_[plainName_] - // if the pararameter is multiple: true, fetch the template - if (par.multiple && filenameTemplate instanceof List) { - filenameTemplate = filenameTemplate[0] - } - // instantiate the template - def filename = filenameTemplate - .replaceAll('\\$id', id_) - .replaceAll('\\$key', key_) - if (par.multiple) { - // if the parameter is multiple: true, the filename - // should contain a wildcard '*' that is replaced with - // the index of the file - assert filename.contains("*") : "Module '${key_}' id '${id_}': Multiple output files specified, but no wildcard '*' in the filename: ${filename}" - def outputPerFile = value.withIndex().collect{ val, ix -> - def value_ = java.nio.file.Paths.get(filename.replace("*", ix.toString())) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = val instanceof File ? val.toPath() : val - [value: value_, srcPath: srcPath, destPath: destPath] - } - def transposedOutputs = ["value", "srcPath", "destPath"].collectEntries{ key -> - [key, outputPerFile.collect{dic -> dic[key]}] - } - return [[key: plainName_] + transposedOutputs] - } else { - def value_ = java.nio.file.Paths.get(filename) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def srcPath = value instanceof File ? value.toPath() : value - return [[key: plainName_, value: value_, srcPath: [srcPath], destPath: [filename]]] - } - } - - def updatedState_ = processedState.collectEntries{[it.key, it.value]} - def inputFiles_ = processedState.collectMany{it.srcPath} - def outputFiles_ = processedState.collectMany{it.destPath} - - // convert state to yaml blob - def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) - - [id_, yamlBlob_, yamlFilename, inputFiles_, outputFiles_] - } - | publishStatesProc - emit: input_ch - } - return publishStatesSimpleWf -} -// helper file: 'src/main/resources/io/viash/platforms/nextflow/states/setState.nf' -def setState(fun) { - assert fun instanceof Closure || fun instanceof Map || fun instanceof List : - "Error in setState: Expected process argument to be a Closure, a Map, or a List. Found: class ${fun.getClass()}" - - // if fun is a List, convert to map - if (fun instanceof List) { - // check whether fun is a list[string] - assert fun.every{it instanceof CharSequence} : "Error in setState: argument is a List, but not all elements are Strings" - fun = fun.collectEntries{[it, it]} - } - - // if fun is a map, convert to closure - if (fun instanceof Map) { - // check whether fun is a map[string, string] - assert fun.values().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all values are Strings" - assert fun.keySet().every{it instanceof CharSequence} : "Error in setState: argument is a Map, but not all keys are Strings" - def funMap = fun.clone() - // turn the map into a closure to be used later on - fun = { id_, state_ -> - assert state_ instanceof Map : "Error in setState: the state is not a Map" - funMap.collectMany{newkey, origkey -> - if (state_.containsKey(origkey)) { - [[newkey, state_[origkey]]] - } else { - [] - } - }.collectEntries() - } - } - - map { tup -> - def id = tup[0] - def state = tup[1] - def unfilteredState = fun(id, state) - def newState = unfilteredState.findAll{key, val -> val != null} - [id, newState] + tup.drop(2) - } -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processAuto.nf' -// TODO: unit test processAuto -def processAuto(Map auto) { - // remove null values - auto = auto.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = ["simplifyInput", "simplifyOutput", "transcript", "publish"] - def unexpectedKeys = auto.keySet() - expectedKeys - assert unexpectedKeys.isEmpty(), "unexpected keys in auto: '${unexpectedKeys.join("', '")}'" - - // check auto.simplifyInput - assert auto.simplifyInput instanceof Boolean, "auto.simplifyInput must be a boolean" - - // check auto.simplifyOutput - assert auto.simplifyOutput instanceof Boolean, "auto.simplifyOutput must be a boolean" - - // check auto.transcript - assert auto.transcript instanceof Boolean, "auto.transcript must be a boolean" - - // check auto.publish - assert auto.publish instanceof Boolean || auto.publish == "state", "auto.publish must be a boolean or 'state'" - - return auto.subMap(expectedKeys) -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processDirectives.nf' -def assertMapKeys(map, expectedKeys, requiredKeys, mapName) { - assert map instanceof Map : "Expected argument '$mapName' to be a Map. Found: class ${map.getClass()}" - map.forEach { key, val -> - assert key in expectedKeys : "Unexpected key '$key' in ${mapName ? mapName + " " : ""}map" - } - requiredKeys.forEach { requiredKey -> - assert map.containsKey(requiredKey) : "Missing required key '$key' in ${mapName ? mapName + " " : ""}map" - } -} - -// TODO: unit test processDirectives -def processDirectives(Map drctv) { - // remove null values - drctv = drctv.findAll{k, v -> v != null} - - // check for unexpected keys - def expectedKeys = [ - "accelerator", "afterScript", "beforeScript", "cache", "conda", "container", "containerOptions", "cpus", "disk", "echo", "errorStrategy", "executor", "machineType", "maxErrors", "maxForks", "maxRetries", "memory", "module", "penv", "pod", "publishDir", "queue", "label", "scratch", "storeDir", "stageInMode", "stageOutMode", "tag", "time" - ] - def unexpectedKeys = drctv.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Unexpected keys in process directive: '${unexpectedKeys.join("', '")}'" - - /* DIRECTIVE accelerator - accepted examples: - - [ limit: 4, type: "nvidia-tesla-k80" ] - */ - if (drctv.containsKey("accelerator")) { - assertMapKeys(drctv["accelerator"], ["type", "limit", "request", "runtime"], [], "accelerator") - } - - /* DIRECTIVE afterScript - accepted examples: - - "source /cluster/bin/cleanup" - */ - if (drctv.containsKey("afterScript")) { - assert drctv["afterScript"] instanceof CharSequence - } - - /* DIRECTIVE beforeScript - accepted examples: - - "source /cluster/bin/setup" - */ - if (drctv.containsKey("beforeScript")) { - assert drctv["beforeScript"] instanceof CharSequence - } - - /* DIRECTIVE cache - accepted examples: - - true - - false - - "deep" - - "lenient" - */ - if (drctv.containsKey("cache")) { - assert drctv["cache"] instanceof CharSequence || drctv["cache"] instanceof Boolean - if (drctv["cache"] instanceof CharSequence) { - assert drctv["cache"] in ["deep", "lenient"] : "Unexpected value for cache" - } - } - - /* DIRECTIVE conda - accepted examples: - - "bwa=0.7.15" - - "bwa=0.7.15 fastqc=0.11.5" - - ["bwa=0.7.15", "fastqc=0.11.5"] - */ - if (drctv.containsKey("conda")) { - if (drctv["conda"] instanceof List) { - drctv["conda"] = drctv["conda"].join(" ") - } - assert drctv["conda"] instanceof CharSequence - } - - /* DIRECTIVE container - accepted examples: - - "foo/bar:tag" - - [ registry: "reg", image: "im", tag: "ta" ] - is transformed to "reg/im:ta" - - [ image: "im" ] - is transformed to "im:latest" - */ - if (drctv.containsKey("container")) { - assert drctv["container"] instanceof Map || drctv["container"] instanceof CharSequence - if (drctv["container"] instanceof Map) { - def m = drctv["container"] - assertMapKeys(m, [ "registry", "image", "tag" ], ["image"], "container") - def part1 = - System.getenv('OVERRIDE_CONTAINER_REGISTRY') ? System.getenv('OVERRIDE_CONTAINER_REGISTRY') + "/" : - params.containsKey("override_container_registry") ? params["override_container_registry"] + "/" : // todo: remove? - m.registry ? m.registry + "/" : - "" - def part2 = m.image - def part3 = m.tag ? ":" + m.tag : ":latest" - drctv["container"] = part1 + part2 + part3 - } - } - - /* DIRECTIVE containerOptions - accepted examples: - - "--foo bar" - - ["--foo bar", "-f b"] - */ - if (drctv.containsKey("containerOptions")) { - if (drctv["containerOptions"] instanceof List) { - drctv["containerOptions"] = drctv["containerOptions"].join(" ") - } - assert drctv["containerOptions"] instanceof CharSequence - } - - /* DIRECTIVE cpus - accepted examples: - - 1 - - 10 - */ - if (drctv.containsKey("cpus")) { - assert drctv["cpus"] instanceof Integer - } - - /* DIRECTIVE disk - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("disk")) { - assert drctv["disk"] instanceof CharSequence - // assert drctv["disk"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE echo - accepted examples: - - true - - false - */ - if (drctv.containsKey("echo")) { - assert drctv["echo"] instanceof Boolean - } - - /* DIRECTIVE errorStrategy - accepted examples: - - "terminate" - - "finish" - */ - if (drctv.containsKey("errorStrategy")) { - assert drctv["errorStrategy"] instanceof CharSequence - assert drctv["errorStrategy"] in ["terminate", "finish", "ignore", "retry"] : "Unexpected value for errorStrategy" - } - - /* DIRECTIVE executor - accepted examples: - - "local" - - "sge" - */ - if (drctv.containsKey("executor")) { - assert drctv["executor"] instanceof CharSequence - assert drctv["executor"] in ["local", "sge", "uge", "lsf", "slurm", "pbs", "pbspro", "moab", "condor", "nqsii", "ignite", "k8s", "awsbatch", "google-pipelines"] : "Unexpected value for executor" - } - - /* DIRECTIVE machineType - accepted examples: - - "n1-highmem-8" - */ - if (drctv.containsKey("machineType")) { - assert drctv["machineType"] instanceof CharSequence - } - - /* DIRECTIVE maxErrors - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxErrors")) { - assert drctv["maxErrors"] instanceof Integer - } - - /* DIRECTIVE maxForks - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxForks")) { - assert drctv["maxForks"] instanceof Integer - } - - /* DIRECTIVE maxRetries - accepted examples: - - 1 - - 3 - */ - if (drctv.containsKey("maxRetries")) { - assert drctv["maxRetries"] instanceof Integer - } - - /* DIRECTIVE memory - accepted examples: - - "1 GB" - - "2TB" - - "3.2KB" - - "10.B" - */ - if (drctv.containsKey("memory")) { - assert drctv["memory"] instanceof CharSequence - // assert drctv["memory"].matches("[0-9]+(\\.[0-9]*)? *[KMGTPEZY]?B") - // ^ does not allow closures - } - - /* DIRECTIVE module - accepted examples: - - "ncbi-blast/2.2.27" - - "ncbi-blast/2.2.27:t_coffee/10.0" - - ["ncbi-blast/2.2.27", "t_coffee/10.0"] - */ - if (drctv.containsKey("module")) { - if (drctv["module"] instanceof List) { - drctv["module"] = drctv["module"].join(":") - } - assert drctv["module"] instanceof CharSequence - } - - /* DIRECTIVE penv - accepted examples: - - "smp" - */ - if (drctv.containsKey("penv")) { - assert drctv["penv"] instanceof CharSequence - } - - /* DIRECTIVE pod - accepted examples: - - [ label: "key", value: "val" ] - - [ annotation: "key", value: "val" ] - - [ env: "key", value: "val" ] - - [ [label: "l", value: "v"], [env: "e", value: "v"]] - */ - if (drctv.containsKey("pod")) { - if (drctv["pod"] instanceof Map) { - drctv["pod"] = [ drctv["pod"] ] - } - assert drctv["pod"] instanceof List - drctv["pod"].forEach { pod -> - assert pod instanceof Map - // TODO: should more checks be added? - // See https://www.nextflow.io/docs/latest/process.html?highlight=directives#pod - // e.g. does it contain 'label' and 'value', or 'annotation' and 'value', or ...? - } - } - - /* DIRECTIVE publishDir - accepted examples: - - [] - - [ [ path: "foo", enabled: true ], [ path: "bar", enabled: false ] ] - - "/path/to/dir" - is transformed to [[ path: "/path/to/dir" ]] - - [ path: "/path/to/dir", mode: "cache" ] - is transformed to [[ path: "/path/to/dir", mode: "cache" ]] - */ - // TODO: should we also look at params["publishDir"]? - if (drctv.containsKey("publishDir")) { - def pblsh = drctv["publishDir"] - - // check different options - assert pblsh instanceof List || pblsh instanceof Map || pblsh instanceof CharSequence - - // turn into list if not already so - // for some reason, 'if (!pblsh instanceof List) pblsh = [ pblsh ]' doesn't work. - pblsh = pblsh instanceof List ? pblsh : [ pblsh ] - - // check elements of publishDir - pblsh = pblsh.collect{ elem -> - // turn into map if not already so - elem = elem instanceof CharSequence ? [ path: elem ] : elem - - // check types and keys - assert elem instanceof Map : "Expected publish argument '$elem' to be a String or a Map. Found: class ${elem.getClass()}" - assertMapKeys(elem, [ "path", "mode", "overwrite", "pattern", "saveAs", "enabled" ], ["path"], "publishDir") - - // check elements in map - assert elem.containsKey("path") - assert elem["path"] instanceof CharSequence - if (elem.containsKey("mode")) { - assert elem["mode"] instanceof CharSequence - assert elem["mode"] in [ "symlink", "rellink", "link", "copy", "copyNoFollow", "move" ] - } - if (elem.containsKey("overwrite")) { - assert elem["overwrite"] instanceof Boolean - } - if (elem.containsKey("pattern")) { - assert elem["pattern"] instanceof CharSequence - } - if (elem.containsKey("saveAs")) { - assert elem["saveAs"] instanceof CharSequence //: "saveAs as a Closure is currently not supported. Surround your closure with single quotes to get the desired effect. Example: '\{ foo \}'" - } - if (elem.containsKey("enabled")) { - assert elem["enabled"] instanceof Boolean - } - - // return final result - elem - } - // store final directive - drctv["publishDir"] = pblsh - } - - /* DIRECTIVE queue - accepted examples: - - "long" - - "short,long" - - ["short", "long"] - */ - if (drctv.containsKey("queue")) { - if (drctv["queue"] instanceof List) { - drctv["queue"] = drctv["queue"].join(",") - } - assert drctv["queue"] instanceof CharSequence - } - - /* DIRECTIVE label - accepted examples: - - "big_mem" - - "big_cpu" - - ["big_mem", "big_cpu"] - */ - if (drctv.containsKey("label")) { - if (drctv["label"] instanceof CharSequence) { - drctv["label"] = [ drctv["label"] ] - } - assert drctv["label"] instanceof List - drctv["label"].forEach { label -> - assert label instanceof CharSequence - // assert label.matches("[a-zA-Z0-9]([a-zA-Z0-9_]*[a-zA-Z0-9])?") - // ^ does not allow closures - } - } - - /* DIRECTIVE scratch - accepted examples: - - true - - "/path/to/scratch" - - '$MY_PATH_TO_SCRATCH' - - "ram-disk" - */ - if (drctv.containsKey("scratch")) { - assert drctv["scratch"] == true || drctv["scratch"] instanceof CharSequence - } - - /* DIRECTIVE storeDir - accepted examples: - - "/path/to/storeDir" - */ - if (drctv.containsKey("storeDir")) { - assert drctv["storeDir"] instanceof CharSequence - } - - /* DIRECTIVE stageInMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageInMode")) { - assert drctv["stageInMode"] instanceof CharSequence - assert drctv["stageInMode"] in ["copy", "link", "symlink", "rellink"] - } - - /* DIRECTIVE stageOutMode - accepted examples: - - "copy" - - "link" - */ - if (drctv.containsKey("stageOutMode")) { - assert drctv["stageOutMode"] instanceof CharSequence - assert drctv["stageOutMode"] in ["copy", "move", "rsync"] - } - - /* DIRECTIVE tag - accepted examples: - - "foo" - - '$id' - */ - if (drctv.containsKey("tag")) { - assert drctv["tag"] instanceof CharSequence - } - - /* DIRECTIVE time - accepted examples: - - "1h" - - "2days" - - "1day 6hours 3minutes 30seconds" - */ - if (drctv.containsKey("time")) { - assert drctv["time"] instanceof CharSequence - // todo: validation regex? - } - - return drctv -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/processWorkflowArgs.nf' -def processWorkflowArgs(Map args, Map defaultWfArgs, Map meta) { - // override defaults with args - def workflowArgs = defaultWfArgs + args - - // check whether 'key' exists - assert workflowArgs.containsKey("key") : "Error in module '${meta.config.functionality.name}': key is a required argument" - - // if 'key' is a closure, apply it to the original key - if (workflowArgs["key"] instanceof Closure) { - workflowArgs["key"] = workflowArgs["key"](meta.config.functionality.name) - } - def key = workflowArgs["key"] - assert key instanceof CharSequence : "Expected process argument 'key' to be a String. Found: class ${key.getClass()}" - assert key ==~ /^[a-zA-Z_]\w*$/ : "Error in module '$key': Expected process argument 'key' to consist of only letters, digits or underscores. Found: ${key}" - - // check for any unexpected keys - def expectedKeys = ["key", "directives", "auto", "map", "mapId", "mapData", "mapPassthrough", "filter", "runIf", "fromState", "toState", "args", "renameKeys", "debug"] - def unexpectedKeys = workflowArgs.keySet() - expectedKeys - assert unexpectedKeys.isEmpty() : "Error in module '$key': unexpected arguments to the '.run()' function: '${unexpectedKeys.join("', '")}'" - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("directives") : "Error in module '$key': directives is a required argument" - assert workflowArgs["directives"] instanceof Map : "Error in module '$key': Expected process argument 'directives' to be a Map. Found: class ${workflowArgs['directives'].getClass()}" - workflowArgs["directives"] = processDirectives(defaultWfArgs.directives + workflowArgs["directives"]) - - // check whether directives exists and apply defaults - assert workflowArgs.containsKey("auto") : "Error in module '$key': auto is a required argument" - assert workflowArgs["auto"] instanceof Map : "Error in module '$key': Expected process argument 'auto' to be a Map. Found: class ${workflowArgs['auto'].getClass()}" - workflowArgs["auto"] = processAuto(defaultWfArgs.auto + workflowArgs["auto"]) - - // auto define publish, if so desired - if (workflowArgs.auto.publish == true && (workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : [:]).isEmpty()) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.publish is true, params.publish_dir needs to be defined.\n" + - // " Example: params.publish_dir = \"./output/\"" - def publishDir = getPublishDir() - - if (publishDir != null) { - workflowArgs.directives.publishDir = [[ - path: publishDir, - saveAs: "{ it.startsWith('.') ? null : it }", // don't publish hidden files, by default - mode: "copy" - ]] - } - } - - // auto define transcript, if so desired - if (workflowArgs.auto.transcript == true) { - // can't assert at this level thanks to the no_publish profile - // assert params.containsKey("transcriptsDir") || params.containsKey("transcripts_dir") || params.containsKey("publishDir") || params.containsKey("publish_dir") : - // "Error in module '${workflowArgs['key']}': if auto.transcript is true, either params.transcripts_dir or params.publish_dir needs to be defined.\n" + - // " Example: params.transcripts_dir = \"./transcripts/\"" - def transcriptsDir = - params.containsKey("transcripts_dir") ? params.transcripts_dir : - params.containsKey("transcriptsDir") ? params.transcriptsDir : - params.containsKey("publish_dir") ? params.publish_dir + "/_transcripts" : - params.containsKey("publishDir") ? params.publishDir + "/_transcripts" : - null - if (transcriptsDir != null) { - def timestamp = nextflow.Nextflow.getSession().getWorkflowMetadata().start.format('yyyy-MM-dd_HH-mm-ss') - def transcriptsPublishDir = [ - path: "$transcriptsDir/$timestamp/\${task.process.replaceAll(':', '-')}/\${id}/", - saveAs: "{ it.startsWith('.') ? it.replaceAll('^.', '') : null }", - mode: "copy" - ] - def publishDirs = workflowArgs.directives.publishDir != null ? workflowArgs.directives.publishDir : null ? workflowArgs.directives.publishDir : [] - workflowArgs.directives.publishDir = publishDirs + transcriptsPublishDir - } - } - - // if this is a stubrun, remove certain directives? - if (workflow.stubRun) { - workflowArgs.directives.keySet().removeAll(["publishDir", "cpus", "memory", "label"]) - } - - for (nam in ["map", "mapId", "mapData", "mapPassthrough", "filter", "runIf"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam]) { - assert workflowArgs[nam] instanceof Closure : "Error in module '$key': Expected process argument '$nam' to be null or a Closure. Found: class ${workflowArgs[nam].getClass()}" - } - } - - // TODO: should functions like 'map', 'mapId', 'mapData', 'mapPassthrough' be deprecated as well? - for (nam in ["map", "mapData", "mapPassthrough", "renameKeys"]) { - if (workflowArgs.containsKey(nam) && workflowArgs[nam] != null) { - log.warn "module '$key': workflow argument '$nam' is deprecated and will be removed in Viash 0.9.0. Please use 'fromState' and 'toState' instead." - } - } - - // check fromState - workflowArgs["fromState"] = _processFromState(workflowArgs.get("fromState"), key, meta.config) - - // check toState - workflowArgs["toState"] = _processToState(workflowArgs.get("toState"), key, meta.config) - - // return output - return workflowArgs -} - -def _processFromState(fromState, key_, config_) { - assert fromState == null || fromState instanceof Closure || fromState instanceof Map || fromState instanceof List : - "Error in module '$key_': Expected process argument 'fromState' to be null, a Closure, a Map, or a List. Found: class ${fromState.getClass()}" - if (fromState == null) { - return null - } - - // if fromState is a List, convert to map - if (fromState instanceof List) { - // check whether fromstate is a list[string] - assert fromState.every{it instanceof CharSequence} : "Error in module '$key_': fromState is a List, but not all elements are Strings" - fromState = fromState.collectEntries{[it, it]} - } - - // if fromState is a map, convert to closure - if (fromState instanceof Map) { - // check whether fromstate is a map[string, string] - assert fromState.values().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all values are Strings" - assert fromState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': fromState is a Map, but not all keys are Strings" - def fromStateMap = fromState.clone() - def requiredInputNames = meta.config.functionality.allArguments.findAll{it.required && it.direction == "Input"}.collect{it.plainName} - // turn the map into a closure to be used later on - fromState = { it -> - def state = it[1] - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def data = fromStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (state.containsKey(origkey)) { - [[newkey, state[origkey]]] - } else if (!requiredInputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': fromState key '$origkey' not found in current state") - } - }.collectEntries() - data - } - } - - return fromState -} - -def _processToState(toState, key_, config_) { - if (toState == null) { - toState = { tup -> tup[1] } - } - - // toState should be a closure, map[string, string], or list[string] - assert toState instanceof Closure || toState instanceof Map || toState instanceof List : - "Error in module '$key_': Expected process argument 'toState' to be a Closure, a Map, or a List. Found: class ${toState.getClass()}" - - // if toState is a List, convert to map - if (toState instanceof List) { - // check whether toState is a list[string] - assert toState.every{it instanceof CharSequence} : "Error in module '$key_': toState is a List, but not all elements are Strings" - toState = toState.collectEntries{[it, it]} - } - - // if toState is a map, convert to closure - if (toState instanceof Map) { - // check whether toState is a map[string, string] - assert toState.values().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all values are Strings" - assert toState.keySet().every{it instanceof CharSequence} : "Error in module '$key_': toState is a Map, but not all keys are Strings" - def toStateMap = toState.clone() - def requiredOutputNames = config_.functionality.allArguments.findAll{it.required && it.direction == "Output"}.collect{it.plainName} - // turn the map into a closure to be used later on - toState = { it -> - def output = it[1] - def state = it[2] - assert output instanceof Map : "Error in module '$key_': the output is not a Map" - assert state instanceof Map : "Error in module '$key_': the state is not a Map" - def extraEntries = toStateMap.collectMany{newkey, origkey -> - // check whether newkey corresponds to a required argument - if (output.containsKey(origkey)) { - [[newkey, output[origkey]]] - } else if (!requiredOutputNames.contains(origkey)) { - [] - } else { - throw new Exception("Error in module '$key_': toState key '$origkey' not found in current output") - } - }.collectEntries() - state + extraEntries - } - } - - return toState -} - -// helper file: 'src/main/resources/io/viash/platforms/nextflow/workflowFactory/workflowFactory.nf' -def _debug(workflowArgs, debugKey) { - if (workflowArgs.debug) { - view { "process '${workflowArgs.key}' $debugKey tuple: $it" } - } else { - map { it } - } -} - -// depends on: innerWorkflowFactory -def workflowFactory(Map args, Map defaultWfArgs, Map meta) { - def workflowArgs = processWorkflowArgs(args, defaultWfArgs, meta) - def key_ = workflowArgs["key"] - - workflow workflowInstance { - take: input_ - - main: - chModified = input_ - | checkUniqueIds([:]) - | _debug(workflowArgs, "input") - | map { tuple -> - tuple = deepClone(tuple) - - if (workflowArgs.map) { - tuple = workflowArgs.map(tuple) - } - if (workflowArgs.mapId) { - tuple[0] = workflowArgs.mapId(tuple[0]) - } - if (workflowArgs.mapData) { - tuple[1] = workflowArgs.mapData(tuple[1]) - } - if (workflowArgs.mapPassthrough) { - tuple = tuple.take(2) + workflowArgs.mapPassthrough(tuple.drop(2)) - } - - // check tuple - assert tuple instanceof List : - "Error in module '${key_}': element in channel should be a tuple [id, data, ...otherargs...]\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: List. Found: tuple.getClass() is ${tuple.getClass()}" - assert tuple.size() >= 2 : - "Error in module '${key_}': expected length of tuple in input channel to be two or greater.\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: tuple.size() == ${tuple.size()}" - - // check id field - assert tuple[0] instanceof CharSequence : - "Error in module '${key_}': first element of tuple in channel should be a String\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Found: ${tuple[0]}" - - // match file to input file - if (workflowArgs.auto.simplifyInput && (tuple[1] instanceof Path || tuple[1] instanceof List)) { - def inputFiles = meta.config.functionality.allArguments - .findAll { it.type == "file" && it.direction == "input" } - - assert inputFiles.size() == 1 : - "Error in module '${key_}' id '${tuple[0]}'.\n" + - " Anonymous file inputs are only allowed when the process has exactly one file input.\n" + - " Expected: inputFiles.size() == 1. Found: inputFiles.size() is ${inputFiles.size()}" - - tuple[1] = [[ inputFiles[0].plainName, tuple[1] ]].collectEntries() - } - - // check data field - assert tuple[1] instanceof Map : - "Error in module '${key_}' id '${tuple[0]}': second element of tuple in channel should be a Map\n" + - " Example: [\"id\", [input: file('foo.txt'), arg: 10]].\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // rename keys of data field in tuple - if (workflowArgs.renameKeys) { - assert workflowArgs.renameKeys instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class: Map. Found: renameKeys.getClass() is ${workflowArgs.renameKeys.getClass()}" - assert tuple[1] instanceof Map : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Expected class: Map. Found: tuple[1].getClass() is ${tuple[1].getClass()}" - - // TODO: allow renameKeys to be a function? - workflowArgs.renameKeys.each { newKey, oldKey -> - assert newKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of newKey: String. Found: newKey.getClass() is ${newKey.getClass()}" - assert oldKey instanceof CharSequence : - "Error renaming data keys in module '${key_}' id '${tuple[0]}'.\n" + - " Example: renameKeys: ['new_key': 'old_key'].\n" + - " Expected class of oldKey: String. Found: oldKey.getClass() is ${oldKey.getClass()}" - assert tuple[1].containsKey(oldKey) : - "Error renaming data keys in module '${key}' id '${tuple[0]}'.\n" + - " Key '$oldKey' is missing in the data map. tuple[1].keySet() is '${tuple[1].keySet()}'" - tuple[1].put(newKey, tuple[1][oldKey]) - } - tuple[1].keySet().removeAll(workflowArgs.renameKeys.collect{ newKey, oldKey -> oldKey }) - } - tuple - } - - chModifiedFiltered = workflowArgs.filter ? - chModified | filter{workflowArgs.filter(it)} : - chModified - - if (workflowArgs.runIf) { - runIfBranch = chModifiedFiltered.branch{ tup -> - run: workflowArgs.runIf(tup[0], tup[1]) - passthrough: true - } - chRun = runIfBranch.run - chPassthrough = runIfBranch.passthrough - } else { - chRun = chModifiedFiltered - chPassthrough = Channel.empty() - } - - chArgs = workflowArgs.fromState ? - chRun | map{ - def new_data = workflowArgs.fromState(it.take(2)) - [it[0], new_data] - } : - chRun | map {tup -> tup.take(2)} - - // fill in defaults - chArgsWithDefaults = chArgs - | map { tuple -> - def id_ = tuple[0] - def data_ = tuple[1] - - // TODO: could move fromState to here - - // fetch default params from functionality - def defaultArgs = meta.config.functionality.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - // fetch overrides in params - def paramArgs = meta.config.functionality.allArguments - .findAll { par -> - def argKey = key_ + "__" + par.plainName - params.containsKey(argKey) - } - .collectEntries { [ it.plainName, params[key_ + "__" + it.plainName] ] } - - // fetch overrides in data - def dataArgs = meta.config.functionality.allArguments - .findAll { data_.containsKey(it.plainName) } - .collectEntries { [ it.plainName, data_[it.plainName] ] } - - // combine params - def combinedArgs = defaultArgs + paramArgs + workflowArgs.args + dataArgs - - // remove arguments with explicit null values - combinedArgs - .removeAll{_, val -> val == null || val == "viash_no_value" || val == "force_null"} - - combinedArgs = _processInputValues(combinedArgs, meta.config, id_, key_) - - [id_, combinedArgs] + tuple.drop(2) - } - - // TODO: move some of the _meta.join_id wrangling to the safeJoin() function. - chInitialOutput = chArgsWithDefaults - | _debug(workflowArgs, "processed") - // run workflow - | innerWorkflowFactory(workflowArgs) - // check output tuple - | map { id_, output_ -> - - // see if output map contains metadata - def meta_ = - output_ instanceof Map && output_.containsKey("_meta") ? - output_["_meta"] : - [:] - def join_id = meta_.join_id ?: id_ - - // remove metadata - output_ = output_.findAll{k, v -> k != "_meta"} - - // check value types - output_ = _processOutputValues(output_, meta.config, id_, key_) - - // simplify output if need be - if (workflowArgs.auto.simplifyOutput && output_.size() == 1) { - output_ = output_.values()[0] - } - - [join_id, id_, output_] - } - // | view{"chInitialOutput: ${it.take(3)}"} - - // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] - chNewState = safeJoin(chInitialOutput, chModifiedFiltered, key_) - // input tuple format: [join_id, id, output, prev_state, ...] - // output tuple format: [join_id, id, new_state, ...] - | map{ tup -> - def new_state = workflowArgs.toState(tup.drop(1).take(3)) - tup.take(2) + [new_state] + tup.drop(4) - } - - if (workflowArgs.auto.publish == "state") { - chPublish = chNewState - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [join_id, id, new_state] - | map{ tup -> - tup.take(3) - } - - safeJoin(chPublish, chArgsWithDefaults, key_) - // input tuple format: [join_id, id, new_state, orig_state, ...] - // output tuple format: [id, new_state, orig_state] - | map { tup -> - tup.drop(1).take(3) - } - | publishStatesByConfig(key: key_, config: meta.config) - } - - // remove join_id and meta - chReturn = chNewState - | map { tup -> - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [id, new_state, ...] - tup.drop(1) - } - | _debug(workflowArgs, "output") - | concat(chPassthrough) - - emit: chReturn - } - - def wf = workflowInstance.cloneWithName(key_) - - // add factory function - wf.metaClass.run = { runArgs -> - workflowFactory(runArgs, workflowArgs, meta) - } - // add config to module for later introspection - wf.metaClass.config = meta.config - - return wf -} - -nextflow.enable.dsl=2 - -// START COMPONENT-SPECIFIC CODE - -// create meta object -meta = [ - "resources_dir": moduleDir.toRealPath().normalize(), - "config": processConfig(readJsonBlob('''{ - "functionality" : { - "name" : "workflow", - "namespace" : "template", - "version" : "0.2.2", - "arguments" : [ - { - "type" : "file", - "name" : "--input", - "alternatives" : [ - "-i" - ], - "description" : "Input TSV file", - "example" : [ - "file1.tar.gz" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "input", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - }, - { - "type" : "integer", - "name" : "--column", - "description" : "The column index to extract from the TSV input file", - "default" : [ - 2 - ], - "required" : false, - "direction" : "input", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - }, - { - "type" : "file", - "name" : "--output", - "alternatives" : [ - "-o" - ], - "description" : "Output TSV file", - "example" : [ - "output.tsv" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "output", - "multiple" : false, - "multiple_sep" : ":", - "dest" : "par" - } - ], - "resources" : [ - { - "type" : "nextflow_script", - "path" : "main.nf", - "is_executable" : true, - "parent" : "file:/Users/toni/code/projects/viash/viash_project_template/src/template/workflow/", - "entrypoint" : "run_wf" - } - ], - "description" : "An example pipeline and project template.\n\nMultiple TSV files can be input, each with a 'column' identifier that\nshould be extracted. All extracted columns are then collated again.\n", - "status" : "enabled", - "dependencies" : [ - { - "name" : "template/combine_columns", - "repository" : { - "type" : "local", - "localPath" : "" - }, - "foundConfigPath" : "/Users/toni/code/projects/viash/viash_project_template/src/template/combine_columns/config.vsh.yaml", - "configInfo" : { - "functionalityName" : "combine_columns", - "git_tag" : "v0.2.1", - "git_remote" : "https://github.com/viash-io/viash_project_template", - "viash_version" : "0.8.4", - "config" : "/Users/toni/code/projects/viash/viash_project_template/src/template/combine_columns/config.vsh.yaml", - "functionalityNamespace" : "template", - "output" : "", - "platform" : "", - "git_commit" : "11b6278597bf22afbfb56a8e83065a55553c9dd0", - "executable" : "/nextflow/template/combine_columns/main.nf" - }, - "writtenPath" : "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/combine_columns" - }, - { - "name" : "template/remove_comments", - "repository" : { - "type" : "local", - "localPath" : "" - }, - "foundConfigPath" : "/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/config.vsh.yaml", - "configInfo" : { - "functionalityName" : "remove_comments", - "git_tag" : "v0.2.1", - "git_remote" : "https://github.com/viash-io/viash_project_template", - "viash_version" : "0.8.4", - "config" : "/Users/toni/code/projects/viash/viash_project_template/src/template/remove_comments/config.vsh.yaml", - "functionalityNamespace" : "template", - "output" : "", - "platform" : "", - "git_commit" : "11b6278597bf22afbfb56a8e83065a55553c9dd0", - "executable" : "/nextflow/template/remove_comments/main.nf" - }, - "writtenPath" : "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/remove_comments" - }, - { - "name" : "template/take_column", - "repository" : { - "type" : "local", - "localPath" : "" - }, - "foundConfigPath" : "/Users/toni/code/projects/viash/viash_project_template/src/template/take_column/config.vsh.yaml", - "configInfo" : { - "functionalityName" : "take_column", - "git_tag" : "v0.2.1", - "git_remote" : "https://github.com/viash-io/viash_project_template", - "viash_version" : "0.8.4", - "config" : "/Users/toni/code/projects/viash/viash_project_template/src/template/take_column/config.vsh.yaml", - "functionalityNamespace" : "template", - "output" : "", - "platform" : "", - "git_commit" : "11b6278597bf22afbfb56a8e83065a55553c9dd0", - "executable" : "/nextflow/template/take_column/main.nf" - }, - "writtenPath" : "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/take_column" - }, - { - "name" : "join/vsh_toList", - "repository" : { - "type" : "vsh", - "name" : "", - "repo" : "data-intuitive/vsh-pipeline-operators", - "tag" : "v0.2.0", - "localPath" : "/tmp/viash_hub_repo2163324410061546398" - }, - "foundConfigPath" : "/tmp/viash_hub_repo2163324410061546398/target/nextflow/join/vsh_toList/.config.vsh.yaml", - "configInfo" : { - "functionalityName" : "vsh_toList", - "git_remote" : "git@viash-hub.com:data-intuitive/vsh-pipeline-operators.git", - "viash_version" : "0.8.3", - "config" : "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/src/join/vsh_toList/config.vsh.yaml", - "functionalityNamespace" : "join", - "output" : "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/target/nextflow/join/vsh_toList", - "platform" : "nextflow", - "git_commit" : "05a5bfa4eaa2c04ba473671e4d30c6c18aceec6e", - "executable" : "/Users/toni/code/projects/viash-hub/vsh-pipeline-operators/target/nextflow/join/vsh_toList/main.nf" - }, - "writtenPath" : "/Users/toni/code/projects/viash/viash_project_template/target/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList" - } - ], - "repositories" : [ - { - "type" : "local", - "name" : "local", - "localPath" : "" - }, - { - "type" : "vsh", - "name" : "vsh-pipeline-operators", - "repo" : "data-intuitive/vsh-pipeline-operators", - "tag" : "v0.2.0", - "localPath" : "" - } - ], - "set_wd_to_resources_dir" : false - }, - "platforms" : [ - { - "type" : "nextflow", - "id" : "nextflow", - "directives" : { - "tag" : "$id" - }, - "auto" : { - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false - }, - "config" : { - "labels" : { - "mem1gb" : "memory = 1.GB", - "mem2gb" : "memory = 2.GB", - "mem4gb" : "memory = 4.GB", - "mem8gb" : "memory = 8.GB", - "mem16gb" : "memory = 16.GB", - "mem32gb" : "memory = 32.GB", - "mem64gb" : "memory = 64.GB", - "mem128gb" : "memory = 128.GB", - "mem256gb" : "memory = 256.GB", - "mem512gb" : "memory = 512.GB", - "mem1tb" : "memory = 1.TB", - "mem2tb" : "memory = 2.TB", - "mem4tb" : "memory = 4.TB", - "mem8tb" : "memory = 8.TB", - "mem16tb" : "memory = 16.TB", - "mem32tb" : "memory = 32.TB", - "mem64tb" : "memory = 64.TB", - "mem128tb" : "memory = 128.TB", - "mem256tb" : "memory = 256.TB", - "mem512tb" : "memory = 512.TB", - "cpu1" : "cpus = 1", - "cpu2" : "cpus = 2", - "cpu5" : "cpus = 5", - "cpu10" : "cpus = 10", - "cpu20" : "cpus = 20", - "cpu50" : "cpus = 50", - "cpu100" : "cpus = 100", - "cpu200" : "cpus = 200", - "cpu500" : "cpus = 500", - "cpu1000" : "cpus = 1000" - } - }, - "debug" : false, - "container" : "docker" - } - ], - "info" : { - "config" : "/Users/toni/code/projects/viash/viash_project_template/src/template/workflow/config.vsh.yaml", - "platform" : "nextflow", - "output" : "/Users/toni/code/projects/viash/viash_project_template/target/nextflow/template/workflow", - "viash_version" : "0.8.4", - "git_commit" : "11b6278597bf22afbfb56a8e83065a55553c9dd0", - "git_remote" : "https://github.com/viash-io/viash_project_template", - "git_tag" : "v0.2.1" - } -}''')) -] - -// resolve dependencies dependencies (if any) -meta["root_dir"] = getRootDir() -include { combine_columns } from "${meta.resources_dir}/../../../nextflow/template/combine_columns/main.nf" -include { remove_comments } from "${meta.resources_dir}/../../../nextflow/template/remove_comments/main.nf" -include { take_column } from "${meta.resources_dir}/../../../nextflow/template/take_column/main.nf" -include { vsh_toList } from "${meta.root_dir}/dependencies/vsh/data-intuitive/vsh-pipeline-operators/v0.2.0/nextflow/join/vsh_toList/main.nf" - -// inner workflow -// user-provided Nextflow code -workflow run_wf { - take: - input_ch - - main: - - output_ch = - - input_ch - - // Remove comments from each TSV input file - | remove_comments.run( - fromState: [ input: "input" ], - toState: { id, result, state -> state + result } - ) - - // Extract a single column from each TSV - // The column to extract is specified in the sample sheet - | take_column.run( - fromState: - [ - input: "output", - column: "column" - ], - toState: { id, result, state -> result } - ) - - // Helper module with extra functionality around - // nextflow's `toSortedList` operator to reformat - // its output list into a channel item that can be used - // directly with downstream components. - | vsh_toList.run( - args: [ id: "combined" ], - fromState: [ input: "output" ], - toState: [ output: "output" ] - ) - - // Concatenate TSVs into one - // and prep the output state. - | combine_columns.run( - auto: [ publish: true ], - fromState: [ input: "output" ], - toState: { id, result, state -> - [ - output: result.output, - _meta: [ join_id: "1" ] - ] - } - ) - - emit: - output_ch -} - -// inner workflow hook -def innerWorkflowFactory(args) { - return run_wf -} - -// defaults -meta["defaults"] = [ - // key to be used to trace the process and determine output names - key: null, - - // fixed arguments to be passed to script - args: [:], - - // default directives - directives: readJsonBlob('''{ - "tag" : "$id" -}'''), - - // auto settings - auto: readJsonBlob('''{ - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false -}'''), - - // Apply a map over the incoming tuple - // Example: `{ tup -> [ tup[0], [input: tup[1].output] ] + tup.drop(2) }` - map: null, - - // Apply a map over the ID element of a tuple (i.e. the first element) - // Example: `{ id -> id + "_foo" }` - mapId: null, - - // Apply a map over the data element of a tuple (i.e. the second element) - // Example: `{ data -> [ input: data.output ] }` - mapData: null, - - // Apply a map over the passthrough elements of a tuple (i.e. the tuple excl. the first two elements) - // Example: `{ pt -> pt.drop(1) }` - mapPassthrough: null, - - // Filter the channel - // Example: `{ tup -> tup[0] == "foo" }` - filter: null, - - // Choose whether or not to run the component on the tuple if the condition is true. - // Otherwise, the tuple will be passed through. - // Example: `{ tup -> tup[0] != "skip_this" }` - runIf: null, - - // Rename keys in the data field of the tuple (i.e. the second element) - // Will likely be deprecated in favour of `fromState`. - // Example: `[ "new_key": "old_key" ]` - renameKeys: null, - - // Fetch data from the state and pass it to the module without altering the current state. - // - // `fromState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be passed to the module as is. - // - If it is a `List[String]`, the data will be the values of the state at the given keys. - // - If it is a `Map[String, String]`, the data will be the values of the state at the given keys, with the keys renamed according to the map. - // - If it is a function, the tuple (`[id, state]`) in the channel will be passed to the function, and the result will be used as the data. - // - // Example: `{ id, state -> [input: state.fastq_file] }` - // Default: `null` - fromState: null, - - // Determine how the state should be updated after the module has been run. - // - // `toState` should be `null`, `List[String]`, `Map[String, String]` or a function. - // - // - If it is `null`, the state will be replaced with the output of the module. - // - If it is a `List[String]`, the state will be updated with the values of the data at the given keys. - // - If it is a `Map[String, String]`, the state will be updated with the values of the data at the given keys, with the keys renamed according to the map. - // - If it is a function, a tuple (`[id, output, state]`) will be passed to the function, and the result will be used as the new state. - // - // Example: `{ id, output, state -> state + [counts: state.output] }` - // Default: `{ id, output, state -> output }` - toState: null, - - // Whether or not to print debug messages - // Default: `false` - debug: false -] - -// initialise default workflow -meta["workflow"] = workflowFactory([key: meta.config.functionality.name], meta.defaults, meta) - -// add workflow to environment -nextflow.script.ScriptMeta.current().addDefinition(meta.workflow) - -// anonymous workflow for running this module as a standalone -workflow { - // add id argument if it's not already in the config - // TODO: deep copy - def newConfig = deepClone(meta.config) - def newParams = deepClone(params) - - def argsContainsId = newConfig.functionality.allArguments.any{it.plainName == "id"} - if (!argsContainsId) { - def idArg = [ - 'name': '--id', - 'required': false, - 'type': 'string', - 'description': 'A unique id for every entry.', - 'multiple': false - ] - newConfig.functionality.arguments.add(0, idArg) - newConfig = processConfig(newConfig) - } - if (!newParams.containsKey("id")) { - newParams.id = "run" - } - - helpMessage(newConfig) - - channelFromParams(newParams, newConfig) - // make sure id is not in the state if id is not in the args - | map {id, state -> - if (!argsContainsId) { - [id, state.findAll{k, v -> k != "id"}] - } else { - [id, state] - } - } - | meta.workflow.run( - auto: [ publish: "state" ] - ) -} - -// END COMPONENT-SPECIFIC CODE diff --git a/target/nextflow/template/workflow/nextflow.config b/target/nextflow/template/workflow/nextflow.config deleted file mode 100644 index 1d5d1c7..0000000 --- a/target/nextflow/template/workflow/nextflow.config +++ /dev/null @@ -1,107 +0,0 @@ -manifest { - name = 'template/workflow' - mainScript = 'main.nf' - nextflowVersion = '!>=20.12.1-edge' - version = '0.2.2' - description = 'An example pipeline and project template.\n\nMultiple TSV files can be input, each with a \'column\' identifier that\nshould be extracted. All extracted columns are then collated again.\n' -} - -process.container = 'nextflow/bash:latest' - -// detect tempdir -tempDir = java.nio.file.Paths.get( - System.getenv('NXF_TEMP') ?: - System.getenv('VIASH_TEMP') ?: - System.getenv('TEMPDIR') ?: - System.getenv('TMPDIR') ?: - '/tmp' -).toAbsolutePath() - -profiles { - no_publish { - process { - withName: '.*' { - publishDir = [ - enabled: false - ] - } - } - } - mount_temp { - docker.temp = tempDir - podman.temp = tempDir - charliecloud.temp = tempDir - } - docker { - docker.enabled = true - // docker.userEmulation = true - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - singularity { - singularity.enabled = true - singularity.autoMounts = true - docker.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - podman { - podman.enabled = true - docker.enabled = false - singularity.enabled = false - shifter.enabled = false - charliecloud.enabled = false - } - shifter { - shifter.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - charliecloud.enabled = false - } - charliecloud { - charliecloud.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - } -} - -process{ - withLabel: mem1gb { memory = 1.GB } - withLabel: mem2gb { memory = 2.GB } - withLabel: mem4gb { memory = 4.GB } - withLabel: mem8gb { memory = 8.GB } - withLabel: mem16gb { memory = 16.GB } - withLabel: mem32gb { memory = 32.GB } - withLabel: mem64gb { memory = 64.GB } - withLabel: mem128gb { memory = 128.GB } - withLabel: mem256gb { memory = 256.GB } - withLabel: mem512gb { memory = 512.GB } - withLabel: mem1tb { memory = 1.TB } - withLabel: mem2tb { memory = 2.TB } - withLabel: mem4tb { memory = 4.TB } - withLabel: mem8tb { memory = 8.TB } - withLabel: mem16tb { memory = 16.TB } - withLabel: mem32tb { memory = 32.TB } - withLabel: mem64tb { memory = 64.TB } - withLabel: mem128tb { memory = 128.TB } - withLabel: mem256tb { memory = 256.TB } - withLabel: mem512tb { memory = 512.TB } - withLabel: cpu1 { cpus = 1 } - withLabel: cpu2 { cpus = 2 } - withLabel: cpu5 { cpus = 5 } - withLabel: cpu10 { cpus = 10 } - withLabel: cpu20 { cpus = 20 } - withLabel: cpu50 { cpus = 50 } - withLabel: cpu100 { cpus = 100 } - withLabel: cpu200 { cpus = 200 } - withLabel: cpu500 { cpus = 500 } - withLabel: cpu1000 { cpus = 1000 } -} - - diff --git a/workflows/demo_pipeline/main.nf b/workflows/demo_pipeline/main.nf new file mode 100644 index 0000000..a2b5ae9 --- /dev/null +++ b/workflows/demo_pipeline/main.nf @@ -0,0 +1,43 @@ +nextflow.enable.dsl=2 + +targetDir = "${params.rootDir}/target/nextflow" + +include { remove_comments } from "$targetDir/demo/remove_comments/main.nf" +include { take_column } from "$targetDir/demo/take_column/main.nf" +include { combine_columns } from "$targetDir/demo/combine_columns/main.nf" + +workflow { + Channel.fromPath(params.input) + + // Assign unique ID to each event + // File -> (String, File) + | map { file -> [ file.baseName, file ] } + + // Remove comments from TSV + // (String, File) -> (String, File) + | remove_comments + + // Extract single column from TSV + // (String, File) -> (String, File) + | take_column + + // Combine all events into a single List event + // (String, File)* -> List[(String, File)] + | toList() + + // Add unique ID to tuple + // List[(String, File)] -> (String, {input: List[File]}) + | map { tups -> + files = tups.collect{id, file -> file} + [ "combined", [ input: files ] ] + } + + // Concatenate TSVs into one + // (String, {input: List[File]}) -> (String, File) + | combine_columns.run( + auto: [ publish: true ] + ) + + // View channel contents + | view { tup -> "Output: $tup" } +} diff --git a/src/template/workflow/nextflow.config b/workflows/demo_pipeline/nextflow.config similarity index 100% rename from src/template/workflow/nextflow.config rename to workflows/demo_pipeline/nextflow.config