diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index ae19e1b..33daf0d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -2,7 +2,7 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. - rev: v0.12.1 + rev: v0.14.0 hooks: - id: ruff-check args: [ --fix ] @@ -19,6 +19,6 @@ repos: - styler - knitr - repo: https://github.com/lorenzwalthert/precommit - rev: v0.4.3.9012 + rev: v0.4.3.9015 hooks: - id: lintr \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 0289146..8e0ec96 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,13 @@ -# openpipeline_spatial x.x.x +# openpipeline_spatial 0.2.0 ## NEW FUNCTIONALITY * `neighbors/spatial_neighborhood_graph`: Calculate the spatial neighborhood graph (PR #29). +* `convert/from_spaceranger_to_h5mu`: Added converter component for convert Spaceranger output to H5MU files (PR #33). + +* `workflows/ingestion/spaceranger_mapping`: Added a workflow to ingest Visium data using Spaceranger and convert the count matrix to an H5MU file (PR #33). + * `nichecompass/nichecompass`: Component to train a NicheCompass model and project latent space embeddings (PR #28). * `workflows/niche/nichecompass_leiden`: Workflow to perform niche analysis using NicheCompass, including spatialneighborhood calculation, NicheCompass analysis and Leiden clustering (PR #28) @@ -12,12 +16,18 @@ * Add `scope` to component and workflow configurations (PR #22). -* Bump version of spatialdata-io to 0.3.0 and spatialdata to 0.5.0. Pin version of pyarrow to 18.0.0 for compatibility (PR #24). - * `convert/from_xenium_to_spatialexperiment`: Add arrow with zstd codec support to handle I/O of zstd-compressed Xenium parquet files (PR #30). * `mapping/spaceranger_count`: Allow providing individual FASTQ files instead of directories (PR #32). +* Bump anndata to 0.12.7 and mudata to 0.3.2 (PR #34). + +* Bump spatialdata to 0.6.1 and spatialdata-io to 0.5.1 (PR #24, #34). + +* Bump squidpy to 1.7.0 (PR #36). + +* Update openpipeline dependencies to v4.0.0 (PR #37). + ## BUG FIXES * `convert/from_cosmx_to_h5mu`: Fixed an issue where parent directories of the cosmx output bundle were duplicated when reading in data (PR #25). diff --git a/_viash.yaml b/_viash.yaml index d16e598..615142b 100644 --- a/_viash.yaml +++ b/_viash.yaml @@ -10,7 +10,7 @@ repositories: - name: openpipeline repo: openpipeline type: vsh - tag: v3.0.0 + tag: v4.0.0 info: test_resources: - type: s3 diff --git a/resources_test_scripts/visium_tiny.sh b/resources_test_scripts/visium_tiny.sh index 70afb66..5bc46f6 100644 --- a/resources_test_scripts/visium_tiny.sh +++ b/resources_test_scripts/visium_tiny.sh @@ -21,14 +21,34 @@ tar xvf "$DIR/Visium_FFPE_Human_Ovarian_Cancer_fastqs.tar" -C "$DIR" # Create subsampled dataset with ImageMagick # https://imagemagick.org/index.php -mkdir -p "$DIR/subsampled" -convert "$DIR/Visium_FFPE_Human_Ovarian_Cancer_image.jpg" -resize 2000x2000 "$DIR/subsampled/Visium_FFPE_Human_Ovarian_Cancer_image.jpg" +mkdir -p "$DIR/Visium_FFPE_Human_Ovarian_Cancer_tiny" +convert "$DIR/Visium_FFPE_Human_Ovarian_Cancer_image.jpg" -resize 2000x2000 "$DIR/Visium_FFPE_Human_Ovarian_Cancer_image_tiny.jpg" for f in "$DIR"/Visium_FFPE_Human_Ovarian_Cancer_fastqs/*L001*R*; do - gzip -cdf "$f" | head -n 40000 | gzip -c > "$DIR/subsampled/$(basename "$f")"; + gzip -cdf "$f" | head -n 40000 | gzip -c > "$DIR/Visium_FFPE_Human_Ovarian_Cancer_tiny/$(basename "$f")"; done +echo "> Downloading and subsampling of datasets complete" + +# Run spaceranger +viash run src/mapping/spaceranger_count/config.vsh.yaml -- \ + --input "$DIR/Visium_FFPE_Human_Ovarian_Cancer_tiny" \ + --gex_reference "$REPO_ROOT/resources_test/GRCh38/" \ + --probe_set "$DIR/Visium_FFPE_Human_Ovarian_Cancer_probe_set.csv" \ + --image "$DIR/Visium_FFPE_Human_Ovarian_Cancer_image_tiny.jpg" \ + --slide "V10L13-020" \ + --area "D1" \ + --create_bam "false" \ + --output "Visium_FFPE_Human_Ovarian_Cancer_tiny_spaceranger" + +mv +echo "> Running spaceranger complete" + +rm -rf "$DIR/Visium_FFPE_Human_Ovarian_Cancer_fastqs" +rm -f "$DIR/Visium_FFPE_Human_Ovarian_Cancer_image.jpg" + aws s3 sync \ --profile di \ + --exclude "*.yaml" \ "$DIR" \ s3://openpipelines-bio/openpipeline_spatial/resources_test/visium \ --delete \ diff --git a/src/base/requirements/anndata.yaml b/src/base/requirements/anndata.yaml index 8ca4664..03552c8 100644 --- a/src/base/requirements/anndata.yaml +++ b/src/base/requirements/anndata.yaml @@ -1,2 +1,3 @@ packages: - - anndata~=0.11.1 + - anndata~=0.12.7 + - awkward \ No newline at end of file diff --git a/src/base/requirements/anndata_mudata.yaml b/src/base/requirements/anndata_mudata.yaml index 577b7e9..5583ffe 100644 --- a/src/base/requirements/anndata_mudata.yaml +++ b/src/base/requirements/anndata_mudata.yaml @@ -1,5 +1,5 @@ __merge__: [/src/base/requirements/anndata.yaml, .] packages: - - mudata~=0.3.1 + - mudata~=0.3.2 script: | - exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)") + exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2") diff --git a/src/base/requirements/spatialdata-io.yaml b/src/base/requirements/spatialdata-io.yaml index de99e0a..a715075 100644 --- a/src/base/requirements/spatialdata-io.yaml +++ b/src/base/requirements/spatialdata-io.yaml @@ -1,3 +1,3 @@ packages: - - spatialdata-io~=0.3.0 + - spatialdata-io~=0.5.1 __merge__: [ ., /src/base/requirements/spatialdata.yaml ] \ No newline at end of file diff --git a/src/base/requirements/spatialdata.yaml b/src/base/requirements/spatialdata.yaml index 9ebb9e5..5bbf1a6 100644 --- a/src/base/requirements/spatialdata.yaml +++ b/src/base/requirements/spatialdata.yaml @@ -1,3 +1,3 @@ packages: - - spatialdata~=0.5.0 + - spatialdata~=0.6.1 - pyarrow~=18.0.0 diff --git a/src/base/requirements/squidpy.yaml b/src/base/requirements/squidpy.yaml index 3d27832..fa976a7 100644 --- a/src/base/requirements/squidpy.yaml +++ b/src/base/requirements/squidpy.yaml @@ -1,3 +1,4 @@ __merge__: [/src/base/requirements/spatialdata.yaml, .] packages: - - squidpy~=1.6.5 + - squidpy~=1.7.0 +__merge__: [/src/base/requirements/scanpy.yaml, .] \ No newline at end of file diff --git a/src/convert/from_cells2stats_to_h5mu/script.py b/src/convert/from_cells2stats_to_h5mu/script.py index 3210079..1322408 100644 --- a/src/convert/from_cells2stats_to_h5mu/script.py +++ b/src/convert/from_cells2stats_to_h5mu/script.py @@ -35,7 +35,7 @@ logger = setup_logger() def assert_matching_order(var_names, count_columns, split_pattern=None): for var, col in zip(var_names, count_columns): - count_var = col if not split_pattern else col.split("_Nuclear")[0] + count_var = col if not split_pattern else col.replace(split_pattern, "") assert var == count_var, "Orders do not match" @@ -224,8 +224,8 @@ def main(): df.index_name = None # var and obs names - var_names = [var.split(".")[0] for var in count_columns] - obs_names = df["Cell"].astype(str).tolist() + var_columns = list(count_columns) + obs_columns = df["Cell"].astype(str).tolist() # Count matrix logger.info("Creating count matrix...") @@ -236,16 +236,21 @@ def main(): logger.info(f"Creating obs field with columns {obs_columns_fixed}") obs_df = df[obs_columns_fixed].copy() + # Var field + var_df = pd.DataFrame(index=pd.Index(var_columns, dtype=str)) + targets, batches = zip(*(c.rsplit(".", 1) for c in var_columns)) + var_df["target"] = targets + var_df["batch"] = batches + # Create AnnData object logger.info("Creating AnnData object...") adata = ad.AnnData( X=count_matrix_sparse, obs=obs_df, - var=pd.DataFrame(index=var_names), + var=var_df, ) - - adata.obs_names = obs_names - adata.var_names = var_names + adata.obs_names = pd.Index(obs_columns, dtype=str) + adata.var_names = pd.Index(var_columns, dtype=str) # Spatial coordinates coordinate_sets = { @@ -282,13 +287,13 @@ def main(): adata.uns[par["obsm_cell_profiler"]] = cell_profiler_columns if par["obsm_unassigned_targets"]: logger.info(f"Adding {par['obsm_unassigned_targets']} to obsm") - adata.obsm["unassigned_targets"] = df[unassigned_columns].copy() - adata.uns["unassigned_targets"] = unassigned_columns + adata.obsm[par["obsm_unassigned_targets"]] = df[unassigned_columns].copy() + adata.uns[par["obsm_unassigned_targets"]] = unassigned_columns # Add (optional) nuclear count layer if par["layer_nuclear_counts"]: assert_matching_order( - var_names, nuclear_count_columns, split_pattern="_Nuclear" + var_columns, nuclear_count_columns, split_pattern="_Nuclear" ) logger.info(f"Adding {par['layer_nuclear_counts']} to layers") nuclear_count_df = df[nuclear_count_columns].copy() diff --git a/src/convert/from_h5mu_to_spatialexperiment/config.vsh.yaml b/src/convert/from_h5mu_to_spatialexperiment/config.vsh.yaml index 3d88cae..42e9045 100644 --- a/src/convert/from_h5mu_to_spatialexperiment/config.vsh.yaml +++ b/src/convert/from_h5mu_to_spatialexperiment/config.vsh.yaml @@ -44,7 +44,7 @@ test_resources: engines: - type: docker - image: rocker/r2u:22.04 + image: rocker/r2u:24.04 setup: - type: apt packages: @@ -56,7 +56,8 @@ engines: test_setup: - type: docker env: - - RETICULATE_PYTHON=/usr/bin/python + - RETICULATE_PYTHON=/usr/bin/python + - PIP_BREAK_SYSTEM_PACKAGES=1 - type: apt packages: - python3 @@ -66,6 +67,7 @@ engines: - type: r cran: [ reticulate, testthat ] - type: python + user: true __merge__: /src/base/requirements/anndata_mudata.yaml runners: diff --git a/src/convert/from_spaceranger_to_h5mu/config.vsh.yaml b/src/convert/from_spaceranger_to_h5mu/config.vsh.yaml new file mode 100644 index 0000000..9ee599d --- /dev/null +++ b/src/convert/from_spaceranger_to_h5mu/config.vsh.yaml @@ -0,0 +1,90 @@ +name: "from_spaceranger_to_h5mu" +namespace: "convert" +scope: "public" +description: | + Converts the output bundle from spaceranger into an h5mu file. +authors: + - __merge__: /src/authors/dorien_roosen.yaml + roles: [ maintainer ] +argument_groups: + - name: Inputs + arguments: + - name: "--input" + alternatives: ["-i"] + type: file + description: | + Convert spatial data resulting from Aviti Teton sequencers that have been processed by the Element Biosciences cells2stats workflow to H5MU format. + + This component processes cells2stats count matrices to create a standardized H5MU file for downstream analysis. + + The component reads: + - Parquet file containing the count matrix and metadata + - Panel.json with target and batch information + + And outputs an H5MU file with: + - Count data as the main .X matrix + - Spatial coordinates in obsm + - Cell Paint intensities in obsm (optional) + - Nuclear count data as a layer (optional) + - CellProfiler morphology metrics in obsm (optional) + - Unassigned targets in obsm (optional) + example: spaceranger_output + direction: input + required: true + - name: Outputs + arguments: + - name: "--output" + type: file + description: Output h5mu file. + example: output.h5mu + direction: output + - name: "--modality" + type: string + description: Name of the modality under which to store the data. + default: "rna" + - name: "--uns_metrics" + type: string + description: Name of the .uns slot under which to QC metrics (if any). + default: "metrics_spaceranger" + - name: "--uns_probe_set" + type: string + description: Name of the .uns slot under which to store probe set information (if any). + default: "probe_set" + - name: "--obsm_coordinates" + type: string + description: Name of the .obsm slot under which to store the cell centroid coordinates. + default: "spatial" + - name: "--output_type" + type: string + description: "Which Spaceranger output to use for converting to h5mu." + choices: [ raw, filtered ] + default: filtered + - name: "--output_compression" + type: string + description: Compression to use when writing the h5mu file. + choices: [ gzip, lzf ] + +resources: + - type: python_script + path: script.py + - path: /src/utils/setup_logger.py +test_resources: + - type: python_script + path: test.py + - path: /resources_test/visium/Visium_FFPE_Human_Ovarian_Cancer_tiny_spaceranger + +engines: +- type: docker + image: python:3.12-slim + setup: + - type: apt + packages: + - procps + - type: python + __merge__: [/src/base/requirements/anndata_mudata.yaml, /src/base/requirements/scanpy.yaml, .] + __merge__: [ /src/base/requirements/python_test_setup.yaml, .] +runners: +- type: executable +- type: nextflow + directives: + label: [lowmem, singlecpu] \ No newline at end of file diff --git a/src/convert/from_spaceranger_to_h5mu/script.py b/src/convert/from_spaceranger_to_h5mu/script.py new file mode 100644 index 0000000..790ddb5 --- /dev/null +++ b/src/convert/from_spaceranger_to_h5mu/script.py @@ -0,0 +1,134 @@ +from pathlib import Path +import mudata +import scanpy as sc +import sys +import pandas as pd + +## VIASH START +par = { + "input": "resources_test/visium/Visium_FFPE_Human_Ovarian_Cancer_tiny_spaceranger", + "modality": "rna", + "uns_metrics": "metrics_spaceranger", + "uns_probe_set": "probe_set", + "obsm_coordinates": "spatial", + "output": "foo.h5mu", + "min_genes": None, + "min_counts": None, + "output_compression": "gzip", + "output_type": "filtered", +} +meta = {"resources_dir": "src/utils"} +## VIASH END + +sys.path.append(meta["resources_dir"]) +from setup_logger import setup_logger + +logger = setup_logger() + + +def retrieve_input_data(spaceranger_output_bundle, input_type="filtered"): + # Expected folder structure (showing only relevant files): + # ├── Spatial/ + # │ └── tissue_positions.csv + # ├── filtered_feature_bc_matrix.h5 OR raw_feature_bc_matrix.h5 + # ├── metrics_summary.csv + # └── probe_set.csv + + matrix_pattern = ( + "**/filtered_feature_bc_matrix.h5" + if input_type == "filtered" + else "**/raw_feature_bc_matrix.h5" + ) + spaceranger_file_patterns = { + "count_matrix": matrix_pattern, + "metrics_summary": "**/metrics_summary.csv", + "probe_set": "**/probe_set.csv", + "spatial_coords": "**/spatial/tissue_positions.csv", + } + + spaceranger_output_bundle = Path(spaceranger_output_bundle) + + spaceranger_files = {} + + for key, pattern in spaceranger_file_patterns.items(): + file = list(spaceranger_output_bundle.glob(pattern)) + assert len(file) == 1, ( + f"Expected exactly one file for pattern '{pattern}', found {len(file)}." + ) + spaceranger_files[key] = file[0] + + return spaceranger_files + + +def main(): + spaceranger_files = retrieve_input_data(par["input"], input_type=par["output_type"]) + + logger.info("Reading count matrix...") + adata = sc.read_10x_h5(spaceranger_files["count_matrix"], gex_only=False) + + # set the gene ids as var_names + logger.info("Renaming var columns") + adata.var = adata.var.rename_axis("gene_symbol").reset_index().set_index("gene_ids") + + if par["uns_metrics"]: + logger.info("Reading metrics summary file...") + metrics_summary = pd.read_csv( + spaceranger_files["metrics_summary"], + decimal=".", + quotechar='"', + thousands=",", + ) + + logger.info("Storing metrics summary in .uns slot...") + adata.uns[par["uns_metrics"]] = metrics_summary + + if par["uns_probe_set"]: + logger.info("Reading probe set file...") + + def read_hash_metadata(path): + meta = {} + with open(path, "r", encoding="utf-8") as f: + for i, line in enumerate(f): + if not line.startswith("#"): + break + line = line[1:].strip() + if "=" in line: + k, v = line.split("=", 1) + meta[k.strip()] = v.strip() + return meta + + meta = read_hash_metadata(spaceranger_files["probe_set"]) + probe_set = pd.read_csv(spaceranger_files["probe_set"], comment="#") + + logger.info("Storing probe set in .uns slot...") + adata.uns[par["uns_probe_set"]] = probe_set + adata.uns[par["uns_probe_set"] + "_meta"] = meta + + logger.info("Reading spatial coordinates...") + spatial_coords = pd.read_csv( + spaceranger_files["spatial_coords"], decimal=".", thousands="," + ) + + spatial_coords_aligned = spatial_coords.set_index("barcode").reindex( + adata.obs_names + ) + logger.info("Storing spatial coordinates in .obsm slot...") + adata.obsm[par["obsm_coordinates"]] = spatial_coords_aligned[ + ["pxl_col_in_fullres", "pxl_row_in_fullres"] + ].to_numpy() + + # generate output + logger.info("Convert to mudata") + mdata = mudata.MuData({par["modality"]: adata}) + + # override root .obs and .uns + mdata.obs = adata.obs + mdata.uns = adata.uns + + # write output + logger.info("Writing %s", par["output"]) + mdata.write_h5mu(par["output"], compression=par["output_compression"]) + + +if __name__ == "__main__": + main() diff --git a/src/convert/from_spaceranger_to_h5mu/test.py b/src/convert/from_spaceranger_to_h5mu/test.py new file mode 100644 index 0000000..26c9985 --- /dev/null +++ b/src/convert/from_spaceranger_to_h5mu/test.py @@ -0,0 +1,44 @@ +import pytest +import sys +import mudata as mu + +## VIASH START +meta = { + "executable": "./target/executable/convert/from_spaceranger_to_h5mu/from_spaceranger_to_h5mu", + "resources_dir": "resources_test/", + "config": "src/convert/from_spaceranger_to_h5mu/config.vsh.yaml", +} +## VIASH END + +input = f"{meta['resources_dir']}/Visium_FFPE_Human_Ovarian_Cancer_tiny_spaceranger" + + +def test_simple_execution(run_component, tmp_path): + output = tmp_path / "xenium.h5mu" + + # run component + run_component( + ["--input", input, "--output", str(output), "--output_compression", "gzip"] + ) + + assert output.is_file(), "output file was not created" + + mdata = mu.read_h5mu(output) + assert list(mdata.mod.keys()) == ["rna"], "Expected modality rna" + adata = mdata.mod["rna"] + + assert list(adata.uns.keys()) == [ + "metrics_spaceranger", + "probe_set", + "probe_set_meta", + ] + assert list(adata.obsm.keys()) == ["spatial"] + assert list(adata.var.keys()) == ["gene_symbol", "feature_types", "genome"] + + assert adata.X.dtype.kind == "f" + assert all(adata.var["feature_types"] == "Gene Expression") + assert adata.obsm["spatial"].dtype == "float" + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) diff --git a/src/convert/from_xenium_to_spatialdata/test.py b/src/convert/from_xenium_to_spatialdata/test.py index c9e090e..d8b8d05 100644 --- a/src/convert/from_xenium_to_spatialdata/test.py +++ b/src/convert/from_xenium_to_spatialdata/test.py @@ -29,7 +29,9 @@ def test_simple_execution(run_component, tmp_path): assert os.path.exists(output_sd_path / "points"), "images folder was not created" assert os.path.exists(output_sd_path / "shapes"), "shapes folder was not created" assert os.path.exists(output_sd_path / "tables"), "tables folder was not created" - assert (output_sd_path / "zmetadata").is_file(), "zmetadata file was not created" + assert (output_sd_path / "zarr.json").is_file(), ( + "zarr metadata file was not created" + ) def test_compressed_input(run_component, tmp_path): @@ -62,7 +64,9 @@ def test_compressed_input(run_component, tmp_path): assert os.path.exists(output_sd_path / "points"), "images folder was not created" assert os.path.exists(output_sd_path / "shapes"), "shapes folder was not created" assert os.path.exists(output_sd_path / "tables"), "tables folder was not created" - assert (output_sd_path / "zmetadata").is_file(), "zmetadata file was not created" + assert (output_sd_path / "zarr.json").is_file(), ( + "zarr metadata file was not created" + ) if __name__ == "__main__": diff --git a/src/dataflow/concatenate_h5mu/config.vsh.yaml b/src/dataflow/concatenate_h5mu/config.vsh.yaml deleted file mode 100644 index b2afdbc..0000000 --- a/src/dataflow/concatenate_h5mu/config.vsh.yaml +++ /dev/null @@ -1,105 +0,0 @@ -name: concatenate_h5mu -namespace: "dataflow" -scope: "public" -description: | - Concatenate observations from samples in several (uni- and/or multi-modal) MuData files into a single file. -authors: - - __merge__: /src/authors/dries_schaumont.yaml - roles: [ maintainer ] -arguments: - - name: "--input" - alternatives: ["-i"] - type: file - multiple: true - description: Paths to the different samples to be concatenated. - required: true - example: sample_paths - - name: "--modality" - type: string - multiple: true - description: "Only output concatenated objects for the provided modalities. Outputs all modalities by default." - required: false - - name: "--input_id" - type: string - multiple: true - description: | - Names of the different samples that have to be concatenated. Must be specified when using '--mode move'. - In this case, the ids will be used for the columns names of the dataframes registring the conflicts. - If specified, must be of same length as `--input`. - required: false - - name: "--output" - description: | - Output location for the concatenated MuData object file. - alternatives: ["-o"] - type: file - direction: output - example: "output.h5mu" - - name: "--obs_sample_name" - type: string - description: Name of the .obs key under which to add the sample names. - default: "sample_id" - - name: "--other_axis_mode" - type: string - choices: [same, unique, first, only, concat, move] - default: move - description: | - How to handle the merging of other axis (var, obs, ...). - - - None: keep no data - - same: only keep elements of the matrices which are the same in each of the samples - - unique: only keep elements for which there is only 1 possible value (1 value that can occur in multiple samples) - - first: keep the annotation from the first sample - - only: keep elements that show up in only one of the objects (1 unique element in only 1 sample) - - move: identical to 'same', but moving the conflicting values to .varm or .obsm - - name: "--uns_merge_mode" - description: | - How to handle the merging of .uns across modalities - - None: keep no data - - same: only keep elements of the matrices which are the same in each of the samples - - unique: only keep elements for which there is only 1 possible value (1 value that can occur in multiple samples) - - first: keep the annotation from the first sample - - only: keep elements that show up in only one of the objects (1 unique element in only 1 sample) - - make_unique: identical to 'unique', but keys which are not unique are made unique by prefixing them with the sample id. - type: string - choices: ["same", "unique", "first", "only", "make_unique"] - default: make_unique - - name: "--obsp_keys" - type: string - multiple: true - description: | - List of `.obsp` keys for which block-diagonal concatenation should be performed. - If not provided, no `.obsp` keys will be concatenated. - Provided keys must be present in all samples for block concatenation to be performed. - required: false -__merge__: [., /src/base/h5_compression_argument.yaml] - -resources: - - type: python_script - path: script.py - - path: /src/utils/setup_logger.py - - path: /src/utils/compress_h5mu.py -test_resources: - - type: python_script - path: test.py - - path: /resources_test/concat_test_data/e18_mouse_brain_fresh_5k_filtered_feature_bc_matrix_subset_unique_obs.h5mu - - path: /resources_test/concat_test_data/human_brain_3k_filtered_feature_bc_matrix_subset_unique_obs.h5mu -engines: - - type: docker - image: python:3.13-slim - setup: - - type: apt - packages: - - procps - - type: python - __merge__: [/src/base/requirements/anndata_mudata.yaml, .] - __merge__: [ /src/base/requirements/python_test_setup.yaml, .] - test_setup: - - type: python - packages: - - pytest-benchmark - __merge__: [ /src/base/requirements/viashpy.yaml, .] -runners: - - type: executable - - type: nextflow - directives: - label: [midcpu, highmem] \ No newline at end of file diff --git a/src/dataflow/concatenate_h5mu/script.py b/src/dataflow/concatenate_h5mu/script.py deleted file mode 100644 index a455ddd..0000000 --- a/src/dataflow/concatenate_h5mu/script.py +++ /dev/null @@ -1,407 +0,0 @@ -from __future__ import annotations -import sys -import anndata -import mudata as mu -import pandas as pd -import numpy as np -from collections.abc import Iterable -from multiprocessing import Pool -from pathlib import Path -from h5py import File as H5File -from typing import Literal -import shutil - -### VIASH START -par = { - "input": [ - "resources_test/concat_test_data/e18_mouse_brain_fresh_5k_filtered_feature_bc_matrix_subset_unique_obs.h5mu", - "resources_test/concat_test_data/human_brain_3k_filtered_feature_bc_matrix_subset_unique_obs.h5mu", - ], - "output": "foo.h5mu", - "input_id": ["mouse", "human"], - "obsp_keys": [], - "other_axis_mode": "move", - "output_compression": "gzip", - "uns_merge_mode": "make_unique", -} -meta = {"cpus": 10, "resources_dir": "resources_test/"} -### VIASH END - -sys.path.append(meta["resources_dir"]) -from compress_h5mu import compress_h5mu -from setup_logger import setup_logger - -logger = setup_logger() - - -def nunique(row): - unique = pd.unique(row) - unique_without_na = pd.core.dtypes.missing.remove_na_arraylike(unique) - return len(unique_without_na) > 1 - - -def any_row_contains_duplicate_values(n_processes: int, frame: pd.DataFrame) -> bool: - """ - Check if any row contains duplicate values, that are not NA. - """ - numpy_array = frame.to_numpy() - with Pool(n_processes) as pool: - is_duplicated = pool.map(nunique, iter(numpy_array)) - return any(is_duplicated) - - -def concatenate_matrices( - n_processes: int, matrices: dict[str, pd.DataFrame], align_to: pd.Index -) -> tuple[ - dict[str, pd.DataFrame], pd.DataFrame | None, dict[str, pd.core.dtypes.dtypes.Dtype] -]: - """ - Merge matrices by combining columns that have the same name. - Columns that contain conflicting values (e.i. the columns have different values), - are not merged, but instead moved to a new dataframe. - """ - column_names = set(column_name for var in matrices.values() for column_name in var) - logger.debug("Trying to concatenate columns: %s.", ",".join(column_names)) - if not column_names: - return {}, pd.DataFrame(index=align_to) - conflicts, concatenated_matrix = split_conflicts_and_concatenated_columns( - n_processes, matrices, column_names, align_to - ) - concatenated_matrix = cast_to_writeable_dtype(concatenated_matrix) - conflicts = { - conflict_name: cast_to_writeable_dtype(conflict_df) - for conflict_name, conflict_df in conflicts.items() - } - return conflicts, concatenated_matrix - - -def get_first_non_na_value_vector(df): - numpy_arr = df.to_numpy() - n_rows, n_cols = numpy_arr.shape - col_index = pd.isna(numpy_arr).argmin(axis=1) - flat_index = n_cols * np.arange(n_rows) + col_index - return pd.Series(numpy_arr.ravel()[flat_index], index=df.index, name=df.columns[0]) - - -def make_uns_keys_unique(mod_data, concatenated_data): - """ - Check if the uns keys across samples are unique before adding them - to the final concatenated object. If a conflict occurs between the samples, - add the sample ID to make the key unique again. - """ - all_uns_keys = {} - for sample_id, mod in mod_data.items(): - for uns_key, _ in mod.uns.items(): - all_uns_keys.setdefault(uns_key, []).append(sample_id) - for uns_key, samples_ids in all_uns_keys.items(): - assert samples_ids - if len(samples_ids) == 1: - sample_id = samples_ids[0] - concatenated_data.uns[uns_key] = mod_data[sample_id].uns[uns_key] - else: - for sample_id in samples_ids: - concatenated_data.uns[f"{sample_id}_{uns_key}"] = mod_data[ - sample_id - ].uns[uns_key] - return concatenated_data - - -def split_conflicts_and_concatenated_columns( - n_processes: int, - matrices: dict[str, pd.DataFrame], - column_names: Iterable[str], - align_to: pd.Index, -) -> tuple[dict[str, pd.DataFrame], pd.DataFrame]: - """ - Retrieve columns with the same name from a list of dataframes which are - identical across all the frames (ignoring NA values). - Columns which are not the same are regarded as 'conflicts', - which are stored in seperate dataframes, one per columns - with the same name that store conflicting values. - """ - conflicts = {} - concatenated_matrix = [] - for column_name in column_names: - columns = { - input_id: var[column_name] - for input_id, var in matrices.items() - if column_name in var - } - assert columns, "Some columns should have been found." - concatenated_columns = pd.concat( - columns.values(), axis=1, join="outer", sort=False - ) - if any_row_contains_duplicate_values(n_processes, concatenated_columns): - concatenated_columns.columns = ( - columns.keys() - ) # Use the sample id as column name - concatenated_columns = concatenated_columns.reindex(align_to, copy=False) - conflicts[f"conflict_{column_name}"] = concatenated_columns - else: - unique_values = get_first_non_na_value_vector(concatenated_columns) - concatenated_matrix.append(unique_values) - if not concatenated_matrix: - return conflicts, pd.DataFrame(index=align_to) - concatenated_matrix = pd.concat( - concatenated_matrix, join="outer", axis=1, sort=False - ) - concatenated_matrix = concatenated_matrix.reindex(align_to, copy=False) - return conflicts, concatenated_matrix - - -def cast_to_writeable_dtype(result: pd.DataFrame) -> pd.DataFrame: - """ - Cast the dataframe to dtypes that can be written by mudata. - """ - # dtype inferral workfs better with np.nan - result = result.replace({pd.NA: np.nan}) - - # MuData supports nullable booleans and ints - # ie. `IntegerArray` and `BooleanArray` - result = result.convert_dtypes( - infer_objects=True, - convert_integer=True, - convert_string=False, - convert_boolean=True, - convert_floating=False, - ) - - # Convert leftover 'object' columns to string - # However, na values are supported, so convert all values except NA's to string - object_cols = result.select_dtypes(include="object").columns.values - for obj_col in object_cols: - result[obj_col] = ( - result[obj_col] - .where(result[obj_col].isna(), result[obj_col].astype(str)) - .astype("category") - ) - return result - - -def split_conflicts_modalities( - n_processes: int, samples: dict[str, anndata.AnnData], output: anndata.AnnData -) -> anndata.AnnData: - """ - Merge .var and .obs matrices of the anndata objects. Columns are merged - when the values (excl NA) are the same in each of the matrices. - Conflicting columns are moved to a separate dataframe (one dataframe for each column, - containing all the corresponding column from each sample). - """ - matrices_to_parse = ("var", "obs") - for matrix_name in matrices_to_parse: - matrices = { - sample_id: getattr(sample, matrix_name) - for sample_id, sample in samples.items() - } - output_index = getattr(output, matrix_name).index - conflicts, concatenated_matrix = concatenate_matrices( - n_processes, matrices, output_index - ) - if concatenated_matrix.empty: - concatenated_matrix.index = output_index - - # Even though we did not touch the varm and obsm matrices that were already present, - # the joining of observations might have caused a dtype change in these matrices as well - # so these also need to be casted to a writable dtype... - for multidim_name, multidim_data in getattr(output, f"{matrix_name}m").items(): - new_data = ( - cast_to_writeable_dtype(multidim_data) - if isinstance(multidim_data, pd.DataFrame) - else multidim_data - ) - getattr(output, f"{matrix_name}m")[multidim_name] = new_data - - # Write the conflicts to the output - for conflict_name, conflict_data in conflicts.items(): - getattr(output, f"{matrix_name}m")[conflict_name] = conflict_data - - # Set other annotation matrices in the output - setattr(output, matrix_name, concatenated_matrix) - - return output - - -def concatenate_modality( - n_processes: int, - mod: str | None, - input_files: Iterable[str | Path], - other_axis_mode: str, - uns_merge_mode: str, - input_ids: tuple[str], -) -> anndata.AnnData: - concat_modes = { - "move": "unique", - } - other_axis_mode_to_apply = concat_modes.get(other_axis_mode, other_axis_mode) - - uns_merge_modes = {"make_unique": None} - uns_merge_mode_to_apply = uns_merge_modes.get(uns_merge_mode, uns_merge_mode) - - mod_data = {} - mod_indices_combined = pd.Index([]) - for input_id, input_file in zip(input_ids, input_files): - if mod is not None: - try: - data = mu.read_h5ad(input_file, mod=mod) - - # Remove obsp keys that are not in par["obsp_keys"] - if par["obsp_keys"]: - # Keep only the obsp keys that are specified in par["obsp_keys"] - keys_to_remove = set(data.obsp.keys()) - set(par["obsp_keys"]) - for key in keys_to_remove: - del data.obsp[key] - - mod_data[input_id] = data - mod_indices_combined = mod_indices_combined.append(data.obs.index) - except KeyError as e: # Modality does not exist for this sample, skip it - if ( - f"Unable to synchronously open object (object '{mod}' doesn't exist)" - not in str(e) - ): - raise e - pass - else: # When mod=None, process the 'global' h5mu state - with H5File(input_file, "r") as input_h5: - if "uns" in input_h5.keys(): - uns_data = anndata.experimental.read_elem(input_h5["uns"]) - if uns_data: - mod_data[input_id] = anndata.AnnData(uns=uns_data) - - if not mod_indices_combined.is_unique: - raise ValueError("Observations are not unique across samples.") - - if not mod_data: - return anndata.AnnData() - - concatenated_data = anndata.concat( - mod_data.values(), - join="outer", - pairwise=True if par["obsp_keys"] else False, - merge=other_axis_mode_to_apply, - uns_merge=uns_merge_mode_to_apply, - ) - - if other_axis_mode == "move": - concatenated_data = split_conflicts_modalities( - n_processes, mod_data, concatenated_data - ) - - if uns_merge_mode == "make_unique": - concatenated_data = make_uns_keys_unique(mod_data, concatenated_data) - - return concatenated_data - - -def concatenate_modalities( - n_processes: int, - modalities: list[str], - input_files: Path | str, - other_axis_mode: str, - uns_merge_mode: str, - output_file: Path | str, - compression: Literal["gzip"] | Literal["lzf"], - input_ids: tuple[str] | None = None, -) -> None: - """ - Join the modalities together into a single multimodal sample. - """ - logger.info("Concatenating samples.") - output_file, input_files = ( - Path(output_file), - [Path(input_file) for input_file in input_files], - ) - output_file_uncompressed = output_file.with_name( - output_file.stem + "_uncompressed.h5mu" - ) - output_file_uncompressed.touch() - # Create empty mudata file - mdata = mu.MuData({modality: anndata.AnnData() for modality in modalities}) - mdata.write(output_file_uncompressed, compression=compression) - - # Use "None" for the global slots (not assigned to any modality) - for mod_name in modalities + [ - None, - ]: - new_mod = concatenate_modality( - n_processes, - mod_name, - input_files, - other_axis_mode, - uns_merge_mode, - input_ids, - ) - if mod_name is None: - if new_mod.uns: - with H5File(output_file_uncompressed, "r+") as open_h5mu_file: - anndata.experimental.write_elem( - open_h5mu_file, "uns", dict(new_mod.uns) - ) - continue - logger.info( - "Writing out modality '%s' to '%s' with compression '%s'.", - mod_name, - output_file_uncompressed, - compression, - ) - mu.write_h5ad(output_file_uncompressed, data=new_mod, mod=mod_name) - - if compression: - compress_h5mu(output_file_uncompressed, output_file, compression=compression) - output_file_uncompressed.unlink() - else: - shutil.move(output_file_uncompressed, output_file) - - logger.info("Concatenation successful.") - - -def main() -> None: - # Get a list of all possible modalities - mods = set() - for path in par["input"]: - try: - with H5File(path, "r") as f_root: - mods = mods | set(f_root["mod"].keys()) - except OSError: - raise OSError(f"Failed to load {path}. Is it a valid h5 file?") - - input_ids = None - if par["input_id"]: - input_ids: tuple[str] = tuple(i.strip() for i in par["input_id"]) - if len(input_ids) != len(par["input"]): - raise ValueError( - "The number of sample names must match the number of sample files." - ) - - if len(set(input_ids)) != len(input_ids): - raise ValueError("The sample names should be unique.") - - logger.info("\nConcatenating data from paths:\n\t%s", "\n\t".join(par["input"])) - - if par["other_axis_mode"] == "move" and not input_ids: - raise ValueError("--mode 'move' requires --input_ids.") - - n_processes = meta["cpus"] if meta["cpus"] else 1 - - if par["modality"]: - par["modality"] = set(par["modality"]) - if not par["modality"].issubset(mods): - mods_joined, input_mods_joined = ", ".join(mods), ", ".join(par["modality"]) - raise ValueError( - f"One of the modalities provided ({input_mods_joined}) is not available in the input data {mods_joined}" - ) - mods = par["modality"] - - concatenate_modalities( - n_processes, - list(mods), - par["input"], - par["other_axis_mode"], - par["uns_merge_mode"], - par["output"], - par["output_compression"], - input_ids=input_ids, - ) - - -if __name__ == "__main__": - main() diff --git a/src/dataflow/concatenate_h5mu/test.py b/src/dataflow/concatenate_h5mu/test.py deleted file mode 100644 index a875424..0000000 --- a/src/dataflow/concatenate_h5mu/test.py +++ /dev/null @@ -1,1305 +0,0 @@ -import mudata as md -import anndata as ad -import subprocess -from pathlib import Path -import pandas as pd -import numpy as np -import pytest -import re -import sys -import scipy.sparse as sp -from openpipeline_testutils.utils import remove_annotation_column -from operator import attrgetter - -## VIASH START -meta = { - "executable": "./target/docker/dataflow/concatenate_h5mu/concatenate_h5mu", - "resources_dir": "./resources_test/concat_test_data/", - "cpus": 2, - "config": "./src/dataflow/concatenate_h5mu/config.vsh.yaml", -} -## VIASH END - -meta["cpus"] = 1 if not meta["cpus"] else meta["cpus"] - - -@pytest.fixture -def sample_1_modality_1(): - """ - >>> ad1.obs - Obs1 Shared_obs - obs1 A B - obs2 C D - - >>> ad1.var - Feat1 Shared_feat - var1 a b - var2 c d - overlapping_var_mod1 e f - - >>> ad1.X - array([[1, 2, 3], - [4, 5, 6]]) - """ - - df = pd.DataFrame( - [[1, 2, 3], [4, 5, 6]], - index=["obs1", "obs2"], - columns=["var1", "var2", "overlapping_var_mod1"], - ) - obs = pd.DataFrame( - [["A", "B"], ["C", "D"]], index=df.index, columns=["Obs1", "Shared_obs"] - ) - var = pd.DataFrame( - [["a", "b"], ["c", "d"], ["e", "f"]], - index=df.columns, - columns=["Feat1", "Shared_feat"], - ) - varm = np.random.rand(df.columns.size, 5) - ad1 = ad.AnnData( - df, - obs=obs, - var=var, - varm={"random_vals_mod1": varm}, - uns={ - "uns_unique_to_sample1": pd.DataFrame( - ["foo"], index=["bar"], columns=["col1"] - ), - "overlapping_uns_key": pd.DataFrame( - ["jing"], index=["jang"], columns=["col2"] - ), - }, - ) - A1 = np.array([[0, 1], [2, 0]]) - ad1.obsp["connectivities"] = sp.csr_matrix(A1) - # ad1 = ad.AnnData(df, obs=obs, var=var) - return ad1 - - -@pytest.fixture -def sample_1_input_modality_2(): - """ - >>> ad2.X - array([[ 7, 8], - [ 9, 10], - [11, 12]]) - - >>> ad2.obs - Obs2 Obs3 Shared_obs - obs3 E F G - obs4 H I J - obs5 K L M - - >>> ad2.var - Feat2 Shared_feat - var4 d e - var5 f g - - """ - df = pd.DataFrame( - [[7, 8], [9, 10], [11, 12]], - index=["obs3", "obs4", "obs5"], - columns=["var3", "var4"], - ) - obs = pd.DataFrame( - [["E", "F", "G"], ["H", "I", "J"], ["K", "L", "M"]], - index=df.index, - columns=["Obs2", "Obs3", "Shared_obs"], - ) - var = pd.DataFrame( - [["d", "e"], ["f", "g"]], index=df.columns, columns=["Feat2", "Shared_feat"] - ) - ad2 = ad.AnnData(df, obs=obs, var=var) - return ad2 - - -@pytest.fixture -def sample_1_h5mu(sample_1_modality_1, sample_1_input_modality_2): - tmp_mudata = md.MuData( - {"mod1": sample_1_modality_1, "mod2": sample_1_input_modality_2} - ) - return tmp_mudata - - -@pytest.fixture -def sample_2_modality_1(): - """ - >>> ad3.X - array([[13, 14], - [15, 16], - [17, 18]]) - - >>> ad3.var - Feat3 Shared_feat - var5 h i - overlapping_var_mod1 j k - - >>> ad3.obs - Obs4 Obs5 Shared_obs - obs6 O P Q - obs7 R S T - obs8 U V W - """ - df = pd.DataFrame( - [[13, 14], [15, 16], [17, 18]], - index=["obs6", "obs7", "obs8"], - columns=["var5", "overlapping_var_mod1"], - ) - obs = pd.DataFrame( - [["O", "P", "Q"], ["R", "S", "T"], ["U", "V", "W"]], - index=df.index, - columns=["Obs4", "Obs5", "Shared_obs"], - ) - var = pd.DataFrame( - [["h", "i"], ["j", "k"]], index=df.columns, columns=["Feat3", "Shared_feat"] - ) - ad3 = ad.AnnData( - df, - obs=obs, - var=var, - uns={ - "uns_unique_to_sample2": pd.DataFrame( - ["baz"], index=["qux"], columns=["col3"] - ), - "overlapping_uns_key": pd.DataFrame( - ["ping"], index=["pong"], columns=["col4"] - ), - }, - ) - A2 = np.array([[0, 3, 4], [5, 0, 6], [7, 8, 0]]) - ad3.obsp["connectivities"] = sp.csr_matrix(A2) - return ad3 - - -@pytest.fixture -def sample_2_modality_2(): - """ - >>> ad4.X - array([[19, 20, 21], - [22, 23, 24]]) - - >>> ad4.obs - Obs6 Shared_obs - obs8 X Y - obs9 Z AA - - >>> ad4.var - Feat4 Shared_feat - var6 l m - var7 n o - var8 p q - """ - df = pd.DataFrame( - [[19, 20, 21], [22, 23, 24]], - index=["obs8", "obs9"], - columns=["var6", "var7", "var8"], - ) - obs = pd.DataFrame( - [["X", "Y"], ["Z", "AA"]], index=df.index, columns=["Obs6", "Shared_obs"] - ) - var = pd.DataFrame( - [["l", "m"], ["n", "o"], ["p", "q"]], - index=df.columns, - columns=["Feat4", "Shared_feat"], - ) - varm = np.random.rand(df.columns.size, 3) - ad4 = ad.AnnData(df, obs=obs, var=var, varm={"random_vals_mod2": varm}) - # ad4 = ad.AnnData(df, obs=obs, var=var) - return ad4 - - -@pytest.fixture -def sample_2_h5mu(sample_2_modality_1, sample_2_modality_2): - tmp_mudata = md.MuData({"mod1": sample_2_modality_1, "mod2": sample_2_modality_2}) - return tmp_mudata - - -@pytest.fixture -def sample_3_modality_1(): - """ - >>> ad3.X - array([[25]]) - - >>> ad3.obs - Obs7 - obs10 AB - - >>> ad3.var - Feat4 - var9 r - - """ - df = pd.DataFrame([[25]], index=["obs10"], columns=["var9"]) - obs = pd.DataFrame([["AB"]], index=df.index, columns=["Obs7"]) - var = pd.DataFrame([["r"]], index=df.columns, columns=["Feat4"]) - ad5 = ad.AnnData(df, obs=obs, var=var) - return ad5 - - -@pytest.fixture -def sample_3_modality_3(): - """ - >>> ad6.X - array([[ 26, 32, 33, 453], - [ 34, 35, 36, 543]]) - - >>> ad6.var - Feat5 Feat6 Feat7 Feat8 - var10 s t u v - var11 w x y z - var12 aa ab ac ad - var13 ae af ag ah - - >>> ad6.obs - Obs8 Obs9 obs10 obs11 - obs11 AC AD AE AF - obs12 AG AH AI AJ - """ - df = pd.DataFrame( - [[26, 32, 33, 453], [34, 35, 36, 543]], - index=["obs11", "obs12"], - columns=["var10", "var11", "var12", "var13"], - ) - obs = pd.DataFrame( - [["AC", "AD", "AE", "AF"], ["AG", "AH", "AI", "AJ"]], - index=df.index, - columns=["Obs8", "Obs9", "obs10", "obs11"], - ) - var = pd.DataFrame( - [ - ["s", "t", "u", "v"], - ["w", "x", "y", "z"], - ["aa", "ab", "ac", "ad"], - ["ae", "af", "ag", "ah"], - ], - index=df.columns, - columns=["Feat5", "Feat6", "Feat7", "Feat8"], - ) - ad6 = ad.AnnData(df, obs=obs, var=var) - return ad6 - - -@pytest.fixture -def sample_3_h5mu(sample_3_modality_1, sample_3_modality_3): - tmp_mudata = md.MuData({"mod1": sample_3_modality_1, "mod3": sample_3_modality_3}) - return tmp_mudata - - -@pytest.fixture -def wrap_anndata_to_mudata(): - def wrapper(anndata_obj, mod_name="mod"): - return md.MuData({mod_name: anndata_obj}) - - return wrapper - - -@pytest.fixture -def change_column_contents(): - def wrapper(mudata_obj, annotation_frame_name, column_name, values_per_modality): - mudata_obj.update() - get_frame = attrgetter(annotation_frame_name) - modality_columns = [] - for mod_name, col_value in values_per_modality.items(): - modality = mudata_obj.mod[mod_name] - annotation_frame = get_frame(modality) - annotation_frame[column_name] = col_value - modality_columns.append(annotation_frame[column_name]) - mudata_obj.update() - global_annotation_frame = get_frame(mudata_obj) - if column_name in global_annotation_frame.columns: - updated_global_column = pd.concat(modality_columns, copy=True, join="inner") - no_duplicates = updated_global_column.reset_index().drop_duplicates( - subset=["index"] - ) - no_duplicates = no_duplicates.set_index("index") - global_annotation_frame[column_name] = no_duplicates - setattr( - mudata_obj, - annotation_frame_name, - global_annotation_frame.convert_dtypes( - infer_objects=True, - convert_integer=True, - convert_string=False, - convert_boolean=True, - convert_floating=False, - ), - ) - - return wrapper - - -def test_concatenate_samples_with_same_observation_ids_raises( - run_component, - wrap_anndata_to_mudata, - write_mudata_to_file, - sample_1_modality_1, - sample_2_modality_1, - random_h5mu_path, -): - """ - Test how concat handles overlapping observation IDs. - This should raise. - """ - # introduce an overlapping observation - input_1_mudata = wrap_anndata_to_mudata(sample_1_modality_1) - old_obs_names = sample_2_modality_1.obs_names - new_obs_names = old_obs_names.where( - old_obs_names.isin([old_obs_names[0]]), sample_1_modality_1.obs.index[0] - ) - sample_2_modality_1.obs_names = new_obs_names - input_2_mudata = wrap_anndata_to_mudata(sample_2_modality_1) - - with pytest.raises(subprocess.CalledProcessError) as err: - run_component( - [ - "--input_id", - "foo;bar", - "--input", - write_mudata_to_file(input_1_mudata), - "--input", - write_mudata_to_file(input_2_mudata), - "--output", - random_h5mu_path(), - "--other_axis_mode", - "move", - "--output_compression", - "gzip", - ] - ) - assert ( - "ValueError: Observations are not unique across samples." - in err.value.stdout.decode("utf-8") - ) - - -def test_concat_different_var_columns_per_sample( - run_component, - sample_1_h5mu, - sample_2_h5mu, - random_h5mu_path, - write_mudata_to_file, - benchmark, -): - """ - Test what happens when concatenating samples with differing auxiliary - (like in .var) columns (present in 1 sample, absent in other). - When concatenating the samples, all columns should be present in the - resulting object, filling the values from samples with the missing - column with NA. - - Looking at Shared_feat here: - - mod1 mod2 - sample 1 present present - sample 2 x x - """ - output_path = random_h5mu_path() - # Before removing the 'Shared_feat' column from one of the samples, - # check if they are present in both - assert "Shared_feat" in sample_1_h5mu.var.columns.to_list() - assert "Shared_feat" in sample_2_h5mu.var.columns.to_list() - - sample_2_h5mu = remove_annotation_column(sample_2_h5mu, ["Shared_feat"], axis="var") - assert "Shared_feat" in sample_1_h5mu.var.columns.to_list() - assert "Shared_feat" not in sample_2_h5mu.var.columns.to_list() - - # 'Shared_feat' column is not missing from sample2, which is what this test is about - input_sample1_path = write_mudata_to_file(sample_1_h5mu) - input_sample2_path = write_mudata_to_file(sample_2_h5mu) - - benchmark( - run_component, - [ - "--input_id", - "sample1;sample2", - "--input", - input_sample1_path, - "--input", - input_sample2_path, - "--output", - output_path, - "--other_axis_mode", - "move", - ], - ) - assert Path(output_path).is_file() - concatenated_data = md.read(output_path) - - data_sample1 = md.read(input_sample1_path) - data_sample2 = md.read(input_sample2_path) - - assert ( - concatenated_data.n_vars - == data_sample1.var.index.union(data_sample2.var.index).size - ) - - for mod_name in ("mod1", "mod2"): - # Check if all features are present - concatenated_mod = concatenated_data.mod[mod_name] - sample1_original_mod = data_sample1.mod[mod_name] - sample2_original_mod = data_sample2.mod[mod_name] - - original_var_keys = set( - sample1_original_mod.var.columns.to_list() - + sample2_original_mod.var.columns.to_list() - + list(sample1_original_mod.varm.keys()) - + list(sample2_original_mod.varm.keys()) - ) - - assert original_var_keys == set(concatenated_mod.varm.keys()) | set( - concatenated_mod.var.columns.tolist() - ) - - # Values from sample2 (which are also not in sample1) should have NA - non_shared_features = data_sample2.var_names.difference(data_sample1.var_names) - assert concatenated_data.var["Shared_feat"].loc[non_shared_features].isna().all() - - # Values from sample1 should not have NA, and should be equal to the original values - var_values = concatenated_data.var["Shared_feat"].loc[data_sample1.var_names] - data_sample1.var["Shared_feat"].equals(var_values) - - -def test_concat_different_columns_per_modality( - run_component, - sample_1_h5mu, - sample_2_h5mu, - write_mudata_to_file, - random_h5mu_path, - benchmark, -): - """ - Test what happens when concatenating samples that have auxiliary columns - that is missing in one modality compared to the other, but the the column - is missing from the same modalities in both samples. - - Looking at Shared_feat here: - - mod1 mod2 - sample 1 x present - sample 2 x present - """ - sample_2_h5mu = remove_annotation_column( - sample_2_h5mu, ["Shared_feat"], axis="var", modality_name="mod1" - ) - sample_1_h5mu = remove_annotation_column( - sample_1_h5mu, ["Shared_feat"], axis="var", modality_name="mod1" - ) - - input_sample1_path = write_mudata_to_file(sample_1_h5mu) - input_sample2_path = write_mudata_to_file(sample_2_h5mu) - - output_path = random_h5mu_path() - benchmark( - run_component, - [ - "--input_id", - "sample1;sample2", - "--input", - input_sample1_path, - "--input", - input_sample2_path, - "--output", - output_path, - "--other_axis_mode", - "move", - ], - ) - - assert Path(output_path).is_file() is True - concatenated_data = md.read(output_path) - - data_sample1 = md.read(str(input_sample1_path)) - data_sample2 = md.read(str(input_sample2_path)) - - # Check if all features are present - assert ( - concatenated_data.n_vars - == data_sample1.var.index.union(data_sample2.var.index).size - ) - - for mod_name in ("mod1", "mod2"): - concatenated_mod = concatenated_data.mod[mod_name] - data_sample1_mod = data_sample1.mod[mod_name] - data_sample2_mod = data_sample2.mod[mod_name] - original_var_keys = set( - data_sample1_mod.var.columns.tolist() - + data_sample2_mod.var.columns.tolist() - + list(data_sample2_mod.varm.keys()) - + list(data_sample1_mod.varm.keys()) - ) - - assert original_var_keys == set(concatenated_mod.varm.keys()) | set( - concatenated_mod.var.columns.tolist() - ) - - # Check if the shared column stays removed from modality - assert "Shared_feat" not in concatenated_data.mod["mod1"].var.columns - - # Values from modality 1 have NA - mod_1_features = data_sample1["mod1"].var_names.union( - data_sample2["mod1"].var_names - ) - assert concatenated_data.var.loc[mod_1_features, "mod2:Shared_feat"].isna().all() - - # Values from modalitu should not have NA, and should be equal to the original values - mod2_data = pd.concat( - [ - data_sample2["mod2"].var["Shared_feat"], - data_sample1["mod2"].var["Shared_feat"], - ] - ) - mod2_features = mod2_data.index - assert ( - concatenated_data.var.loc[mod2_features, "mod2:Shared_feat"] - .astype(str) - .equals(mod2_data) - ) - - -def test_concat_different_columns_per_modality_and_per_sample( - run_component, - sample_1_h5mu, - sample_2_h5mu, - write_mudata_to_file, - random_h5mu_path, - benchmark, -): - """ - Test what happens when concatenating samples that have auxiliary columns - that differ between the modalities and also between samples - - - Looking at 'Feat4' from sample 2 here: - mod1 mod2 - sample 1 x x - sample 2 x present - """ - - input_sample1_path = write_mudata_to_file(sample_1_h5mu) - input_sample2_path = write_mudata_to_file(sample_2_h5mu) - output_path = random_h5mu_path() - - benchmark( - run_component, - [ - "--input_id", - "mouse;human", - "--input", - input_sample1_path, - "--input", - input_sample2_path, - "--output", - output_path, - "--other_axis_mode", - "move", - ], - ) - - assert Path(output_path).is_file() - concatenated_data = md.read(output_path) - - data_sample1 = md.read(input_sample1_path) - data_sample2 = md.read(input_sample2_path) - - # Check if all features are present - assert ( - concatenated_data.n_vars - == data_sample1.var_names.union(data_sample2.var_names).size - ) - - # Check if all features are present - for mod_name in ("mod1", "mod2"): - concatenated_mod = concatenated_data.mod[mod_name] - data_sample1_mod = data_sample1.mod[mod_name] - data_sample2_mod = data_sample2.mod[mod_name] - original_var_keys = set( - data_sample1_mod.var.columns.to_list() - + data_sample2_mod.var.columns.to_list() - + list(data_sample2_mod.varm.keys()) - + list(data_sample1_mod.varm.keys()) - ) - - assert original_var_keys == set( - column_name.removeprefix("conflict_") - for column_name in concatenated_mod.varm.keys() - ) | set(concatenated_mod.var.columns.to_list()) - - assert "Shared_feat" in concatenated_data.mod["mod2"].var.columns - - # Values from modality 1 have NA - mod_1_features = data_sample1["mod1"].var_names.union( - data_sample2["mod1"].var_names - ) - assert concatenated_data.var.loc[mod_1_features, "mod2:Feat4"].isna().all() - - # Values from modality 2 should not have NA if they originate from sample2 - # These values should be equal to the original values - mod2_data = data_sample2["mod2"].var["Feat4"].rename("mod2:Feat4") - mod2_features = mod2_data.index - assert ( - concatenated_data.var.loc[mod2_features, "mod2:Feat4"] - .astype(str) - .equals(mod2_data) - ) - - # Values from modality2 should have NA if they originate from sample1 (and only from sample1) - non_shared_features = data_sample1.var_names.difference(data_sample2.var_names) - assert concatenated_data.var.loc[non_shared_features, "mod2:Feat4"].isna().all() - - -@pytest.mark.parametrize( - "test_value,test_value_dtype,expected", - [ - ("bar", "str", "bar"), - (True, pd.BooleanDtype(), True), - (1, pd.Int16Dtype(), 1), - (0.1, float, 0.1), - (0.1, np.float64, 0.1), - (np.nan, np.float64, pd.NA), - ], -) -def test_concat_remove_na( - run_component, - sample_1_h5mu, - sample_2_h5mu, - write_mudata_to_file, - random_h5mu_path, - test_value, - test_value_dtype, - expected, - change_column_contents, - benchmark, -): - """ - Test concatenation of samples where the column from one sample contains NA values - NA values should be removed from the concatenated result - - mod1 mod2 - sample 1 NA NA - sample 2 test_value NA - """ - change_column_contents( - sample_1_h5mu, "var", "Shared_feat", {"mod1": np.nan, "mod2": np.nan} - ) - change_column_contents( - sample_2_h5mu, "var", "Shared_feat", {"mod1": test_value, "mod2": np.nan} - ) - sample_2_h5mu.var["Shared_feat"] = sample_2_h5mu.var["Shared_feat"].astype( - test_value_dtype - ) - output_path = random_h5mu_path() - benchmark( - run_component, - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_path, - "--other_axis_mode", - "move", - ], - ) - - assert Path(output_path).is_file() - concatenated_data = md.read(output_path) - - # Values from modality 2 have NA - mod_2_features = sample_1_h5mu["mod2"].var_names.union( - sample_2_h5mu["mod2"].var_names - ) - assert concatenated_data.var.loc[mod_2_features, "Shared_feat"].isna().all() - - # Values from modality 1 should not have NA if they originate from sample 1 - # These values should be equal to the original values - assert sample_1_h5mu["mod1"].var["Shared_feat"].isna().all() - - # Values from modality 1 should hold a value if they originate from sample 2 - mod1_features = sample_2_h5mu["mod1"].var_names.difference(sample_1_h5mu.var_names) - if not pd.isna(expected): - assert ( - concatenated_data.var.loc[mod1_features, "Shared_feat"] == expected - ).all() - else: - assert concatenated_data.var.loc[mod1_features, "Shared_feat"].isna().all() - - # The 'Shared_feat' column for mod1 contains an overlapping feature. - # For sample 1, it is NA, for sample 2 is is filled with test value. - # The concat component should choose the test-value over NA - shared_features = sample_2_h5mu.var_names.intersection(sample_1_h5mu.var_names) - if not pd.isna(expected): - assert ( - concatenated_data.var.loc[shared_features, "Shared_feat"] == expected - ).all() - else: - assert concatenated_data.var.loc[shared_features, "Shared_feat"].isna().all() - - -def test_concat_invalid_h5_error_includes_path( - run_component, tmp_path, sample_1_h5mu, write_mudata_to_file -): - empty_file = tmp_path / "empty.h5mu" - empty_file.touch() - with pytest.raises(subprocess.CalledProcessError) as err: - run_component( - [ - "--input_id", - "mouse;empty", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - empty_file, - "--output", - "concat.h5mu", - "--other_axis_mode", - "move", - ] - ) - assert re.search( - rf"OSError: Failed to load .*{str(empty_file)}\. Is it a valid h5 file?", - err.value.stdout.decode("utf-8"), - ) - - -@pytest.mark.parametrize( - "test_value_1,value_1_dtype,test_value_2,value_2_dtype,expected", - [ - (1, float, "1", str, pd.CategoricalDtype(categories=["1.0", "1"])), - (1, np.float64, "1", str, pd.CategoricalDtype(categories=["1.0", "1"])), - (1, pd.Int16Dtype(), 2.0, pd.Int16Dtype(), pd.Int64Dtype()), - (True, bool, False, bool, pd.BooleanDtype()), - (True, pd.BooleanDtype(), False, bool, pd.BooleanDtype()), - ("foo", str, "bar", str, pd.CategoricalDtype(categories=["bar", "foo"])), - ], -) -def test_concat_dtypes_per_modality( - run_component, - write_mudata_to_file, - change_column_contents, - sample_1_h5mu, - sample_2_h5mu, - test_value_1, - value_1_dtype, - test_value_2, - value_2_dtype, - expected, - random_h5mu_path, -): - """ - Test joining column with different dtypes to make sure that they are writable. - The default path is to convert all non-na values to strings and wrap the column into a categorical dtype. - Here, we test on the level of a single modality only. Because the mod1 modality for both sample 1 and - sample 2 contain a column 'test_col' and there is an overlapping feature name (overlapping_var_mod1), - there is a conflict for this var column in mod 1 for this column. Upon concatenation, the column is moved - to .varm, but for mod1 only. The column is concatenated for mod2 as planned. Here we check if the results - for the test column in mod2 is still writable. - """ - change_column_contents( - sample_1_h5mu, "var", "test_col", {"mod1": test_value_1, "mod2": test_value_1} - ) - sample_1_h5mu.var["test_col"] = sample_1_h5mu.var["test_col"].astype(value_1_dtype) - change_column_contents( - sample_2_h5mu, "var", "test_col", {"mod1": test_value_2, "mod2": test_value_2} - ) - sample_2_h5mu.var["test_col"] = sample_2_h5mu.var["test_col"].astype(value_2_dtype) - - output_file = random_h5mu_path() - run_component( - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_file, - "--other_axis_mode", - "move", - ] - ) - concatenated_data = md.read(output_file) - assert concatenated_data["mod2"].var["test_col"].dtype == expected - - -@pytest.mark.parametrize( - "test_value,value_dtype,expected", - [ - (1, float, pd.Int64Dtype()), - (1, np.float64, pd.Int64Dtype()), - (1, pd.Int16Dtype(), pd.Int16Dtype()), - (True, bool, pd.BooleanDtype()), - (True, pd.BooleanDtype(), pd.BooleanDtype()), - ("foo", str, pd.CategoricalDtype(categories=["foo"])), - ], -) -def test_concat_dtypes_per_modality_multidim( - run_component, - write_mudata_to_file, - sample_1_h5mu, - sample_2_h5mu, - test_value, - value_dtype, - expected, - random_h5mu_path, -): - """ - Test if the result of concatenation is still writable when the input already contain - data in .varm and this data is kept. Because we are joining observations, the dtype of this - data may change and the result might not be writable anymore - """ - - sample_1_h5mu["mod1"].varm["test_df"] = pd.DataFrame( - index=sample_1_h5mu["mod1"].var_names - ) - sample_1_h5mu["mod1"].varm["test_df"]["test_col"] = test_value - sample_1_h5mu["mod1"].varm["test_df"]["test_col"] = ( - sample_1_h5mu["mod1"].varm["test_df"]["test_col"].astype(value_dtype) - ) - - output_file = random_h5mu_path() - run_component( - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_file, - "--other_axis_mode", - "move", - ] - ) - concatenated_data = md.read(output_file) - assert concatenated_data["mod1"].varm["test_df"]["test_col"].dtype == expected - - -@pytest.mark.parametrize( - "test_value_1,test_value_2,expected", - [(1, "1", pd.CategoricalDtype(categories=["1.0", "1"]))], -) -def test_concat_dtypes_global( - run_component, - write_mudata_to_file, - change_column_contents, - sample_1_h5mu, - sample_2_h5mu, - test_value_1, - test_value_2, - expected, - random_h5mu_path, -): - """ - Test joining column with different dtypes to make sure that they are writable. - The default path is to convert all non-na values to strings and wrap the column into a categorical dtype. - Here, we test on the level of a column that is added to a global annotation matrix. - """ - change_column_contents( - sample_1_h5mu, "var", "test_col", {"mod1": test_value_1, "mod2": test_value_1} - ) - change_column_contents( - sample_2_h5mu, "var", "test_col", {"mod1": test_value_2, "mod2": test_value_2} - ) - sample1_mod1_names = sample_2_h5mu["mod1"].var_names - # Here, we avoid a conflict between sample 1 and sample 2 by making sure there is no overlap in features - # between sample 1 and sample 2 (no shared var_names). If this change would not be done, a different - # value for sample 1 and sample 2 would be found by the concat component for the var feature - # 'overlapping_var_mod1' for modality 'mod1'. The concat component would move the column for mod1 to - # .varm because of this conflict, and in the global .var column of the concatenated object, only - # a 'mod2:test_col' column would be present. But here, we want to test the column that is populated by - # both 'mod1' and 'mod2' - assert "overlapping_var_mod1" in sample1_mod1_names - new_names = sample1_mod1_names.where( - ~sample1_mod1_names.isin(["overlapping_var_mod1"]), "non_overlapping" - ) - sample_2_h5mu["mod1"].var_names = new_names - sample_2_h5mu.update() - output_file = random_h5mu_path() - run_component( - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_file, - "--other_axis_mode", - "move", - ] - ) - concatenated_data = md.read(output_file) - assert concatenated_data.var["test_col"].dtype == expected - - -def test_non_overlapping_modalities( - run_component, sample_2_h5mu, sample_3_h5mu, random_h5mu_path, write_mudata_to_file -): - """ - Test that the component does not fail when the modalities are not shared between samples. - """ - output_path = random_h5mu_path() - input_file_2 = write_mudata_to_file(sample_2_h5mu) - input_file_3 = write_mudata_to_file(sample_3_h5mu) - - run_component( - [ - "--input_id", - "sample2;sample3", - "--input", - input_file_2, - "--input", - input_file_3, - "--output", - output_path, - "--other_axis_mode", - "move", - ] - ) - output_data = md.read(output_path) - assert set(output_data.mod.keys()) == {"mod1", "mod2", "mod3"} - - -def test_resolve_annotation_conflict_missing_column( - run_component, - sample_1_h5mu, - sample_2_h5mu, - sample_3_h5mu, - write_mudata_to_file, - random_h5mu_path, -): - """ - Test using mode 'move' and resolving a conflict in metadata between the samples, - but the metadata column is missing in one of the samples. - """ - output_path = random_h5mu_path() - input_file_1 = write_mudata_to_file(sample_1_h5mu) - input_file_2 = write_mudata_to_file(sample_2_h5mu) - input_file_3 = write_mudata_to_file(sample_3_h5mu) - - run_component( - [ - "--input_id", - "sample1;sample2;sample3", - "--input", - input_file_1, - "--input", - input_file_2, - "--input", - input_file_3, - "--output", - output_path, - "--other_axis_mode", - "move", - ] - ) - - concatenated_data = md.read(output_path) - # 'Shared_feat' is defined for mod1 in sample 1 and 2 and there is a conflict - assert "conflict_Shared_feat" in concatenated_data["mod1"].varm - # 'Shared_feat' is defined for mod2 in sample 1 and 2 and there is no conflict - assert "Shared_feat" in concatenated_data["mod2"].var.columns - # 'Shared_feat' is not defined in any of the samples samples for modality 3 - assert "Shared_feat" not in concatenated_data["mod3"].var.columns - assert "Shared_feat" not in concatenated_data["mod3"].varm - - -def test_mode_move( - run_component, - sample_1_h5mu, - sample_2_h5mu, - random_h5mu_path, - write_mudata_to_file, - benchmark, -): - """ - Test that in case of a conflict, the conflicting columns are move to the multidimensional annotation slot - (.varm and .obsm). The key of the datafame in the slot should start with 'conflict_' followed by the name - of the column and the columns of the dataframe should contain the sample names. - """ - output_path = random_h5mu_path() - benchmark( - run_component, - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_path, - "--other_axis_mode", - "move", - ], - ) - assert output_path.is_file() - concatenated_data = md.read(output_path) - - # Check if observations from all of the samples are present - assert concatenated_data.n_obs == sample_1_h5mu.n_obs + sample_2_h5mu.n_obs - - # Check if all modalities are present - sample1_mods, sample2_mods = ( - set(sample_1_h5mu.mod.keys()), - set(sample_2_h5mu.mod.keys()), - ) - concatentated_mods = set(concatenated_data.mod.keys()) - assert (sample1_mods | sample2_mods) == concatentated_mods - - varm_check = { - "mod1": ({"conflict_Shared_feat": ("sample1", "sample2")}), - "mod2": {}, - } - - # Check if all features are present - for mod_name in ("mod1", "mod2"): - concatenated_mod = concatenated_data.mod[mod_name] - sample_1_mod = sample_1_h5mu.mod[mod_name] - sample_2_mod = sample_2_h5mu.mod[mod_name] - original_varm_keys = set( - list(sample_1_mod.varm.keys()) + list(sample_2_mod.varm.keys()) - ) - original_var_keys = ( - set(sample_1_mod.var.columns.to_list() + sample_2_mod.var.columns.to_list()) - | original_varm_keys - ) - - assert original_var_keys == set( - column_name.removeprefix("conflict_") - for column_name in concatenated_mod.varm.keys() - ) | set(concatenated_mod.var.columns.tolist()) - - varm_expected = varm_check[mod_name] - assert set(concatenated_mod.varm.keys()) == set( - varm_expected.keys() | original_varm_keys - ) - for varm_key, expected_columns in varm_expected.items(): - assert tuple(concatenated_mod.varm[varm_key].columns) == expected_columns - if not varm_expected: - assert set(concatenated_mod.varm.keys()) == original_varm_keys - assert concatenated_mod.obsm == {} - - -# Execute this test multiple times, anndata.concat sometimes returns the observations in a different order -@pytest.mark.parametrize("_", range(10)) -def test_concat_var_obs_names_order( - run_component, - sample_1_h5mu, - sample_2_h5mu, - write_mudata_to_file, - random_h5mu_path, - _, -): - """ - Test that the var_names and obs_names are still linked to the correct count data. - """ - output_path = random_h5mu_path() - sample_1_h5mu["mod1"].obs["sample_id"] = "sample1" - sample_1_h5mu["mod2"].obs["sample_id"] = "sample1" - sample_2_h5mu["mod1"].obs["sample_id"] = "sample2" - sample_2_h5mu["mod2"].obs["sample_id"] = "sample2" - run_component( - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_path, - "--other_axis_mode", - "move", - ] - ) - assert output_path.is_file() - for sample_name, sample_h5mu in { - "sample1": sample_1_h5mu, - "sample2": sample_2_h5mu, - }.items(): - for mod_name in ["mod1", "mod2"]: - data_sample = sample_h5mu[mod_name].copy() - processed_data_ad = md.read_h5ad(output_path, mod=mod_name) - processed_data_ad = processed_data_ad[ - processed_data_ad.obs["sample_id"] == sample_name - ] - processed_data_ad = processed_data_ad[:, data_sample.var_names] - processed_data = pd.DataFrame( - processed_data_ad.X, - index=processed_data_ad.obs_names, - columns=processed_data_ad.var_names, - ) - data_sample = pd.DataFrame( - data_sample.X, - index=data_sample.obs_names, - columns=data_sample.var_names, - ).reindex_like(processed_data) - pd.testing.assert_frame_equal( - processed_data, data_sample, check_dtype=False - ) - - -def test_keep_uns( - run_component, - sample_1_h5mu, - sample_2_h5mu, - write_mudata_to_file, - random_h5mu_path, - benchmark, -): - sample_1_h5mu.uns["global_uns_sample1"] = "dolor" - sample_1_h5mu.uns["overlapping_global"] = "sed" - sample_2_h5mu.uns["global_uns_sample2"] = "amet" - sample_2_h5mu.uns["overlapping_global"] = "elit" - output_path = random_h5mu_path() - benchmark( - run_component, - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_path, - "--other_axis_mode", - "move", - "--uns_merge_mode", - "make_unique", - ], - ) - assert output_path.is_file() - concatenated_data = md.read(output_path) - mod1 = concatenated_data.mod["mod1"] - mod2 = concatenated_data.mod["mod2"] - assert set(concatenated_data.uns.keys()) == set( - [ - "global_uns_sample1", - "global_uns_sample2", - "sample1_overlapping_global", - "sample2_overlapping_global", - ] - ) - assert set(mod1.uns.keys()) == set( - [ - "sample1_overlapping_uns_key", - "uns_unique_to_sample1", - "sample2_overlapping_uns_key", - "uns_unique_to_sample2", - ] - ) - assert set(mod2.uns.keys()) == set() - - -def test_subset_modalities( - run_component, sample_1_h5mu, sample_2_h5mu, write_mudata_to_file, random_h5mu_path -): - """ - Test if outputting a subset of the modalities works - """ - output_path = random_h5mu_path() - run_component( - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_path, - "--modality", - "mod1", - "--other_axis_mode", - "move", - "--uns_merge_mode", - "make_unique", - ] - ) - assert output_path.is_file() - concatenated_data = md.read(output_path) - assert set(concatenated_data.mod.keys()) == set(["mod1"]) - - -def test_obsp_block_diag_concat( - run_component, - sample_1_h5mu, - sample_2_h5mu, - write_mudata_to_file, - random_h5mu_path, -): - """ - Test that `.obsp` for a given key is concatenated as a block-diagonal matrix - across samples for the same modality (here: mod1), and that the block order - matches the sample order. - """ - - output_path = random_h5mu_path() - run_component( - [ - "--input_id", - "sample1;sample2", - "--input", - write_mudata_to_file(sample_1_h5mu), - "--input", - write_mudata_to_file(sample_2_h5mu), - "--output", - output_path, - "--other_axis_mode", - "move", - "--uns_merge_mode", - "make_unique", - "--obsp_keys", - "connectivities", - ] - ) - - concatenated = md.read(output_path) - mod1 = concatenated["mod1"] - mod2 = concatenated["mod2"] - - assert "connectivities" in mod1.obsp - assert "connectivities" not in mod2.obsp - - expected = sp.csr_matrix( - [ - [0, 1, 0, 0, 0], - [2, 0, 0, 0, 0], - [0, 0, 0, 3, 4], - [0, 0, 5, 0, 6], - [0, 0, 7, 8, 0], - ] - ) - - pairwise_obsp = mod1.obsp["connectivities"].tocsr() - assert pairwise_obsp.shape == expected.shape, ( - "obsp 'connectivities' has incorrect shape after concatenation" - ) - assert (pairwise_obsp - expected).nnz == 0, ( - "obsp 'connectivities' not correctly concatenated as block-diagonal matrix" - ) - - -if __name__ == "__main__": - sys.exit( - pytest.main( - [ - __file__, - "-v", - "--benchmark-group-by", - "func", - "--benchmark-time-unit", - "s", - "--benchmark-columns", - "min, max, mean, stddev, median, iqr, outliers, ops", - ] - ) - ) diff --git a/src/mapping/spaceranger_count/script.sh b/src/mapping/spaceranger_count/script.sh index 20d3244..7429ffd 100644 --- a/src/mapping/spaceranger_count/script.sh +++ b/src/mapping/spaceranger_count/script.sh @@ -23,7 +23,7 @@ for par in ${unset_if_false[@]}; do [[ "$test_val" == "false" ]] && unset $par done -# just to make sure paths are absolute +# Make sure paths are absolute par_gex_reference=`realpath $par_gex_reference` par_output=`realpath $par_output` par_probe_set=`realpath $par_probe_set` diff --git a/src/nichecompass/nichecompass/config.vsh.yaml b/src/nichecompass/nichecompass/config.vsh.yaml index cdba7bd..a206b5c 100644 --- a/src/nichecompass/nichecompass/config.vsh.yaml +++ b/src/nichecompass/nichecompass/config.vsh.yaml @@ -439,14 +439,8 @@ test_resources: engines: - type: docker - image: nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04 + image: pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime setup: - - type: apt - packages: - - libhdf5-dev - - python3-pip - - python3-dev - - python-is-python3 - type: docker run: | pip install torch --index-url https://download.pytorch.org/whl/cu124 \ diff --git a/src/nichecompass/nichecompass/script.py b/src/nichecompass/nichecompass/script.py index 27e756b..4f0774f 100644 --- a/src/nichecompass/nichecompass/script.py +++ b/src/nichecompass/nichecompass/script.py @@ -1,6 +1,7 @@ import sys import json import mudata as mu +import torch from nichecompass.models import NicheCompass from nichecompass.utils import add_gps_from_gp_dict_to_adata @@ -91,6 +92,12 @@ from setup_logger import setup_logger logger = setup_logger() +# Verify torch and CUDA availability +logger.info(f"Torch version: {torch.__version__}") +logger.info(f"CUDA available: {torch.cuda.is_available()}") +logger.info(f"Torch CUDA version: {torch.version.cuda}") +logger.info(f"GPU count: {torch.cuda.device_count()}") + ## Read in data adata = mu.read_h5ad(par["input"], mod=par["modality"]) diff --git a/src/workflows/ingestion/spaceranger_mapping/config.vsh.yaml b/src/workflows/ingestion/spaceranger_mapping/config.vsh.yaml new file mode 100644 index 0000000..b0adeab --- /dev/null +++ b/src/workflows/ingestion/spaceranger_mapping/config.vsh.yaml @@ -0,0 +1,211 @@ +name: "spaceranger_mapping" +namespace: "workflows/ingestion" +scope: "public" +description: "A pipeline for running SpaceRanger mapping." +info: + name: SpaceRanger mapping + test_dependencies: + - name: spaceranger_mapping_test + namespace: test_workflows/ingestion +authors: + - __merge__: /src/authors/dorien_roosen.yaml + roles: [ maintainer ] + - __merge__: /src/authors/weiwei_schultz.yaml + roles: [ contributor ] + +argument_groups: + - name: Inputs + arguments: + - name: "--id" + required: true + type: string + description: ID of the sample. + example: foo + - name: --input + type: file + required: true + multiple: true + description: | + The fastq.gz files to align. Can also be a single directory containing fastq.gz files. + + Individual FASTQ files should follow the naming convention of 10x Genomics: + [Sample Name]_S[Sample Number]_L[Lane Number]_[Read Type]_001.fastq.gz + + Where: + [Sample Name] is the name assigned during sample preparation/sequencing + S[Sample Number] is the sample index (usually S1, S2, etc.) + L[Lane Number] identifies the sequencing lane (L001, L002, etc.) + + [Read Type] will be one of: + R1 - Read 1 (contains the spatial barcode and UMI) + R2 - Read 2 (contains the actual cDNA sequence) + + example: [ "sample_S1_L001_R1_001.fastq.gz", "sample_S1_L001_R2_001.fastq.gz" ] + - name: --gex_reference + type: file + required: true + description: Path of folder containing 10x-compatible reference + example: "/path/to/refdata-gex-GRCh38-2020-A" + - name: --probe_set + type: file + required: true + description: CSV file specifying the probe set used + example: "Visium_Human_Transcriptome_Probe_Set_v2.0_GRCh38-2020-A.csv" + - name: --cytaimage + type: file + required: false + description: | + Brightfield image generated by the CytAssist instrument. + When using CytAssist workflow, either this or --image must be provided. + example: "cyta_image.tif" + - name: --image + type: file + required: false + description: | + H&E or fluorescence microscope image in TIFF or JPG format. + Required for standard Visium workflow, optional when using --cytaimage for CytAssist workflow. + example: "brightfield.tif" + + - name: Outputs + arguments: + - name: "--output_raw" + type: file + direction: output + description: "Location where the output folder from Cell Ranger will be stored." + required: true + example: output_dir/ + - name: "--output_h5mu" + type: file + direction: output + description: "The output from Cell Ranger, converted to h5mu." + required: true + example: output.h5mu + - name: "--output_type" + type: string + description: "Which Cell Ranger output to use for converting to h5mu." + choices: [ raw, filtered ] + default: raw + - name: "--uns_metrics" + type: string + description: Name of the .uns slot under which to QC metrics (if any). + default: "metrics_summary" + - name: "--uns_probe_set" + type: string + description: Name of the .uns slot under which to store probe set information (if any). + default: "probe_set" + - name: "--obsm_coordinates" + type: string + description: Name of the .obsm slot under which to store the cell centroid coordinates. + default: "spatial" + - name: "--output_compression" + type: string + description: Compression to use when writing the h5mu file. + choices: [ gzip, lzf ] + + - name: Image Options + arguments: + - name: --darkimage + type: file + description: Multi-channel, dark-background fluorescence image + required: false + example: "fluorescence.tif" + - name: --colorizedimage + type: file + description: Color image representing pre-colored dark-background fluorescence images + required: false + example: "colored_fluorescence.tif" + - name: --dapi_index + type: integer + description: Index of DAPI channel (1-indexed) of fluorescence image + required: false + example: 1 + min: 1 + - name: --image_scale + type: double + description: Microns per microscope image pixel + required: false + example: 0.65 + min: 0.01 + max: 10 + - name: --reorient_images + type: boolean + default: true + description: Whether to rotate and mirror image to align fiducial pattern + + - name: Slide Information + arguments: + - name: --slide + type: string + description: Visium slide serial number (e.g., 'V10J25-015') + required: false + example: "V10J25-015" + - name: --area + type: string + description: Visium capture area identifier (e.g., 'A1') + required: false + example: "A1" + - name: --unknown_slide + type: string + description: | + Use this option if the slide serial number and area were entered incorrectly on the CytAssist + instrument and the correct values are unknown. Not compatible with --slide, --area, or + --slide-file options + required: false + choices: [visium-1, visium-2, visium-2-large, visium-hd] + - name: --slidefile + type: file + description: Slide design file for offline use + required: false + example: "slide_design.gpr" + - name: --override_id + type: boolean_true + description: Overrides the slide serial number and capture area provided in the Cytassist image metadata + + - name: SpaceRanger arguments + arguments: + - name: --create_bam + type: boolean + required: true + description: Enable or disable BAM file generation + default: true + - name: --nosecondary + type: boolean_true + description: Disable secondary analysis (e.g., clustering) + - name: --r1_length + type: integer + required: false + description: Hard trim the input Read 1 to this length before analysis + min: 1 + - name: --r2_length + type: integer + required: false + description: Hard trim the input Read 2 to this length before analysis + min: 1 + - name: --filter_probes + type: boolean + default: true + description: Whether to filter the probe set using the "included" column + - name: --custom_bin_size + type: integer + description: Bin Visium HD data to specified size in microns (4-100, even values only) in addition to the standard binning size (2 µm, 8 µm, 16 µm) + min: 4 + max: 100 + +dependencies: + - name: mapping/spaceranger_count + - name: convert/from_spaceranger_to_h5mu + +resources: + - type: nextflow_script + path: main.nf + entrypoint: run_wf + - type: file + path: /src/workflows/utils/ +test_resources: + - type: nextflow_script + path: test.nf + entrypoint: test_wf + - path: /resources_test/visium + - path: /resources_test/GRCh38 +runners: + - type: nextflow \ No newline at end of file diff --git a/src/workflows/ingestion/spaceranger_mapping/integration_test.sh b/src/workflows/ingestion/spaceranger_mapping/integration_test.sh new file mode 100755 index 0000000..f01dcdf --- /dev/null +++ b/src/workflows/ingestion/spaceranger_mapping/integration_test.sh @@ -0,0 +1,15 @@ +#!/bin/bash + +# get the root of the directory +REPO_ROOT=$(git rev-parse --show-toplevel) + +# ensure that the command below is run from the root of the repository +cd "$REPO_ROOT" + +nextflow \ + run . \ + -main-script src/workflows/ingestion/spaceranger_mapping/test.nf \ + -entry test_wf \ + -profile docker \ + -c src/workflows/utils/labels_ci.config \ + -c src/workflows/utils/integration_tests.config diff --git a/src/workflows/ingestion/spaceranger_mapping/main.nf b/src/workflows/ingestion/spaceranger_mapping/main.nf new file mode 100644 index 0000000..ea61e55 --- /dev/null +++ b/src/workflows/ingestion/spaceranger_mapping/main.nf @@ -0,0 +1,57 @@ +workflow run_wf { + take: + input_ch + + main: + output_ch = input_ch + | spaceranger_count.run( + fromState: { id, state -> [ + "input": state.input, + "gex_reference": state.gex_reference, + "probe_set": state.probe_set, + "cytaimage": state.cytaimage, + "image": state.image, + "slide": state.slide, + "area": state.area, + "unkown_slide": state.unkown_slide, + "slidefile": state.slidefile, + "override_id": state.override_id, + "darkimage": state.darkimage, + "colorizedimage": state.colorizedimage, + "dapi_index": state.dapi_index, + "image_scale": state.image_scale, + "reorient_images": state.reorient_images, + "create_bam": state.create_bam, + "nosecondary": state.nosecondary, + "r1_length": state.r1_length, + "r2_length": state.r2_length, + "filter_probes": state.filter_probes, + "custom_bin_size": state.custom_bin_size, + "output": state.output_raw, + ]}, + toState: [ + "input": "output", + "output_raw": "output" + ] + ) + // convert to h5mu + | from_spaceranger_to_h5mu.run( + fromState: {id, state -> + [ + "input": state.input, + "output_compression": state.output_compression, + "output": state.output_h5mu, + "uns_metrics": state.uns_metrics, + "uns_probe_set": state.uns_probe_set, + "obsm_coordinates": state.obsm_coordinates, + "output_type": state.output_type, + "output_compression": state.output_compression, + ] + }, + toState: ["output_h5mu": "output"] + ) + | setState(["output_raw", "output_h5mu"]) + + emit: + output_ch +} \ No newline at end of file diff --git a/src/workflows/ingestion/spaceranger_mapping/nextflow.config b/src/workflows/ingestion/spaceranger_mapping/nextflow.config new file mode 100644 index 0000000..059100c --- /dev/null +++ b/src/workflows/ingestion/spaceranger_mapping/nextflow.config @@ -0,0 +1,10 @@ +manifest { + nextflowVersion = '!>=20.12.1-edge' +} + +params { + rootDir = java.nio.file.Paths.get("$projectDir/../../../../").toAbsolutePath().normalize().toString() +} + +// include common settings +includeConfig("${params.rootDir}/src/workflows/utils/labels.config") diff --git a/src/workflows/ingestion/spaceranger_mapping/test.nf b/src/workflows/ingestion/spaceranger_mapping/test.nf new file mode 100644 index 0000000..13338f9 --- /dev/null +++ b/src/workflows/ingestion/spaceranger_mapping/test.nf @@ -0,0 +1,42 @@ +nextflow.enable.dsl=2 + +include { spaceranger_mapping } from params.rootDir + "/target/nextflow/workflows/ingestion/spaceranger_mapping/main.nf" +include { spaceranger_mapping_test } from params.rootDir + "/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/main.nf" + +params.resources_test = params.rootDir + "/resources_test" + +workflow test_wf { + + resources_test = file(params.resources_test) + + output_ch = Channel.fromList([ + [ + id: "foo", + input: resources_test.resolve("visium/Visium_FFPE_Human_Ovarian_Cancer_tiny"), + gex_reference: resources_test.resolve("GRCh38"), + image: resources_test.resolve("visium/Visium_FFPE_Human_Ovarian_Cancer_image_tiny.jpg"), + probe_set: resources_test.resolve("visium/Visium_FFPE_Human_Ovarian_Cancer_probe_set.csv"), + create_bam: "false", + slide: "V10L13-020", + area: "D1", + output_type: "filtered", + ] + ]) + | map{ state -> [state.id, state] } + | spaceranger_mapping + | view { output -> + assert output.size() == 2 : "outputs should contain two elements; [id, out]" + assert output[1] instanceof Map : "Output should be a Map." + "Output: $output" + } + + | spaceranger_mapping_test.run( + fromState: ["input": "output_h5mu"] + ) + + | toSortedList() + | map { output_list -> + assert output_list.size() == 1 : "output channel should contain one event" + assert output_list[0][0] == "foo" : "Output ID should be same as input ID" + } +} diff --git a/src/workflows/niche/nichecompass_leiden/config.vsh.yaml b/src/workflows/niche/nichecompass_leiden/config.vsh.yaml index 91e3301..af51ac2 100644 --- a/src/workflows/niche/nichecompass_leiden/config.vsh.yaml +++ b/src/workflows/niche/nichecompass_leiden/config.vsh.yaml @@ -353,6 +353,7 @@ argument_groups: dependencies: - name: dataflow/concatenate_h5mu + repository: openpipeline - name: neighbors/spatial_neighborhood_graph - name: nichecompass/nichecompass - name: dataflow/split_h5mu diff --git a/src/workflows/test_workflows/ingestion/spaceranger_mapping_test/config.vsh.yaml b/src/workflows/test_workflows/ingestion/spaceranger_mapping_test/config.vsh.yaml new file mode 100644 index 0000000..6e6d6d9 --- /dev/null +++ b/src/workflows/test_workflows/ingestion/spaceranger_mapping_test/config.vsh.yaml @@ -0,0 +1,25 @@ +name: "spaceranger_mapping_test" +namespace: "test_workflows/ingestion" +scope: "test" +description: "This component test the output of the integration test of the spaceranger mapping workflow." +authors: + - __merge__: /src/authors/dorien_roosen.yaml +argument_groups: + - name: Inputs + arguments: + - name: "--input" + type: file + required: true + description: Path to h5mu output. + example: foo.final.h5mu +resources: + - type: python_script + path: script.py + - path: /src/utils/setup_logger.py +engines: + - type: docker + image: python:3.12-slim + __merge__: /src/base/requirements/testworkflows_setup.yaml +runners: + - type: executable + - type: nextflow diff --git a/src/workflows/test_workflows/ingestion/spaceranger_mapping_test/script.py b/src/workflows/test_workflows/ingestion/spaceranger_mapping_test/script.py new file mode 100644 index 0000000..46b8e8a --- /dev/null +++ b/src/workflows/test_workflows/ingestion/spaceranger_mapping_test/script.py @@ -0,0 +1,32 @@ +from mudata import read_h5mu +import sys +import pytest + +##VIASH START +par = {"input": "input.h5mu"} + +meta = {"resources_dir": "resources_test"} +##VIASH END + + +def test_run(): + input_mudata = read_h5mu(par["input"]) + expected_var_columns = ["gene_symbol", "feature_types", "genome"] + + assert list(input_mudata.mod.keys()) == ["rna"], ( + "Input should contain rna modality." + ) + assert list(input_mudata.var.columns) == expected_var_columns, ( + f"Input var columns should be: {expected_var_columns}." + ) + assert list(input_mudata.mod["rna"].var.columns) == expected_var_columns, ( + f"Input mod['rna'] var columns should be: {expected_var_columns}." + ) + + assert list(input_mudata.mod["rna"].obsm.keys()) == ["spatial"], ( + "Input mod['rna'] obsm should contain spatial column." + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "--import-mode=importlib"])) diff --git a/target/_private/executable/filter/subset_cosmx/.config.vsh.yaml b/target/_private/executable/filter/subset_cosmx/.config.vsh.yaml index ee12e05..fc24b90 100644 --- a/target/_private/executable/filter/subset_cosmx/.config.vsh.yaml +++ b/target/_private/executable/filter/subset_cosmx/.config.vsh.yaml @@ -112,7 +112,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -201,9 +201,8 @@ engines: - type: "python" user: false packages: - - "spatialdata~=0.5.0" - - "pyarrow~=18.0.0" - - "squidpy~=1.6.5" + - "scanpy~=1.10.4" + - "squidpy~=1.7.0" upgrade: true test_setup: - type: "apt" @@ -228,7 +227,7 @@ build_info: output: "target/_private/executable/filter/subset_cosmx" executable: "target/_private/executable/filter/subset_cosmx/subset_cosmx" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -242,7 +241,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/_private/executable/filter/subset_cosmx/subset_cosmx b/target/_private/executable/filter/subset_cosmx/subset_cosmx index 88889d3..6b2601d 100755 --- a/target/_private/executable/filter/subset_cosmx/subset_cosmx +++ b/target/_private/executable/filter/subset_cosmx/subset_cosmx @@ -454,13 +454,13 @@ RUN apt-get update && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "spatialdata~=0.5.0" "pyarrow~=18.0.0" "squidpy~=1.6.5" + pip install --upgrade --no-cache-dir "scanpy~=1.10.4" "squidpy~=1.7.0" LABEL org.opencontainers.image.authors="Dorien Roosen, Weiwei Schultz" LABEL org.opencontainers.image.description="Companion container for running component filter subset_cosmx" -LABEL org.opencontainers.image.created="2026-01-26T08:53:43Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:56Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/_private/nextflow/filter/subset_cosmx/.config.vsh.yaml b/target/_private/nextflow/filter/subset_cosmx/.config.vsh.yaml index 377b11c..603a1f2 100644 --- a/target/_private/nextflow/filter/subset_cosmx/.config.vsh.yaml +++ b/target/_private/nextflow/filter/subset_cosmx/.config.vsh.yaml @@ -112,7 +112,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -201,9 +201,8 @@ engines: - type: "python" user: false packages: - - "spatialdata~=0.5.0" - - "pyarrow~=18.0.0" - - "squidpy~=1.6.5" + - "scanpy~=1.10.4" + - "squidpy~=1.7.0" upgrade: true test_setup: - type: "apt" @@ -228,7 +227,7 @@ build_info: output: "target/_private/nextflow/filter/subset_cosmx" executable: "target/_private/nextflow/filter/subset_cosmx/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -242,7 +241,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/_private/nextflow/filter/subset_cosmx/main.nf b/target/_private/nextflow/filter/subset_cosmx/main.nf index e29d415..551d136 100644 --- a/target/_private/nextflow/filter/subset_cosmx/main.nf +++ b/target/_private/nextflow/filter/subset_cosmx/main.nf @@ -3187,7 +3187,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3295,9 +3295,8 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "spatialdata~=0.5.0", - "pyarrow~=18.0.0", - "squidpy~=1.6.5" + "scanpy~=1.10.4", + "squidpy~=1.7.0" ], "upgrade" : true } @@ -3334,7 +3333,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/_private/nextflow/filter/subset_cosmx", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3354,7 +3353,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/.config.vsh.yaml b/target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/.config.vsh.yaml new file mode 100644 index 0000000..14643bc --- /dev/null +++ b/target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/.config.vsh.yaml @@ -0,0 +1,188 @@ +name: "spaceranger_mapping_test" +namespace: "test_workflows/ingestion" +version: "niche-compass" +authors: +- name: "Dorien Roosen" + info: + role: "Core Team Member" + links: + email: "dorien@data-intuitive.com" + github: "dorien-er" + linkedin: "dorien-roosen" + organizations: + - name: "Data Intuitive" + href: "https://www.data-intuitive.com" + role: "Data Scientist" +argument_groups: +- name: "Inputs" + arguments: + - type: "file" + name: "--input" + description: "Path to h5mu output." + info: null + example: + - "foo.final.h5mu" + must_exist: true + create_parent: true + required: true + direction: "input" + multiple: false + multiple_sep: ";" +resources: +- type: "python_script" + path: "script.py" + is_executable: true +- type: "file" + path: "setup_logger.py" +- type: "file" + path: "nextflow_labels.config" + dest: "nextflow_labels.config" +description: "This component test the output of the integration test of the spaceranger\ + \ mapping workflow." +info: null +status: "enabled" +scope: + image: "test" + target: "test" +repositories: +- type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" +links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" +runners: +- type: "executable" + id: "executable" + docker_setup_strategy: "ifneedbepullelsecachedbuild" +- type: "nextflow" + id: "nextflow" + directives: + tag: "$id" + auto: + simplifyInput: true + simplifyOutput: false + transcript: false + publish: false + config: + labels: + mem1gb: "memory = 1000000000.B" + mem2gb: "memory = 2000000000.B" + mem5gb: "memory = 5000000000.B" + mem10gb: "memory = 10000000000.B" + mem20gb: "memory = 20000000000.B" + mem50gb: "memory = 50000000000.B" + mem100gb: "memory = 100000000000.B" + mem200gb: "memory = 200000000000.B" + mem500gb: "memory = 500000000000.B" + mem1tb: "memory = 1000000000000.B" + mem2tb: "memory = 2000000000000.B" + mem5tb: "memory = 5000000000000.B" + mem10tb: "memory = 10000000000000.B" + mem20tb: "memory = 20000000000000.B" + mem50tb: "memory = 50000000000000.B" + mem100tb: "memory = 100000000000000.B" + mem200tb: "memory = 200000000000000.B" + mem500tb: "memory = 500000000000000.B" + mem1gib: "memory = 1073741824.B" + mem2gib: "memory = 2147483648.B" + mem4gib: "memory = 4294967296.B" + mem8gib: "memory = 8589934592.B" + mem16gib: "memory = 17179869184.B" + mem32gib: "memory = 34359738368.B" + mem64gib: "memory = 68719476736.B" + mem128gib: "memory = 137438953472.B" + mem256gib: "memory = 274877906944.B" + mem512gib: "memory = 549755813888.B" + mem1tib: "memory = 1099511627776.B" + mem2tib: "memory = 2199023255552.B" + mem4tib: "memory = 4398046511104.B" + mem8tib: "memory = 8796093022208.B" + mem16tib: "memory = 17592186044416.B" + mem32tib: "memory = 35184372088832.B" + mem64tib: "memory = 70368744177664.B" + mem128tib: "memory = 140737488355328.B" + mem256tib: "memory = 281474976710656.B" + mem512tib: "memory = 562949953421312.B" + 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" + script: + - "includeConfig(\"nextflow_labels.config\")" + debug: false + container: "docker" +engines: +- type: "docker" + id: "docker" + image: "python:3.12-slim" + target_registry: "images.viash-hub.com" + target_tag: "niche-compass" + namespace_separator: "/" + setup: + - type: "apt" + packages: + - "procps" + - "git" + interactive: false + - type: "python" + user: false + packages: + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "viashpy==0.9.0" + github: + - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" + script: + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" + upgrade: true + entrypoint: [] + cmd: null +- type: "native" + id: "native" +build_info: + config: "src/workflows/test_workflows/ingestion/spaceranger_mapping_test/config.vsh.yaml" + runner: "executable" + engine: "docker|native" + output: "target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test" + executable: "target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/spaceranger_mapping_test" + viash_version: "0.9.4" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" + git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" +package_config: + name: "openpipeline_spatial" + version: "niche-compass" + info: + test_resources: + - type: "s3" + path: "s3://openpipelines-bio/openpipeline_spatial/resources_test" + dest: "resources_test" + repositories: + - type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" + viash_version: "0.9.4" + source: "src" + target: "target" + config_mods: + - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n\ + .runners[.type == 'nextflow'].config.script := 'includeConfig(\"nextflow_labels.config\"\ + )'" + - ".engines += { type: \"native\" }" + - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" + - ".engines[.type == 'docker'].target_tag := 'niche-compass'" + organization: "vsh" + links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" diff --git a/target/executable/dataflow/concatenate_h5mu/nextflow_labels.config b/target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/nextflow_labels.config similarity index 100% rename from target/executable/dataflow/concatenate_h5mu/nextflow_labels.config rename to target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/setup_logger.py b/target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/setup_logger.py rename to target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/setup_logger.py diff --git a/target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/spaceranger_mapping_test b/target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/spaceranger_mapping_test new file mode 100755 index 0000000..2ad6611 --- /dev/null +++ b/target/_test/executable/test_workflows/ingestion/spaceranger_mapping_test/spaceranger_mapping_test @@ -0,0 +1,1103 @@ +#!/usr/bin/env bash + +# spaceranger_mapping_test niche-compass +# +# This wrapper script is auto-generated by viash 0.9.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. +# +# Component authors: +# * Dorien Roosen + +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 { + local source="$1" + while [ -h "$source" ]; do + local 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 { + local 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_NAME="spaceranger_mapping_test" +VIASH_META_FUNCTIONALITY_NAME="spaceranger_mapping_test" +VIASH_META_EXECUTABLE="$VIASH_META_RESOURCES_DIR/$VIASH_META_NAME" +VIASH_META_CONFIG="$VIASH_META_RESOURCES_DIR/.config.vsh.yaml" +VIASH_META_TEMP_DIR="$VIASH_TEMP" + + + +# initialise variables +VIASH_MODE='run' +VIASH_ENGINE_ID='docker' + +######## 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" + local save=$-; set +e + local docker_version=$(docker version --format '{{.Client.APIVersion}}' 2> /dev/null) + local 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 + local save=$-; set +e + docker pull $1 2> /dev/null > /dev/null + local 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'" + local save=$-; set +e + local out + 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 '$1' push succeeded." + else + ViashError "Container '$1' 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 { + local save=$-; set +e + ViashDockerPull $1 + local 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 +# examples: +# ViashDockerSetup mynewcomponent alwaysbuild +function ViashDockerSetup { + local image_id="$1" + local setup_strategy="$2" + if [ "$setup_strategy" == "alwaysbuild" -o "$setup_strategy" == "build" -o "$setup_strategy" == "b" ]; then + ViashDockerBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id") + elif [ "$setup_strategy" == "alwayspull" -o "$setup_strategy" == "pull" -o "$setup_strategy" == "p" ]; then + ViashDockerPull $image_id + elif [ "$setup_strategy" == "alwayspullelsebuild" -o "$setup_strategy" == "pullelsebuild" ]; then + ViashDockerPullElseBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id") + elif [ "$setup_strategy" == "alwayspullelsecachedbuild" -o "$setup_strategy" == "pullelsecachedbuild" ]; then + ViashDockerPullElseBuild $image_id $(ViashDockerBuildArgs "$engine_id") + elif [ "$setup_strategy" == "alwayscachedbuild" -o "$setup_strategy" == "cachedbuild" -o "$setup_strategy" == "cb" ]; then + ViashDockerBuild $image_id $(ViashDockerBuildArgs "$engine_id") + elif [[ "$setup_strategy" =~ ^ifneedbe ]]; then + local save=$-; set +e + ViashDockerLocalTagCheck $image_id + local outCheck=$? + [[ $save =~ e ]] && set -e + if [ $outCheck -eq 0 ]; then + ViashInfo "Image $image_id already exists" + elif [ "$setup_strategy" == "ifneedbebuild" ]; then + ViashDockerBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id") + elif [ "$setup_strategy" == "ifneedbecachedbuild" ]; then + ViashDockerBuild $image_id $(ViashDockerBuildArgs "$engine_id") + elif [ "$setup_strategy" == "ifneedbepull" ]; then + ViashDockerPull $image_id + elif [ "$setup_strategy" == "ifneedbepullelsebuild" ]; then + ViashDockerPullElseBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id") + elif [ "$setup_strategy" == "ifneedbepullelsecachedbuild" ]; then + ViashDockerPullElseBuild $image_id $(ViashDockerBuildArgs "$engine_id") + else + ViashError "Unrecognised Docker strategy: $setup_strategy" + exit 1 + fi + elif [ "$setup_strategy" == "push" -o "$setup_strategy" == "forcepush" -o "$setup_strategy" == "alwayspush" ]; then + ViashDockerPush "$image_id" + elif [ "$setup_strategy" == "pushifnotpresent" -o "$setup_strategy" == "gentlepush" -o "$setup_strategy" == "maybepush" ]; then + local save=$-; set +e + ViashDockerRemoteTagCheck $image_id + local outCheck=$? + [[ $save =~ e ]] && set -e + if [ $outCheck -eq 0 ]; then + ViashNotice "Container '$image_id' exists, doing nothing." + else + ViashNotice "Container '$image_id' does not yet exist." + ViashDockerPush "$image_id" + fi + elif [ "$setup_strategy" == "donothing" -o "$setup_strategy" == "meh" ]; then + ViashNotice "Skipping setup." + else + ViashError "Unrecognised Docker strategy: $setup_strategy" + 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 { + local image_id="$1" + shift 1 + local commands="$@" + local save=$-; set +e + local missing # mark 'missing' as local in advance, otherwise the exit code of the command will be missing and always be '0' + missing=$(docker run --rm --entrypoint=sh "$image_id" -c "for command in $commands; do command -v \$command >/dev/null 2>&1; if [ \$? -ne 0 ]; then echo \$command; exit 1; fi; done") + local outCheck=$? + [[ $save =~ e ]] && set -e + if [ $outCheck -ne 0 ]; then + ViashError "Docker container '$image_id' does not contain command '$missing'." + exit 1 + fi +} + +# ViashDockerBuild: build a docker image +# $1 : image identifier with format `[registry/]image[:tag]` +# $... : additional arguments to pass to docker build +# $VIASH_META_TEMP_DIR : temporary directory to store dockerfile & optional resources in +# $VIASH_META_NAME : name of the component +# $VIASH_META_RESOURCES_DIR : directory containing the resources +# $VIASH_VERBOSITY : verbosity level +# exit code $? : whether or not the image was built successfully +function ViashDockerBuild { + local image_id="$1" + shift 1 + + # create temporary directory to store dockerfile & optional resources in + local tmpdir=$(mktemp -d "$VIASH_META_TEMP_DIR/dockerbuild-$VIASH_META_NAME-XXXXXX") + local dockerfile="$tmpdir/Dockerfile" + function clean_up { + rm -rf "$tmpdir" + } + trap clean_up EXIT + + # store dockerfile and resources + ViashDockerfile "$VIASH_ENGINE_ID" > "$dockerfile" + + # generate the build command + local docker_build_cmd="docker build -t '$image_id' $@ '$VIASH_META_RESOURCES_DIR' -f '$dockerfile'" + + # build the container + ViashNotice "Building container '$image_id' with Dockerfile" + ViashInfo "$docker_build_cmd" + local save=$-; set +e + if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then + eval $docker_build_cmd + else + eval $docker_build_cmd &> "$tmpdir/docker_build.log" + fi + + # check exit code + local out=$? + [[ $save =~ e ]] && set -e + if [ $out -ne 0 ]; then + ViashError "Error occurred while building container '$image_id'" + if [ $VIASH_VERBOSITY -lt $VIASH_LOGCODE_INFO ]; then + ViashError "Transcript: --------------------------------" + cat "$tmpdir/docker_build.log" + ViashError "End of transcript --------------------------" + fi + exit 1 + fi +} + +######## End of helper functions for setting up Docker images for viash ######## + +# ViashDockerFile: print the dockerfile to stdout +# $1 : engine identifier +# return : dockerfile required to run this component +# examples: +# ViashDockerFile +function ViashDockerfile { + local engine_id="$1" + + if [[ "$engine_id" == "docker" ]]; then + cat << 'VIASHDOCKER' +FROM python:3.12-slim +ENTRYPOINT [] +RUN apt-get update && \ + DEBIAN_FRONTEND=noninteractive apt-get install -y procps git && \ + rm -rf /var/lib/apt/lists/* + +RUN pip install --upgrade pip && \ + pip install --upgrade --no-cache-dir "anndata~=0.12.7" "awkward" "mudata~=0.3.2" "viashpy==0.9.0" && \ + pip install --upgrade --no-cache-dir "git+https://github.com/openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" && \ + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' + +LABEL org.opencontainers.image.authors="Dorien Roosen" +LABEL org.opencontainers.image.description="Companion container for running component test_workflows/ingestion spaceranger_mapping_test" +LABEL org.opencontainers.image.created="2026-01-27T10:47:55Z" +LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" +LABEL org.opencontainers.image.version="niche-compass" + +VIASHDOCKER + fi +} + +# ViashDockerBuildArgs: return the arguments to pass to docker build +# $1 : engine identifier +# return : arguments to pass to docker build +function ViashDockerBuildArgs { + local engine_id="$1" + + if [[ "$engine_id" == "docker" ]]; then + echo "" + fi +} + +# 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 + local parr + local outp + local len + 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[*]}" + ) +} +# ViashDockerAutodetectMount: auto configuring docker mounts from parameters +# $1 : The parameter value +# returns : New parameter +# $VIASH_DIRECTORY_MOUNTS : Added another parameter to be passed to docker +# $VIASH_DOCKER_AUTOMOUNT_PREFIX : The prefix to be used for the automounts +# examples: +# ViashDockerAutodetectMount /path/to/bar # returns '/viash_automount/path/to/bar' +# ViashDockerAutodetectMountArg /path/to/bar # returns '--volume="/path/to:/viash_automount/path/to"' +function ViashDockerAutodetectMount { + local abs_path=$(ViashAbsolutePath "$1") + local mount_source + local base_name + if [ -d "$abs_path" ]; then + mount_source="$abs_path" + base_name="" + else + mount_source=`dirname "$abs_path"` + base_name=`basename "$abs_path"` + fi + local mount_target="$VIASH_DOCKER_AUTOMOUNT_PREFIX$mount_source" + if [ -z "$base_name" ]; then + echo "$mount_target" + else + echo "$mount_target/$base_name" + fi +} +function ViashDockerAutodetectMountArg { + local abs_path=$(ViashAbsolutePath "$1") + local mount_source + local base_name + if [ -d "$abs_path" ]; then + mount_source="$abs_path" + base_name="" + else + mount_source=`dirname "$abs_path"` + base_name=`basename "$abs_path"` + fi + local mount_target="$VIASH_DOCKER_AUTOMOUNT_PREFIX$mount_source" + ViashDebug "ViashDockerAutodetectMountArg $1 -> $mount_source -> $mount_target" + echo "--volume=\"$mount_source:$mount_target\"" +} +function ViashDockerStripAutomount { + local abs_path=$(ViashAbsolutePath "$1") + echo "${abs_path#$VIASH_DOCKER_AUTOMOUNT_PREFIX}" +} +# initialise variables +VIASH_DIRECTORY_MOUNTS=() + +# configure default docker automount prefix if it is unset +if [ -z "${VIASH_DOCKER_AUTOMOUNT_PREFIX+x}" ]; then + VIASH_DOCKER_AUTOMOUNT_PREFIX="/viash_automount" +fi + +# initialise docker variables +VIASH_DOCKER_RUN_ARGS=(-i --rm) + + +# ViashHelp: Display helpful explanation about this executable +function ViashHelp { + echo "spaceranger_mapping_test niche-compass" + echo "" + echo "This component test the output of the integration test of the spaceranger" + echo "mapping workflow." + echo "" + echo "Inputs:" + echo " --input" + echo " type: file, required parameter, file must exist" + echo " example: foo.final.h5mu" + echo " Path to h5mu output." + echo "" + echo "Viash built in Computational Requirements:" + echo " ---cpus=INT" + echo " Number of CPUs to use" + echo " ---memory=STRING" + echo " Amount of memory to use. Examples: 4GB, 3MiB." + echo "" + echo "Viash built in Docker:" + echo " ---setup=STRATEGY" + echo " Setup the docker container. Options are: alwaysbuild, alwayscachedbuild, ifneedbebuild, ifneedbecachedbuild, alwayspull, alwayspullelsebuild, alwayspullelsecachedbuild, ifneedbepull, ifneedbepullelsebuild, ifneedbepullelsecachedbuild, push, pushifnotpresent, donothing." + echo " Default: ifneedbepullelsecachedbuild" + echo " ---dockerfile" + echo " Print the dockerfile to stdout." + echo " ---docker_run_args=ARG" + echo " Provide runtime arguments to Docker. See the documentation on \`docker run\` for more information." + echo " ---docker_image_id" + echo " Print the docker image id to stdout." + echo " ---debug" + echo " Enter the docker container for debugging purposes." + echo "" + echo "Viash built in Engines:" + echo " ---engine=ENGINE_ID" + echo " Specify the engine to use. Options are: docker, native." + echo " Default: docker" +} + +# initialise array +VIASH_POSITIONAL_ARGS='' + +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 "spaceranger_mapping_test niche-compass" + 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 + ;; + ---engine) + VIASH_ENGINE_ID="$2" + shift 2 + ;; + ---engine=*) + VIASH_ENGINE_ID="$(ViashRemoveFlags "$1")" + shift 1 + ;; + ---setup) + VIASH_MODE='setup' + VIASH_SETUP_STRATEGY="$2" + shift 2 + ;; + ---setup=*) + VIASH_MODE='setup' + VIASH_SETUP_STRATEGY="$(ViashRemoveFlags "$1")" + shift 1 + ;; + ---dockerfile) + VIASH_MODE='dockerfile' + shift 1 + ;; + ---docker_run_args) + VIASH_DOCKER_RUN_ARGS+=("$2") + shift 2 + ;; + ---docker_run_args=*) + VIASH_DOCKER_RUN_ARGS+=("$(ViashRemoveFlags "$1")") + shift 1 + ;; + ---docker_image_id) + VIASH_MODE='docker_image_id' + shift 1 + ;; + ---debug) + VIASH_MODE='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 + + +if [ "$VIASH_ENGINE_ID" == "native" ] ; then + VIASH_ENGINE_TYPE='native' +elif [ "$VIASH_ENGINE_ID" == "docker" ] ; then + VIASH_ENGINE_TYPE='docker' +else + ViashError "Engine '$VIASH_ENGINE_ID' is not recognized. Options are: docker, native." + exit 1 +fi + +if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then + # check if docker is installed properly + ViashDockerInstallationCheck + + # determine docker image id + if [[ "$VIASH_ENGINE_ID" == 'docker' ]]; then + VIASH_DOCKER_IMAGE_ID='images.viash-hub.com/vsh/openpipeline_spatial/test_workflows/ingestion/spaceranger_mapping_test:niche-compass' + fi + + # print dockerfile + if [ "$VIASH_MODE" == "dockerfile" ]; then + ViashDockerfile "$VIASH_ENGINE_ID" + exit 0 + + elif [ "$VIASH_MODE" == "docker_image_id" ]; then + echo "$VIASH_DOCKER_IMAGE_ID" + exit 0 + + # enter docker container + elif [[ "$VIASH_MODE" == "debug" ]]; then + VIASH_CMD="docker run --entrypoint=bash ${VIASH_DOCKER_RUN_ARGS[@]} -v '$(pwd)':/pwd --workdir /pwd -t $VIASH_DOCKER_IMAGE_ID" + ViashNotice "+ $VIASH_CMD" + eval $VIASH_CMD + exit + + # build docker image + elif [ "$VIASH_MODE" == "setup" ]; then + ViashDockerSetup "$VIASH_DOCKER_IMAGE_ID" "$VIASH_SETUP_STRATEGY" + ViashDockerCheckCommands "$VIASH_DOCKER_IMAGE_ID" 'bash' + exit 0 + fi + + # check if docker image exists + ViashDockerSetup "$VIASH_DOCKER_IMAGE_ID" ifneedbepullelsecachedbuild + ViashDockerCheckCommands "$VIASH_DOCKER_IMAGE_ID" 'bash' +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]i?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 * 1000 )) ;; + mb|m) memory_b=$(( $number * 1000 * 1000 )) ;; + gb|g) memory_b=$(( $number * 1000 * 1000 * 1000 )) ;; + tb|t) memory_b=$(( $number * 1000 * 1000 * 1000 * 1000 )) ;; + pb|p) memory_b=$(( $number * 1000 * 1000 * 1000 * 1000 * 1000 )) ;; + kib|ki) memory_b=$(( $number * 1024 )) ;; + mib|mi) memory_b=$(( $number * 1024 * 1024 )) ;; + gib|gi) memory_b=$(( $number * 1024 * 1024 * 1024 )) ;; + tib|ti) memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 )) ;; + pib|pi) 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+999) / 1000 )) + VIASH_META_MEMORY_MB=$(( ($VIASH_META_MEMORY_KB+999) / 1000 )) + VIASH_META_MEMORY_GB=$(( ($VIASH_META_MEMORY_MB+999) / 1000 )) + VIASH_META_MEMORY_TB=$(( ($VIASH_META_MEMORY_GB+999) / 1000 )) + VIASH_META_MEMORY_PB=$(( ($VIASH_META_MEMORY_TB+999) / 1000 )) + VIASH_META_MEMORY_KIB=$(( ($VIASH_META_MEMORY_B+1023) / 1024 )) + VIASH_META_MEMORY_MIB=$(( ($VIASH_META_MEMORY_KIB+1023) / 1024 )) + VIASH_META_MEMORY_GIB=$(( ($VIASH_META_MEMORY_MIB+1023) / 1024 )) + VIASH_META_MEMORY_TIB=$(( ($VIASH_META_MEMORY_GIB+1023) / 1024 )) + VIASH_META_MEMORY_PIB=$(( ($VIASH_META_MEMORY_TIB+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_META_NAME+x} ]; then + ViashError 'name' 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 +if [[ -n "$VIASH_META_MEMORY_KIB" ]]; then + if ! [[ "$VIASH_META_MEMORY_KIB" =~ ^[-+]?[0-9]+$ ]]; then + ViashError 'memory_kib' has to be a long. Use "--help" to get more information on the parameters. + exit 1 + fi +fi +if [[ -n "$VIASH_META_MEMORY_MIB" ]]; then + if ! [[ "$VIASH_META_MEMORY_MIB" =~ ^[-+]?[0-9]+$ ]]; then + ViashError 'memory_mib' has to be a long. Use "--help" to get more information on the parameters. + exit 1 + fi +fi +if [[ -n "$VIASH_META_MEMORY_GIB" ]]; then + if ! [[ "$VIASH_META_MEMORY_GIB" =~ ^[-+]?[0-9]+$ ]]; then + ViashError 'memory_gib' has to be a long. Use "--help" to get more information on the parameters. + exit 1 + fi +fi +if [[ -n "$VIASH_META_MEMORY_TIB" ]]; then + if ! [[ "$VIASH_META_MEMORY_TIB" =~ ^[-+]?[0-9]+$ ]]; then + ViashError 'memory_tib' has to be a long. Use "--help" to get more information on the parameters. + exit 1 + fi +fi +if [[ -n "$VIASH_META_MEMORY_PIB" ]]; then + if ! [[ "$VIASH_META_MEMORY_PIB" =~ ^[-+]?[0-9]+$ ]]; then + ViashError 'memory_pib' has to be a long. Use "--help" to get more information on the parameters. + exit 1 + fi +fi + +if [ "$VIASH_ENGINE_ID" == "native" ] ; then + if [ "$VIASH_MODE" == "run" ]; then + VIASH_CMD="bash" + else + ViashError "Engine '$VIASH_ENGINE_ID' does not support mode '$VIASH_MODE'." + exit 1 + fi +fi + +if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then + # detect volumes from file arguments + VIASH_CHOWN_VARS=() +if [ ! -z "$VIASH_PAR_INPUT" ]; then + VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_INPUT")" ) + VIASH_PAR_INPUT=$(ViashDockerAutodetectMount "$VIASH_PAR_INPUT") +fi +if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then + VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_RESOURCES_DIR")" ) + VIASH_META_RESOURCES_DIR=$(ViashDockerAutodetectMount "$VIASH_META_RESOURCES_DIR") +fi +if [ ! -z "$VIASH_META_EXECUTABLE" ]; then + VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_EXECUTABLE")" ) + VIASH_META_EXECUTABLE=$(ViashDockerAutodetectMount "$VIASH_META_EXECUTABLE") +fi +if [ ! -z "$VIASH_META_CONFIG" ]; then + VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_CONFIG")" ) + VIASH_META_CONFIG=$(ViashDockerAutodetectMount "$VIASH_META_CONFIG") +fi +if [ ! -z "$VIASH_META_TEMP_DIR" ]; then + VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_TEMP_DIR")" ) + VIASH_META_TEMP_DIR=$(ViashDockerAutodetectMount "$VIASH_META_TEMP_DIR") +fi + + # get unique mounts + VIASH_UNIQUE_MOUNTS=($(for val in "${VIASH_DIRECTORY_MOUNTS[@]}"; do echo "$val"; done | sort -u)) +fi + +if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then + # change file ownership + function ViashPerformChown { + if (( ${#VIASH_CHOWN_VARS[@]} )); then + set +e + VIASH_CMD="docker run --entrypoint=bash --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_DOCKER_IMAGE_ID -c 'chown $(id -u):$(id -g) --silent --recursive ${VIASH_CHOWN_VARS[@]}'" + ViashDebug "+ $VIASH_CMD" + eval $VIASH_CMD + set -e + fi + } + trap ViashPerformChown EXIT +fi + +if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then + # helper function for filling in extra docker args + if [ ! -z "$VIASH_META_MEMORY_B" ]; then + VIASH_DOCKER_RUN_ARGS+=("--memory=${VIASH_META_MEMORY_B}") + fi + if [ ! -z "$VIASH_META_CPUS" ]; then + VIASH_DOCKER_RUN_ARGS+=("--cpus=${VIASH_META_CPUS}") + fi +fi + +if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then + VIASH_CMD="docker run --entrypoint=bash ${VIASH_DOCKER_RUN_ARGS[@]} ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_DOCKER_IMAGE_ID" +fi + + +# set dependency paths + + +ViashDebug "Running command: $(echo $VIASH_CMD)" +cat << VIASHEOF | eval $VIASH_CMD +set -e +tempscript=\$(mktemp "$VIASH_META_TEMP_DIR/viash-run-spaceranger_mapping_test-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' +from mudata import read_h5mu +import sys +import pytest + +##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 ) +} +meta = { + 'name': $( if [ ! -z ${VIASH_META_NAME+x} ]; then echo "r'${VIASH_META_NAME//\'/\'\"\'\"r\'}'"; else echo None; fi ), + '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 ), + 'memory_kib': $( if [ ! -z ${VIASH_META_MEMORY_KIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_KIB//\'/\'\"\'\"r\'}')"; else echo None; fi ), + 'memory_mib': $( if [ ! -z ${VIASH_META_MEMORY_MIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_MIB//\'/\'\"\'\"r\'}')"; else echo None; fi ), + 'memory_gib': $( if [ ! -z ${VIASH_META_MEMORY_GIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_GIB//\'/\'\"\'\"r\'}')"; else echo None; fi ), + 'memory_tib': $( if [ ! -z ${VIASH_META_MEMORY_TIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_TIB//\'/\'\"\'\"r\'}')"; else echo None; fi ), + 'memory_pib': $( if [ ! -z ${VIASH_META_MEMORY_PIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_PIB//\'/\'\"\'\"r\'}')"; else echo None; fi ) +} +dep = { + +} + +##VIASH END + + +def test_run(): + input_mudata = read_h5mu(par["input"]) + expected_var_columns = ["gene_symbol", "feature_types", "genome"] + + assert list(input_mudata.mod.keys()) == ["rna"], ( + "Input should contain rna modality." + ) + assert list(input_mudata.var.columns) == expected_var_columns, ( + f"Input var columns should be: {expected_var_columns}." + ) + assert list(input_mudata.mod["rna"].var.columns) == expected_var_columns, ( + f"Input mod['rna'] var columns should be: {expected_var_columns}." + ) + + assert list(input_mudata.mod["rna"].obsm.keys()) == ["spatial"], ( + "Input mod['rna'] obsm should contain spatial column." + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "--import-mode=importlib"])) +VIASHMAIN +python -B "\$tempscript" & +wait "\$!" + +VIASHEOF + + +if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then + # strip viash automount from file paths + + if [ ! -z "$VIASH_PAR_INPUT" ]; then + VIASH_PAR_INPUT=$(ViashDockerStripAutomount "$VIASH_PAR_INPUT") + fi + if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then + VIASH_META_RESOURCES_DIR=$(ViashDockerStripAutomount "$VIASH_META_RESOURCES_DIR") + fi + if [ ! -z "$VIASH_META_EXECUTABLE" ]; then + VIASH_META_EXECUTABLE=$(ViashDockerStripAutomount "$VIASH_META_EXECUTABLE") + fi + if [ ! -z "$VIASH_META_CONFIG" ]; then + VIASH_META_CONFIG=$(ViashDockerStripAutomount "$VIASH_META_CONFIG") + fi + if [ ! -z "$VIASH_META_TEMP_DIR" ]; then + VIASH_META_TEMP_DIR=$(ViashDockerStripAutomount "$VIASH_META_TEMP_DIR") + fi +fi + + +exit 0 diff --git a/target/_test/executable/test_workflows/niche/nichecompass_leiden_test/.config.vsh.yaml b/target/_test/executable/test_workflows/niche/nichecompass_leiden_test/.config.vsh.yaml index f30b4f2..148c610 100644 --- a/target/_test/executable/test_workflows/niche/nichecompass_leiden_test/.config.vsh.yaml +++ b/target/_test/executable/test_workflows/niche/nichecompass_leiden_test/.config.vsh.yaml @@ -47,7 +47,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -134,14 +134,16 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" - "viashpy==0.9.0" github: - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true entrypoint: [] cmd: null @@ -154,7 +156,7 @@ build_info: output: "target/_test/executable/test_workflows/niche/nichecompass_leiden_test" executable: "target/_test/executable/test_workflows/niche/nichecompass_leiden_test/nichecompass_leiden_test" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -168,7 +170,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/_test/executable/test_workflows/niche/nichecompass_leiden_test/nichecompass_leiden_test b/target/_test/executable/test_workflows/niche/nichecompass_leiden_test/nichecompass_leiden_test index e0e60ca..6e9fab6 100755 --- a/target/_test/executable/test_workflows/niche/nichecompass_leiden_test/nichecompass_leiden_test +++ b/target/_test/executable/test_workflows/niche/nichecompass_leiden_test/nichecompass_leiden_test @@ -453,15 +453,15 @@ RUN apt-get update && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "anndata~=0.11.1" "mudata~=0.3.1" "viashpy==0.9.0" && \ + pip install --upgrade --no-cache-dir "anndata~=0.12.7" "awkward" "mudata~=0.3.2" "viashpy==0.9.0" && \ pip install --upgrade --no-cache-dir "git+https://github.com/openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" && \ - python -c 'exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)")' + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' LABEL org.opencontainers.image.authors="Dorien Roosen" LABEL org.opencontainers.image.description="Companion container for running component test_workflows/niche nichecompass_leiden_test" -LABEL org.opencontainers.image.created="2026-01-26T08:53:42Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:55Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/.config.vsh.yaml b/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/.config.vsh.yaml new file mode 100644 index 0000000..e6cb637 --- /dev/null +++ b/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/.config.vsh.yaml @@ -0,0 +1,188 @@ +name: "spaceranger_mapping_test" +namespace: "test_workflows/ingestion" +version: "niche-compass" +authors: +- name: "Dorien Roosen" + info: + role: "Core Team Member" + links: + email: "dorien@data-intuitive.com" + github: "dorien-er" + linkedin: "dorien-roosen" + organizations: + - name: "Data Intuitive" + href: "https://www.data-intuitive.com" + role: "Data Scientist" +argument_groups: +- name: "Inputs" + arguments: + - type: "file" + name: "--input" + description: "Path to h5mu output." + info: null + example: + - "foo.final.h5mu" + must_exist: true + create_parent: true + required: true + direction: "input" + multiple: false + multiple_sep: ";" +resources: +- type: "python_script" + path: "script.py" + is_executable: true +- type: "file" + path: "setup_logger.py" +- type: "file" + path: "nextflow_labels.config" + dest: "nextflow_labels.config" +description: "This component test the output of the integration test of the spaceranger\ + \ mapping workflow." +info: null +status: "enabled" +scope: + image: "test" + target: "test" +repositories: +- type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" +links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" +runners: +- type: "executable" + id: "executable" + docker_setup_strategy: "ifneedbepullelsecachedbuild" +- type: "nextflow" + id: "nextflow" + directives: + tag: "$id" + auto: + simplifyInput: true + simplifyOutput: false + transcript: false + publish: false + config: + labels: + mem1gb: "memory = 1000000000.B" + mem2gb: "memory = 2000000000.B" + mem5gb: "memory = 5000000000.B" + mem10gb: "memory = 10000000000.B" + mem20gb: "memory = 20000000000.B" + mem50gb: "memory = 50000000000.B" + mem100gb: "memory = 100000000000.B" + mem200gb: "memory = 200000000000.B" + mem500gb: "memory = 500000000000.B" + mem1tb: "memory = 1000000000000.B" + mem2tb: "memory = 2000000000000.B" + mem5tb: "memory = 5000000000000.B" + mem10tb: "memory = 10000000000000.B" + mem20tb: "memory = 20000000000000.B" + mem50tb: "memory = 50000000000000.B" + mem100tb: "memory = 100000000000000.B" + mem200tb: "memory = 200000000000000.B" + mem500tb: "memory = 500000000000000.B" + mem1gib: "memory = 1073741824.B" + mem2gib: "memory = 2147483648.B" + mem4gib: "memory = 4294967296.B" + mem8gib: "memory = 8589934592.B" + mem16gib: "memory = 17179869184.B" + mem32gib: "memory = 34359738368.B" + mem64gib: "memory = 68719476736.B" + mem128gib: "memory = 137438953472.B" + mem256gib: "memory = 274877906944.B" + mem512gib: "memory = 549755813888.B" + mem1tib: "memory = 1099511627776.B" + mem2tib: "memory = 2199023255552.B" + mem4tib: "memory = 4398046511104.B" + mem8tib: "memory = 8796093022208.B" + mem16tib: "memory = 17592186044416.B" + mem32tib: "memory = 35184372088832.B" + mem64tib: "memory = 70368744177664.B" + mem128tib: "memory = 140737488355328.B" + mem256tib: "memory = 281474976710656.B" + mem512tib: "memory = 562949953421312.B" + 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" + script: + - "includeConfig(\"nextflow_labels.config\")" + debug: false + container: "docker" +engines: +- type: "docker" + id: "docker" + image: "python:3.12-slim" + target_registry: "images.viash-hub.com" + target_tag: "niche-compass" + namespace_separator: "/" + setup: + - type: "apt" + packages: + - "procps" + - "git" + interactive: false + - type: "python" + user: false + packages: + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "viashpy==0.9.0" + github: + - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" + script: + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" + upgrade: true + entrypoint: [] + cmd: null +- type: "native" + id: "native" +build_info: + config: "src/workflows/test_workflows/ingestion/spaceranger_mapping_test/config.vsh.yaml" + runner: "nextflow" + engine: "docker|native" + output: "target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test" + executable: "target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/main.nf" + viash_version: "0.9.4" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" + git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" +package_config: + name: "openpipeline_spatial" + version: "niche-compass" + info: + test_resources: + - type: "s3" + path: "s3://openpipelines-bio/openpipeline_spatial/resources_test" + dest: "resources_test" + repositories: + - type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" + viash_version: "0.9.4" + source: "src" + target: "target" + config_mods: + - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n\ + .runners[.type == 'nextflow'].config.script := 'includeConfig(\"nextflow_labels.config\"\ + )'" + - ".engines += { type: \"native\" }" + - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" + - ".engines[.type == 'docker'].target_tag := 'niche-compass'" + organization: "vsh" + links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" diff --git a/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/main.nf b/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/main.nf new file mode 100644 index 0000000..5c5b38a --- /dev/null +++ b/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/main.nf @@ -0,0 +1,3846 @@ +// spaceranger_mapping_test niche-compass +// +// This wrapper script is auto-generated by viash 0.9.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. +// +// Component authors: +// * Dorien Roosen + +//////////////////////////// +// VDSL3 helper functions // +//////////////////////////// + +// helper file: 'src/main/resources/io/viash/runners/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. only cast if the value is a GString + if (value instanceof GString) { + value = value as String + } + expectedClass = value instanceof String ? null : "String" + } else if (par.type == "integer") { + // cast to integer if need be + if (value !instanceof Integer) { + try { + value = value as Integer + } catch (NumberFormatException e) { + expectedClass = "Integer" + } + } + } else if (par.type == "long") { + // cast to long if need be + if (value !instanceof Long) { + try { + value = value as Long + } catch (NumberFormatException e) { + expectedClass = "Long" + } + } + } else if (par.type == "double") { + // cast to double if need be + if (value !instanceof Double) { + try { + value = value as Double + } catch (NumberFormatException e) { + expectedClass = "Double" + } + } + } else if (par.type == "float") { + // cast to float if need be + if (value !instanceof Float) { + try { + value = value as Float + } catch (NumberFormatException e) { + expectedClass = "Float" + } + } + } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { + // cast to boolean if need be + if (value !instanceof Boolean) { + try { + value = value as Boolean + } catch (Exception e) { + expectedClass = "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 String) { + try { + value = value as String + } catch (Exception e) { + expectedClass = "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/runners/nextflow/arguments/_processInputValues.nf' +Map _processInputValues(Map inputs, Map config, String id, String key) { + if (!workflow.stubRun) { + config.allArguments.each { arg -> + if (arg.required && arg.direction == "input") { + 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.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/runners/nextflow/arguments/_processOutputValues.nf' +Map _checkValidOutputArgument(Map outputs, Map config, String id, String key) { + if (!workflow.stubRun) { + outputs = outputs.collectEntries { name, value -> + def par = config.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 +} + +void _checkAllRequiredOuputsPresent(Map outputs, Map config, String id, String key) { + if (!workflow.stubRun) { + config.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" + } + } + } +} +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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/runners/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.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/runners/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.name + + /* parse regular parameters (not in param_list) */ + /*************************************************/ + def globalParams = config.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 && !id) { + // if stub run, explicitly add an id if missing + 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.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/runners/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/runners/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.name + + // Get different parameter types (used throughout this function) + def defaultArgs = config.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.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/runners/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] + 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_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/runners/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 runIf_ = args.runIf + def id_ = args.id + + assert !runIf_ || runIf_ instanceof Closure: "runEach: must pass a Closure to runIf." + + 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 chPassthrough = null + def chRun = null + if (runIf_) { + def idRunIfBranch = id_ch.branch{ tup -> + run: runIf_(tup[0], tup[1], comp_) + passthrough: true + } + chPassthrough = idRunIfBranch.passthrough + chRun = idRunIfBranch.run + } else { + chRun = id_ch + chPassthrough = Channel.empty() + } + def data_ch = chRun | 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 + + def return_ch = post_ch + | concat(chPassthrough) + + return_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/runners/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/runners/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/runners/nextflow/config/addGlobalParams.nf' +def addGlobalArguments(config) { + def localConfig = [ + "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/runners/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 + + // 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/runners/nextflow/config/processConfig.nf' +def processConfig(config) { + // set defaults for arguments + config.arguments = + (config.arguments ?: []).collect{_processArgument(it)} + + // set defaults for argument_group arguments + config.argument_groups = + (config.argument_groups ?: []).collect{grp -> + grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} + grp + } + + // create combined arguments list + config.allArguments = + config.arguments + + config.argument_groups.collectMany{it.arguments} + + // add missing argument groups (based on Functionality::allArgumentGroups()) + def argGroups = config.argument_groups + if (argGroups.any{it.name.toLowerCase() == "arguments"}) { + argGroups = argGroups.collect{ grp -> + if (grp.name.toLowerCase() == "arguments") { + grp = grp + [ + arguments: grp.arguments + config.arguments + ] + } + grp + } + } else { + argGroups = argGroups + [ + name: "Arguments", + arguments: config.arguments + ] + } + config.allArgumentGroups = argGroups + + config +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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) { + def _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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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 + } + def 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/runners/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/runners/nextflow/readwrite/readJsonBlob.nf' +def readJsonBlob(str) { + def jsonSlurper = new groovy.json.JsonSlurper() + jsonSlurper.parseText(str) +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/nextflow/readwrite/readYamlBlob.nf' +def readYamlBlob(str) { + def yamlSlurper = new org.yaml.snakeyaml.Yaml() + yamlSlurper.load(str) +} + +// helper file: 'src/main/resources/io/viash/runners/nextflow/readwrite/toJsonBlob.nf' +String toJsonBlob(data) { + return groovy.json.JsonOutput.toJson(data) +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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/runners/nextflow/states/findStates.nf' +def findStates(Map params, Map config) { + def auto_config = deepClone(config) + def auto_params = deepClone(params) + + auto_config = auto_config.clone() + // override arguments + auto_config.argument_groups = [] + auto_config.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', or 'newKey:oldKey;newKey:oldKey' in case of multiple values" + 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/runners/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/runners/nextflow/states/publishFiles.nf' +def publishFiles(Map args) { + def key_ = args.get("key") + + assert key_ != null : "publishFiles: key must be specified" + + workflow publishFilesWf { + 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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() + def inputFiles_ = inputoutputFilenames_[0] + def outputFilenames_ = inputoutputFilenames_[1] + + [id_, inputFiles_, outputFilenames_] + } + | publishFilesProc + emit: input_ch + } + return publishFilesWf +} + +process publishFilesProc { + // todo: check publishpath? + publishDir path: "${getPublishDir()}/", mode: "copy" + tag "$id" + input: + tuple val(id), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) + output: + tuple val(id), path{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 + [] + } + } + """ + 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 publishFilesByConfig(Map args) { + def config = args.get("config") + assert config != null : "publishFilesByConfig: config must be specified" + + def key_ = args.get("key", config.name) + assert key_ != null : "publishFilesByConfig: key must be specified" + + workflow publishFilesSimpleWf { + 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'] + + + // the processed state is a list of [key, value, inputPath, outputFilename] tuples, where + // - key is a String + // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) + // - inputPath is a List[Path] + // - outputFilename is a List[String] + // - (inputPath, outputFilename) are the files that will be copied from src to dest (relative to the state.yaml) + def processedState = + config.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 OR multiple channels were emitted + // and the output was just not added to using the channel + // that is now being parsed + 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 [[inputPath: [], outputFilename: []]] + } + // 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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .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 filename_ix = filename.replace("*", ix.toString()) + def inputPath = val instanceof File ? val.toPath() : val + [inputPath: inputPath, outputFilename: filename_ix] + } + def transposedOutputs = ["inputPath", "outputFilename"].collectEntries{ key -> + [key, outputPerFile.collect{dic -> dic[key]}] + } + return [[key: plainName_] + transposedOutputs] + } else { + def value_ = java.nio.file.Paths.get(filename) + def inputPath = value instanceof File ? value.toPath() : value + return [[inputPath: [inputPath], outputFilename: [filename]]] + } + } + + def inputPaths = processedState.collectMany{it.inputPath} + def outputFilenames = processedState.collectMany{it.outputFilename} + + + [id_, inputPaths, outputFilenames] + } + | publishFilesProc + emit: input_ch + } + return publishFilesSimpleWf +} + + + + +// helper file: 'src/main/resources/io/viash/runners/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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() + + def yamlFilename = yamlTemplate_ + .replaceAll('\\$id', id_) + .replaceAll('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .replaceAll('\\$\\{key\\}', key_) + + // TODO: do the pathnames in state_ match up with the outputFilenames_? + + // convert state to yaml blob + def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) + + [id_, yamlBlob_, yamlFilename] + } + | 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) + output: + tuple val(id), path{[yamlFile]} + script: + """ + mkdir -p "\$(dirname '${yamlFile}')" + echo "Storing state as yaml" + cat > '${yamlFile}' << HERE +${yamlBlob} +HERE + """ +} + + +// 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.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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .replaceAll('\\$\\{key\\}', key_) + def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() + + // the processed state is a list of [key, value] tuples, where + // - key is a String + // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) + // - (key, value) are the tuples that will be saved to the state.yaml file + def processedState = + config.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]] + } + // 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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .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 filename_ix = filename.replace("*", ix.toString()) + def value_ = java.nio.file.Paths.get(filename_ix) + // if id contains a slash + if (yamlDir != null) { + value_ = yamlDir.relativize(value_) + } + return value_ + } + return [["key": plainName_, "value": outputPerFile]] + } else { + def value_ = java.nio.file.Paths.get(filename) + // if id contains a slash + if (yamlDir != null) { + value_ = yamlDir.relativize(value_) + } + def inputPath = value instanceof File ? value.toPath() : value + return [["key": plainName_, value: value_]] + } + } + + + def updatedState_ = processedState.collectEntries{[it.key, it.value]} + + // convert state to yaml blob + def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) + + [id_, yamlBlob_, yamlFilename] + } + | publishStatesProc + emit: input_ch + } + return publishStatesSimpleWf +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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.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_.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/runners/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"] + def multipleArgs = meta.config.allArguments.findAll{ it.multiple }.collect{it.plainName} + + workflow workflowInstance { + take: input_ + + main: + def 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 + if (tuple[0] instanceof GString) { + tuple[0] = tuple[0].toString() + } + 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.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 + } + + + def chRun = null + def chPassthrough = null + if (workflowArgs.runIf) { + def runIfBranch = chModified.branch{ tup -> + run: workflowArgs.runIf(tup[0], tup[1]) + passthrough: true + } + chRun = runIfBranch.run + chPassthrough = runIfBranch.passthrough + } else { + chRun = chModified + chPassthrough = Channel.empty() + } + + def chRunFiltered = workflowArgs.filter ? + chRun | filter{workflowArgs.filter(it)} : + chRun + + def chArgs = workflowArgs.fromState ? + chRunFiltered | map{ + def new_data = workflowArgs.fromState(it.take(2)) + [it[0], new_data] + } : + chRunFiltered | map {tup -> tup.take(2)} + + // fill in defaults + def 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.allArguments + .findAll { it.containsKey("default") } + .collectEntries { [ it.plainName, it.default ] } + + // fetch overrides in params + def paramArgs = meta.config.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.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. + def chInitialOutputMulti = chArgsWithDefaults + | _debug(workflowArgs, "processed") + // run workflow + | innerWorkflowFactory(workflowArgs) + def chInitialOutputList = chInitialOutputMulti instanceof List ? chInitialOutputMulti : [chInitialOutputMulti] + assert chInitialOutputList.size() > 0: "should have emitted at least one output channel" + // Add a channel ID to the events, which designates the channel the event was emitted from as a running number + // This number is used to sort the events later when the events are gathered from across the channels. + def chInitialOutputListWithIndexedEvents = chInitialOutputList.withIndex().collect{channel, channelIndex -> + def newChannel = channel + | map {tuple -> + assert tuple instanceof List : + "Error in module '${key_}': element in output 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()}" + + def newEvent = [channelIndex] + tuple + return newEvent + } + return newChannel + } + // Put the events into 1 channel, cover case where there is only one channel is emitted + def chInitialOutput = chInitialOutputList.size() > 1 ? \ + chInitialOutputListWithIndexedEvents[0].mix(*chInitialOutputListWithIndexedEvents.tail()) : \ + chInitialOutputListWithIndexedEvents[0] + def chInitialOutputProcessed = chInitialOutput + | map { tuple -> + def channelId = tuple[0] + def id_ = tuple[1] + def output_ = tuple[2] + + // 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_ = _checkValidOutputArgument(output_, meta.config, id_, key_) + + [join_id, channelId, id_, output_] + } + // | view{"chInitialOutput: ${it.take(3)}"} + + // join the output [prev_id, channel_id, new_id, output] with the previous state [prev_id, state, ...] + def chPublishWithPreviousState = safeJoin(chInitialOutputProcessed, chRunFiltered, key_) + // input tuple format: [join_id, channel_id, id, output, prev_state, ...] + // output tuple format: [join_id, channel_id, id, new_state, ...] + | map{ tup -> + def new_state = workflowArgs.toState(tup.drop(2).take(3)) + tup.take(3) + [new_state] + tup.drop(5) + } + if (workflowArgs.auto.publish == "state") { + def chPublishFiles = chPublishWithPreviousState + // input tuple format: [join_id, channel_id, id, new_state, ...] + // output tuple format: [join_id, channel_id, id, new_state] + | map{ tup -> + tup.take(4) + } + + safeJoin(chPublishFiles, chArgsWithDefaults, key_) + // input tuple format: [join_id, channel_id, id, new_state, orig_state, ...] + // output tuple format: [id, new_state, orig_state] + | map { tup -> + tup.drop(2).take(3) + } + | publishFilesByConfig(key: key_, config: meta.config) + } + // Join the state from the events that were emitted from different channels + def chJoined = chInitialOutputProcessed + | map {tuple -> + def join_id = tuple[0] + def channel_id = tuple[1] + def id = tuple[2] + def other = tuple.drop(3) + // Below, groupTuple is used to join the events. To make sure resuming a workflow + // keeps working, the output state must be deterministic. This means the state needs to be + // sorted with groupTuple's has a 'sort' argument. This argument can be set to 'hash', + // but hashing the state when it is large can be problematic in terms of performance. + // Therefore, a custom comparator function is provided. We add the channel ID to the + // states so that we can use the channel ID to sort the items. + def stateWithChannelID = [[channel_id] * other.size(), other].transpose() + // A comparator that is provided to groupTuple's 'sort' argument is applied + // to all elements of the event tuple (that is not the 'id'). The comparator + // closure that is used below expects the input to be List. So the join_id and + // channel_id must also be wrapped in a list. + [[join_id], [channel_id], id] + stateWithChannelID + } + | groupTuple(by: 2, sort: {a, b -> a[0] <=> b[0]}, size: chInitialOutputList.size(), remainder: true) + | map {join_ids, _, id, statesWithChannelID -> + // Remove the channel IDs from the states + def states = statesWithChannelID.collect{it[1]} + def newJoinId = join_ids.flatten().unique{a, b -> a <=> b} + assert newJoinId.size() == 1: "Multiple events were emitted for '$id'." + def newJoinIdUnique = newJoinId[0] + + // Merge the states from the different channels + def newState = states.inject([:]){ old_state, state_to_add -> + return old_state + state_to_add.collectEntries{k, v -> + if (!multipleArgs.contains(k)) { + // if the key is not a multiple argument, we expect only one value + if (old_state.containsKey(k)) { + assert old_state[k] == v : "ID $id: multiple entries for argument $k were emitted." + } + [k, v] + } else { + // if the key is a multiple argument, append the different values into one list + def prevValue = old_state.getOrDefault(k, []) + def prevValueAsList = prevValue instanceof List ? prevValue : [prevValue] + [k, prevValueAsList + v] + } + } + } + + _checkAllRequiredOuputsPresent(newState, meta.config, id, key_) + + // simplify output if need be + if (workflowArgs.auto.simplifyOutput && newState.size() == 1) { + newState = newState.values()[0] + } + + return [newJoinIdUnique, id, newState] + } + + // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] + def chNewState = safeJoin(chJoined, chRunFiltered, 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") { + def chPublishStates = chNewState + // input tuple format: [join_id, id, new_state, ...] + // output tuple format: [join_id, id, new_state] + | map{ tup -> + tup.take(3) + } + + safeJoin(chPublishStates, 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) + } + 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('''{ + "name" : "spaceranger_mapping_test", + "namespace" : "test_workflows/ingestion", + "version" : "niche-compass", + "authors" : [ + { + "name" : "Dorien Roosen", + "info" : { + "role" : "Core Team Member", + "links" : { + "email" : "dorien@data-intuitive.com", + "github" : "dorien-er", + "linkedin" : "dorien-roosen" + }, + "organizations" : [ + { + "name" : "Data Intuitive", + "href" : "https://www.data-intuitive.com", + "role" : "Data Scientist" + } + ] + } + } + ], + "argument_groups" : [ + { + "name" : "Inputs", + "arguments" : [ + { + "type" : "file", + "name" : "--input", + "description" : "Path to h5mu output.", + "example" : [ + "foo.final.h5mu" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + } + ], + "resources" : [ + { + "type" : "python_script", + "path" : "script.py", + "is_executable" : true + }, + { + "type" : "file", + "path" : "/src/utils/setup_logger.py" + }, + { + "type" : "file", + "path" : "/src/workflows/utils/labels.config", + "dest" : "nextflow_labels.config" + } + ], + "description" : "This component test the output of the integration test of the spaceranger mapping workflow.", + "status" : "enabled", + "scope" : { + "image" : "test", + "target" : "test" + }, + "repositories" : [ + { + "type" : "vsh", + "name" : "openpipeline", + "repo" : "openpipeline", + "tag" : "v4.0.0" + } + ], + "links" : { + "repository" : "https://github.com/openpipelines-bio/openpipeline_spatial", + "docker_registry" : "ghcr.io" + }, + "runners" : [ + { + "type" : "executable", + "id" : "executable", + "docker_setup_strategy" : "ifneedbepullelsecachedbuild" + }, + { + "type" : "nextflow", + "id" : "nextflow", + "directives" : { + "tag" : "$id" + }, + "auto" : { + "simplifyInput" : true, + "simplifyOutput" : false, + "transcript" : false, + "publish" : false + }, + "config" : { + "labels" : { + "mem1gb" : "memory = 1000000000.B", + "mem2gb" : "memory = 2000000000.B", + "mem5gb" : "memory = 5000000000.B", + "mem10gb" : "memory = 10000000000.B", + "mem20gb" : "memory = 20000000000.B", + "mem50gb" : "memory = 50000000000.B", + "mem100gb" : "memory = 100000000000.B", + "mem200gb" : "memory = 200000000000.B", + "mem500gb" : "memory = 500000000000.B", + "mem1tb" : "memory = 1000000000000.B", + "mem2tb" : "memory = 2000000000000.B", + "mem5tb" : "memory = 5000000000000.B", + "mem10tb" : "memory = 10000000000000.B", + "mem20tb" : "memory = 20000000000000.B", + "mem50tb" : "memory = 50000000000000.B", + "mem100tb" : "memory = 100000000000000.B", + "mem200tb" : "memory = 200000000000000.B", + "mem500tb" : "memory = 500000000000000.B", + "mem1gib" : "memory = 1073741824.B", + "mem2gib" : "memory = 2147483648.B", + "mem4gib" : "memory = 4294967296.B", + "mem8gib" : "memory = 8589934592.B", + "mem16gib" : "memory = 17179869184.B", + "mem32gib" : "memory = 34359738368.B", + "mem64gib" : "memory = 68719476736.B", + "mem128gib" : "memory = 137438953472.B", + "mem256gib" : "memory = 274877906944.B", + "mem512gib" : "memory = 549755813888.B", + "mem1tib" : "memory = 1099511627776.B", + "mem2tib" : "memory = 2199023255552.B", + "mem4tib" : "memory = 4398046511104.B", + "mem8tib" : "memory = 8796093022208.B", + "mem16tib" : "memory = 17592186044416.B", + "mem32tib" : "memory = 35184372088832.B", + "mem64tib" : "memory = 70368744177664.B", + "mem128tib" : "memory = 140737488355328.B", + "mem256tib" : "memory = 281474976710656.B", + "mem512tib" : "memory = 562949953421312.B", + "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" + }, + "script" : [ + "includeConfig(\\"nextflow_labels.config\\")" + ] + }, + "debug" : false, + "container" : "docker" + } + ], + "engines" : [ + { + "type" : "docker", + "id" : "docker", + "image" : "python:3.12-slim", + "target_registry" : "images.viash-hub.com", + "target_tag" : "niche-compass", + "namespace_separator" : "/", + "setup" : [ + { + "type" : "apt", + "packages" : [ + "procps", + "git" + ], + "interactive" : false + }, + { + "type" : "python", + "user" : false, + "packages" : [ + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "viashpy==0.9.0" + ], + "github" : [ + "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" + ], + "script" : [ + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" + ], + "upgrade" : true + } + ] + }, + { + "type" : "native", + "id" : "native" + } + ], + "build_info" : { + "config" : "/workdir/root/repo/src/workflows/test_workflows/ingestion/spaceranger_mapping_test/config.vsh.yaml", + "runner" : "nextflow", + "engine" : "docker|native", + "output" : "/workdir/root/repo/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test", + "viash_version" : "0.9.4", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" + }, + "package_config" : { + "name" : "openpipeline_spatial", + "version" : "niche-compass", + "info" : { + "test_resources" : [ + { + "type" : "s3", + "path" : "s3://openpipelines-bio/openpipeline_spatial/resources_test", + "dest" : "resources_test" + } + ] + }, + "repositories" : [ + { + "type" : "vsh", + "name" : "openpipeline", + "repo" : "openpipeline", + "tag" : "v4.0.0" + } + ], + "viash_version" : "0.9.4", + "source" : "/workdir/root/repo/src", + "target" : "/workdir/root/repo/target", + "config_mods" : [ + ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", + ".engines += { type: \\"native\\" }", + ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", + ".engines[.type == 'docker'].target_tag := 'niche-compass'" + ], + "organization" : "vsh", + "links" : { + "repository" : "https://github.com/openpipelines-bio/openpipeline_spatial", + "docker_registry" : "ghcr.io" + } + } +}''')) +] + +// resolve dependencies dependencies (if any) + + +// inner workflow +// inner workflow hook +def innerWorkflowFactory(args) { + def rawScript = '''set -e +tempscript=".viash_script.py" +cat > "$tempscript" << VIASHMAIN +from mudata import read_h5mu +import sys +import pytest + +##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 ) +} +meta = { + 'name': $( if [ ! -z ${VIASH_META_NAME+x} ]; then echo "r'${VIASH_META_NAME//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), + '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 ), + 'memory_kib': $( if [ ! -z ${VIASH_META_MEMORY_KIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_KIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), + 'memory_mib': $( if [ ! -z ${VIASH_META_MEMORY_MIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_MIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), + 'memory_gib': $( if [ ! -z ${VIASH_META_MEMORY_GIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_GIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), + 'memory_tib': $( if [ ! -z ${VIASH_META_MEMORY_TIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_TIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), + 'memory_pib': $( if [ ! -z ${VIASH_META_MEMORY_PIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_PIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ) +} +dep = { + +} + +##VIASH END + + +def test_run(): + input_mudata = read_h5mu(par["input"]) + expected_var_columns = ["gene_symbol", "feature_types", "genome"] + + assert list(input_mudata.mod.keys()) == ["rna"], ( + "Input should contain rna modality." + ) + assert list(input_mudata.var.columns) == expected_var_columns, ( + f"Input var columns should be: {expected_var_columns}." + ) + assert list(input_mudata.mod["rna"].var.columns) == expected_var_columns, ( + f"Input mod['rna'] var columns should be: {expected_var_columns}." + ) + + assert list(input_mudata.mod["rna"].obsm.keys()) == ["spatial"], ( + "Input mod['rna'] obsm should contain spatial column." + ) + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__, "--import-mode=importlib"])) +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.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.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('\\$\\{id\\}', id) + .replaceAll('\\$key', key) + .replaceAll('\\$\\{key\\}', key) + } + [parName, val] + } + + [ id ] + inputPaths + [ argsExclInputFiles, meta.resources_dir ] + } + | processObj + | map { output -> + def outputFiles = meta.config.allArguments + .findAll { it.type == "file" && it.direction == "output" } + .indexed() + .collectEntries{ index, par -> + def 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.allArguments + .findAll { it.type == "file" && it.direction == "input" } + .collect { ', path(viash_par_' + it.plainName + ', stageAs: "_viash_par/' + it.plainName + '_?/*")' } + .join() + + def outputPaths = meta.config.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.allArguments + .findAll { it.type == "file" && it.direction == "output" && it.create_parent } + .collect { par -> + def contents = "args[\"${par.plainName}\"] instanceof List ? args[\"${par.plainName}\"].join('\" \"') : args[\"${par.plainName}\"]" + "\${ args.containsKey(\"${par.plainName}\") ? \"mkdir_parent '\" + escapeText(${contents}) + \"'\" : \"\" }" + } + .join("\n") + + // construct inputFileExports + def inputFileExports = meta.config.allArguments + .findAll { it.type == "file" && it.direction.toLowerCase() == "input" } + .collect { par -> + def 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()}='\" + escapeText(${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.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 + | + |def escapeText = { s -> s.toString().replaceAll("'", "'\\\"'\\\"'") } + |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 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}" + |export VIASH_META_TEMP_DIR="${['docker', 'podman', 'charliecloud'].any{ it == workflow.containerEngine } ? '/tmp' : tmpDir}" + |export VIASH_META_NAME="${meta.config.name}" + |# export VIASH_META_EXECUTABLE="\\\$VIASH_META_RESOURCES_DIR/\\\$VIASH_META_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+999) / 1000 )) + | export VIASH_META_MEMORY_MB=\\\$(( (\\\$VIASH_META_MEMORY_KB+999) / 1000 )) + | export VIASH_META_MEMORY_GB=\\\$(( (\\\$VIASH_META_MEMORY_MB+999) / 1000 )) + | export VIASH_META_MEMORY_TB=\\\$(( (\\\$VIASH_META_MEMORY_GB+999) / 1000 )) + | export VIASH_META_MEMORY_PB=\\\$(( (\\\$VIASH_META_MEMORY_TB+999) / 1000 )) + | export VIASH_META_MEMORY_KIB=\\\$(( (\\\$VIASH_META_MEMORY_B+1023) / 1024 )) + | export VIASH_META_MEMORY_MIB=\\\$(( (\\\$VIASH_META_MEMORY_KIB+1023) / 1024 )) + | export VIASH_META_MEMORY_GIB=\\\$(( (\\\$VIASH_META_MEMORY_MIB+1023) / 1024 )) + | export VIASH_META_MEMORY_TIB=\\\$(( (\\\$VIASH_META_MEMORY_GIB+1023) / 1024 )) + | export VIASH_META_MEMORY_PIB=\\\$(( (\\\$VIASH_META_MEMORY_TIB+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######################") + // } + + // write process to temp file + def tempFile = java.nio.file.Files.createTempFile("viash-process-${procKey}-", ".nf") + addShutdownHook { java.nio.file.Files.deleteIfExists(tempFile) } + tempFile.text = procStr + + // create process from temp file + def binding = new nextflow.script.ScriptBinding([:]) + def session = nextflow.Nextflow.getSession() + def parser = _getScriptLoader(session) + .setModule(true) + .setBinding(binding) + def moduleScript = parser.runScript(tempFile) + .getScript() + + // register module in meta + def module = new nextflow.script.IncludeDef.Module(name: procKey) + scriptMeta.addModule(moduleScript, module.name, module.alias) + + // retrieve and return process from meta + return scriptMeta.getProcess(procKey) +} + +// use Reflection to get a ScriptParser / ScriptLoader +// <25.02.0-edge: new nextflow.script.ScriptParser(session) +// >=25.02.0-edge: nextflow.script.ScriptLoaderFactory.create(session) +def _getScriptLoader(nextflow.Session session) { + // try using the old method + try { + Class scriptParserClass = Class.forName('nextflow.script.ScriptParser') + return scriptParserClass.getDeclaredConstructor(nextflow.Session).newInstance(session) + } catch (ClassNotFoundException e) { + // else try with the new method + try { + Class scriptLoaderFactoryClass = Class.forName('nextflow.script.ScriptLoaderFactory') + def createMethod = scriptLoaderFactoryClass.getDeclaredMethod('create', nextflow.Session) + return createMethod.invoke(null, session) // null because create is static + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | java.lang.reflect.InvocationTargetException e2) { + // Handle the case where neither class is found + throw new Exception("Neither nextflow.script.ScriptParser nor nextflow.script.ScriptLoaderFactory could be found. Is this a compatible Nextflow version?", e2) + } + } +} + +// 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" : "images.viash-hub.com", + "image" : "vsh/openpipeline_spatial/test_workflows/ingestion/spaceranger_mapping_test", + "tag" : "niche-compass" + }, + "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.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.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.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/dataflow/concatenate_h5mu/nextflow.config b/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/nextflow.config similarity index 95% rename from target/nextflow/dataflow/concatenate_h5mu/nextflow.config rename to target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/nextflow.config index 6cf9222..a53e64f 100644 --- a/target/nextflow/dataflow/concatenate_h5mu/nextflow.config +++ b/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/nextflow.config @@ -1,10 +1,10 @@ manifest { - name = 'dataflow/concatenate_h5mu' + name = 'test_workflows/ingestion/spaceranger_mapping_test' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' version = 'niche-compass' - description = 'Concatenate observations from samples in several (uni- and/or multi-modal) MuData files into a single file.\n' - author = 'Dries Schaumont' + description = 'This component test the output of the integration test of the spaceranger mapping workflow.' + author = 'Dorien Roosen' } process.container = 'nextflow/bash:latest' diff --git a/target/nextflow/dataflow/concatenate_h5mu/nextflow_labels.config b/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/nextflow_labels.config similarity index 100% rename from target/nextflow/dataflow/concatenate_h5mu/nextflow_labels.config rename to target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/setup_logger.py b/target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/setup_logger.py rename to target/_test/nextflow/test_workflows/ingestion/spaceranger_mapping_test/setup_logger.py diff --git a/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/.config.vsh.yaml b/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/.config.vsh.yaml index 744e230..8e5bfd2 100644 --- a/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/.config.vsh.yaml +++ b/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/.config.vsh.yaml @@ -47,7 +47,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -134,14 +134,16 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" - "viashpy==0.9.0" github: - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true entrypoint: [] cmd: null @@ -154,7 +156,7 @@ build_info: output: "target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test" executable: "target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -168,7 +170,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/main.nf b/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/main.nf index c2ac148..ffe00ac 100644 --- a/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/main.nf +++ b/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test/main.nf @@ -3104,7 +3104,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3209,15 +3209,16 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", "viashpy==0.9.0" ], "github" : [ "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3234,7 +3235,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/_test/nextflow/test_workflows/niche/nichecompass_leiden_test", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3254,7 +3255,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_schema.json deleted file mode 100644 index d511fad..0000000 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_schema.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "concatenate_h5mu", - "description": "Concatenate observations from samples in several (uni- and/or multi-modal) MuData files into a single file.\n", - "type": "object", - "$defs": { - "arguments": { - "title": "Arguments", - "type": "object", - "description": "No description", - "properties": { - "input": { - "type": "array", - "items": { - "type": "string" - }, - "format": "path", - "exists": true, - "description": "Paths to the different samples to be concatenated.", - "help_text": "Type: `file`, multiple: `True`, required, direction: `input`, example: `[\"sample_paths\"]`. " - }, - "modality": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Only output concatenated objects for the provided modalities", - "help_text": "Type: `string`, multiple: `True`. " - }, - "input_id": { - "type": "array", - "items": { - "type": "string" - }, - "description": "Names of the different samples that have to be concatenated", - "help_text": "Type: `string`, multiple: `True`. " - }, - "output": { - "type": "string", - "format": "path", - "description": "Output location for the concatenated MuData object file.\n", - "help_text": "Type: `file`, multiple: `False`, default: `\"$id.$key.output.h5mu\"`, direction: `output`, example: `\"output.h5mu\"`. ", - "default": "$id.$key.output.h5mu" - }, - "obs_sample_name": { - "type": "string", - "description": "Name of the .obs key under which to add the sample names.", - "help_text": "Type: `string`, multiple: `False`, default: `\"sample_id\"`. ", - "default": "sample_id" - }, - "other_axis_mode": { - "type": "string", - "description": "How to handle the merging of other axis (var, obs, ...).\n\n - None: keep no data\n - same: only keep elements of the matrices which are the same in each of the samples\n - unique: only keep elements for which there is only 1 possible value (1 value that can occur in multiple samples)\n - first: keep the annotation from the first sample\n - only: keep elements that show up in only one of the objects (1 unique element in only 1 sample)\n - move: identical to 'same', but moving the conflicting values to .varm or .obsm\n", - "help_text": "Type: `string`, multiple: `False`, default: `\"move\"`, choices: ``same`, `unique`, `first`, `only`, `concat`, `move``. ", - "enum": [ - "same", - "unique", - "first", - "only", - "concat", - "move" - ], - "default": "move" - }, - "uns_merge_mode": { - "type": "string", - "description": "How to handle the merging of .uns across modalities\n - None: keep no data\n - same: only keep elements of the matrices which are the same in each of the samples\n - unique: only keep elements for which there is only 1 possible value (1 value that can occur in multiple samples)\n - first: keep the annotation from the first sample\n - only: keep elements that show up in only one of the objects (1 unique element in only 1 sample)\n - make_unique: identical to 'unique', but keys which are not unique are made unique by prefixing them with the sample id.\n", - "help_text": "Type: `string`, multiple: `False`, default: `\"make_unique\"`, choices: ``same`, `unique`, `first`, `only`, `make_unique``. ", - "enum": [ - "same", - "unique", - "first", - "only", - "make_unique" - ], - "default": "make_unique" - }, - "output_compression": { - "type": "string", - "description": "Compression format to use for the output AnnData and/or Mudata objects.\nBy default no compression is applied.\n", - "help_text": "Type: `string`, multiple: `False`, example: `\"gzip\"`, choices: ``gzip`, `lzf``. ", - "enum": [ - "gzip", - "lzf" - ] - } - } - }, - "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.", - "help_text": "Type: `string`, multiple: `False`, required, example: `\"output/\"`. " - } - } - } - }, - "allOf": [ - { - "$ref": "#/$defs/arguments" - }, - { - "$ref": "#/$defs/nextflow input-output arguments" - } - ] -} diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/.config.vsh.yaml similarity index 97% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/.config.vsh.yaml index 5115130..941b02e 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "split_modalities" namespace: "workflows/multiomics" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -183,14 +183,13 @@ build_info: output: "target/_private/nextflow/workflows/multiomics/split_modalities" executable: "target/_private/nextflow/workflows/multiomics/split_modalities/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/dataflow/split_modalities" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -220,7 +219,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/main.nf index 5599cb5..2bd887c 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/main.nf @@ -1,4 +1,4 @@ -// split_modalities v3.0.0 +// split_modalities v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "split_modalities", "namespace" : "workflows/multiomics", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3274,13 +3274,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/_private/nextflow/workflows/multiomics/split_modalities", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3305,7 +3304,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow.config index 71f3be2..990d7f4 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/multiomics/split_modalities' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'A pipeline to split a multimodal mudata files into several unimodal mudata files.' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/multiomics/split_modalities/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/.config.vsh.yaml new file mode 100644 index 0000000..595ba1f --- /dev/null +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/.config.vsh.yaml @@ -0,0 +1,250 @@ +name: "log_normalize" +namespace: "workflows/rna" +version: "v4.0.0" +authors: +- name: "Dries Schaumont" + roles: + - "author" + info: + role: "Core Team Member" + links: + email: "dries@data-intuitive.com" + github: "DriesSchaumont" + orcid: "0000-0002-4389-0440" + linkedin: "dries-schaumont" + organizations: + - name: "Data Intuitive" + href: "https://www.data-intuitive.com" + role: "Data Scientist" +argument_groups: +- name: "Inputs" + arguments: + - type: "file" + name: "--input" + description: "MuData file to transform." + info: null + example: + - "dataset.h5mu" + must_exist: true + create_parent: true + required: true + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--modality" + description: "Modality to process." + info: null + default: + - "rna" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--layer" + description: "Input layer containing raw counts. If not specified, .X is used." + info: null + required: false + direction: "input" + multiple: false + multiple_sep: ";" +- name: "Transormation options" + arguments: + - type: "integer" + name: "--target_sum" + description: "Normalize total counts to the specified amount. If not set, after\ + \ normalization each observation (cell) \nwill have a total count equal to the\ + \ median of total counts for observations (cells) before normalization.\n" + info: null + required: false + min: 1 + direction: "input" + multiple: false + multiple_sep: ";" +- name: "Output slots" + arguments: + - type: "string" + name: "--output_layer" + description: "Layer to write the log-transformed counts to.\n" + info: null + required: true + direction: "input" + multiple: false + multiple_sep: ";" +- name: "Output" + arguments: + - type: "file" + name: "--output" + description: "Destination path to the output." + info: null + example: + - "output.h5mu" + must_exist: true + create_parent: true + required: true + direction: "output" + multiple: false + multiple_sep: ";" +resources: +- type: "nextflow_script" + path: "main.nf" + is_executable: true + entrypoint: "run_wf" +- type: "file" + path: "utils" +- type: "file" + path: "nextflow_labels.config" + dest: "nextflow_labels.config" +description: "Performs normalization and subsequent log-transformation of raw count\ + \ data." +test_resources: +- type: "nextflow_script" + path: "test.nf" + is_executable: true + entrypoint: "test_wf" +- type: "file" + path: "pbmc_1k_protein_v3" +info: null +status: "enabled" +scope: + image: "private" + target: "private" +dependencies: +- name: "transform/normalize_total" + repository: + type: "local" +- name: "transform/log1p" + repository: + type: "local" +- name: "transform/delete_layer" + repository: + type: "local" +license: "MIT" +links: + repository: "https://github.com/openpipelines-bio/openpipeline" + docker_registry: "ghcr.io" +runners: +- type: "nextflow" + id: "nextflow" + directives: + tag: "$id" + auto: + simplifyInput: true + simplifyOutput: false + transcript: false + publish: false + config: + labels: + mem1gb: "memory = 1000000000.B" + mem2gb: "memory = 2000000000.B" + mem5gb: "memory = 5000000000.B" + mem10gb: "memory = 10000000000.B" + mem20gb: "memory = 20000000000.B" + mem50gb: "memory = 50000000000.B" + mem100gb: "memory = 100000000000.B" + mem200gb: "memory = 200000000000.B" + mem500gb: "memory = 500000000000.B" + mem1tb: "memory = 1000000000000.B" + mem2tb: "memory = 2000000000000.B" + mem5tb: "memory = 5000000000000.B" + mem10tb: "memory = 10000000000000.B" + mem20tb: "memory = 20000000000000.B" + mem50tb: "memory = 50000000000000.B" + mem100tb: "memory = 100000000000000.B" + mem200tb: "memory = 200000000000000.B" + mem500tb: "memory = 500000000000000.B" + mem1gib: "memory = 1073741824.B" + mem2gib: "memory = 2147483648.B" + mem4gib: "memory = 4294967296.B" + mem8gib: "memory = 8589934592.B" + mem16gib: "memory = 17179869184.B" + mem32gib: "memory = 34359738368.B" + mem64gib: "memory = 68719476736.B" + mem128gib: "memory = 137438953472.B" + mem256gib: "memory = 274877906944.B" + mem512gib: "memory = 549755813888.B" + mem1tib: "memory = 1099511627776.B" + mem2tib: "memory = 2199023255552.B" + mem4tib: "memory = 4398046511104.B" + mem8tib: "memory = 8796093022208.B" + mem16tib: "memory = 17592186044416.B" + mem32tib: "memory = 35184372088832.B" + mem64tib: "memory = 70368744177664.B" + mem128tib: "memory = 140737488355328.B" + mem256tib: "memory = 281474976710656.B" + mem512tib: "memory = 562949953421312.B" + 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" + script: + - "includeConfig(\"nextflow_labels.config\")" + debug: false + container: "docker" +engines: +- type: "native" + id: "native" +build_info: + config: "src/workflows/rna/log_normalize/config.vsh.yaml" + runner: "nextflow" + engine: "native" + output: "target/_private/nextflow/workflows/rna/log_normalize" + executable: "target/_private/nextflow/workflows/rna/log_normalize/main.nf" + viash_version: "0.9.4" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" + git_remote: "https://github.com/openpipelines-bio/openpipeline" + dependencies: + - "target/nextflow/transform/normalize_total" + - "target/nextflow/transform/log1p" + - "target/nextflow/transform/delete_layer" +package_config: + name: "openpipeline" + version: "v4.0.0" + summary: "Best-practice workflows for single-cell multi-omics analyses.\n" + description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ + \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ + \nIn terms of workflows, the following has been made available, but keep in mind\ + \ that\nindividual tools and functionality can be executed as standalone components\ + \ as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n\ + \ * Ingestion: Read mapping and generating a count matrix.\n * Single sample\ + \ processing: cell filtering and doublet detection.\n * Multisample processing:\ + \ Count transformation, normalization, QC metric calulations.\n * Integration:\ + \ Clustering, integration and batch correction using single and multimodal methods.\n\ + \ * Downstream analysis workflows\n" + info: + test_resources: + - type: "s3" + path: "s3://openpipelines-data" + dest: "resources_test" + nextflow_labels_ci: + - path: "src/workflows/utils/labels_ci.config" + description: "Adds the correct memory and CPU labels when running on the Viash\ + \ Hub CI." + viash_version: "0.9.4" + source: "src" + target: "target" + config_mods: + - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n\ + .runners[.type == 'nextflow'].config.script := 'includeConfig(\"nextflow_labels.config\"\ + )'" + - ".engines += { type: \"native\" }" + - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" + keywords: + - "single-cell" + - "multimodal" + license: "MIT" + organization: "vsh" + links: + repository: "https://github.com/openpipelines-bio/openpipeline" + docker_registry: "ghcr.io" + homepage: "https://openpipelines.bio" + documentation: "https://openpipelines.bio/fundamentals" + issue_tracker: "https://github.com/openpipelines-bio/openpipeline/issues" diff --git a/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/main.nf new file mode 100644 index 0000000..6b15a04 --- /dev/null +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/main.nf @@ -0,0 +1,3542 @@ +// log_normalize v4.0.0 +// +// This wrapper script is auto-generated by viash 0.9.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. +// +// Component authors: +// * Dries Schaumont (author) + +//////////////////////////// +// VDSL3 helper functions // +//////////////////////////// + +// helper file: 'src/main/resources/io/viash/runners/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. only cast if the value is a GString + if (value instanceof GString) { + value = value as String + } + expectedClass = value instanceof String ? null : "String" + } else if (par.type == "integer") { + // cast to integer if need be + if (value !instanceof Integer) { + try { + value = value as Integer + } catch (NumberFormatException e) { + expectedClass = "Integer" + } + } + } else if (par.type == "long") { + // cast to long if need be + if (value !instanceof Long) { + try { + value = value as Long + } catch (NumberFormatException e) { + expectedClass = "Long" + } + } + } else if (par.type == "double") { + // cast to double if need be + if (value !instanceof Double) { + try { + value = value as Double + } catch (NumberFormatException e) { + expectedClass = "Double" + } + } + } else if (par.type == "float") { + // cast to float if need be + if (value !instanceof Float) { + try { + value = value as Float + } catch (NumberFormatException e) { + expectedClass = "Float" + } + } + } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { + // cast to boolean if need be + if (value !instanceof Boolean) { + try { + value = value as Boolean + } catch (Exception e) { + expectedClass = "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 String) { + try { + value = value as String + } catch (Exception e) { + expectedClass = "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/runners/nextflow/arguments/_processInputValues.nf' +Map _processInputValues(Map inputs, Map config, String id, String key) { + if (!workflow.stubRun) { + config.allArguments.each { arg -> + if (arg.required && arg.direction == "input") { + 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.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/runners/nextflow/arguments/_processOutputValues.nf' +Map _checkValidOutputArgument(Map outputs, Map config, String id, String key) { + if (!workflow.stubRun) { + outputs = outputs.collectEntries { name, value -> + def par = config.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 +} + +void _checkAllRequiredOuputsPresent(Map outputs, Map config, String id, String key) { + if (!workflow.stubRun) { + config.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" + } + } + } +} +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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/runners/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.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/runners/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.name + + /* parse regular parameters (not in param_list) */ + /*************************************************/ + def globalParams = config.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 && !id) { + // if stub run, explicitly add an id if missing + 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.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/runners/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/runners/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.name + + // Get different parameter types (used throughout this function) + def defaultArgs = config.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.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/runners/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] + 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_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/runners/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 runIf_ = args.runIf + def id_ = args.id + + assert !runIf_ || runIf_ instanceof Closure: "runEach: must pass a Closure to runIf." + + 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 chPassthrough = null + def chRun = null + if (runIf_) { + def idRunIfBranch = id_ch.branch{ tup -> + run: runIf_(tup[0], tup[1], comp_) + passthrough: true + } + chPassthrough = idRunIfBranch.passthrough + chRun = idRunIfBranch.run + } else { + chRun = id_ch + chPassthrough = Channel.empty() + } + def data_ch = chRun | 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 + + def return_ch = post_ch + | concat(chPassthrough) + + return_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/runners/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/runners/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/runners/nextflow/config/addGlobalParams.nf' +def addGlobalArguments(config) { + def localConfig = [ + "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/runners/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 + + // 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/runners/nextflow/config/processConfig.nf' +def processConfig(config) { + // set defaults for arguments + config.arguments = + (config.arguments ?: []).collect{_processArgument(it)} + + // set defaults for argument_group arguments + config.argument_groups = + (config.argument_groups ?: []).collect{grp -> + grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} + grp + } + + // create combined arguments list + config.allArguments = + config.arguments + + config.argument_groups.collectMany{it.arguments} + + // add missing argument groups (based on Functionality::allArgumentGroups()) + def argGroups = config.argument_groups + if (argGroups.any{it.name.toLowerCase() == "arguments"}) { + argGroups = argGroups.collect{ grp -> + if (grp.name.toLowerCase() == "arguments") { + grp = grp + [ + arguments: grp.arguments + config.arguments + ] + } + grp + } + } else { + argGroups = argGroups + [ + name: "Arguments", + arguments: config.arguments + ] + } + config.allArgumentGroups = argGroups + + config +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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) { + def _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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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 + } + def 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/runners/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/runners/nextflow/readwrite/readJsonBlob.nf' +def readJsonBlob(str) { + def jsonSlurper = new groovy.json.JsonSlurper() + jsonSlurper.parseText(str) +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/nextflow/readwrite/readYamlBlob.nf' +def readYamlBlob(str) { + def yamlSlurper = new org.yaml.snakeyaml.Yaml() + yamlSlurper.load(str) +} + +// helper file: 'src/main/resources/io/viash/runners/nextflow/readwrite/toJsonBlob.nf' +String toJsonBlob(data) { + return groovy.json.JsonOutput.toJson(data) +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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/runners/nextflow/states/findStates.nf' +def findStates(Map params, Map config) { + def auto_config = deepClone(config) + def auto_params = deepClone(params) + + auto_config = auto_config.clone() + // override arguments + auto_config.argument_groups = [] + auto_config.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', or 'newKey:oldKey;newKey:oldKey' in case of multiple values" + 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/runners/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/runners/nextflow/states/publishFiles.nf' +def publishFiles(Map args) { + def key_ = args.get("key") + + assert key_ != null : "publishFiles: key must be specified" + + workflow publishFilesWf { + 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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() + def inputFiles_ = inputoutputFilenames_[0] + def outputFilenames_ = inputoutputFilenames_[1] + + [id_, inputFiles_, outputFilenames_] + } + | publishFilesProc + emit: input_ch + } + return publishFilesWf +} + +process publishFilesProc { + // todo: check publishpath? + publishDir path: "${getPublishDir()}/", mode: "copy" + tag "$id" + input: + tuple val(id), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) + output: + tuple val(id), path{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 + [] + } + } + """ + 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 publishFilesByConfig(Map args) { + def config = args.get("config") + assert config != null : "publishFilesByConfig: config must be specified" + + def key_ = args.get("key", config.name) + assert key_ != null : "publishFilesByConfig: key must be specified" + + workflow publishFilesSimpleWf { + 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'] + + + // the processed state is a list of [key, value, inputPath, outputFilename] tuples, where + // - key is a String + // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) + // - inputPath is a List[Path] + // - outputFilename is a List[String] + // - (inputPath, outputFilename) are the files that will be copied from src to dest (relative to the state.yaml) + def processedState = + config.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 OR multiple channels were emitted + // and the output was just not added to using the channel + // that is now being parsed + 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 [[inputPath: [], outputFilename: []]] + } + // 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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .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 filename_ix = filename.replace("*", ix.toString()) + def inputPath = val instanceof File ? val.toPath() : val + [inputPath: inputPath, outputFilename: filename_ix] + } + def transposedOutputs = ["inputPath", "outputFilename"].collectEntries{ key -> + [key, outputPerFile.collect{dic -> dic[key]}] + } + return [[key: plainName_] + transposedOutputs] + } else { + def value_ = java.nio.file.Paths.get(filename) + def inputPath = value instanceof File ? value.toPath() : value + return [[inputPath: [inputPath], outputFilename: [filename]]] + } + } + + def inputPaths = processedState.collectMany{it.inputPath} + def outputFilenames = processedState.collectMany{it.outputFilename} + + + [id_, inputPaths, outputFilenames] + } + | publishFilesProc + emit: input_ch + } + return publishFilesSimpleWf +} + + + + +// helper file: 'src/main/resources/io/viash/runners/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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() + + def yamlFilename = yamlTemplate_ + .replaceAll('\\$id', id_) + .replaceAll('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .replaceAll('\\$\\{key\\}', key_) + + // TODO: do the pathnames in state_ match up with the outputFilenames_? + + // convert state to yaml blob + def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) + + [id_, yamlBlob_, yamlFilename] + } + | 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) + output: + tuple val(id), path{[yamlFile]} + script: + """ + mkdir -p "\$(dirname '${yamlFile}')" + echo "Storing state as yaml" + cat > '${yamlFile}' << HERE +${yamlBlob} +HERE + """ +} + + +// 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.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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .replaceAll('\\$\\{key\\}', key_) + def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() + + // the processed state is a list of [key, value] tuples, where + // - key is a String + // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) + // - (key, value) are the tuples that will be saved to the state.yaml file + def processedState = + config.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]] + } + // 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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .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 filename_ix = filename.replace("*", ix.toString()) + def value_ = java.nio.file.Paths.get(filename_ix) + // if id contains a slash + if (yamlDir != null) { + value_ = yamlDir.relativize(value_) + } + return value_ + } + return [["key": plainName_, "value": outputPerFile]] + } else { + def value_ = java.nio.file.Paths.get(filename) + // if id contains a slash + if (yamlDir != null) { + value_ = yamlDir.relativize(value_) + } + def inputPath = value instanceof File ? value.toPath() : value + return [["key": plainName_, value: value_]] + } + } + + + def updatedState_ = processedState.collectEntries{[it.key, it.value]} + + // convert state to yaml blob + def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) + + [id_, yamlBlob_, yamlFilename] + } + | publishStatesProc + emit: input_ch + } + return publishStatesSimpleWf +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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.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_.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/runners/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"] + def multipleArgs = meta.config.allArguments.findAll{ it.multiple }.collect{it.plainName} + + workflow workflowInstance { + take: input_ + + main: + def 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 + if (tuple[0] instanceof GString) { + tuple[0] = tuple[0].toString() + } + 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.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 + } + + + def chRun = null + def chPassthrough = null + if (workflowArgs.runIf) { + def runIfBranch = chModified.branch{ tup -> + run: workflowArgs.runIf(tup[0], tup[1]) + passthrough: true + } + chRun = runIfBranch.run + chPassthrough = runIfBranch.passthrough + } else { + chRun = chModified + chPassthrough = Channel.empty() + } + + def chRunFiltered = workflowArgs.filter ? + chRun | filter{workflowArgs.filter(it)} : + chRun + + def chArgs = workflowArgs.fromState ? + chRunFiltered | map{ + def new_data = workflowArgs.fromState(it.take(2)) + [it[0], new_data] + } : + chRunFiltered | map {tup -> tup.take(2)} + + // fill in defaults + def 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.allArguments + .findAll { it.containsKey("default") } + .collectEntries { [ it.plainName, it.default ] } + + // fetch overrides in params + def paramArgs = meta.config.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.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. + def chInitialOutputMulti = chArgsWithDefaults + | _debug(workflowArgs, "processed") + // run workflow + | innerWorkflowFactory(workflowArgs) + def chInitialOutputList = chInitialOutputMulti instanceof List ? chInitialOutputMulti : [chInitialOutputMulti] + assert chInitialOutputList.size() > 0: "should have emitted at least one output channel" + // Add a channel ID to the events, which designates the channel the event was emitted from as a running number + // This number is used to sort the events later when the events are gathered from across the channels. + def chInitialOutputListWithIndexedEvents = chInitialOutputList.withIndex().collect{channel, channelIndex -> + def newChannel = channel + | map {tuple -> + assert tuple instanceof List : + "Error in module '${key_}': element in output 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()}" + + def newEvent = [channelIndex] + tuple + return newEvent + } + return newChannel + } + // Put the events into 1 channel, cover case where there is only one channel is emitted + def chInitialOutput = chInitialOutputList.size() > 1 ? \ + chInitialOutputListWithIndexedEvents[0].mix(*chInitialOutputListWithIndexedEvents.tail()) : \ + chInitialOutputListWithIndexedEvents[0] + def chInitialOutputProcessed = chInitialOutput + | map { tuple -> + def channelId = tuple[0] + def id_ = tuple[1] + def output_ = tuple[2] + + // 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_ = _checkValidOutputArgument(output_, meta.config, id_, key_) + + [join_id, channelId, id_, output_] + } + // | view{"chInitialOutput: ${it.take(3)}"} + + // join the output [prev_id, channel_id, new_id, output] with the previous state [prev_id, state, ...] + def chPublishWithPreviousState = safeJoin(chInitialOutputProcessed, chRunFiltered, key_) + // input tuple format: [join_id, channel_id, id, output, prev_state, ...] + // output tuple format: [join_id, channel_id, id, new_state, ...] + | map{ tup -> + def new_state = workflowArgs.toState(tup.drop(2).take(3)) + tup.take(3) + [new_state] + tup.drop(5) + } + if (workflowArgs.auto.publish == "state") { + def chPublishFiles = chPublishWithPreviousState + // input tuple format: [join_id, channel_id, id, new_state, ...] + // output tuple format: [join_id, channel_id, id, new_state] + | map{ tup -> + tup.take(4) + } + + safeJoin(chPublishFiles, chArgsWithDefaults, key_) + // input tuple format: [join_id, channel_id, id, new_state, orig_state, ...] + // output tuple format: [id, new_state, orig_state] + | map { tup -> + tup.drop(2).take(3) + } + | publishFilesByConfig(key: key_, config: meta.config) + } + // Join the state from the events that were emitted from different channels + def chJoined = chInitialOutputProcessed + | map {tuple -> + def join_id = tuple[0] + def channel_id = tuple[1] + def id = tuple[2] + def other = tuple.drop(3) + // Below, groupTuple is used to join the events. To make sure resuming a workflow + // keeps working, the output state must be deterministic. This means the state needs to be + // sorted with groupTuple's has a 'sort' argument. This argument can be set to 'hash', + // but hashing the state when it is large can be problematic in terms of performance. + // Therefore, a custom comparator function is provided. We add the channel ID to the + // states so that we can use the channel ID to sort the items. + def stateWithChannelID = [[channel_id] * other.size(), other].transpose() + // A comparator that is provided to groupTuple's 'sort' argument is applied + // to all elements of the event tuple (that is not the 'id'). The comparator + // closure that is used below expects the input to be List. So the join_id and + // channel_id must also be wrapped in a list. + [[join_id], [channel_id], id] + stateWithChannelID + } + | groupTuple(by: 2, sort: {a, b -> a[0] <=> b[0]}, size: chInitialOutputList.size(), remainder: true) + | map {join_ids, _, id, statesWithChannelID -> + // Remove the channel IDs from the states + def states = statesWithChannelID.collect{it[1]} + def newJoinId = join_ids.flatten().unique{a, b -> a <=> b} + assert newJoinId.size() == 1: "Multiple events were emitted for '$id'." + def newJoinIdUnique = newJoinId[0] + + // Merge the states from the different channels + def newState = states.inject([:]){ old_state, state_to_add -> + return old_state + state_to_add.collectEntries{k, v -> + if (!multipleArgs.contains(k)) { + // if the key is not a multiple argument, we expect only one value + if (old_state.containsKey(k)) { + assert old_state[k] == v : "ID $id: multiple entries for argument $k were emitted." + } + [k, v] + } else { + // if the key is a multiple argument, append the different values into one list + def prevValue = old_state.getOrDefault(k, []) + def prevValueAsList = prevValue instanceof List ? prevValue : [prevValue] + [k, prevValueAsList + v] + } + } + } + + _checkAllRequiredOuputsPresent(newState, meta.config, id, key_) + + // simplify output if need be + if (workflowArgs.auto.simplifyOutput && newState.size() == 1) { + newState = newState.values()[0] + } + + return [newJoinIdUnique, id, newState] + } + + // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] + def chNewState = safeJoin(chJoined, chRunFiltered, 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") { + def chPublishStates = chNewState + // input tuple format: [join_id, id, new_state, ...] + // output tuple format: [join_id, id, new_state] + | map{ tup -> + tup.take(3) + } + + safeJoin(chPublishStates, 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) + } + 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('''{ + "name" : "log_normalize", + "namespace" : "workflows/rna", + "version" : "v4.0.0", + "authors" : [ + { + "name" : "Dries Schaumont", + "roles" : [ + "author" + ], + "info" : { + "role" : "Core Team Member", + "links" : { + "email" : "dries@data-intuitive.com", + "github" : "DriesSchaumont", + "orcid" : "0000-0002-4389-0440", + "linkedin" : "dries-schaumont" + }, + "organizations" : [ + { + "name" : "Data Intuitive", + "href" : "https://www.data-intuitive.com", + "role" : "Data Scientist" + } + ] + } + } + ], + "argument_groups" : [ + { + "name" : "Inputs", + "arguments" : [ + { + "type" : "file", + "name" : "--input", + "description" : "MuData file to transform.", + "example" : [ + "dataset.h5mu" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--modality", + "description" : "Modality to process.", + "default" : [ + "rna" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--layer", + "description" : "Input layer containing raw counts. If not specified, .X is used.", + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + }, + { + "name" : "Transormation options", + "arguments" : [ + { + "type" : "integer", + "name" : "--target_sum", + "description" : "Normalize total counts to the specified amount. If not set, after normalization each observation (cell) \nwill have a total count equal to the median of total counts for observations (cells) before normalization.\n", + "required" : false, + "min" : 1, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + }, + { + "name" : "Output slots", + "arguments" : [ + { + "type" : "string", + "name" : "--output_layer", + "description" : "Layer to write the log-transformed counts to.\n", + "required" : true, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + }, + { + "name" : "Output", + "arguments" : [ + { + "type" : "file", + "name" : "--output", + "description" : "Destination path to the output.", + "example" : [ + "output.h5mu" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "output", + "multiple" : false, + "multiple_sep" : ";" + } + ] + } + ], + "resources" : [ + { + "type" : "nextflow_script", + "path" : "main.nf", + "is_executable" : true, + "entrypoint" : "run_wf" + }, + { + "type" : "file", + "path" : "/src/workflows/utils/" + }, + { + "type" : "file", + "path" : "/src/workflows/utils/labels.config", + "dest" : "nextflow_labels.config" + } + ], + "description" : "Performs normalization and subsequent log-transformation of raw count data.", + "test_resources" : [ + { + "type" : "nextflow_script", + "path" : "test.nf", + "is_executable" : true, + "entrypoint" : "test_wf" + }, + { + "type" : "file", + "path" : "/resources_test/pbmc_1k_protein_v3" + } + ], + "status" : "enabled", + "scope" : { + "image" : "private", + "target" : "private" + }, + "dependencies" : [ + { + "name" : "transform/normalize_total", + "repository" : { + "type" : "local" + } + }, + { + "name" : "transform/log1p", + "repository" : { + "type" : "local" + } + }, + { + "name" : "transform/delete_layer", + "repository" : { + "type" : "local" + } + } + ], + "license" : "MIT", + "links" : { + "repository" : "https://github.com/openpipelines-bio/openpipeline", + "docker_registry" : "ghcr.io" + }, + "runners" : [ + { + "type" : "nextflow", + "id" : "nextflow", + "directives" : { + "tag" : "$id" + }, + "auto" : { + "simplifyInput" : true, + "simplifyOutput" : false, + "transcript" : false, + "publish" : false + }, + "config" : { + "labels" : { + "mem1gb" : "memory = 1000000000.B", + "mem2gb" : "memory = 2000000000.B", + "mem5gb" : "memory = 5000000000.B", + "mem10gb" : "memory = 10000000000.B", + "mem20gb" : "memory = 20000000000.B", + "mem50gb" : "memory = 50000000000.B", + "mem100gb" : "memory = 100000000000.B", + "mem200gb" : "memory = 200000000000.B", + "mem500gb" : "memory = 500000000000.B", + "mem1tb" : "memory = 1000000000000.B", + "mem2tb" : "memory = 2000000000000.B", + "mem5tb" : "memory = 5000000000000.B", + "mem10tb" : "memory = 10000000000000.B", + "mem20tb" : "memory = 20000000000000.B", + "mem50tb" : "memory = 50000000000000.B", + "mem100tb" : "memory = 100000000000000.B", + "mem200tb" : "memory = 200000000000000.B", + "mem500tb" : "memory = 500000000000000.B", + "mem1gib" : "memory = 1073741824.B", + "mem2gib" : "memory = 2147483648.B", + "mem4gib" : "memory = 4294967296.B", + "mem8gib" : "memory = 8589934592.B", + "mem16gib" : "memory = 17179869184.B", + "mem32gib" : "memory = 34359738368.B", + "mem64gib" : "memory = 68719476736.B", + "mem128gib" : "memory = 137438953472.B", + "mem256gib" : "memory = 274877906944.B", + "mem512gib" : "memory = 549755813888.B", + "mem1tib" : "memory = 1099511627776.B", + "mem2tib" : "memory = 2199023255552.B", + "mem4tib" : "memory = 4398046511104.B", + "mem8tib" : "memory = 8796093022208.B", + "mem16tib" : "memory = 17592186044416.B", + "mem32tib" : "memory = 35184372088832.B", + "mem64tib" : "memory = 70368744177664.B", + "mem128tib" : "memory = 140737488355328.B", + "mem256tib" : "memory = 281474976710656.B", + "mem512tib" : "memory = 562949953421312.B", + "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" + }, + "script" : [ + "includeConfig(\\"nextflow_labels.config\\")" + ] + }, + "debug" : false, + "container" : "docker" + } + ], + "engines" : [ + { + "type" : "native", + "id" : "native" + } + ], + "build_info" : { + "config" : "/workdir/root/repo/src/workflows/rna/log_normalize/config.vsh.yaml", + "runner" : "nextflow", + "engine" : "native", + "output" : "/workdir/root/repo/target/_private/nextflow/workflows/rna/log_normalize", + "viash_version" : "0.9.4", + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" + }, + "package_config" : { + "name" : "openpipeline", + "version" : "v4.0.0", + "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", + "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", + "info" : { + "test_resources" : [ + { + "type" : "s3", + "path" : "s3://openpipelines-data", + "dest" : "resources_test" + } + ], + "nextflow_labels_ci" : [ + { + "path" : "src/workflows/utils/labels_ci.config", + "description" : "Adds the correct memory and CPU labels when running on the Viash Hub CI." + } + ] + }, + "viash_version" : "0.9.4", + "source" : "/workdir/root/repo/src", + "target" : "/workdir/root/repo/target", + "config_mods" : [ + ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", + ".engines += { type: \\"native\\" }", + ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" + ], + "keywords" : [ + "single-cell", + "multimodal" + ], + "license" : "MIT", + "organization" : "vsh", + "links" : { + "repository" : "https://github.com/openpipelines-bio/openpipeline", + "docker_registry" : "ghcr.io", + "homepage" : "https://openpipelines.bio", + "documentation" : "https://openpipelines.bio/fundamentals", + "issue_tracker" : "https://github.com/openpipelines-bio/openpipeline/issues" + } + } +}''')) +] + +// resolve dependencies dependencies (if any) +meta["root_dir"] = getRootDir() +include { normalize_total } from "${meta.resources_dir}/../../../../../nextflow/transform/normalize_total/main.nf" +include { log1p } from "${meta.resources_dir}/../../../../../nextflow/transform/log1p/main.nf" +include { delete_layer } from "${meta.resources_dir}/../../../../../nextflow/transform/delete_layer/main.nf" + +// inner workflow +// user-provided Nextflow code + + + +workflow run_wf { + take: + input_ch + + main: + output_ch = input_ch + | normalize_total.run( + fromState: [ + "input": "input", + "modality": "modality", + "input_layer": "layer", + "target_sum": "target_sum" + ], + args: [ + "output_layer": "normalized", + ], + toState: [ + "input": "output", + ] + ) + | log1p.run( + fromState: [ + "input": "input", + "modality": "modality", + "output_layer": "output_layer" + ], + args: [ + "input_layer": "normalized", + ], + toState: [ + "input": "output" + ] + ) + | delete_layer.run( + fromState: [ + "input": "input", + "modality": "modality" + ], + args: [ + "layer": "normalized" + ], + toState: [ + "output": "output" + ] + ) + | setState(["output"]) + + 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.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.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.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/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/nextflow.config new file mode 100644 index 0000000..813fc41 --- /dev/null +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/nextflow.config @@ -0,0 +1,126 @@ +manifest { + name = 'workflows/rna/log_normalize' + mainScript = 'main.nf' + nextflowVersion = '!>=20.12.1-edge' + version = 'v4.0.0' + description = 'Performs normalization and subsequent log-transformation of raw count data.' + author = 'Dries Schaumont' +} + +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 = 1000000000.B } + withLabel: mem2gb { memory = 2000000000.B } + withLabel: mem5gb { memory = 5000000000.B } + withLabel: mem10gb { memory = 10000000000.B } + withLabel: mem20gb { memory = 20000000000.B } + withLabel: mem50gb { memory = 50000000000.B } + withLabel: mem100gb { memory = 100000000000.B } + withLabel: mem200gb { memory = 200000000000.B } + withLabel: mem500gb { memory = 500000000000.B } + withLabel: mem1tb { memory = 1000000000000.B } + withLabel: mem2tb { memory = 2000000000000.B } + withLabel: mem5tb { memory = 5000000000000.B } + withLabel: mem10tb { memory = 10000000000000.B } + withLabel: mem20tb { memory = 20000000000000.B } + withLabel: mem50tb { memory = 50000000000000.B } + withLabel: mem100tb { memory = 100000000000000.B } + withLabel: mem200tb { memory = 200000000000000.B } + withLabel: mem500tb { memory = 500000000000000.B } + withLabel: mem1gib { memory = 1073741824.B } + withLabel: mem2gib { memory = 2147483648.B } + withLabel: mem4gib { memory = 4294967296.B } + withLabel: mem8gib { memory = 8589934592.B } + withLabel: mem16gib { memory = 17179869184.B } + withLabel: mem32gib { memory = 34359738368.B } + withLabel: mem64gib { memory = 68719476736.B } + withLabel: mem128gib { memory = 137438953472.B } + withLabel: mem256gib { memory = 274877906944.B } + withLabel: mem512gib { memory = 549755813888.B } + withLabel: mem1tib { memory = 1099511627776.B } + withLabel: mem2tib { memory = 2199023255552.B } + withLabel: mem4tib { memory = 4398046511104.B } + withLabel: mem8tib { memory = 8796093022208.B } + withLabel: mem16tib { memory = 17592186044416.B } + withLabel: mem32tib { memory = 35184372088832.B } + withLabel: mem64tib { memory = 70368744177664.B } + withLabel: mem128tib { memory = 140737488355328.B } + withLabel: mem256tib { memory = 281474976710656.B } + withLabel: mem512tib { memory = 562949953421312.B } + 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 } +} + +includeConfig("nextflow_labels.config") diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/_private/nextflow/workflows/rna/log_normalize/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/.config.vsh.yaml similarity index 95% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/.config.vsh.yaml index a7271fa..8a4ec97 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "leiden" namespace: "cluster" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -215,7 +215,7 @@ engines: id: "docker" image: "python:3.13-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -225,13 +225,15 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" - "leidenalg~=0.10.0" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -256,12 +258,11 @@ build_info: output: "target/nextflow/cluster/leiden" executable: "target/nextflow/cluster/leiden/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -291,7 +292,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/main.nf index 351e087..c259993 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/main.nf @@ -1,4 +1,4 @@ -// leiden v3.0.0 +// leiden v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "leiden", "namespace" : "cluster", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3294,7 +3294,7 @@ meta = [ "id" : "docker", "image" : "python:3.13-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3308,13 +3308,14 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4", "leidenalg~=0.10.0" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3351,13 +3352,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/cluster/leiden", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3382,7 +3382,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3417,6 +3417,7 @@ import time import logging import logging.handlers import warnings +import h5py import mudata as mu import pandas as pd import scanpy as sc @@ -3734,7 +3735,8 @@ def main(): logger.info("Waiting for shutdown of processes") executor.shutdown() logger.info("Executor shut down.") - adata.obsm[par["obsm_name"]] = pd.DataFrame(results) + del adata + results = pd.DataFrame(results) output_file = Path(par["output"]) logger.info("Writing output to %s.", par["output"]) @@ -3744,9 +3746,11 @@ def main(): else output_file ) shutil.copyfile(par["input"], output_file_uncompressed) - mu.write_h5ad( - filename=output_file_uncompressed, mod=par["modality"], data=adata - ) + logger.info("Opening %s", output_file_uncompressed) + with h5py.File(output_file_uncompressed, "a") as storage: + group_path = f"/mod/{par['modality']}/obsm/{par['obsm_name']}" + logger.info("Adding output to %s", group_path) + ad.io.write_elem(storage, k=group_path, elem=results) if par["output_compression"]: compress_h5mu( output_file_uncompressed, @@ -4143,7 +4147,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/cluster/leiden", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "highcpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/nextflow.config index ea05c9e..f8d69f9 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'cluster/leiden' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Cluster cells using the [Leiden algorithm] [Traag18] implemented in the [Scanpy framework] [Wolf18]. \nLeiden is an improved version of the [Louvain algorithm] [Blondel08]. \nIt has been proposed for single-cell analysis by [Levine15] [Levine15]. \nThis requires having ran `neighbors/find_neighbors` or `neighbors/bbknn` first.\n\n[Blondel08]: Blondel et al. (2008), Fast unfolding of communities in large networks, J. Stat. Mech. \n[Levine15]: Levine et al. (2015), Data-Driven Phenotypic Dissection of AML Reveals Progenitor-like Cells that Correlate with Prognosis, Cell. \n[Traag18]: Traag et al. (2018), From Louvain to Leiden: guaranteeing well-connected communities arXiv. \n[Wolf18]: Wolf et al. (2018), Scanpy: large-scale single-cell gene expression data analysis, Genome Biology. \n' author = 'Dries De Maeyer' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/cluster/leiden/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/cluster/leiden/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml similarity index 91% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml index 943b94e..479329b 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "concatenate_h5mu" namespace: "dataflow" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -124,6 +124,16 @@ argument_groups: direction: "input" multiple: false multiple_sep: ";" + - type: "string" + name: "--obsp_keys" + description: "List of `.obsp` keys for which block-diagonal concatenation should\ + \ be performed.\nIf not provided, no `.obsp` keys will be concatenated.\nProvided\ + \ keys must be present in all samples for block concatenation to be performed.\n" + info: null + required: false + direction: "input" + multiple: true + multiple_sep: ";" - type: "string" name: "--output_compression" description: "Compression format to use for the output AnnData and/or Mudata objects.\n\ @@ -241,9 +251,9 @@ runners: engines: - type: "docker" id: "docker" - image: "python:3.11-slim" + image: "python:3.13-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -253,12 +263,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "pandas~=2.1.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -276,6 +287,7 @@ engines: user: false packages: - "viashpy==0.8.0" + - "pytest-benchmark" upgrade: true entrypoint: [] cmd: null @@ -288,12 +300,11 @@ build_info: output: "target/nextflow/dataflow/concatenate_h5mu" executable: "target/nextflow/dataflow/concatenate_h5mu/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -323,7 +334,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/main.nf similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/main.nf index 7be934b..cfd315a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/main.nf @@ -1,4 +1,4 @@ -// concatenate_h5mu v3.0.0 +// concatenate_h5mu v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "concatenate_h5mu", "namespace" : "dataflow", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3167,6 +3167,15 @@ meta = [ "multiple" : false, "multiple_sep" : ";" }, + { + "type" : "string", + "name" : "--obsp_keys", + "description" : "List of `.obsp` keys for which block-diagonal concatenation should be performed.\nIf not provided, no `.obsp` keys will be concatenated.\nProvided keys must be present in all samples for block concatenation to be performed.\n", + "required" : false, + "direction" : "input", + "multiple" : true, + "multiple_sep" : ";" + }, { "type" : "string", "name" : "--output_compression", @@ -3317,9 +3326,9 @@ meta = [ { "type" : "docker", "id" : "docker", - "image" : "python:3.11-slim", + "image" : "python:3.13-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3333,12 +3342,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "pandas~=2.1.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3366,7 +3375,8 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "viashpy==0.8.0" + "viashpy==0.8.0", + "pytest-benchmark" ], "upgrade" : true } @@ -3383,13 +3393,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/dataflow/concatenate_h5mu", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3414,7 +3423,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3465,6 +3474,7 @@ par = { 'obs_sample_name': $( if [ ! -z ${VIASH_PAR_OBS_SAMPLE_NAME+x} ]; then echo "r'${VIASH_PAR_OBS_SAMPLE_NAME//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), 'other_axis_mode': $( if [ ! -z ${VIASH_PAR_OTHER_AXIS_MODE+x} ]; then echo "r'${VIASH_PAR_OTHER_AXIS_MODE//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), 'uns_merge_mode': $( if [ ! -z ${VIASH_PAR_UNS_MERGE_MODE+x} ]; then echo "r'${VIASH_PAR_UNS_MERGE_MODE//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), + 'obsp_keys': $( if [ ! -z ${VIASH_PAR_OBSP_KEYS+x} ]; then echo "r'${VIASH_PAR_OBSP_KEYS//\\'/\\'\\"\\'\\"r\\'}'.split(';')"; else echo None; fi ), 'output_compression': $( if [ ! -z ${VIASH_PAR_OUTPUT_COMPRESSION+x} ]; then echo "r'${VIASH_PAR_OUTPUT_COMPRESSION//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ) } meta = { @@ -3709,8 +3719,19 @@ def concatenate_modality( if mod is not None: try: data = mu.read_h5ad(input_file, mod=mod) + + # Remove obsp keys that are not in par["obsp_keys"] + obsp_keys_to_keep = par.get("obsp_keys") or [] + obsp_keys_to_remove = set(data.obsp.keys()) - set(obsp_keys_to_keep) + for key in obsp_keys_to_remove: + try: + del data.obsp[key] + except KeyError: + pass + mod_data[input_id] = data mod_indices_combined = mod_indices_combined.append(data.obs.index) + except KeyError as e: # Modality does not exist for this sample, skip it if ( f"Unable to synchronously open object (object '{mod}' doesn't exist)" @@ -3734,6 +3755,7 @@ def concatenate_modality( concatenated_data = anndata.concat( mod_data.values(), join="outer", + pairwise=True if par["obsp_keys"] else False, merge=other_axis_mode_to_apply, uns_merge=uns_merge_mode_to_apply, ) @@ -4244,7 +4266,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/dataflow/concatenate_h5mu", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "midcpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/nextflow.config index 418f5f0..47f4ccf 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/concatenate_h5mu/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'dataflow/concatenate_h5mu' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Concatenate observations from samples in several (uni- and/or multi-modal) MuData files into a single file.\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_labels.config diff --git a/target/nextflow/dataflow/concatenate_h5mu/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_schema.json similarity index 100% rename from target/nextflow/dataflow/concatenate_h5mu/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/.config.vsh.yaml index 724f826..a29e974 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "merge" namespace: "dataflow" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -163,7 +163,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -173,11 +173,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -202,12 +204,11 @@ build_info: output: "target/nextflow/dataflow/merge" executable: "target/nextflow/dataflow/merge/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -237,7 +238,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/main.nf index 37d2ca2..ea55660 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/main.nf @@ -1,4 +1,4 @@ -// merge v3.0.0 +// merge v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "merge", "namespace" : "dataflow", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3246,7 +3246,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3260,11 +3260,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3301,13 +3302,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/dataflow/merge", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3332,7 +3332,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3847,7 +3847,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/dataflow/merge", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/nextflow.config index 892f36a..777ee54 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'dataflow/merge' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Combine one or more single-modality .h5mu files together into one .h5mu file.\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/merge/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/merge/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/.config.vsh.yaml similarity index 95% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/.config.vsh.yaml index 4b55466..a08d5fc 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "split_h5mu" namespace: "dataflow" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dorien Roosen" roles: @@ -203,7 +203,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -213,11 +213,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -242,12 +244,11 @@ build_info: output: "target/nextflow/dataflow/split_h5mu" executable: "target/nextflow/dataflow/split_h5mu/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -277,7 +278,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/main.nf index cd0b56d..543ebc4 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/main.nf @@ -1,4 +1,4 @@ -// split_h5mu v3.0.0 +// split_h5mu v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "split_h5mu", "namespace" : "dataflow", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dorien Roosen", @@ -3285,7 +3285,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3299,11 +3299,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3340,13 +3341,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/dataflow/split_h5mu", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3371,7 +3371,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3908,7 +3908,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/dataflow/split_h5mu", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "lowcpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/nextflow.config index e035b8b..72e0c97 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'dataflow/split_h5mu' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Split the samples of a single modality from a .h5mu (multimodal) sample into seperate .h5mu files based on the values of an .obs column of this modality. \n' author = 'Dorien Roosen' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/.config.vsh.yaml index 7a475e7..e98b274 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "split_modalities" namespace: "dataflow" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -190,7 +190,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -200,11 +200,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -229,12 +231,11 @@ build_info: output: "target/nextflow/dataflow/split_modalities" executable: "target/nextflow/dataflow/split_modalities/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -264,7 +265,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/main.nf index c72923a..cbd9f52 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/main.nf @@ -1,4 +1,4 @@ -// split_modalities v3.0.0 +// split_modalities v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3036,7 +3036,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "split_modalities", "namespace" : "dataflow", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3280,7 +3280,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3294,11 +3294,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3335,13 +3336,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/dataflow/split_modalities", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3366,7 +3366,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3865,7 +3865,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/dataflow/split_modalities", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/nextflow.config index 1e03511..15a4d6b 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'dataflow/split_modalities' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Split the modalities from a single .h5mu multimodal sample into seperate .h5mu files. \n' author = 'Dries Schaumont, Robrecht Cannoodt' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_modalities/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_modalities/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/.config.vsh.yaml similarity index 95% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/.config.vsh.yaml index 0dbcd09..cab800a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "pca" namespace: "dimred" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -240,7 +240,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -250,12 +250,14 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "python" @@ -274,12 +276,11 @@ build_info: output: "target/nextflow/dimred/pca" executable: "target/nextflow/dimred/pca/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -309,7 +310,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/main.nf index 33b04b3..07a8b5d 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/main.nf @@ -1,4 +1,4 @@ -// pca v3.0.0 +// pca v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "pca", "namespace" : "dimred", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3333,7 +3333,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3347,12 +3347,13 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3379,13 +3380,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/dimred/pca", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3410,7 +3410,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3933,7 +3933,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/dimred/pca", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "highcpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/nextflow.config index aaf7758..59a4a55 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'dimred/pca' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Computes PCA coordinates, loadings and variance decomposition. Uses the implementation of scikit-learn [Pedregosa11].\n' author = 'Dries De Maeyer' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/pca/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/pca/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/.config.vsh.yaml similarity index 96% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/.config.vsh.yaml index 312bab8..32cdaa9 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "umap" namespace: "dimred" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -294,7 +294,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -304,12 +304,14 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "python" @@ -328,12 +330,11 @@ build_info: output: "target/nextflow/dimred/umap" executable: "target/nextflow/dimred/umap/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -363,7 +364,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/main.nf index 29e0ece..6e3e3fc 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/main.nf @@ -1,4 +1,4 @@ -// umap v3.0.0 +// umap v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "umap", "namespace" : "dimred", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3382,7 +3382,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3396,12 +3396,13 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3428,13 +3429,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/dimred/umap", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3459,7 +3459,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3971,7 +3971,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/dimred/umap", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "highcpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/nextflow.config index eaa7fb3..008fca3 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'dimred/umap' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'UMAP (Uniform Manifold Approximation and Projection) is a manifold learning technique suitable for visualizing high-dimensional data. Besides tending to be faster than tSNE, it optimizes the embedding such that it best reflects the topology of the data, which we represent throughout Scanpy using a neighborhood graph. tSNE, by contrast, optimizes the distribution of nearest-neighbor distances in the embedding such that these best match the distribution of distances in the high-dimensional space. We use the implementation of umap-learn [McInnes18]. For a few comparisons of UMAP with tSNE, see this preprint.\n' author = 'Dries De Maeyer' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dimred/umap/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dimred/umap/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/.config.vsh.yaml similarity index 96% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/.config.vsh.yaml index 92c9aae..ca1929b 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "highly_variable_features_scanpy" namespace: "feature_annotation" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -342,19 +342,21 @@ engines: id: "docker" image: "python:3.12" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" - "scikit-misc" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -379,12 +381,11 @@ build_info: output: "target/nextflow/feature_annotation/highly_variable_features_scanpy" executable: "target/nextflow/feature_annotation/highly_variable_features_scanpy/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -414,7 +415,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/main.nf index a83cf9f..064d717 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/main.nf @@ -1,4 +1,4 @@ -// highly_variable_features_scanpy v3.0.0 +// highly_variable_features_scanpy v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3036,7 +3036,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "highly_variable_features_scanpy", "namespace" : "feature_annotation", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3430,20 +3430,21 @@ meta = [ "id" : "docker", "image" : "python:3.12", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4", "scikit-misc" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3480,13 +3481,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/feature_annotation/highly_variable_features_scanpy", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3511,7 +3511,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -4110,7 +4110,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/feature_annotation/highly_variable_features_scanpy", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow.config index 805aab7..22968ac 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'feature_annotation/highly_variable_features_scanpy' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Annotate highly variable features [Satija15] [Zheng17] [Stuart19].\n\nExpects logarithmized data, except when flavor=\'seurat_v3\' in which count data is expected.\n\nDepending on flavor, this reproduces the R-implementations of Seurat [Satija15], Cell Ranger [Zheng17], and Seurat v3 [Stuart19].\n\nFor the dispersion-based methods ([Satija15] and [Zheng17]), the normalized dispersion is obtained by scaling with the mean and standard deviation of the dispersions for features falling into a given bin for mean expression of features. This means that for each bin of mean expression, highly variable features are selected.\n\nFor [Stuart19], a normalized variance for each feature is computed. First, the data are standardized (i.e., z-score normalization per feature) with a regularized standard deviation. Next, the normalized variance is computed as the variance of each feature after the transformation. Features are ranked by the normalized variance.\n' author = 'Dries De Maeyer, Robrecht Cannoodt' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/subset_vars.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/subset_vars.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/subset_vars.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/feature_annotation/highly_variable_features_scanpy/subset_vars.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/.config.vsh.yaml similarity index 95% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/.config.vsh.yaml index 216395b..6ef9b53 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "delimit_fraction" namespace: "filter" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -219,7 +219,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -229,11 +229,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -258,12 +260,11 @@ build_info: output: "target/nextflow/filter/delimit_fraction" executable: "target/nextflow/filter/delimit_fraction/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -293,7 +294,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/main.nf index af4c828..b098158 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/main.nf @@ -1,4 +1,4 @@ -// delimit_fraction v3.0.0 +// delimit_fraction v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "delimit_fraction", "namespace" : "filter", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3312,7 +3312,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3326,11 +3326,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3367,13 +3368,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/filter/delimit_fraction", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3398,7 +3398,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3928,7 +3928,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/filter/delimit_fraction", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/nextflow.config index c0a4ffe..6b0447a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'filter/delimit_fraction' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Turns a column containing values between 0 and 1 into a boolean column based on thresholds.\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/delimit_fraction/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/delimit_fraction/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/.config.vsh.yaml index 9b95f06..86bad07 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "do_filter" namespace: "filter" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Robrecht Cannoodt" roles: @@ -193,7 +193,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -203,11 +203,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "python" @@ -226,12 +228,11 @@ build_info: output: "target/nextflow/filter/do_filter" executable: "target/nextflow/filter/do_filter/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -261,7 +262,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/main.nf index f536ada..89c6758 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/main.nf @@ -1,4 +1,4 @@ -// do_filter v3.0.0 +// do_filter v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "do_filter", "namespace" : "filter", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Robrecht Cannoodt", @@ -3282,7 +3282,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3296,11 +3296,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3327,13 +3328,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/filter/do_filter", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3358,7 +3358,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3851,7 +3851,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/filter/do_filter", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/nextflow.config index 3f1e1a5..17c11f1 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'filter/do_filter' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Remove observations and variables based on specified .obs and .var columns.\n' author = 'Robrecht Cannoodt' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/do_filter/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/do_filter/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/.config.vsh.yaml index 2669e7f..089d6a4 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "filter_with_counts" namespace: "filter" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -280,7 +280,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -290,17 +290,25 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: + - type: "apt" + packages: + - "git" + interactive: false - type: "python" user: false packages: - "viashpy==0.8.0" + github: + - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" upgrade: true entrypoint: [] cmd: null @@ -313,12 +321,11 @@ build_info: output: "target/nextflow/filter/filter_with_counts" executable: "target/nextflow/filter/filter_with_counts/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -348,7 +355,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/main.nf similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/main.nf index fb7ae7f..0452c27 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/main.nf @@ -1,4 +1,4 @@ -// filter_with_counts v3.0.0 +// filter_with_counts v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3036,7 +3036,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "filter_with_counts", "namespace" : "filter", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3392,7 +3392,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3406,22 +3406,33 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } ], "test_setup" : [ + { + "type" : "apt", + "packages" : [ + "git" + ], + "interactive" : false + }, { "type" : "python", "user" : false, "packages" : [ "viashpy==0.8.0" ], + "github" : [ + "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" + ], "upgrade" : true } ] @@ -3437,13 +3448,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/filter/filter_with_counts", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3468,7 +3478,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3500,6 +3510,7 @@ import mudata as mu import numpy as np import sys from operator import le, ge, gt +import scipy ### VIASH START # The following code has been auto-generated by Viash. @@ -3555,10 +3566,22 @@ modality_data = mu.read_h5ad(par["input"], mod=par["modality"]) logger.info("\\\\tUnfiltered data: %s", modality_data) -logger.info("Selecting input layer %s", "X" if par["layer"] else par["layer"]) +layer_name = "X" if not par["layer"] else par["layer"] +logger.info("Selecting input layer %s", layer_name) input_layer = ( modality_data.X if not par["layer"] else modality_data.layers[par["layer"]] ) +if scipy.sparse.issparse(input_layer): + # Below is a check that scipy does not do with check_format; see https://github.com/scipy/scipy/issues/23784 + # also, check_format might adjust the matrix attributes in place; so do this check before check_format + + assert input_layer.nnz == input_layer.data.size, ( + f"The provided sparse matrix (i.e. {layer_name} from modality {par['modality']}) is malformatted. " + f"The number of elements that the matrix should hold (i.e. .nnz={input_layer.nnz}) does not correspond with " + f"the number of elements actually being stored (i.e. .data.size={input_layer.data.size})" + ) + input_layer.check_format(full_check=True) + logger.info("\\\\tComputing aggregations.") n_counts_per_cell = np.ravel(np.sum(input_layer, axis=1)) @@ -4027,7 +4050,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/filter/filter_with_counts", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/nextflow.config index 53cf9b9..6732015 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'filter/filter_with_counts' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Filter scRNA-seq data based on the primary QC metrics. \nThis is based on both the UMI counts, the gene counts \nand the mitochondrial genes (genes starting with mt/MT).\n' author = 'Dries De Maeyer, Robrecht Cannoodt' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_counts/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_counts/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/.config.vsh.yaml similarity index 96% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/.config.vsh.yaml index d78e102..c8c0a7a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "filter_with_scrublet" namespace: "filter" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -331,9 +331,9 @@ runners: engines: - type: "docker" id: "docker" - image: "python:3.10-slim" + image: "python:3.13-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -344,14 +344,16 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" - "scrublet" - "annoy==1.17.3" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -376,12 +378,11 @@ build_info: output: "target/nextflow/filter/filter_with_scrublet" executable: "target/nextflow/filter/filter_with_scrublet/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -411,7 +412,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/main.nf index 6ce2f64..c1bc139 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/main.nf @@ -1,4 +1,4 @@ -// filter_with_scrublet v3.0.0 +// filter_with_scrublet v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3036,7 +3036,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "filter_with_scrublet", "namespace" : "filter", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3427,9 +3427,9 @@ meta = [ { "type" : "docker", "id" : "docker", - "image" : "python:3.10-slim", + "image" : "python:3.13-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3444,14 +3444,15 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4", "scrublet", "annoy==1.17.3" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3488,13 +3489,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/filter/filter_with_scrublet", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3519,7 +3519,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -4065,7 +4065,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/filter/filter_with_scrublet", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "highcpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/nextflow.config index 89e0b6b..dd320d5 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'filter/filter_with_scrublet' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Doublet detection using the Scrublet method (Wolock, Lopez and Klein, 2019).\nThe method tests for potential doublets by using the expression profiles of\ncells to generate synthetic potential doubles which are tested against cells. \nThe method returns a "doublet score" on which it calls for potential doublets.\n\nFor the source code please visit https://github.com/AllonKleinLab/scrublet.\n\nFor 10x we expect the doublet rates to be:\n Multiplet Rate (%) - # of Cells Loaded - # of Cells Recovered\n ~0.4% ~800 ~500\n ~0.8% ~1,600 ~1,000\n ~1.6% ~3,200 ~2,000\n ~2.3% ~4,800 ~3,000\n ~3.1% ~6,400 ~4,000\n ~3.9% ~8,000 ~5,000\n ~4.6% ~9,600 ~6,000\n ~5.4% ~11,200 ~7,000\n ~6.1% ~12,800 ~8,000\n ~6.9% ~14,400 ~9,000\n ~7.6% ~16,000 ~10,000\n' author = 'Dries De Maeyer, Robrecht Cannoodt' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/filter/filter_with_scrublet/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/filter/filter_with_scrublet/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/.config.vsh.yaml index da76554..5de843a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "add_id" namespace: "metadata" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -185,7 +185,7 @@ engines: id: "docker" image: "python:3.11-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -195,11 +195,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -224,12 +226,11 @@ build_info: output: "target/nextflow/metadata/add_id" executable: "target/nextflow/metadata/add_id/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -259,7 +260,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/main.nf index b73f113..37499a0 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/main.nf @@ -1,4 +1,4 @@ -// add_id v3.0.0 +// add_id v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "add_id", "namespace" : "metadata", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3269,7 +3269,7 @@ meta = [ "id" : "docker", "image" : "python:3.11-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3283,11 +3283,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3324,13 +3325,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/metadata/add_id", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3355,7 +3355,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3871,7 +3871,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/metadata/add_id", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/nextflow.config index 3701e08..01e0efb 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'metadata/add_id' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Add id of .obs. Also allows to make .obs_names (the .obs index) unique \nby prefixing the values with an unique id per .h5mu file.\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/add_id/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/add_id/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/.config.vsh.yaml similarity index 95% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/.config.vsh.yaml index 7bbe0e1..9ab246a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "grep_annotation_column" namespace: "metadata" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -241,7 +241,7 @@ engines: id: "docker" image: "python:3.11-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -251,11 +251,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -280,12 +282,11 @@ build_info: output: "target/nextflow/metadata/grep_annotation_column" executable: "target/nextflow/metadata/grep_annotation_column/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -315,7 +316,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/main.nf index 8718d4d..665edca 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/main.nf @@ -1,4 +1,4 @@ -// grep_annotation_column v3.0.0 +// grep_annotation_column v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "grep_annotation_column", "namespace" : "metadata", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3335,7 +3335,7 @@ meta = [ "id" : "docker", "image" : "python:3.11-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3349,11 +3349,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3390,13 +3391,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/metadata/grep_annotation_column", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3421,7 +3421,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -4010,7 +4010,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/metadata/grep_annotation_column", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/nextflow.config index 91378a5..5d333ac 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'metadata/grep_annotation_column' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Perform a regex lookup on a column from the annotation matrices .obs or .var.\nThe annotation matrix can originate from either a modality, or all modalities (global .var or .obs).\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/grep_annotation_column/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/grep_annotation_column/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/.config.vsh.yaml index 3561b20..10676ed 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "move_obsm_to_obs" namespace: "metadata" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -183,7 +183,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -193,11 +193,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -222,12 +224,11 @@ build_info: output: "target/nextflow/metadata/move_obsm_to_obs" executable: "target/nextflow/metadata/move_obsm_to_obs/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -257,7 +258,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/main.nf index e060e28..2d61de8 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/main.nf @@ -1,4 +1,4 @@ -// move_obsm_to_obs v3.0.0 +// move_obsm_to_obs v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "move_obsm_to_obs", "namespace" : "metadata", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3268,7 +3268,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3282,11 +3282,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3323,13 +3324,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/metadata/move_obsm_to_obs", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3354,7 +3354,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3860,7 +3860,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/metadata/move_obsm_to_obs", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/nextflow.config index 5a0bf12..f76bc54 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'metadata/move_obsm_to_obs' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Move a matrix from .obsm to .obs. Newly created columns in .obs will \nbe created from the .obsm key suffixed with an underscore and the name of the columns\nof the specified .obsm matrix.\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/metadata/move_obsm_to_obs/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/metadata/move_obsm_to_obs/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/.config.vsh.yaml similarity index 95% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/.config.vsh.yaml index 8a2acda..4ca02d7 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "find_neighbors" namespace: "neighbors" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -296,7 +296,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -306,12 +306,14 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -336,12 +338,11 @@ build_info: output: "target/nextflow/neighbors/find_neighbors" executable: "target/nextflow/neighbors/find_neighbors/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -371,7 +372,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/main.nf index 4304dcc..a074833 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/main.nf @@ -1,4 +1,4 @@ -// find_neighbors v3.0.0 +// find_neighbors v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3036,7 +3036,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "find_neighbors", "namespace" : "neighbors", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3395,7 +3395,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3409,12 +3409,13 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3451,13 +3452,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/neighbors/find_neighbors", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3482,7 +3482,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3983,7 +3983,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/neighbors/find_neighbors", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "lowcpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/nextflow.config index ffd620f..c79a63e 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'neighbors/find_neighbors' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Compute a neighborhood graph of observations [McInnes18].\n\nThe neighbor search efficiency of this heavily relies on UMAP [McInnes18], which also provides a method for estimating connectivities of data points - the connectivity of the manifold (method==\'umap\'). If method==\'gauss\', connectivities are computed according to [Coifman05], in the adaption of [Haghverdi16].\n' author = 'Dries De Maeyer, Robrecht Cannoodt' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/neighbors/find_neighbors/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/neighbors/find_neighbors/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/.config.vsh.yaml similarity index 96% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/.config.vsh.yaml index b783354..1656546 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "calculate_qc_metrics" namespace: "qc" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -295,7 +295,7 @@ engines: id: "docker" image: "python:3.11-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -305,12 +305,14 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" - "scipy" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -340,12 +342,11 @@ build_info: output: "target/nextflow/qc/calculate_qc_metrics" executable: "target/nextflow/qc/calculate_qc_metrics/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -375,7 +376,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/main.nf index 0c87391..d5e8075 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/main.nf @@ -1,4 +1,4 @@ -// calculate_qc_metrics v3.0.0 +// calculate_qc_metrics v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "calculate_qc_metrics", "namespace" : "qc", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3381,7 +3381,7 @@ meta = [ "id" : "docker", "image" : "python:3.11-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3395,12 +3395,13 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", "scipy" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3445,13 +3446,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/qc/calculate_qc_metrics", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3476,7 +3476,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -4107,7 +4107,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/qc/calculate_qc_metrics", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "singlecpu", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/nextflow.config index 5529ec7..e002241 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'qc/calculate_qc_metrics' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Add basic quality control metrics to an .h5mu file.\n\nThe metrics are comparable to what scanpy.pp.calculate_qc_metrics output,\nalthough they have slightly different names:\n\nVar metrics (name in this component -> name in scanpy):\n - pct_dropout -> pct_dropout_by_{expr_type}\n - num_nonzero_obs -> n_cells_by_{expr_type}\n - obs_mean -> mean_{expr_type}\n - total_counts -> total_{expr_type}\n\n Obs metrics:\n - num_nonzero_vars -> n_genes_by_{expr_type}\n - pct_{var_qc_metrics} -> pct_{expr_type}_{qc_var}\n - total_counts_{var_qc_metrics} -> total_{expr_type}_{qc_var}\n - pct_of_counts_in_top_{top_n_vars}_vars -> pct_{expr_type}_in_top_{n}_{var_type}\n - total_counts -> total_{expr_type}\n \n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/qc/calculate_qc_metrics/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/qc/calculate_qc_metrics/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/.config.vsh.yaml similarity index 93% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/.config.vsh.yaml index 12623a9..cf57ba3 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "clr" namespace: "transform" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -137,6 +137,7 @@ runners: label: - "lowmem" - "midcpu" + - "middisk" tag: "$id" auto: simplifyInput: true @@ -200,9 +201,9 @@ runners: engines: - type: "docker" id: "docker" - image: "python:3.10-slim" + image: "python:3.13-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -212,13 +213,15 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" - - "muon~=0.1.5" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" + - "muon~=0.1.7" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "python" @@ -237,12 +240,11 @@ build_info: output: "target/nextflow/transform/clr" executable: "target/nextflow/transform/clr/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -272,7 +274,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/main.nf index f426bdf..59b623b 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/main.nf @@ -1,4 +1,4 @@ -// clr v3.0.0 +// clr v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "clr", "namespace" : "transform", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3213,7 +3213,8 @@ meta = [ "directives" : { "label" : [ "lowmem", - "midcpu" + "midcpu", + "middisk" ], "tag" : "$id" }, @@ -3286,9 +3287,9 @@ meta = [ { "type" : "docker", "id" : "docker", - "image" : "python:3.10-slim", + "image" : "python:3.13-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3302,13 +3303,14 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4", - "muon~=0.1.5" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4", + "muon~=0.1.7" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3335,13 +3337,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/transform/clr", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3366,7 +3367,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3852,11 +3853,12 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/transform/clr", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "lowmem", - "midcpu" + "midcpu", + "middisk" ], "tag" : "$id" }'''), diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/nextflow.config index e7d8be0..06b1823 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'transform/clr' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Perform CLR normalization on CITE-seq data (Stoeckius et al., 2017).\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/clr/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/clr/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/.config.vsh.yaml index a05efc2..c4417a5 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "delete_layer" namespace: "transform" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -186,7 +186,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -196,11 +196,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -225,12 +227,11 @@ build_info: output: "target/nextflow/transform/delete_layer" executable: "target/nextflow/transform/delete_layer/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -260,7 +261,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/main.nf index ac3869c..dad9409 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/main.nf @@ -1,4 +1,4 @@ -// delete_layer v3.0.0 +// delete_layer v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "delete_layer", "namespace" : "transform", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3273,7 +3273,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3287,11 +3287,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3328,13 +3329,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/transform/delete_layer", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3359,7 +3359,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3844,7 +3844,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/transform/delete_layer", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "midmem", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/nextflow.config index 4b820cb..ac515ab 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'transform/delete_layer' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Delete an anndata layer from one or more modalities.\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/delete_layer/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/delete_layer/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/.config.vsh.yaml index 7b31838..194c1d9 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "log1p" namespace: "transform" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -151,6 +151,7 @@ runners: label: - "midmem" - "lowcpu" + - "highdisk" tag: "$id" auto: simplifyInput: true @@ -216,7 +217,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -226,12 +227,14 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "python" @@ -250,12 +253,11 @@ build_info: output: "target/nextflow/transform/log1p" executable: "target/nextflow/transform/log1p/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -285,7 +287,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/main.nf index f22350e..17268a9 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/main.nf @@ -1,4 +1,4 @@ -// log1p v3.0.0 +// log1p v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3036,7 +3036,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "log1p", "namespace" : "transform", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3240,7 +3240,8 @@ meta = [ "directives" : { "label" : [ "midmem", - "lowcpu" + "lowcpu", + "highdisk" ], "tag" : "$id" }, @@ -3315,7 +3316,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3329,12 +3330,13 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3361,13 +3363,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/transform/log1p", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3392,7 +3393,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3878,11 +3879,12 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/transform/log1p", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "midmem", - "lowcpu" + "lowcpu", + "highdisk" ], "tag" : "$id" }'''), diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/nextflow.config index da80aa7..d3c172a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'transform/log1p' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Logarithmize the data matrix. Computes X = log(X + 1), where log denotes the natural logarithm unless a different base is given.\n' author = 'Dries De Maeyer, Robrecht Cannoodt' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/log1p/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/setup_logger.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/log1p/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/.config.vsh.yaml similarity index 95% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/.config.vsh.yaml index c2afe73..eebbda2 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "normalize_total" namespace: "transform" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -163,6 +163,7 @@ runners: label: - "midmem" - "lowcpu" + - "highdisk" tag: "$id" auto: simplifyInput: true @@ -228,7 +229,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -238,12 +239,14 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -268,12 +271,11 @@ build_info: output: "target/nextflow/transform/normalize_total" executable: "target/nextflow/transform/normalize_total/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -303,7 +305,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/main.nf index 4378e56..100078f 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/main.nf @@ -1,4 +1,4 @@ -// normalize_total v3.0.0 +// normalize_total v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3036,7 +3036,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "normalize_total", "namespace" : "transform", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3243,7 +3243,8 @@ meta = [ "directives" : { "label" : [ "midmem", - "lowcpu" + "lowcpu", + "highdisk" ], "tag" : "$id" }, @@ -3318,7 +3319,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3332,12 +3333,13 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3374,13 +3376,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/transform/normalize_total", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3405,7 +3406,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3895,11 +3896,12 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/transform/normalize_total", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "midmem", - "lowcpu" + "lowcpu", + "highdisk" ], "tag" : "$id" }'''), diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/nextflow.config index 4d597d6..c288337 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'transform/normalize_total' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Normalize counts per cell.\n\nNormalize each cell by total counts over all genes, so that every cell has the same total count after normalization. If choosing target_sum=1e6, this is CPM normalization.\n\nIf exclude_highly_expressed=True, very highly expressed genes are excluded from the computation of the normalization factor (size factor) for each cell. This is meaningful as these can strongly influence the resulting normalized values for all other genes [Weinreb17].\n' author = 'Dries De Maeyer, Robrecht Cannoodt' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/normalize_total/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/nextflow_schema.json diff --git a/target/executable/dataflow/concatenate_h5mu/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/setup_logger.py similarity index 100% rename from target/executable/dataflow/concatenate_h5mu/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/normalize_total/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/.config.vsh.yaml similarity index 94% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/.config.vsh.yaml index 7c2bf31..11a004b 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "scale" namespace: "transform" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -204,7 +204,7 @@ engines: id: "docker" image: "python:3.12-slim" target_registry: "images.viash-hub.com" - target_tag: "v3.0.0" + target_tag: "v4.0.0" namespace_separator: "/" setup: - type: "apt" @@ -214,12 +214,14 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "scanpy~=1.10.4" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.11.4" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -244,12 +246,11 @@ build_info: output: "target/nextflow/transform/scale" executable: "target/nextflow/transform/scale/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -279,7 +280,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/compress_h5mu.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/compress_h5mu.py similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/compress_h5mu.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/compress_h5mu.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/main.nf index 51b7157..f3a1de8 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/main.nf @@ -1,4 +1,4 @@ -// scale v3.0.0 +// scale v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "scale", "namespace" : "transform", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3291,7 +3291,7 @@ meta = [ "id" : "docker", "image" : "python:3.12-slim", "target_registry" : "images.viash-hub.com", - "target_tag" : "v3.0.0", + "target_tag" : "v4.0.0", "namespace_separator" : "/", "setup" : [ { @@ -3305,12 +3305,13 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "scanpy~=1.10.4" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.11.4" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3347,13 +3348,12 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/transform/scale", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3378,7 +3378,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3873,7 +3873,7 @@ meta["defaults"] = [ "container" : { "registry" : "images.viash-hub.com", "image" : "vsh/openpipeline/transform/scale", - "tag" : "v3.0.0" + "tag" : "v4.0.0" }, "label" : [ "lowmem", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/nextflow.config index 6334300..1a7adc0 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'transform/scale' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Scale data to unit variance and zero mean.\n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/transform/scale/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/nextflow_schema.json diff --git a/target/nextflow/dataflow/concatenate_h5mu/setup_logger.py b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/setup_logger.py similarity index 100% rename from target/nextflow/dataflow/concatenate_h5mu/setup_logger.py rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/transform/scale/setup_logger.py diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/.config.vsh.yaml similarity index 97% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/.config.vsh.yaml index 18ab9d6..f19db40 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "gdo_singlesample" namespace: "workflows/gdo" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -225,15 +225,14 @@ build_info: output: "target/nextflow/workflows/gdo/gdo_singlesample" executable: "target/nextflow/workflows/gdo/gdo_singlesample/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/filter/filter_with_counts" - "target/nextflow/filter/do_filter" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -263,7 +262,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/main.nf index ba1da68..e9b71c3 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/main.nf @@ -1,4 +1,4 @@ -// gdo_singlesample v3.0.0 +// gdo_singlesample v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "gdo_singlesample", "namespace" : "workflows/gdo", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3327,13 +3327,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/gdo/gdo_singlesample", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3358,7 +3357,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow.config index e429467..4851e48 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/gdo/gdo_singlesample' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Processing unimodal single-sample guide-derived oligonucleotide (GDO) data.' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/gdo/gdo_singlesample/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/.config.vsh.yaml similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/.config.vsh.yaml index 7debcce..0c82a5a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "dimensionality_reduction" namespace: "workflows/multiomics" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -278,15 +278,14 @@ build_info: output: "target/nextflow/workflows/multiomics/dimensionality_reduction" executable: "target/nextflow/workflows/multiomics/dimensionality_reduction/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/dimred/pca" - "target/nextflow/workflows/multiomics/neighbors_leiden_umap" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -316,7 +315,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/main.nf index ac64ec9..cd8c1ef 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/main.nf @@ -1,4 +1,4 @@ -// dimensionality_reduction v3.0.0 +// dimensionality_reduction v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "dimensionality_reduction", "namespace" : "workflows/multiomics", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3390,13 +3390,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/multiomics/dimensionality_reduction", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3421,7 +3420,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow.config index 82425a1..86befac 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/multiomics/dimensionality_reduction' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Run calculations that output information required for most integration methods: PCA, nearest neighbour and UMAP.' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/dimensionality_reduction/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/.config.vsh.yaml similarity index 97% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/.config.vsh.yaml index 0fa2065..59ee718 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "neighbors_leiden_umap" namespace: "workflows/multiomics" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -234,9 +234,8 @@ build_info: output: "target/nextflow/workflows/multiomics/neighbors_leiden_umap" executable: "target/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/cluster/leiden" - "target/nextflow/dimred/umap" @@ -244,7 +243,7 @@ build_info: - "target/nextflow/metadata/move_obsm_to_obs" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -274,7 +273,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf index c604705..0f94630 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf @@ -1,4 +1,4 @@ -// neighbors_leiden_umap v3.0.0 +// neighbors_leiden_umap v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "neighbors_leiden_umap", "namespace" : "workflows/multiomics", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3331,13 +3331,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/multiomics/neighbors_leiden_umap", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3362,7 +3361,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow.config index c1f7c15..0469f20 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/multiomics/neighbors_leiden_umap' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Performs neighborhood search, leiden clustering and run umap on an integrated embedding.' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/.config.vsh.yaml similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/.config.vsh.yaml index efd777b..2edfafa 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "process_batches" namespace: "workflows/multiomics" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -380,9 +380,8 @@ build_info: output: "target/nextflow/workflows/multiomics/process_batches" executable: "target/nextflow/workflows/multiomics/process_batches/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/dataflow/merge" - "target/_private/nextflow/workflows/multiomics/split_modalities" @@ -393,7 +392,7 @@ build_info: - "target/nextflow/workflows/multiomics/dimensionality_reduction" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -423,7 +422,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/main.nf index 73f18ed..379df74 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/main.nf @@ -1,4 +1,4 @@ -// process_batches v3.0.0 +// process_batches v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "process_batches", "namespace" : "workflows/multiomics", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3513,13 +3513,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/multiomics/process_batches", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3544,7 +3543,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/nextflow.config index 013fd8b..feff87c 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/multiomics/process_batches' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'This workflow serves as an entrypoint into the \'full_pipeline\' in order to\nre-run the multisample processing and the integration setup. An input .h5mu file will \nfirst be split in order to run the multisample processing per modality. Next, the modalities\nare merged again and the integration setup pipeline is executed. Please note that this workflow\nassumes that samples from multiple pipelines are already concatenated. \n' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_batches/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_batches/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/.config.vsh.yaml similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/.config.vsh.yaml index 37cc7cc..68b70f6 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "process_samples" namespace: "workflows/multiomics" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -601,6 +601,8 @@ info: namespace: "transform" - name: "remove_modality" namespace: "filter" + - name: "assert_test_workflow_2_output" + namespace: "test_workflows/multiomics/process_samples" status: "enabled" scope: image: "public" @@ -709,9 +711,8 @@ build_info: output: "target/nextflow/workflows/multiomics/process_samples" executable: "target/nextflow/workflows/multiomics/process_samples/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/metadata/add_id" - "target/_private/nextflow/workflows/multiomics/split_modalities" @@ -723,7 +724,7 @@ build_info: - "target/nextflow/workflows/multiomics/process_batches" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -753,7 +754,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/main.nf index ba70286..a35e97a 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/main.nf @@ -1,4 +1,4 @@ -// process_samples v3.0.0 +// process_samples v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "process_samples", "namespace" : "workflows/multiomics", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3764,6 +3764,10 @@ meta = [ { "name" : "remove_modality", "namespace" : "filter" + }, + { + "name" : "assert_test_workflow_2_output", + "namespace" : "test_workflows/multiomics/process_samples" } ] }, @@ -3912,13 +3916,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/multiomics/process_samples", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3943,7 +3946,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/nextflow.config index 4842f7c..17b39a5 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/multiomics/process_samples' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'A pipeline to analyse multiple multiomics samples.' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/.config.vsh.yaml similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/.config.vsh.yaml index 5eee348..be61720 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "prot_multisample" namespace: "workflows/prot" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -284,15 +284,14 @@ build_info: output: "target/nextflow/workflows/prot/prot_multisample" executable: "target/nextflow/workflows/prot/prot_multisample/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/transform/clr" - "target/nextflow/workflows/qc/qc" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -322,7 +321,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/main.nf index 8ca52d9..c1be081 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/main.nf @@ -1,4 +1,4 @@ -// prot_multisample v3.0.0 +// prot_multisample v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "prot_multisample", "namespace" : "workflows/prot", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3384,13 +3384,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/prot/prot_multisample", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3415,7 +3414,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/nextflow.config index 551701b..f3bf4b5 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/prot/prot_multisample' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Processing unimodal multi-sample ADT data.' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_multisample/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_multisample/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/.config.vsh.yaml similarity index 97% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/.config.vsh.yaml index 006cc1b..533c8bf 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "prot_singlesample" namespace: "workflows/prot" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -255,15 +255,14 @@ build_info: output: "target/nextflow/workflows/prot/prot_singlesample" executable: "target/nextflow/workflows/prot/prot_singlesample/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/filter/filter_with_counts" - "target/nextflow/filter/do_filter" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -293,7 +292,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/main.nf index 9fcde69..7cc6b23 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/main.nf @@ -1,4 +1,4 @@ -// prot_singlesample v3.0.0 +// prot_singlesample v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3037,7 +3037,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "prot_singlesample", "namespace" : "workflows/prot", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3378,13 +3378,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/prot/prot_singlesample", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3409,7 +3408,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/nextflow.config index a13d68a..7dc56ca 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/prot/prot_singlesample' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Processing unimodal single-sample CITE-seq data.' author = 'Dries De Maeyer, Robrecht Cannoodt, Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/prot/prot_singlesample/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/prot/prot_singlesample/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/.config.vsh.yaml similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/.config.vsh.yaml index 6483bda..f6268a3 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "qc" namespace: "workflows/qc" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries Schaumont" roles: @@ -364,15 +364,14 @@ build_info: output: "target/nextflow/workflows/qc/qc" executable: "target/nextflow/workflows/qc/qc/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/metadata/grep_annotation_column" - "target/nextflow/qc/calculate_qc_metrics" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -402,7 +401,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/main.nf index b68e58b..53db6d5 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/main.nf @@ -1,4 +1,4 @@ -// qc v3.0.0 +// qc v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3035,7 +3035,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "qc", "namespace" : "workflows/qc", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries Schaumont", @@ -3471,13 +3471,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/qc/qc", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3502,7 +3501,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/nextflow.config index c9b994e..d9abf28 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/qc/qc' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'A pipeline to add basic qc statistics to a MuData ' author = 'Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/.config.vsh.yaml similarity index 96% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/.config.vsh.yaml index 50e0c4e..ce7fb90 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "rna_multisample" namespace: "workflows/rna" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -328,12 +328,6 @@ scope: image: "public" target: "public" dependencies: -- name: "transform/normalize_total" - repository: - type: "local" -- name: "transform/log1p" - repository: - type: "local" - name: "feature_annotation/highly_variable_features_scanpy" repository: type: "local" @@ -341,15 +335,15 @@ dependencies: alias: "rna_qc" repository: type: "local" -- name: "transform/delete_layer" - repository: - type: "local" - name: "metadata/add_id" repository: type: "local" - name: "transform/scale" repository: type: "local" +- name: "workflows/rna/log_normalize" + repository: + type: "local" license: "MIT" links: repository: "https://github.com/openpipelines-bio/openpipeline" @@ -428,20 +422,17 @@ build_info: output: "target/nextflow/workflows/rna/rna_multisample" executable: "target/nextflow/workflows/rna/rna_multisample/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - - "target/nextflow/transform/normalize_total" - - "target/nextflow/transform/log1p" - "target/nextflow/feature_annotation/highly_variable_features_scanpy" - "target/nextflow/workflows/qc/qc" - - "target/nextflow/transform/delete_layer" - "target/nextflow/metadata/add_id" - "target/nextflow/transform/scale" + - "target/_private/nextflow/workflows/rna/log_normalize" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -471,7 +462,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/main.nf similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/main.nf index 64a3604..cd3e212 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/main.nf @@ -1,4 +1,4 @@ -// rna_multisample v3.0.0 +// rna_multisample v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3037,7 +3037,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "rna_multisample", "namespace" : "workflows/rna", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3436,18 +3436,6 @@ meta = [ "target" : "public" }, "dependencies" : [ - { - "name" : "transform/normalize_total", - "repository" : { - "type" : "local" - } - }, - { - "name" : "transform/log1p", - "repository" : { - "type" : "local" - } - }, { "name" : "feature_annotation/highly_variable_features_scanpy", "repository" : { @@ -3461,12 +3449,6 @@ meta = [ "type" : "local" } }, - { - "name" : "transform/delete_layer", - "repository" : { - "type" : "local" - } - }, { "name" : "metadata/add_id", "repository" : { @@ -3478,6 +3460,12 @@ meta = [ "repository" : { "type" : "local" } + }, + { + "name" : "workflows/rna/log_normalize", + "repository" : { + "type" : "local" + } } ], "license" : "MIT", @@ -3569,13 +3557,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/rna/rna_multisample", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3600,7 +3587,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", @@ -3621,14 +3608,12 @@ meta = [ // resolve dependencies dependencies (if any) meta["root_dir"] = getRootDir() -include { normalize_total } from "${meta.resources_dir}/../../../../nextflow/transform/normalize_total/main.nf" -include { log1p } from "${meta.resources_dir}/../../../../nextflow/transform/log1p/main.nf" include { highly_variable_features_scanpy } from "${meta.resources_dir}/../../../../nextflow/feature_annotation/highly_variable_features_scanpy/main.nf" include { qc as rna_qc_viashalias } from "${meta.resources_dir}/../../../../nextflow/workflows/qc/qc/main.nf" rna_qc = rna_qc_viashalias.run(key: "rna_qc") -include { delete_layer } from "${meta.resources_dir}/../../../../nextflow/transform/delete_layer/main.nf" include { add_id } from "${meta.resources_dir}/../../../../nextflow/metadata/add_id/main.nf" include { scale } from "${meta.resources_dir}/../../../../nextflow/transform/scale/main.nf" +include { log_normalize } from "${meta.resources_dir}/../../../../_private/nextflow/workflows/rna/log_normalize/main.nf" // inner workflow // user-provided Nextflow code @@ -3642,37 +3627,16 @@ workflow run_wf { def new_state = state + ["workflow_output": state.output] [id, new_state] } - | normalize_total.run( - fromState: { id, state -> - [ - "input": state.input, - "input_layer": state.layer, - "output_layer": "normalized", - "modality": state.modality - ] - }, - toState: ["input": "output"], - ) - | log1p.run( - fromState: { id, state -> - [ - "input": state.input, - "output_layer": "log_normalized", - "input_layer": "normalized", - "modality": state.modality - ] - }, - toState: ["input": "output"] - ) - | delete_layer.run( - fromState: {id, state -> - [ - "input": state.input, - "layer": "normalized", - "modality": state.modality - ] - }, - toState: ["input": "output"] + | log_normalize.run( + args: ["output_layer": "log_normalized"], + fromState: [ + "input": "input", + "layer": "layer", + "modality": "modality" + ], + toState: [ + "input": "output" + ] ) | scale.run( runIf: {id, state -> state.enable_scaling}, diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/nextflow.config index ddc58d7..3618c96 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/rna/rna_multisample' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Processing unimodal multi-sample RNA transcriptomics data.' author = 'Dries De Maeyer, Robrecht Cannoodt, Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/nextflow_labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/nextflow_labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_multisample/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/utils/errorstrat_ignore.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/utils/errorstrat_ignore.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/utils/errorstrat_ignore.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/utils/integration_tests.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/utils/integration_tests.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/utils/integration_tests.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/utils/labels.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/utils/labels.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/utils/labels_ci.config similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels_ci.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_multisample/utils/labels_ci.config diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/.config.vsh.yaml b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/.config.vsh.yaml similarity index 98% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/.config.vsh.yaml rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/.config.vsh.yaml index 9980e18..7c11375 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/.config.vsh.yaml +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/.config.vsh.yaml @@ -1,6 +1,6 @@ name: "rna_singlesample" namespace: "workflows/rna" -version: "v3.0.0" +version: "v4.0.0" authors: - name: "Dries De Maeyer" roles: @@ -396,9 +396,8 @@ build_info: output: "target/nextflow/workflows/rna/rna_singlesample" executable: "target/nextflow/workflows/rna/rna_singlesample/main.nf" viash_version: "0.9.4" - git_commit: "e92e56b49125af8ef2ebb11586191a6cbf9a8457" + git_commit: "de02293c9e13198622b988dac952b2c8c70a1e35" git_remote: "https://github.com/openpipelines-bio/openpipeline" - git_tag: "0.2.0-2059-ge92e56b4" dependencies: - "target/nextflow/filter/filter_with_counts" - "target/nextflow/filter/filter_with_scrublet" @@ -407,7 +406,7 @@ build_info: - "target/nextflow/workflows/qc/qc" package_config: name: "openpipeline" - version: "v3.0.0" + version: "v4.0.0" summary: "Best-practice workflows for single-cell multi-omics analyses.\n" description: "OpenPipelines are extensible single cell analysis pipelines for reproducible\ \ and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\ @@ -437,7 +436,7 @@ package_config: )'" - ".engines += { type: \"native\" }" - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + - ".engines[.type == 'docker'].target_tag := 'v4.0.0'" keywords: - "single-cell" - "multimodal" diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/main.nf b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/main.nf similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/main.nf rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/main.nf index ced752f..039779e 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/main.nf +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/main.nf @@ -1,4 +1,4 @@ -// rna_singlesample v3.0.0 +// rna_singlesample v4.0.0 // // This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative // work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -3037,7 +3037,7 @@ meta = [ "config": processConfig(readJsonBlob('''{ "name" : "rna_singlesample", "namespace" : "workflows/rna", - "version" : "v3.0.0", + "version" : "v4.0.0", "authors" : [ { "name" : "Dries De Maeyer", @@ -3541,13 +3541,12 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/rna/rna_singlesample", "viash_version" : "0.9.4", - "git_commit" : "e92e56b49125af8ef2ebb11586191a6cbf9a8457", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline", - "git_tag" : "0.2.0-2059-ge92e56b4" + "git_commit" : "de02293c9e13198622b988dac952b2c8c70a1e35", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline" }, "package_config" : { "name" : "openpipeline", - "version" : "v3.0.0", + "version" : "v4.0.0", "summary" : "Best-practice workflows for single-cell multi-omics analyses.\n", "description" : "OpenPipelines are extensible single cell analysis pipelines for reproducible and large-scale single cell processing using [Viash](https://viash.io) and [Nextflow](https://www.nextflow.io/).\n\nIn terms of workflows, the following has been made available, but keep in mind that\nindividual tools and functionality can be executed as standalone components as well.\n\n * Demultiplexing: conversion of raw sequencing data to FASTQ objects.\n * Ingestion: Read mapping and generating a count matrix.\n * Single sample processing: cell filtering and doublet detection.\n * Multisample processing: Count transformation, normalization, QC metric calulations.\n * Integration: Clustering, integration and batch correction using single and multimodal methods.\n * Downstream analysis workflows\n", "info" : { @@ -3572,7 +3571,7 @@ meta = [ ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", ".engines += { type: \\"native\\" }", ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'v3.0.0'" + ".engines[.type == 'docker'].target_tag := 'v4.0.0'" ], "keywords" : [ "single-cell", diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/nextflow.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/nextflow.config similarity index 99% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/nextflow.config rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/nextflow.config index 77574d9..2cc9f1c 100644 --- a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/nextflow.config +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/nextflow.config @@ -2,7 +2,7 @@ manifest { name = 'workflows/rna/rna_singlesample' mainScript = 'main.nf' nextflowVersion = '!>=20.12.1-edge' - version = 'v3.0.0' + version = 'v4.0.0' description = 'Processing unimodal single-sample RNA transcriptomics data.' author = 'Dries De Maeyer, Robrecht Cannoodt, Dries Schaumont' } diff --git a/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_labels.config new file mode 100644 index 0000000..94570ec --- /dev/null +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_labels.config @@ -0,0 +1,48 @@ +process { + // Default resources for components that hardly do any processing + memory = { 2.GB * task.attempt } + cpus = 1 + + // Retry for exit codes that have something to do with memory issues + errorStrategy = { task.exitStatus in 137..140 ? 'retry' : 'terminate' } + maxRetries = 3 + + // The memory a task is assinged increases with each attempt + // uncomment the line below and adjust the value to set a global upper limit on the memory. + // resourceLimits = [ memory: 240.Gb ] + + // CPU resources + withLabel: singlecpu { cpus = 1 } + withLabel: lowcpu { cpus = 4 } + withLabel: midcpu { cpus = 10 } + withLabel: highcpu { cpus = 20 } + + // Memory resources + withLabel: lowmem { memory = { task?.resourceLimits?.memory && task?.maxRetries && task.attempt >= task.maxRetries ? task.resourceLimits.memory : 4.GB * task.attempt } } + withLabel: midmem { memory = { task?.resourceLimits?.memory && task?.maxRetries && task.attempt >= task.maxRetries ? task.resourceLimits.memory : 25.GB * task.attempt } } + withLabel: highmem { memory = { task?.resourceLimits?.memory && task?.maxRetries && task.attempt >= task.maxRetries ? task.resourceLimits.memory : 50.GB * task.attempt } } + withLabel: veryhighmem { memory = { task?.resourceLimits?.memory && task?.maxRetries && task.attempt >= task.maxRetries ? task.resourceLimits.memory : 75.GB * task.attempt } } + + // Disk space + withLabel: lowdisk { + disk = {process.disk ? process.disk : null} + } + withLabel: middisk { + disk = {process.disk ? process.disk : null} + } + withLabel: highdisk { + disk = {process.disk ? process.disk : null} + } + withLabel: veryhighdisk { + disk = {process.disk ? process.disk : null} + } + + // NOTE: The above labels intentionally do not have an effect by default. + // The user should set the disk space requirements by adding the following + // to the compute environment: + // + // withLabel: lowdisk { disk = { 20.GB * task.attempt } } + // withLabel: middisk { disk = { 100.GB * task.attempt } } + // withLabel: highdisk { disk = { 200.GB * task.attempt } } + // withLabel: veryhighdisk { disk = { 500.GB * task.attempt } } +} diff --git a/target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_schema.json b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_schema.json similarity index 100% rename from target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_schema.json rename to target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/nextflow_schema.json diff --git a/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/errorstrat_ignore.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/errorstrat_ignore.config new file mode 100644 index 0000000..6b4b029 --- /dev/null +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/errorstrat_ignore.config @@ -0,0 +1 @@ +process.errorStrategy = 'ignore' \ No newline at end of file diff --git a/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/integration_tests.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/integration_tests.config new file mode 100644 index 0000000..59d5b09 --- /dev/null +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/integration_tests.config @@ -0,0 +1,36 @@ +profiles { + + // detect tempdir + tempDir = java.nio.file.Paths.get( + System.getenv('NXF_TEMP') ?: + System.getenv('VIASH_TEMP') ?: + System.getenv('TEMPDIR') ?: + System.getenv('TMPDIR') ?: + '/tmp' + ).toAbsolutePath() + + mount_temp { + docker.temp = tempDir + podman.temp = tempDir + charliecloud.temp = tempDir + } + + no_publish { + process { + withName: '.*' { + publishDir = [ + enabled: false + ] + } + } + } + + docker { + docker.enabled = true + // docker.userEmulation = true + singularity.enabled = false + podman.enabled = false + shifter.enabled = false + charliecloud.enabled = false + } +} \ No newline at end of file diff --git a/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels.config new file mode 100644 index 0000000..94570ec --- /dev/null +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels.config @@ -0,0 +1,48 @@ +process { + // Default resources for components that hardly do any processing + memory = { 2.GB * task.attempt } + cpus = 1 + + // Retry for exit codes that have something to do with memory issues + errorStrategy = { task.exitStatus in 137..140 ? 'retry' : 'terminate' } + maxRetries = 3 + + // The memory a task is assinged increases with each attempt + // uncomment the line below and adjust the value to set a global upper limit on the memory. + // resourceLimits = [ memory: 240.Gb ] + + // CPU resources + withLabel: singlecpu { cpus = 1 } + withLabel: lowcpu { cpus = 4 } + withLabel: midcpu { cpus = 10 } + withLabel: highcpu { cpus = 20 } + + // Memory resources + withLabel: lowmem { memory = { task?.resourceLimits?.memory && task?.maxRetries && task.attempt >= task.maxRetries ? task.resourceLimits.memory : 4.GB * task.attempt } } + withLabel: midmem { memory = { task?.resourceLimits?.memory && task?.maxRetries && task.attempt >= task.maxRetries ? task.resourceLimits.memory : 25.GB * task.attempt } } + withLabel: highmem { memory = { task?.resourceLimits?.memory && task?.maxRetries && task.attempt >= task.maxRetries ? task.resourceLimits.memory : 50.GB * task.attempt } } + withLabel: veryhighmem { memory = { task?.resourceLimits?.memory && task?.maxRetries && task.attempt >= task.maxRetries ? task.resourceLimits.memory : 75.GB * task.attempt } } + + // Disk space + withLabel: lowdisk { + disk = {process.disk ? process.disk : null} + } + withLabel: middisk { + disk = {process.disk ? process.disk : null} + } + withLabel: highdisk { + disk = {process.disk ? process.disk : null} + } + withLabel: veryhighdisk { + disk = {process.disk ? process.disk : null} + } + + // NOTE: The above labels intentionally do not have an effect by default. + // The user should set the disk space requirements by adding the following + // to the compute environment: + // + // withLabel: lowdisk { disk = { 20.GB * task.attempt } } + // withLabel: middisk { disk = { 100.GB * task.attempt } } + // withLabel: highdisk { disk = { 200.GB * task.attempt } } + // withLabel: veryhighdisk { disk = { 500.GB * task.attempt } } +} diff --git a/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels_ci.config b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels_ci.config new file mode 100644 index 0000000..aee866d --- /dev/null +++ b/target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/rna/rna_singlesample/utils/labels_ci.config @@ -0,0 +1,33 @@ +process { + withLabel: lowmem { memory = 13.Gb } + withLabel: lowcpu { cpus = 4 } + withLabel: midmem { memory = 13.Gb } + withLabel: midcpu { cpus = 4 } + withLabel: highmem { memory = 13.Gb } + withLabel: highcpu { cpus = 4 } + withLabel: veryhighmem { memory = 13.Gb } + withLabel: lowdisk { + disk = {process.disk ? process.disk : null} + } + withLabel: middisk { + disk = {process.disk ? process.disk : null} + } + withLabel: highdisk { + disk = {process.disk ? process.disk : null} + } + withLabel: veryhighdisk { + disk = {process.disk ? process.disk : null} + } +} + +env.NUMBA_CACHE_DIR = '/tmp' + +trace { + enabled = true + overwrite = true +} +dag { + overwrite = true +} + +process.maxForks = 1 diff --git a/target/executable/convert/from_cells2stats_to_h5mu/.config.vsh.yaml b/target/executable/convert/from_cells2stats_to_h5mu/.config.vsh.yaml index de03cfe..d375ef6 100644 --- a/target/executable/convert/from_cells2stats_to_h5mu/.config.vsh.yaml +++ b/target/executable/convert/from_cells2stats_to_h5mu/.config.vsh.yaml @@ -179,7 +179,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -271,14 +271,16 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" - "pyarrow" git: - "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -301,7 +303,7 @@ build_info: output: "target/executable/convert/from_cells2stats_to_h5mu" executable: "target/executable/convert/from_cells2stats_to_h5mu/from_cells2stats_to_h5mu" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -315,7 +317,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/convert/from_cells2stats_to_h5mu/from_cells2stats_to_h5mu b/target/executable/convert/from_cells2stats_to_h5mu/from_cells2stats_to_h5mu index e47f8dd..2d2745b 100755 --- a/target/executable/convert/from_cells2stats_to_h5mu/from_cells2stats_to_h5mu +++ b/target/executable/convert/from_cells2stats_to_h5mu/from_cells2stats_to_h5mu @@ -453,15 +453,15 @@ RUN apt-get update && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "anndata~=0.11.1" "mudata~=0.3.1" "pyarrow" && \ + pip install --upgrade --no-cache-dir "anndata~=0.12.7" "awkward" "mudata~=0.3.2" "pyarrow" && \ pip install --upgrade --no-cache-dir "git+https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" && \ - python -c 'exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)")' + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' LABEL org.opencontainers.image.authors="Dorien Roosen" LABEL org.opencontainers.image.description="Companion container for running component convert from_cells2stats_to_h5mu" -LABEL org.opencontainers.image.created="2026-01-26T08:53:43Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:56Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER @@ -1296,7 +1296,7 @@ logger = setup_logger() def assert_matching_order(var_names, count_columns, split_pattern=None): for var, col in zip(var_names, count_columns): - count_var = col if not split_pattern else col.split("_Nuclear")[0] + count_var = col if not split_pattern else col.replace(split_pattern, "") assert var == count_var, "Orders do not match" @@ -1485,8 +1485,8 @@ def main(): df.index_name = None # var and obs names - var_names = [var.split(".")[0] for var in count_columns] - obs_names = df["Cell"].astype(str).tolist() + var_columns = list(count_columns) + obs_columns = df["Cell"].astype(str).tolist() # Count matrix logger.info("Creating count matrix...") @@ -1497,16 +1497,21 @@ def main(): logger.info(f"Creating obs field with columns {obs_columns_fixed}") obs_df = df[obs_columns_fixed].copy() + # Var field + var_df = pd.DataFrame(index=pd.Index(var_columns, dtype=str)) + targets, batches = zip(*(c.rsplit(".", 1) for c in var_columns)) + var_df["target"] = targets + var_df["batch"] = batches + # Create AnnData object logger.info("Creating AnnData object...") adata = ad.AnnData( X=count_matrix_sparse, obs=obs_df, - var=pd.DataFrame(index=var_names), + var=var_df, ) - - adata.obs_names = obs_names - adata.var_names = var_names + adata.obs_names = pd.Index(obs_columns, dtype=str) + adata.var_names = pd.Index(var_columns, dtype=str) # Spatial coordinates coordinate_sets = { @@ -1543,13 +1548,13 @@ def main(): adata.uns[par["obsm_cell_profiler"]] = cell_profiler_columns if par["obsm_unassigned_targets"]: logger.info(f"Adding {par['obsm_unassigned_targets']} to obsm") - adata.obsm["unassigned_targets"] = df[unassigned_columns].copy() - adata.uns["unassigned_targets"] = unassigned_columns + adata.obsm[par["obsm_unassigned_targets"]] = df[unassigned_columns].copy() + adata.uns[par["obsm_unassigned_targets"]] = unassigned_columns # Add (optional) nuclear count layer if par["layer_nuclear_counts"]: assert_matching_order( - var_names, nuclear_count_columns, split_pattern="_Nuclear" + var_columns, nuclear_count_columns, split_pattern="_Nuclear" ) logger.info(f"Adding {par['layer_nuclear_counts']} to layers") nuclear_count_df = df[nuclear_count_columns].copy() diff --git a/target/executable/convert/from_cosmx_to_h5mu/.config.vsh.yaml b/target/executable/convert/from_cosmx_to_h5mu/.config.vsh.yaml index f0be718..4e0453d 100644 --- a/target/executable/convert/from_cosmx_to_h5mu/.config.vsh.yaml +++ b/target/executable/convert/from_cosmx_to_h5mu/.config.vsh.yaml @@ -107,7 +107,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -199,17 +199,18 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "spatialdata~=0.5.0" - - "pyarrow~=18.0.0" - - "squidpy~=1.6.5" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.10.4" + - "squidpy~=1.7.0" - "pyarrow" git: - "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -238,7 +239,7 @@ build_info: output: "target/executable/convert/from_cosmx_to_h5mu" executable: "target/executable/convert/from_cosmx_to_h5mu/from_cosmx_to_h5mu" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -252,7 +253,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/convert/from_cosmx_to_h5mu/from_cosmx_to_h5mu b/target/executable/convert/from_cosmx_to_h5mu/from_cosmx_to_h5mu index 1195e1c..90e6380 100755 --- a/target/executable/convert/from_cosmx_to_h5mu/from_cosmx_to_h5mu +++ b/target/executable/convert/from_cosmx_to_h5mu/from_cosmx_to_h5mu @@ -454,15 +454,15 @@ RUN apt-get update && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "anndata~=0.11.1" "mudata~=0.3.1" "spatialdata~=0.5.0" "pyarrow~=18.0.0" "squidpy~=1.6.5" "pyarrow" && \ + pip install --upgrade --no-cache-dir "anndata~=0.12.7" "awkward" "mudata~=0.3.2" "scanpy~=1.10.4" "squidpy~=1.7.0" "pyarrow" && \ pip install --upgrade --no-cache-dir "git+https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" && \ - python -c 'exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)")' + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' LABEL org.opencontainers.image.authors="Dorien Roosen, Weiwei Schultz" LABEL org.opencontainers.image.description="Companion container for running component convert from_cosmx_to_h5mu" -LABEL org.opencontainers.image.created="2026-01-26T08:53:42Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:54Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/executable/convert/from_cosmx_to_spatialexperiment/.config.vsh.yaml b/target/executable/convert/from_cosmx_to_spatialexperiment/.config.vsh.yaml index c70b4ee..3ec04a7 100644 --- a/target/executable/convert/from_cosmx_to_spatialexperiment/.config.vsh.yaml +++ b/target/executable/convert/from_cosmx_to_spatialexperiment/.config.vsh.yaml @@ -125,7 +125,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -234,7 +234,7 @@ build_info: output: "target/executable/convert/from_cosmx_to_spatialexperiment" executable: "target/executable/convert/from_cosmx_to_spatialexperiment/from_cosmx_to_spatialexperiment" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -248,7 +248,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/convert/from_cosmx_to_spatialexperiment/from_cosmx_to_spatialexperiment b/target/executable/convert/from_cosmx_to_spatialexperiment/from_cosmx_to_spatialexperiment index 43a1a10..a97f3f5 100755 --- a/target/executable/convert/from_cosmx_to_spatialexperiment/from_cosmx_to_spatialexperiment +++ b/target/executable/convert/from_cosmx_to_spatialexperiment/from_cosmx_to_spatialexperiment @@ -457,9 +457,9 @@ RUN Rscript -e 'options(warn = 2); if (!requireNamespace("BiocManager", quietly LABEL org.opencontainers.image.authors="Dorien Roosen" LABEL org.opencontainers.image.description="Companion container for running component convert from_cosmx_to_spatialexperiment" -LABEL org.opencontainers.image.created="2026-01-26T08:53:41Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:54Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/executable/convert/from_h5mu_to_spatialexperiment/.config.vsh.yaml b/target/executable/convert/from_h5mu_to_spatialexperiment/.config.vsh.yaml index 6735bcf..c0a0360 100644 --- a/target/executable/convert/from_h5mu_to_spatialexperiment/.config.vsh.yaml +++ b/target/executable/convert/from_h5mu_to_spatialexperiment/.config.vsh.yaml @@ -92,7 +92,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -169,7 +169,7 @@ runners: engines: - type: "docker" id: "docker" - image: "rocker/r2u:22.04" + image: "rocker/r2u:24.04" target_registry: "images.viash-hub.com" target_tag: "niche-compass" namespace_separator: "/" @@ -191,6 +191,7 @@ engines: - type: "docker" env: - "RETICULATE_PYTHON=/usr/bin/python" + - "PIP_BREAK_SYSTEM_PACKAGES=1" - type: "apt" packages: - "python3" @@ -205,13 +206,15 @@ engines: bioc_force_install: false warnings_as_errors: true - type: "python" - user: false + user: true packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true entrypoint: [] cmd: null @@ -224,7 +227,7 @@ build_info: output: "target/executable/convert/from_h5mu_to_spatialexperiment" executable: "target/executable/convert/from_h5mu_to_spatialexperiment/from_h5mu_to_spatialexperiment" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -238,7 +241,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/convert/from_h5mu_to_spatialexperiment/from_h5mu_to_spatialexperiment b/target/executable/convert/from_h5mu_to_spatialexperiment/from_h5mu_to_spatialexperiment index e4d925d..3b109d9 100755 --- a/target/executable/convert/from_h5mu_to_spatialexperiment/from_h5mu_to_spatialexperiment +++ b/target/executable/convert/from_h5mu_to_spatialexperiment/from_h5mu_to_spatialexperiment @@ -446,7 +446,7 @@ function ViashDockerfile { if [[ "$engine_id" == "docker" ]]; then cat << 'VIASHDOCKER' -FROM rocker/r2u:22.04 +FROM rocker/r2u:24.04 ENTRYPOINT [] RUN apt-get update && \ DEBIAN_FRONTEND=noninteractive apt-get install -y libhdf5-dev libgeos-dev && \ @@ -458,9 +458,9 @@ RUN Rscript -e 'options(warn = 2); if (!requireNamespace("remotes", quietly = TR LABEL org.opencontainers.image.authors="Dorien Roosen" LABEL org.opencontainers.image.description="Companion container for running component convert from_h5mu_to_spatialexperiment" -LABEL org.opencontainers.image.created="2026-01-26T08:53:43Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:55Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/executable/convert/from_spaceranger_to_h5mu/.config.vsh.yaml b/target/executable/convert/from_spaceranger_to_h5mu/.config.vsh.yaml new file mode 100644 index 0000000..834519c --- /dev/null +++ b/target/executable/convert/from_spaceranger_to_h5mu/.config.vsh.yaml @@ -0,0 +1,296 @@ +name: "from_spaceranger_to_h5mu" +namespace: "convert" +version: "niche-compass" +authors: +- name: "Dorien Roosen" + roles: + - "maintainer" + info: + role: "Core Team Member" + links: + email: "dorien@data-intuitive.com" + github: "dorien-er" + linkedin: "dorien-roosen" + organizations: + - name: "Data Intuitive" + href: "https://www.data-intuitive.com" + role: "Data Scientist" +argument_groups: +- name: "Inputs" + arguments: + - type: "file" + name: "--input" + alternatives: + - "-i" + description: "Convert spatial data resulting from Aviti Teton sequencers that\ + \ have been processed by the Element Biosciences cells2stats workflow to H5MU\ + \ format.\n\nThis component processes cells2stats count matrices to create a\ + \ standardized H5MU file for downstream analysis.\n\nThe component reads:\n\ + - Parquet file containing the count matrix and metadata\n- Panel.json with target\ + \ and batch information\n\nAnd outputs an H5MU file with:\n- Count data as the\ + \ main .X matrix\n- Spatial coordinates in obsm\n- Cell Paint intensities in\ + \ obsm (optional)\n- Nuclear count data as a layer (optional)\n- CellProfiler\ + \ morphology metrics in obsm (optional)\n- Unassigned targets in obsm (optional)\n" + info: null + example: + - "spaceranger_output" + must_exist: true + create_parent: true + required: true + direction: "input" + multiple: false + multiple_sep: ";" +- name: "Outputs" + arguments: + - type: "file" + name: "--output" + description: "Output h5mu file." + info: null + example: + - "output.h5mu" + must_exist: true + create_parent: true + required: false + direction: "output" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--modality" + description: "Name of the modality under which to store the data." + info: null + default: + - "rna" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--uns_metrics" + description: "Name of the .uns slot under which to QC metrics (if any)." + info: null + default: + - "metrics_spaceranger" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--uns_probe_set" + description: "Name of the .uns slot under which to store probe set information\ + \ (if any)." + info: null + default: + - "probe_set" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--obsm_coordinates" + description: "Name of the .obsm slot under which to store the cell centroid coordinates." + info: null + default: + - "spatial" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--output_type" + description: "Which Spaceranger output to use for converting to h5mu." + info: null + default: + - "filtered" + required: false + choices: + - "raw" + - "filtered" + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--output_compression" + description: "Compression to use when writing the h5mu file." + info: null + required: false + choices: + - "gzip" + - "lzf" + direction: "input" + multiple: false + multiple_sep: ";" +resources: +- type: "python_script" + path: "script.py" + is_executable: true +- type: "file" + path: "setup_logger.py" +- type: "file" + path: "nextflow_labels.config" + dest: "nextflow_labels.config" +description: "Converts the output bundle from spaceranger into an h5mu file.\n" +test_resources: +- type: "python_script" + path: "test.py" + is_executable: true +- type: "file" + path: "Visium_FFPE_Human_Ovarian_Cancer_tiny_spaceranger" +info: null +status: "enabled" +scope: + image: "public" + target: "public" +repositories: +- type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" +links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" +runners: +- type: "executable" + id: "executable" + docker_setup_strategy: "ifneedbepullelsecachedbuild" +- type: "nextflow" + id: "nextflow" + directives: + label: + - "lowmem" + - "singlecpu" + tag: "$id" + auto: + simplifyInput: true + simplifyOutput: false + transcript: false + publish: false + config: + labels: + mem1gb: "memory = 1000000000.B" + mem2gb: "memory = 2000000000.B" + mem5gb: "memory = 5000000000.B" + mem10gb: "memory = 10000000000.B" + mem20gb: "memory = 20000000000.B" + mem50gb: "memory = 50000000000.B" + mem100gb: "memory = 100000000000.B" + mem200gb: "memory = 200000000000.B" + mem500gb: "memory = 500000000000.B" + mem1tb: "memory = 1000000000000.B" + mem2tb: "memory = 2000000000000.B" + mem5tb: "memory = 5000000000000.B" + mem10tb: "memory = 10000000000000.B" + mem20tb: "memory = 20000000000000.B" + mem50tb: "memory = 50000000000000.B" + mem100tb: "memory = 100000000000000.B" + mem200tb: "memory = 200000000000000.B" + mem500tb: "memory = 500000000000000.B" + mem1gib: "memory = 1073741824.B" + mem2gib: "memory = 2147483648.B" + mem4gib: "memory = 4294967296.B" + mem8gib: "memory = 8589934592.B" + mem16gib: "memory = 17179869184.B" + mem32gib: "memory = 34359738368.B" + mem64gib: "memory = 68719476736.B" + mem128gib: "memory = 137438953472.B" + mem256gib: "memory = 274877906944.B" + mem512gib: "memory = 549755813888.B" + mem1tib: "memory = 1099511627776.B" + mem2tib: "memory = 2199023255552.B" + mem4tib: "memory = 4398046511104.B" + mem8tib: "memory = 8796093022208.B" + mem16tib: "memory = 17592186044416.B" + mem32tib: "memory = 35184372088832.B" + mem64tib: "memory = 70368744177664.B" + mem128tib: "memory = 140737488355328.B" + mem256tib: "memory = 281474976710656.B" + mem512tib: "memory = 562949953421312.B" + 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" + script: + - "includeConfig(\"nextflow_labels.config\")" + debug: false + container: "docker" +engines: +- type: "docker" + id: "docker" + image: "python:3.12-slim" + target_registry: "images.viash-hub.com" + target_tag: "niche-compass" + namespace_separator: "/" + setup: + - type: "apt" + packages: + - "procps" + interactive: false + - type: "python" + user: false + packages: + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.10.4" + script: + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" + upgrade: true + test_setup: + - type: "apt" + packages: + - "git" + interactive: false + - type: "python" + user: false + packages: + - "viashpy==0.9.0" + github: + - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" + upgrade: true + entrypoint: [] + cmd: null +- type: "native" + id: "native" +build_info: + config: "src/convert/from_spaceranger_to_h5mu/config.vsh.yaml" + runner: "executable" + engine: "docker|native" + output: "target/executable/convert/from_spaceranger_to_h5mu" + executable: "target/executable/convert/from_spaceranger_to_h5mu/from_spaceranger_to_h5mu" + viash_version: "0.9.4" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" + git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" +package_config: + name: "openpipeline_spatial" + version: "niche-compass" + info: + test_resources: + - type: "s3" + path: "s3://openpipelines-bio/openpipeline_spatial/resources_test" + dest: "resources_test" + repositories: + - type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" + viash_version: "0.9.4" + source: "src" + target: "target" + config_mods: + - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n\ + .runners[.type == 'nextflow'].config.script := 'includeConfig(\"nextflow_labels.config\"\ + )'" + - ".engines += { type: \"native\" }" + - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" + - ".engines[.type == 'docker'].target_tag := 'niche-compass'" + organization: "vsh" + links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" diff --git a/target/executable/dataflow/concatenate_h5mu/concatenate_h5mu b/target/executable/convert/from_spaceranger_to_h5mu/from_spaceranger_to_h5mu similarity index 62% rename from target/executable/dataflow/concatenate_h5mu/concatenate_h5mu rename to target/executable/convert/from_spaceranger_to_h5mu/from_spaceranger_to_h5mu index 0595c4c..d00fd89 100755 --- a/target/executable/dataflow/concatenate_h5mu/concatenate_h5mu +++ b/target/executable/convert/from_spaceranger_to_h5mu/from_spaceranger_to_h5mu @@ -1,6 +1,6 @@ #!/usr/bin/env bash -# concatenate_h5mu niche-compass +# from_spaceranger_to_h5mu niche-compass # # This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative # work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data @@ -12,7 +12,7 @@ # files. # # Component authors: -# * Dries Schaumont (maintainer) +# * Dorien Roosen (maintainer) set -e @@ -165,8 +165,8 @@ VIASH_META_RESOURCES_DIR=`ViashSourceDir ${BASH_SOURCE[0]}` VIASH_TARGET_DIR=`ViashFindTargetDir $VIASH_META_RESOURCES_DIR` # define meta fields -VIASH_META_NAME="concatenate_h5mu" -VIASH_META_FUNCTIONALITY_NAME="concatenate_h5mu" +VIASH_META_NAME="from_spaceranger_to_h5mu" +VIASH_META_FUNCTIONALITY_NAME="from_spaceranger_to_h5mu" VIASH_META_EXECUTABLE="$VIASH_META_RESOURCES_DIR/$VIASH_META_NAME" VIASH_META_CONFIG="$VIASH_META_RESOURCES_DIR/.config.vsh.yaml" VIASH_META_TEMP_DIR="$VIASH_TEMP" @@ -446,21 +446,21 @@ function ViashDockerfile { if [[ "$engine_id" == "docker" ]]; then cat << 'VIASHDOCKER' -FROM python:3.13-slim +FROM python:3.12-slim ENTRYPOINT [] RUN apt-get update && \ DEBIAN_FRONTEND=noninteractive apt-get install -y procps && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "anndata~=0.11.1" "mudata~=0.3.1" && \ - python -c 'exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)")' + pip install --upgrade --no-cache-dir "anndata~=0.12.7" "awkward" "mudata~=0.3.2" "scanpy~=1.10.4" && \ + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' -LABEL org.opencontainers.image.authors="Dries Schaumont" -LABEL org.opencontainers.image.description="Companion container for running component dataflow concatenate_h5mu" -LABEL org.opencontainers.image.created="2026-01-26T08:53:43Z" +LABEL org.opencontainers.image.authors="Dorien Roosen" +LABEL org.opencontainers.image.description="Companion container for running component convert from_spaceranger_to_h5mu" +LABEL org.opencontainers.image.created="2026-01-27T10:47:54Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER @@ -578,86 +578,68 @@ VIASH_DOCKER_RUN_ARGS=(-i --rm) # ViashHelp: Display helpful explanation about this executable function ViashHelp { - echo "concatenate_h5mu niche-compass" + echo "from_spaceranger_to_h5mu niche-compass" echo "" - echo "Concatenate observations from samples in several (uni- and/or multi-modal)" - echo "MuData files into a single file." + echo "Converts the output bundle from spaceranger into an h5mu file." echo "" - echo "Arguments:" + echo "Inputs:" echo " -i, --input" - echo " type: file, required parameter, multiple values allowed, file must exist" - echo " example: sample_paths" - echo " Paths to the different samples to be concatenated." + echo " type: file, required parameter, file must exist" + echo " example: spaceranger_output" + echo " Convert spatial data resulting from Aviti Teton sequencers that have" + echo " been processed by the Element Biosciences cells2stats workflow to H5MU" + echo " format." + echo " This component processes cells2stats count matrices to create a" + echo " standardized H5MU file for downstream analysis." + echo " The component reads:" + echo " - Parquet file containing the count matrix and metadata" + echo " - Panel.json with target and batch information" + echo " And outputs an H5MU file with:" + echo " - Count data as the main .X matrix" + echo " - Spatial coordinates in obsm" + echo " - Cell Paint intensities in obsm (optional)" + echo " - Nuclear count data as a layer (optional)" + echo " - CellProfiler morphology metrics in obsm (optional)" + echo " - Unassigned targets in obsm (optional)" echo "" - echo " --modality" - echo " type: string, multiple values allowed" - echo " Only output concatenated objects for the provided modalities. Outputs" - echo " all modalities by default." - echo "" - echo " --input_id" - echo " type: string, multiple values allowed" - echo " Names of the different samples that have to be concatenated. Must be" - echo " specified when using '--mode move'." - echo " In this case, the ids will be used for the columns names of the" - echo " dataframes registring the conflicts." - echo " If specified, must be of same length as \`--input\`." - echo "" - echo " -o, --output" + echo "Outputs:" + echo " --output" echo " type: file, output, file must exist" echo " example: output.h5mu" - echo " Output location for the concatenated MuData object file." + echo " Output h5mu file." echo "" - echo " --obs_sample_name" + echo " --modality" echo " type: string" - echo " default: sample_id" - echo " Name of the .obs key under which to add the sample names." + echo " default: rna" + echo " Name of the modality under which to store the data." echo "" - echo " --other_axis_mode" + echo " --uns_metrics" echo " type: string" - echo " default: move" - echo " choices: [ same, unique, first, only, concat, move ]" - echo " How to handle the merging of other axis (var, obs, ...)." - echo " - None: keep no data" - echo " - same: only keep elements of the matrices which are the same in each" - echo " of the samples" - echo " - unique: only keep elements for which there is only 1 possible value" - echo " (1 value that can occur in multiple samples)" - echo " - first: keep the annotation from the first sample" - echo " - only: keep elements that show up in only one of the objects (1" - echo " unique element in only 1 sample)" - echo " - move: identical to 'same', but moving the conflicting values to" - echo " .varm or .obsm" + echo " default: metrics_spaceranger" + echo " Name of the .uns slot under which to QC metrics (if any)." echo "" - echo " --uns_merge_mode" + echo " --uns_probe_set" echo " type: string" - echo " default: make_unique" - echo " choices: [ same, unique, first, only, make_unique ]" - echo " How to handle the merging of .uns across modalities" - echo " - None: keep no data" - echo " - same: only keep elements of the matrices which are the same in each" - echo " of the samples" - echo " - unique: only keep elements for which there is only 1 possible value" - echo " (1 value that can occur in multiple samples)" - echo " - first: keep the annotation from the first sample" - echo " - only: keep elements that show up in only one of the objects (1" - echo " unique element in only 1 sample)" - echo " - make_unique: identical to 'unique', but keys which are not unique" - echo " are made unique by prefixing them with the sample id." + echo " default: probe_set" + echo " Name of the .uns slot under which to store probe set information (if" + echo " any)." echo "" - echo " --obsp_keys" - echo " type: string, multiple values allowed" - echo " List of \`.obsp\` keys for which block-diagonal concatenation should be" - echo " performed." - echo " If not provided, no \`.obsp\` keys will be concatenated." - echo " Provided keys must be present in all samples for block concatenation to" - echo " be performed." + echo " --obsm_coordinates" + echo " type: string" + echo " default: spatial" + echo " Name of the .obsm slot under which to store the cell centroid" + echo " coordinates." + echo "" + echo " --output_type" + echo " type: string" + echo " default: filtered" + echo " choices: [ raw, filtered ]" + echo " Which Spaceranger output to use for converting to h5mu." echo "" echo " --output_compression" echo " type: string" - echo " example: gzip" echo " choices: [ gzip, lzf ]" - echo " Compression format to use for the output AnnData and/or Mudata objects." - echo " By default no compression is applied." + echo " Compression to use when writing the h5mu file." echo "" echo "Viash built in Computational Requirements:" echo " ---cpus=INT" @@ -706,69 +688,26 @@ while [[ $# -gt 0 ]]; do shift 1 ;; --version) - echo "concatenate_h5mu niche-compass" + echo "from_spaceranger_to_h5mu niche-compass" exit ;; --input) - if [ -z "$VIASH_PAR_INPUT" ]; then - VIASH_PAR_INPUT="$2" - else - VIASH_PAR_INPUT="$VIASH_PAR_INPUT;""$2" - fi + [ -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=*) - if [ -z "$VIASH_PAR_INPUT" ]; then - VIASH_PAR_INPUT=$(ViashRemoveFlags "$1") - else - VIASH_PAR_INPUT="$VIASH_PAR_INPUT;"$(ViashRemoveFlags "$1") - fi + [ -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) - if [ -z "$VIASH_PAR_INPUT" ]; then - VIASH_PAR_INPUT="$2" - else - VIASH_PAR_INPUT="$VIASH_PAR_INPUT;""$2" - fi + [ -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 ;; - --modality) - if [ -z "$VIASH_PAR_MODALITY" ]; then - VIASH_PAR_MODALITY="$2" - else - VIASH_PAR_MODALITY="$VIASH_PAR_MODALITY;""$2" - fi - [ $# -lt 2 ] && ViashError Not enough arguments passed to --modality. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --modality=*) - if [ -z "$VIASH_PAR_MODALITY" ]; then - VIASH_PAR_MODALITY=$(ViashRemoveFlags "$1") - else - VIASH_PAR_MODALITY="$VIASH_PAR_MODALITY;"$(ViashRemoveFlags "$1") - fi - shift 1 - ;; - --input_id) - if [ -z "$VIASH_PAR_INPUT_ID" ]; then - VIASH_PAR_INPUT_ID="$2" - else - VIASH_PAR_INPUT_ID="$VIASH_PAR_INPUT_ID;""$2" - fi - [ $# -lt 2 ] && ViashError Not enough arguments passed to --input_id. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --input_id=*) - if [ -z "$VIASH_PAR_INPUT_ID" ]; then - VIASH_PAR_INPUT_ID=$(ViashRemoveFlags "$1") - else - VIASH_PAR_INPUT_ID="$VIASH_PAR_INPUT_ID;"$(ViashRemoveFlags "$1") - fi - shift 1 - ;; --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" @@ -780,60 +719,59 @@ while [[ $# -gt 0 ]]; do 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 + --modality) + [ -n "$VIASH_PAR_MODALITY" ] && ViashError Bad arguments for option \'--modality\': \'$VIASH_PAR_MODALITY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_MODALITY="$2" + [ $# -lt 2 ] && ViashError Not enough arguments passed to --modality. Use "--help" to get more information on the parameters. && exit 1 shift 2 ;; - --obs_sample_name) - [ -n "$VIASH_PAR_OBS_SAMPLE_NAME" ] && ViashError Bad arguments for option \'--obs_sample_name\': \'$VIASH_PAR_OBS_SAMPLE_NAME\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OBS_SAMPLE_NAME="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --obs_sample_name. Use "--help" to get more information on the parameters. && exit 1 - shift 2 - ;; - --obs_sample_name=*) - [ -n "$VIASH_PAR_OBS_SAMPLE_NAME" ] && ViashError Bad arguments for option \'--obs_sample_name=*\': \'$VIASH_PAR_OBS_SAMPLE_NAME\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OBS_SAMPLE_NAME=$(ViashRemoveFlags "$1") + --modality=*) + [ -n "$VIASH_PAR_MODALITY" ] && ViashError Bad arguments for option \'--modality=*\': \'$VIASH_PAR_MODALITY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_MODALITY=$(ViashRemoveFlags "$1") shift 1 ;; - --other_axis_mode) - [ -n "$VIASH_PAR_OTHER_AXIS_MODE" ] && ViashError Bad arguments for option \'--other_axis_mode\': \'$VIASH_PAR_OTHER_AXIS_MODE\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OTHER_AXIS_MODE="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --other_axis_mode. Use "--help" to get more information on the parameters. && exit 1 + --uns_metrics) + [ -n "$VIASH_PAR_UNS_METRICS" ] && ViashError Bad arguments for option \'--uns_metrics\': \'$VIASH_PAR_UNS_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_UNS_METRICS="$2" + [ $# -lt 2 ] && ViashError Not enough arguments passed to --uns_metrics. Use "--help" to get more information on the parameters. && exit 1 shift 2 ;; - --other_axis_mode=*) - [ -n "$VIASH_PAR_OTHER_AXIS_MODE" ] && ViashError Bad arguments for option \'--other_axis_mode=*\': \'$VIASH_PAR_OTHER_AXIS_MODE\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_OTHER_AXIS_MODE=$(ViashRemoveFlags "$1") + --uns_metrics=*) + [ -n "$VIASH_PAR_UNS_METRICS" ] && ViashError Bad arguments for option \'--uns_metrics=*\': \'$VIASH_PAR_UNS_METRICS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_UNS_METRICS=$(ViashRemoveFlags "$1") shift 1 ;; - --uns_merge_mode) - [ -n "$VIASH_PAR_UNS_MERGE_MODE" ] && ViashError Bad arguments for option \'--uns_merge_mode\': \'$VIASH_PAR_UNS_MERGE_MODE\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_UNS_MERGE_MODE="$2" - [ $# -lt 2 ] && ViashError Not enough arguments passed to --uns_merge_mode. Use "--help" to get more information on the parameters. && exit 1 + --uns_probe_set) + [ -n "$VIASH_PAR_UNS_PROBE_SET" ] && ViashError Bad arguments for option \'--uns_probe_set\': \'$VIASH_PAR_UNS_PROBE_SET\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_UNS_PROBE_SET="$2" + [ $# -lt 2 ] && ViashError Not enough arguments passed to --uns_probe_set. Use "--help" to get more information on the parameters. && exit 1 shift 2 ;; - --uns_merge_mode=*) - [ -n "$VIASH_PAR_UNS_MERGE_MODE" ] && ViashError Bad arguments for option \'--uns_merge_mode=*\': \'$VIASH_PAR_UNS_MERGE_MODE\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 - VIASH_PAR_UNS_MERGE_MODE=$(ViashRemoveFlags "$1") + --uns_probe_set=*) + [ -n "$VIASH_PAR_UNS_PROBE_SET" ] && ViashError Bad arguments for option \'--uns_probe_set=*\': \'$VIASH_PAR_UNS_PROBE_SET\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_UNS_PROBE_SET=$(ViashRemoveFlags "$1") shift 1 ;; - --obsp_keys) - if [ -z "$VIASH_PAR_OBSP_KEYS" ]; then - VIASH_PAR_OBSP_KEYS="$2" - else - VIASH_PAR_OBSP_KEYS="$VIASH_PAR_OBSP_KEYS;""$2" - fi - [ $# -lt 2 ] && ViashError Not enough arguments passed to --obsp_keys. Use "--help" to get more information on the parameters. && exit 1 + --obsm_coordinates) + [ -n "$VIASH_PAR_OBSM_COORDINATES" ] && ViashError Bad arguments for option \'--obsm_coordinates\': \'$VIASH_PAR_OBSM_COORDINATES\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_OBSM_COORDINATES="$2" + [ $# -lt 2 ] && ViashError Not enough arguments passed to --obsm_coordinates. Use "--help" to get more information on the parameters. && exit 1 shift 2 ;; - --obsp_keys=*) - if [ -z "$VIASH_PAR_OBSP_KEYS" ]; then - VIASH_PAR_OBSP_KEYS=$(ViashRemoveFlags "$1") - else - VIASH_PAR_OBSP_KEYS="$VIASH_PAR_OBSP_KEYS;"$(ViashRemoveFlags "$1") - fi + --obsm_coordinates=*) + [ -n "$VIASH_PAR_OBSM_COORDINATES" ] && ViashError Bad arguments for option \'--obsm_coordinates=*\': \'$VIASH_PAR_OBSM_COORDINATES\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_OBSM_COORDINATES=$(ViashRemoveFlags "$1") + shift 1 + ;; + --output_type) + [ -n "$VIASH_PAR_OUTPUT_TYPE" ] && ViashError Bad arguments for option \'--output_type\': \'$VIASH_PAR_OUTPUT_TYPE\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_OUTPUT_TYPE="$2" + [ $# -lt 2 ] && ViashError Not enough arguments passed to --output_type. Use "--help" to get more information on the parameters. && exit 1 + shift 2 + ;; + --output_type=*) + [ -n "$VIASH_PAR_OUTPUT_TYPE" ] && ViashError Bad arguments for option \'--output_type=*\': \'$VIASH_PAR_OUTPUT_TYPE\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1 + VIASH_PAR_OUTPUT_TYPE=$(ViashRemoveFlags "$1") shift 1 ;; --output_compression) @@ -935,7 +873,7 @@ if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then # determine docker image id if [[ "$VIASH_ENGINE_ID" == 'docker' ]]; then - VIASH_DOCKER_IMAGE_ID='images.viash-hub.com/vsh/openpipeline_spatial/dataflow/concatenate_h5mu:niche-compass' + VIASH_DOCKER_IMAGE_ID='images.viash-hub.com/vsh/openpipeline_spatial/convert/from_spaceranger_to_h5mu:niche-compass' fi # print dockerfile @@ -1049,28 +987,26 @@ if [ -z ${VIASH_META_TEMP_DIR+x} ]; then fi # filling in defaults -if [ -z ${VIASH_PAR_OBS_SAMPLE_NAME+x} ]; then - VIASH_PAR_OBS_SAMPLE_NAME="sample_id" +if [ -z ${VIASH_PAR_MODALITY+x} ]; then + VIASH_PAR_MODALITY="rna" fi -if [ -z ${VIASH_PAR_OTHER_AXIS_MODE+x} ]; then - VIASH_PAR_OTHER_AXIS_MODE="move" +if [ -z ${VIASH_PAR_UNS_METRICS+x} ]; then + VIASH_PAR_UNS_METRICS="metrics_spaceranger" fi -if [ -z ${VIASH_PAR_UNS_MERGE_MODE+x} ]; then - VIASH_PAR_UNS_MERGE_MODE="make_unique" +if [ -z ${VIASH_PAR_UNS_PROBE_SET+x} ]; then + VIASH_PAR_UNS_PROBE_SET="probe_set" +fi +if [ -z ${VIASH_PAR_OBSM_COORDINATES+x} ]; then + VIASH_PAR_OBSM_COORDINATES="spatial" +fi +if [ -z ${VIASH_PAR_OUTPUT_TYPE+x} ]; then + VIASH_PAR_OUTPUT_TYPE="filtered" 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 +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 @@ -1148,24 +1084,12 @@ if [[ -n "$VIASH_META_MEMORY_PIB" ]]; then fi # check whether value is belongs to a set of choices -if [ ! -z "$VIASH_PAR_OTHER_AXIS_MODE" ]; then - VIASH_PAR_OTHER_AXIS_MODE_CHOICES=("same;unique;first;only;concat;move") +if [ ! -z "$VIASH_PAR_OUTPUT_TYPE" ]; then + VIASH_PAR_OUTPUT_TYPE_CHOICES=("raw;filtered") IFS=';' set -f - if ! [[ ";${VIASH_PAR_OTHER_AXIS_MODE_CHOICES[*]};" =~ ";$VIASH_PAR_OTHER_AXIS_MODE;" ]]; then - ViashError '--other_axis_mode' specified value of \'$VIASH_PAR_OTHER_AXIS_MODE\' is not in the list of allowed values. Use "--help" to get more information on the parameters. - exit 1 - fi - set +f - unset IFS -fi - -if [ ! -z "$VIASH_PAR_UNS_MERGE_MODE" ]; then - VIASH_PAR_UNS_MERGE_MODE_CHOICES=("same;unique;first;only;make_unique") - IFS=';' - set -f - if ! [[ ";${VIASH_PAR_UNS_MERGE_MODE_CHOICES[*]};" =~ ";$VIASH_PAR_UNS_MERGE_MODE;" ]]; then - ViashError '--uns_merge_mode' specified value of \'$VIASH_PAR_UNS_MERGE_MODE\' is not in the list of allowed values. Use "--help" to get more information on the parameters. + if ! [[ ";${VIASH_PAR_OUTPUT_TYPE_CHOICES[*]};" =~ ";$VIASH_PAR_OUTPUT_TYPE;" ]]; then + ViashError '--output_type' specified value of \'$VIASH_PAR_OUTPUT_TYPE\' is not in the list of allowed values. Use "--help" to get more information on the parameters. exit 1 fi set +f @@ -1202,15 +1126,8 @@ if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then # 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_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$var")" ) - var=$(ViashDockerAutodetectMount "$var") - VIASH_TEST_INPUT+=( "$var" ) - done - VIASH_PAR_INPUT=$(IFS=';' ; echo "${VIASH_TEST_INPUT[*]}") + VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_INPUT")" ) + VIASH_PAR_INPUT=$(ViashDockerAutodetectMount "$VIASH_PAR_INPUT") fi if [ ! -z "$VIASH_PAR_OUTPUT" ]; then VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_OUTPUT")" ) @@ -1273,7 +1190,7 @@ fi ViashDebug "Running command: $(echo $VIASH_CMD)" cat << VIASHEOF | eval $VIASH_CMD set -e -tempscript=\$(mktemp "$VIASH_META_TEMP_DIR/viash-run-concatenate_h5mu-XXXXXX").py +tempscript=\$(mktemp "$VIASH_META_TEMP_DIR/viash-run-from_spaceranger_to_h5mu-XXXXXX").py function clean_up { rm "\$tempscript" } @@ -1284,30 +1201,22 @@ function interrupt { trap clean_up EXIT trap interrupt INT SIGINT cat > "\$tempscript" << 'VIASHMAIN' -from __future__ import annotations -import sys -import anndata -import mudata as mu -import pandas as pd -import numpy as np -from collections.abc import Iterable -from multiprocessing import Pool from pathlib import Path -from h5py import File as H5File -from typing import Literal -import shutil +import mudata +import scanpy as sc +import sys +import pandas as pd -### VIASH START +## 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\'}'.split(';')"; else echo None; fi ), - 'modality': $( if [ ! -z ${VIASH_PAR_MODALITY+x} ]; then echo "r'${VIASH_PAR_MODALITY//\'/\'\"\'\"r\'}'.split(';')"; else echo None; fi ), - 'input_id': $( if [ ! -z ${VIASH_PAR_INPUT_ID+x} ]; then echo "r'${VIASH_PAR_INPUT_ID//\'/\'\"\'\"r\'}'.split(';')"; else echo None; fi ), + '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 ), - 'obs_sample_name': $( if [ ! -z ${VIASH_PAR_OBS_SAMPLE_NAME+x} ]; then echo "r'${VIASH_PAR_OBS_SAMPLE_NAME//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'other_axis_mode': $( if [ ! -z ${VIASH_PAR_OTHER_AXIS_MODE+x} ]; then echo "r'${VIASH_PAR_OTHER_AXIS_MODE//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'uns_merge_mode': $( if [ ! -z ${VIASH_PAR_UNS_MERGE_MODE+x} ]; then echo "r'${VIASH_PAR_UNS_MERGE_MODE//\'/\'\"\'\"r\'}'"; else echo None; fi ), - 'obsp_keys': $( if [ ! -z ${VIASH_PAR_OBSP_KEYS+x} ]; then echo "r'${VIASH_PAR_OBSP_KEYS//\'/\'\"\'\"r\'}'.split(';')"; else echo None; fi ), + 'modality': $( if [ ! -z ${VIASH_PAR_MODALITY+x} ]; then echo "r'${VIASH_PAR_MODALITY//\'/\'\"\'\"r\'}'"; else echo None; fi ), + 'uns_metrics': $( if [ ! -z ${VIASH_PAR_UNS_METRICS+x} ]; then echo "r'${VIASH_PAR_UNS_METRICS//\'/\'\"\'\"r\'}'"; else echo None; fi ), + 'uns_probe_set': $( if [ ! -z ${VIASH_PAR_UNS_PROBE_SET+x} ]; then echo "r'${VIASH_PAR_UNS_PROBE_SET//\'/\'\"\'\"r\'}'"; else echo None; fi ), + 'obsm_coordinates': $( if [ ! -z ${VIASH_PAR_OBSM_COORDINATES+x} ]; then echo "r'${VIASH_PAR_OBSM_COORDINATES//\'/\'\"\'\"r\'}'"; else echo None; fi ), + 'output_type': $( if [ ! -z ${VIASH_PAR_OUTPUT_TYPE+x} ]; then echo "r'${VIASH_PAR_OUTPUT_TYPE//\'/\'\"\'\"r\'}'"; else echo None; fi ), 'output_compression': $( if [ ! -z ${VIASH_PAR_OUTPUT_COMPRESSION+x} ]; then echo "r'${VIASH_PAR_OUTPUT_COMPRESSION//\'/\'\"\'\"r\'}'"; else echo None; fi ) } meta = { @@ -1334,382 +1243,116 @@ dep = { } -### VIASH END +## VIASH END sys.path.append(meta["resources_dir"]) -from compress_h5mu import compress_h5mu from setup_logger import setup_logger logger = setup_logger() -def nunique(row): - unique = pd.unique(row) - unique_without_na = pd.core.dtypes.missing.remove_na_arraylike(unique) - return len(unique_without_na) > 1 +def retrieve_input_data(spaceranger_output_bundle, input_type="filtered"): + # Expected folder structure (showing only relevant files): + # ├── Spatial/ + # │ └── tissue_positions.csv + # ├── filtered_feature_bc_matrix.h5 OR raw_feature_bc_matrix.h5 + # ├── metrics_summary.csv + # └── probe_set.csv - -def any_row_contains_duplicate_values(n_processes: int, frame: pd.DataFrame) -> bool: - """ - Check if any row contains duplicate values, that are not NA. - """ - numpy_array = frame.to_numpy() - with Pool(n_processes) as pool: - is_duplicated = pool.map(nunique, iter(numpy_array)) - return any(is_duplicated) - - -def concatenate_matrices( - n_processes: int, matrices: dict[str, pd.DataFrame], align_to: pd.Index -) -> tuple[ - dict[str, pd.DataFrame], pd.DataFrame | None, dict[str, pd.core.dtypes.dtypes.Dtype] -]: - """ - Merge matrices by combining columns that have the same name. - Columns that contain conflicting values (e.i. the columns have different values), - are not merged, but instead moved to a new dataframe. - """ - column_names = set(column_name for var in matrices.values() for column_name in var) - logger.debug("Trying to concatenate columns: %s.", ",".join(column_names)) - if not column_names: - return {}, pd.DataFrame(index=align_to) - conflicts, concatenated_matrix = split_conflicts_and_concatenated_columns( - n_processes, matrices, column_names, align_to + matrix_pattern = ( + "**/filtered_feature_bc_matrix.h5" + if input_type == "filtered" + else "**/raw_feature_bc_matrix.h5" ) - concatenated_matrix = cast_to_writeable_dtype(concatenated_matrix) - conflicts = { - conflict_name: cast_to_writeable_dtype(conflict_df) - for conflict_name, conflict_df in conflicts.items() + spaceranger_file_patterns = { + "count_matrix": matrix_pattern, + "metrics_summary": "**/metrics_summary.csv", + "probe_set": "**/probe_set.csv", + "spatial_coords": "**/spatial/tissue_positions.csv", } - return conflicts, concatenated_matrix + spaceranger_output_bundle = Path(spaceranger_output_bundle) -def get_first_non_na_value_vector(df): - numpy_arr = df.to_numpy() - n_rows, n_cols = numpy_arr.shape - col_index = pd.isna(numpy_arr).argmin(axis=1) - flat_index = n_cols * np.arange(n_rows) + col_index - return pd.Series(numpy_arr.ravel()[flat_index], index=df.index, name=df.columns[0]) + spaceranger_files = {} - -def make_uns_keys_unique(mod_data, concatenated_data): - """ - Check if the uns keys across samples are unique before adding them - to the final concatenated object. If a conflict occurs between the samples, - add the sample ID to make the key unique again. - """ - all_uns_keys = {} - for sample_id, mod in mod_data.items(): - for uns_key, _ in mod.uns.items(): - all_uns_keys.setdefault(uns_key, []).append(sample_id) - for uns_key, samples_ids in all_uns_keys.items(): - assert samples_ids - if len(samples_ids) == 1: - sample_id = samples_ids[0] - concatenated_data.uns[uns_key] = mod_data[sample_id].uns[uns_key] - else: - for sample_id in samples_ids: - concatenated_data.uns[f"{sample_id}_{uns_key}"] = mod_data[ - sample_id - ].uns[uns_key] - return concatenated_data - - -def split_conflicts_and_concatenated_columns( - n_processes: int, - matrices: dict[str, pd.DataFrame], - column_names: Iterable[str], - align_to: pd.Index, -) -> tuple[dict[str, pd.DataFrame], pd.DataFrame]: - """ - Retrieve columns with the same name from a list of dataframes which are - identical across all the frames (ignoring NA values). - Columns which are not the same are regarded as 'conflicts', - which are stored in seperate dataframes, one per columns - with the same name that store conflicting values. - """ - conflicts = {} - concatenated_matrix = [] - for column_name in column_names: - columns = { - input_id: var[column_name] - for input_id, var in matrices.items() - if column_name in var - } - assert columns, "Some columns should have been found." - concatenated_columns = pd.concat( - columns.values(), axis=1, join="outer", sort=False + for key, pattern in spaceranger_file_patterns.items(): + file = list(spaceranger_output_bundle.glob(pattern)) + assert len(file) == 1, ( + f"Expected exactly one file for pattern '{pattern}', found {len(file)}." ) - if any_row_contains_duplicate_values(n_processes, concatenated_columns): - concatenated_columns.columns = ( - columns.keys() - ) # Use the sample id as column name - concatenated_columns = concatenated_columns.reindex(align_to, copy=False) - conflicts[f"conflict_{column_name}"] = concatenated_columns - else: - unique_values = get_first_non_na_value_vector(concatenated_columns) - concatenated_matrix.append(unique_values) - if not concatenated_matrix: - return conflicts, pd.DataFrame(index=align_to) - concatenated_matrix = pd.concat( - concatenated_matrix, join="outer", axis=1, sort=False - ) - concatenated_matrix = concatenated_matrix.reindex(align_to, copy=False) - return conflicts, concatenated_matrix + spaceranger_files[key] = file[0] + + return spaceranger_files -def cast_to_writeable_dtype(result: pd.DataFrame) -> pd.DataFrame: - """ - Cast the dataframe to dtypes that can be written by mudata. - """ - # dtype inferral workfs better with np.nan - result = result.replace({pd.NA: np.nan}) +def main(): + spaceranger_files = retrieve_input_data(par["input"], input_type=par["output_type"]) - # MuData supports nullable booleans and ints - # ie. \`IntegerArray\` and \`BooleanArray\` - result = result.convert_dtypes( - infer_objects=True, - convert_integer=True, - convert_string=False, - convert_boolean=True, - convert_floating=False, - ) + logger.info("Reading count matrix...") + adata = sc.read_10x_h5(spaceranger_files["count_matrix"], gex_only=False) - # Convert leftover 'object' columns to string - # However, na values are supported, so convert all values except NA's to string - object_cols = result.select_dtypes(include="object").columns.values - for obj_col in object_cols: - result[obj_col] = ( - result[obj_col] - .where(result[obj_col].isna(), result[obj_col].astype(str)) - .astype("category") - ) - return result + # set the gene ids as var_names + logger.info("Renaming var columns") + adata.var = adata.var.rename_axis("gene_symbol").reset_index().set_index("gene_ids") - -def split_conflicts_modalities( - n_processes: int, samples: dict[str, anndata.AnnData], output: anndata.AnnData -) -> anndata.AnnData: - """ - Merge .var and .obs matrices of the anndata objects. Columns are merged - when the values (excl NA) are the same in each of the matrices. - Conflicting columns are moved to a separate dataframe (one dataframe for each column, - containing all the corresponding column from each sample). - """ - matrices_to_parse = ("var", "obs") - for matrix_name in matrices_to_parse: - matrices = { - sample_id: getattr(sample, matrix_name) - for sample_id, sample in samples.items() - } - output_index = getattr(output, matrix_name).index - conflicts, concatenated_matrix = concatenate_matrices( - n_processes, matrices, output_index - ) - if concatenated_matrix.empty: - concatenated_matrix.index = output_index - - # Even though we did not touch the varm and obsm matrices that were already present, - # the joining of observations might have caused a dtype change in these matrices as well - # so these also need to be casted to a writable dtype... - for multidim_name, multidim_data in getattr(output, f"{matrix_name}m").items(): - new_data = ( - cast_to_writeable_dtype(multidim_data) - if isinstance(multidim_data, pd.DataFrame) - else multidim_data - ) - getattr(output, f"{matrix_name}m")[multidim_name] = new_data - - # Write the conflicts to the output - for conflict_name, conflict_data in conflicts.items(): - getattr(output, f"{matrix_name}m")[conflict_name] = conflict_data - - # Set other annotation matrices in the output - setattr(output, matrix_name, concatenated_matrix) - - return output - - -def concatenate_modality( - n_processes: int, - mod: str | None, - input_files: Iterable[str | Path], - other_axis_mode: str, - uns_merge_mode: str, - input_ids: tuple[str], -) -> anndata.AnnData: - concat_modes = { - "move": "unique", - } - other_axis_mode_to_apply = concat_modes.get(other_axis_mode, other_axis_mode) - - uns_merge_modes = {"make_unique": None} - uns_merge_mode_to_apply = uns_merge_modes.get(uns_merge_mode, uns_merge_mode) - - mod_data = {} - mod_indices_combined = pd.Index([]) - for input_id, input_file in zip(input_ids, input_files): - if mod is not None: - try: - data = mu.read_h5ad(input_file, mod=mod) - - # Remove obsp keys that are not in par["obsp_keys"] - if par["obsp_keys"]: - # Keep only the obsp keys that are specified in par["obsp_keys"] - keys_to_remove = set(data.obsp.keys()) - set(par["obsp_keys"]) - for key in keys_to_remove: - del data.obsp[key] - - mod_data[input_id] = data - mod_indices_combined = mod_indices_combined.append(data.obs.index) - except KeyError as e: # Modality does not exist for this sample, skip it - if ( - f"Unable to synchronously open object (object '{mod}' doesn't exist)" - not in str(e) - ): - raise e - pass - else: # When mod=None, process the 'global' h5mu state - with H5File(input_file, "r") as input_h5: - if "uns" in input_h5.keys(): - uns_data = anndata.experimental.read_elem(input_h5["uns"]) - if uns_data: - mod_data[input_id] = anndata.AnnData(uns=uns_data) - - if not mod_indices_combined.is_unique: - raise ValueError("Observations are not unique across samples.") - - if not mod_data: - return anndata.AnnData() - - concatenated_data = anndata.concat( - mod_data.values(), - join="outer", - pairwise=True if par["obsp_keys"] else False, - merge=other_axis_mode_to_apply, - uns_merge=uns_merge_mode_to_apply, - ) - - if other_axis_mode == "move": - concatenated_data = split_conflicts_modalities( - n_processes, mod_data, concatenated_data + if par["uns_metrics"]: + logger.info("Reading metrics summary file...") + metrics_summary = pd.read_csv( + spaceranger_files["metrics_summary"], + decimal=".", + quotechar='"', + thousands=",", ) - if uns_merge_mode == "make_unique": - concatenated_data = make_uns_keys_unique(mod_data, concatenated_data) + logger.info("Storing metrics summary in .uns slot...") + adata.uns[par["uns_metrics"]] = metrics_summary - return concatenated_data + if par["uns_probe_set"]: + logger.info("Reading probe set file...") + def read_hash_metadata(path): + meta = {} + with open(path, "r", encoding="utf-8") as f: + for i, line in enumerate(f): + if not line.startswith("#"): + break + line = line[1:].strip() + if "=" in line: + k, v = line.split("=", 1) + meta[k.strip()] = v.strip() + return meta -def concatenate_modalities( - n_processes: int, - modalities: list[str], - input_files: Path | str, - other_axis_mode: str, - uns_merge_mode: str, - output_file: Path | str, - compression: Literal["gzip"] | Literal["lzf"], - input_ids: tuple[str] | None = None, -) -> None: - """ - Join the modalities together into a single multimodal sample. - """ - logger.info("Concatenating samples.") - output_file, input_files = ( - Path(output_file), - [Path(input_file) for input_file in input_files], + meta = read_hash_metadata(spaceranger_files["probe_set"]) + probe_set = pd.read_csv(spaceranger_files["probe_set"], comment="#") + + logger.info("Storing probe set in .uns slot...") + adata.uns[par["uns_probe_set"]] = probe_set + adata.uns[par["uns_probe_set"] + "_meta"] = meta + + logger.info("Reading spatial coordinates...") + spatial_coords = pd.read_csv( + spaceranger_files["spatial_coords"], decimal=".", thousands="," ) - output_file_uncompressed = output_file.with_name( - output_file.stem + "_uncompressed.h5mu" + + spatial_coords_aligned = spatial_coords.set_index("barcode").reindex( + adata.obs_names ) - output_file_uncompressed.touch() - # Create empty mudata file - mdata = mu.MuData({modality: anndata.AnnData() for modality in modalities}) - mdata.write(output_file_uncompressed, compression=compression) + logger.info("Storing spatial coordinates in .obsm slot...") + adata.obsm[par["obsm_coordinates"]] = spatial_coords_aligned[ + ["pxl_col_in_fullres", "pxl_row_in_fullres"] + ].to_numpy() - # Use "None" for the global slots (not assigned to any modality) - for mod_name in modalities + [ - None, - ]: - new_mod = concatenate_modality( - n_processes, - mod_name, - input_files, - other_axis_mode, - uns_merge_mode, - input_ids, - ) - if mod_name is None: - if new_mod.uns: - with H5File(output_file_uncompressed, "r+") as open_h5mu_file: - anndata.experimental.write_elem( - open_h5mu_file, "uns", dict(new_mod.uns) - ) - continue - logger.info( - "Writing out modality '%s' to '%s' with compression '%s'.", - mod_name, - output_file_uncompressed, - compression, - ) - mu.write_h5ad(output_file_uncompressed, data=new_mod, mod=mod_name) + # generate output + logger.info("Convert to mudata") + mdata = mudata.MuData({par["modality"]: adata}) - if compression: - compress_h5mu(output_file_uncompressed, output_file, compression=compression) - output_file_uncompressed.unlink() - else: - shutil.move(output_file_uncompressed, output_file) + # override root .obs and .uns + mdata.obs = adata.obs + mdata.uns = adata.uns - logger.info("Concatenation successful.") - - -def main() -> None: - # Get a list of all possible modalities - mods = set() - for path in par["input"]: - try: - with H5File(path, "r") as f_root: - mods = mods | set(f_root["mod"].keys()) - except OSError: - raise OSError(f"Failed to load {path}. Is it a valid h5 file?") - - input_ids = None - if par["input_id"]: - input_ids: tuple[str] = tuple(i.strip() for i in par["input_id"]) - if len(input_ids) != len(par["input"]): - raise ValueError( - "The number of sample names must match the number of sample files." - ) - - if len(set(input_ids)) != len(input_ids): - raise ValueError("The sample names should be unique.") - - logger.info("\\nConcatenating data from paths:\\n\\t%s", "\\n\\t".join(par["input"])) - - if par["other_axis_mode"] == "move" and not input_ids: - raise ValueError("--mode 'move' requires --input_ids.") - - n_processes = meta["cpus"] if meta["cpus"] else 1 - - if par["modality"]: - par["modality"] = set(par["modality"]) - if not par["modality"].issubset(mods): - mods_joined, input_mods_joined = ", ".join(mods), ", ".join(par["modality"]) - raise ValueError( - f"One of the modalities provided ({input_mods_joined}) is not available in the input data {mods_joined}" - ) - mods = par["modality"] - - concatenate_modalities( - n_processes, - list(mods), - par["input"], - par["other_axis_mode"], - par["uns_merge_mode"], - par["output"], - par["output_compression"], - input_ids=input_ids, - ) + # write output + logger.info("Writing %s", par["output"]) + mdata.write_h5mu(par["output"], compression=par["output_compression"]) if __name__ == "__main__": @@ -1725,17 +1368,7 @@ if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then # 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="$(ViashDockerStripAutomount "$var")" - else - VIASH_TEST_INPUT="$VIASH_TEST_INPUT;""$(ViashDockerStripAutomount "$var")" - fi - done - VIASH_PAR_INPUT="$VIASH_TEST_INPUT" + VIASH_PAR_INPUT=$(ViashDockerStripAutomount "$VIASH_PAR_INPUT") fi if [ ! -z "$VIASH_PAR_OUTPUT" ]; then VIASH_PAR_OUTPUT=$(ViashDockerStripAutomount "$VIASH_PAR_OUTPUT") diff --git a/target/executable/convert/from_spaceranger_to_h5mu/nextflow_labels.config b/target/executable/convert/from_spaceranger_to_h5mu/nextflow_labels.config new file mode 100644 index 0000000..541aaad --- /dev/null +++ b/target/executable/convert/from_spaceranger_to_h5mu/nextflow_labels.config @@ -0,0 +1,68 @@ +process { + // Default resources for components that hardly do any processing + memory = { 2.GB * task.attempt } + cpus = 1 + + // Retry for exit codes that have something to do with memory issues + errorStrategy = { task.exitStatus in 137..140 ? 'retry' : 'terminate' } + maxRetries = 3 + maxMemory = null + + // CPU resources + withLabel: singlecpu { cpus = 1 } + withLabel: lowcpu { cpus = 4 } + withLabel: midcpu { cpus = 10 } + withLabel: highcpu { cpus = 20 } + + // Memory resources + withLabel: lowmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: midmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: highmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: veryhighmem { memory = { get_memory( 75.GB * task.attempt ) } } + + // Disk space + // Nextflow apparently can't handle empty directives, i.e. + // withLabel: lowdisk {} + // so for that reason we have to add a dummy directive + withLabel: lowdisk { + dummyDirective = "dummyValue" + } + withLabel: middisk { + dummyDirective = "dummyValue" + } + withLabel: highdisk { + dummyDirective = "dummyValue" + } + withLabel: veryhighdisk { + dummyDirective = "dummyValue" + } + // NOTE: The above labels intentionally do not have an effect by default. + // The user should set the disk space requirements by adding the following + // to the compute environment: + // + // withLabel: lowdisk { disk = { 20.GB * task.attempt } } + // withLabel: middisk { disk = { 100.GB * task.attempt } } + // withLabel: highdisk { disk = { 200.GB * task.attempt } } + // withLabel: veryhighdisk { disk = { 500.GB * task.attempt } } +} + +def get_memory(to_compare) { + if (!process.containsKey("maxMemory") || !process.maxMemory) { + return to_compare + } + + try { + if (process.containsKey("maxRetries") && process.maxRetries && task.attempt == (process.maxRetries as int)) { + return process.maxMemory + } + else if (to_compare.compareTo(process.maxMemory as nextflow.util.MemoryUnit) == 1) { + return max_memory as nextflow.util.MemoryUnit + } + else { + return to_compare + } + } catch (all) { + println "Error processing memory resources. Please check that process.maxMemory '${process.maxMemory}' and process.maxRetries '${process.maxRetries}' are valid!" + System.exit(1) + } +} diff --git a/target/executable/convert/from_spaceranger_to_h5mu/setup_logger.py b/target/executable/convert/from_spaceranger_to_h5mu/setup_logger.py new file mode 100644 index 0000000..3ca1cdb --- /dev/null +++ b/target/executable/convert/from_spaceranger_to_h5mu/setup_logger.py @@ -0,0 +1,12 @@ +def setup_logger(): + import logging + from sys import stdout + + logger = logging.getLogger() + logger.setLevel(logging.INFO) + console_handler = logging.StreamHandler(stdout) + logFormatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s") + console_handler.setFormatter(logFormatter) + logger.addHandler(console_handler) + + return logger diff --git a/target/executable/convert/from_spatialdata_to_h5mu/.config.vsh.yaml b/target/executable/convert/from_spatialdata_to_h5mu/.config.vsh.yaml index 5633de9..7ffa45a 100644 --- a/target/executable/convert/from_spatialdata_to_h5mu/.config.vsh.yaml +++ b/target/executable/convert/from_spatialdata_to_h5mu/.config.vsh.yaml @@ -101,7 +101,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -190,13 +190,15 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "spatialdata~=0.5.0" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "spatialdata~=0.6.1" - "pyarrow~=18.0.0" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -221,7 +223,7 @@ build_info: output: "target/executable/convert/from_spatialdata_to_h5mu" executable: "target/executable/convert/from_spatialdata_to_h5mu/from_spatialdata_to_h5mu" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -235,7 +237,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/convert/from_spatialdata_to_h5mu/from_spatialdata_to_h5mu b/target/executable/convert/from_spatialdata_to_h5mu/from_spatialdata_to_h5mu index 3ee54ed..5e7bc8b 100755 --- a/target/executable/convert/from_spatialdata_to_h5mu/from_spatialdata_to_h5mu +++ b/target/executable/convert/from_spatialdata_to_h5mu/from_spatialdata_to_h5mu @@ -454,14 +454,14 @@ RUN apt-get update && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "anndata~=0.11.1" "mudata~=0.3.1" "spatialdata~=0.5.0" "pyarrow~=18.0.0" && \ - python -c 'exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)")' + pip install --upgrade --no-cache-dir "anndata~=0.12.7" "awkward" "mudata~=0.3.2" "spatialdata~=0.6.1" "pyarrow~=18.0.0" && \ + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' LABEL org.opencontainers.image.authors="Dorien Roosen, Weiwei Schultz" LABEL org.opencontainers.image.description="Companion container for running component convert from_spatialdata_to_h5mu" -LABEL org.opencontainers.image.created="2026-01-26T08:53:42Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:55Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/executable/convert/from_xenium_to_h5mu/.config.vsh.yaml b/target/executable/convert/from_xenium_to_h5mu/.config.vsh.yaml index 9d78700..6957c44 100644 --- a/target/executable/convert/from_xenium_to_h5mu/.config.vsh.yaml +++ b/target/executable/convert/from_xenium_to_h5mu/.config.vsh.yaml @@ -121,7 +121,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -213,15 +213,17 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" - "scanpy~=1.10.4" - "pyarrow" git: - "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -244,7 +246,7 @@ build_info: output: "target/executable/convert/from_xenium_to_h5mu" executable: "target/executable/convert/from_xenium_to_h5mu/from_xenium_to_h5mu" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -258,7 +260,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/convert/from_xenium_to_h5mu/from_xenium_to_h5mu b/target/executable/convert/from_xenium_to_h5mu/from_xenium_to_h5mu index 1a6e179..5f09df0 100755 --- a/target/executable/convert/from_xenium_to_h5mu/from_xenium_to_h5mu +++ b/target/executable/convert/from_xenium_to_h5mu/from_xenium_to_h5mu @@ -453,15 +453,15 @@ RUN apt-get update && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "anndata~=0.11.1" "mudata~=0.3.1" "scanpy~=1.10.4" "pyarrow" && \ + pip install --upgrade --no-cache-dir "anndata~=0.12.7" "awkward" "mudata~=0.3.2" "scanpy~=1.10.4" "pyarrow" && \ pip install --upgrade --no-cache-dir "git+https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" && \ - python -c 'exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)")' + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' LABEL org.opencontainers.image.authors="Dorien Roosen" LABEL org.opencontainers.image.description="Companion container for running component convert from_xenium_to_h5mu" -LABEL org.opencontainers.image.created="2026-01-26T08:53:42Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:54Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/executable/convert/from_xenium_to_spatialdata/.config.vsh.yaml b/target/executable/convert/from_xenium_to_spatialdata/.config.vsh.yaml index c930cab..b4bafc8 100644 --- a/target/executable/convert/from_xenium_to_spatialdata/.config.vsh.yaml +++ b/target/executable/convert/from_xenium_to_spatialdata/.config.vsh.yaml @@ -201,7 +201,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -293,8 +293,8 @@ engines: - type: "python" user: false packages: - - "spatialdata-io~=0.3.0" - - "spatialdata~=0.5.0" + - "spatialdata-io~=0.5.1" + - "spatialdata~=0.6.1" - "pyarrow~=18.0.0" git: - "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" @@ -326,7 +326,7 @@ build_info: output: "target/executable/convert/from_xenium_to_spatialdata" executable: "target/executable/convert/from_xenium_to_spatialdata/from_xenium_to_spatialdata" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -340,7 +340,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/convert/from_xenium_to_spatialdata/from_xenium_to_spatialdata b/target/executable/convert/from_xenium_to_spatialdata/from_xenium_to_spatialdata index ec5649d..a30db0d 100755 --- a/target/executable/convert/from_xenium_to_spatialdata/from_xenium_to_spatialdata +++ b/target/executable/convert/from_xenium_to_spatialdata/from_xenium_to_spatialdata @@ -454,14 +454,14 @@ RUN apt-get update && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "spatialdata-io~=0.3.0" "spatialdata~=0.5.0" "pyarrow~=18.0.0" && \ + pip install --upgrade --no-cache-dir "spatialdata-io~=0.5.1" "spatialdata~=0.6.1" "pyarrow~=18.0.0" && \ pip install --upgrade --no-cache-dir "git+https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" LABEL org.opencontainers.image.authors="Dorien Roosen, Weiwei Schultz" LABEL org.opencontainers.image.description="Companion container for running component convert from_xenium_to_spatialdata" -LABEL org.opencontainers.image.created="2026-01-26T08:53:43Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:55Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/executable/convert/from_xenium_to_spatialexperiment/.config.vsh.yaml b/target/executable/convert/from_xenium_to_spatialexperiment/.config.vsh.yaml index a406bbd..8a61b2d 100644 --- a/target/executable/convert/from_xenium_to_spatialexperiment/.config.vsh.yaml +++ b/target/executable/convert/from_xenium_to_spatialexperiment/.config.vsh.yaml @@ -115,7 +115,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -238,7 +238,7 @@ build_info: output: "target/executable/convert/from_xenium_to_spatialexperiment" executable: "target/executable/convert/from_xenium_to_spatialexperiment/from_xenium_to_spatialexperiment" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -252,7 +252,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/convert/from_xenium_to_spatialexperiment/from_xenium_to_spatialexperiment b/target/executable/convert/from_xenium_to_spatialexperiment/from_xenium_to_spatialexperiment index a1e9cd9..9987ab0 100755 --- a/target/executable/convert/from_xenium_to_spatialexperiment/from_xenium_to_spatialexperiment +++ b/target/executable/convert/from_xenium_to_spatialexperiment/from_xenium_to_spatialexperiment @@ -462,9 +462,9 @@ RUN Rscript -e 'options(warn = 2); if (!requireNamespace("BiocManager", quietly LABEL org.opencontainers.image.authors="Dorien Roosen" LABEL org.opencontainers.image.description="Companion container for running component convert from_xenium_to_spatialexperiment" -LABEL org.opencontainers.image.created="2026-01-26T08:53:42Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:55Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/executable/dataflow/concatenate_h5mu/.config.vsh.yaml b/target/executable/dataflow/concatenate_h5mu/.config.vsh.yaml deleted file mode 100644 index 6ee0600..0000000 --- a/target/executable/dataflow/concatenate_h5mu/.config.vsh.yaml +++ /dev/null @@ -1,333 +0,0 @@ -name: "concatenate_h5mu" -namespace: "dataflow" -version: "niche-compass" -authors: -- name: "Dries Schaumont" - roles: - - "maintainer" - info: - role: "Core Team Member" - links: - email: "dries@data-intuitive.com" - github: "DriesSchaumont" - orcid: "0000-0002-4389-0440" - linkedin: "dries-schaumont" - organizations: - - name: "Data Intuitive" - href: "https://www.data-intuitive.com" - role: "Data Scientist" -argument_groups: -- name: "Arguments" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - description: "Paths to the different samples to be concatenated." - info: null - example: - - "sample_paths" - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: true - multiple_sep: ";" - - type: "string" - name: "--modality" - description: "Only output concatenated objects for the provided modalities. Outputs\ - \ all modalities by default." - info: null - required: false - direction: "input" - multiple: true - multiple_sep: ";" - - type: "string" - name: "--input_id" - description: "Names of the different samples that have to be concatenated. Must\ - \ be specified when using '--mode move'.\nIn this case, the ids will be used\ - \ for the columns names of the dataframes registring the conflicts.\nIf specified,\ - \ must be of same length as `--input`.\n" - info: null - required: false - direction: "input" - multiple: true - multiple_sep: ";" - - type: "file" - name: "--output" - alternatives: - - "-o" - description: "Output location for the concatenated MuData object file.\n" - info: null - example: - - "output.h5mu" - must_exist: true - create_parent: true - required: false - direction: "output" - multiple: false - multiple_sep: ";" - - type: "string" - name: "--obs_sample_name" - description: "Name of the .obs key under which to add the sample names." - info: null - default: - - "sample_id" - required: false - direction: "input" - multiple: false - multiple_sep: ";" - - type: "string" - name: "--other_axis_mode" - description: "How to handle the merging of other axis (var, obs, ...).\n\n -\ - \ None: keep no data\n - same: only keep elements of the matrices which are\ - \ the same in each of the samples\n - unique: only keep elements for which\ - \ there is only 1 possible value (1 value that can occur in multiple samples)\n\ - \ - first: keep the annotation from the first sample\n - only: keep elements\ - \ that show up in only one of the objects (1 unique element in only 1 sample)\n\ - \ - move: identical to 'same', but moving the conflicting values to .varm or\ - \ .obsm\n" - info: null - default: - - "move" - required: false - choices: - - "same" - - "unique" - - "first" - - "only" - - "concat" - - "move" - direction: "input" - multiple: false - multiple_sep: ";" - - type: "string" - name: "--uns_merge_mode" - description: "How to handle the merging of .uns across modalities\n - None: keep\ - \ no data\n - same: only keep elements of the matrices which are the same in\ - \ each of the samples\n - unique: only keep elements for which there is only\ - \ 1 possible value (1 value that can occur in multiple samples)\n - first:\ - \ keep the annotation from the first sample\n - only: keep elements that show\ - \ up in only one of the objects (1 unique element in only 1 sample)\n - make_unique:\ - \ identical to 'unique', but keys which are not unique are made unique by prefixing\ - \ them with the sample id.\n" - info: null - default: - - "make_unique" - required: false - choices: - - "same" - - "unique" - - "first" - - "only" - - "make_unique" - direction: "input" - multiple: false - multiple_sep: ";" - - type: "string" - name: "--obsp_keys" - description: "List of `.obsp` keys for which block-diagonal concatenation should\ - \ be performed.\nIf not provided, no `.obsp` keys will be concatenated.\nProvided\ - \ keys must be present in all samples for block concatenation to be performed.\n" - info: null - required: false - direction: "input" - multiple: true - multiple_sep: ";" - - type: "string" - name: "--output_compression" - description: "Compression format to use for the output AnnData and/or Mudata objects.\n\ - By default no compression is applied.\n" - info: null - example: - - "gzip" - required: false - choices: - - "gzip" - - "lzf" - direction: "input" - multiple: false - multiple_sep: ";" -resources: -- type: "python_script" - path: "script.py" - is_executable: true -- type: "file" - path: "setup_logger.py" -- type: "file" - path: "compress_h5mu.py" -- type: "file" - path: "nextflow_labels.config" - dest: "nextflow_labels.config" -description: "Concatenate observations from samples in several (uni- and/or multi-modal)\ - \ MuData files into a single file.\n" -test_resources: -- type: "python_script" - path: "test.py" - is_executable: true -- type: "file" - path: "e18_mouse_brain_fresh_5k_filtered_feature_bc_matrix_subset_unique_obs.h5mu" -- type: "file" - path: "human_brain_3k_filtered_feature_bc_matrix_subset_unique_obs.h5mu" -info: null -status: "enabled" -scope: - image: "public" - target: "public" -repositories: -- type: "vsh" - name: "openpipeline" - repo: "openpipeline" - tag: "v3.0.0" -links: - repository: "https://github.com/openpipelines-bio/openpipeline_spatial" - docker_registry: "ghcr.io" -runners: -- type: "executable" - id: "executable" - docker_setup_strategy: "ifneedbepullelsecachedbuild" -- type: "nextflow" - id: "nextflow" - directives: - label: - - "midcpu" - - "highmem" - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1000000000.B" - mem2gb: "memory = 2000000000.B" - mem5gb: "memory = 5000000000.B" - mem10gb: "memory = 10000000000.B" - mem20gb: "memory = 20000000000.B" - mem50gb: "memory = 50000000000.B" - mem100gb: "memory = 100000000000.B" - mem200gb: "memory = 200000000000.B" - mem500gb: "memory = 500000000000.B" - mem1tb: "memory = 1000000000000.B" - mem2tb: "memory = 2000000000000.B" - mem5tb: "memory = 5000000000000.B" - mem10tb: "memory = 10000000000000.B" - mem20tb: "memory = 20000000000000.B" - mem50tb: "memory = 50000000000000.B" - mem100tb: "memory = 100000000000000.B" - mem200tb: "memory = 200000000000000.B" - mem500tb: "memory = 500000000000000.B" - mem1gib: "memory = 1073741824.B" - mem2gib: "memory = 2147483648.B" - mem4gib: "memory = 4294967296.B" - mem8gib: "memory = 8589934592.B" - mem16gib: "memory = 17179869184.B" - mem32gib: "memory = 34359738368.B" - mem64gib: "memory = 68719476736.B" - mem128gib: "memory = 137438953472.B" - mem256gib: "memory = 274877906944.B" - mem512gib: "memory = 549755813888.B" - mem1tib: "memory = 1099511627776.B" - mem2tib: "memory = 2199023255552.B" - mem4tib: "memory = 4398046511104.B" - mem8tib: "memory = 8796093022208.B" - mem16tib: "memory = 17592186044416.B" - mem32tib: "memory = 35184372088832.B" - mem64tib: "memory = 70368744177664.B" - mem128tib: "memory = 140737488355328.B" - mem256tib: "memory = 281474976710656.B" - mem512tib: "memory = 562949953421312.B" - 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" - script: - - "includeConfig(\"nextflow_labels.config\")" - debug: false - container: "docker" -engines: -- type: "docker" - id: "docker" - image: "python:3.13-slim" - target_registry: "images.viash-hub.com" - target_tag: "niche-compass" - namespace_separator: "/" - setup: - - type: "apt" - packages: - - "procps" - interactive: false - - type: "python" - user: false - packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" - upgrade: true - test_setup: - - type: "apt" - packages: - - "git" - interactive: false - - type: "python" - user: false - packages: - - "viashpy==0.9.0" - github: - - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" - upgrade: true - - type: "python" - user: false - packages: - - "viashpy==0.9.0" - - "pytest-benchmark" - upgrade: true - entrypoint: [] - cmd: null -- type: "native" - id: "native" -build_info: - config: "src/dataflow/concatenate_h5mu/config.vsh.yaml" - runner: "executable" - engine: "docker|native" - output: "target/executable/dataflow/concatenate_h5mu" - executable: "target/executable/dataflow/concatenate_h5mu/concatenate_h5mu" - viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" - git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" -package_config: - name: "openpipeline_spatial" - version: "niche-compass" - info: - test_resources: - - type: "s3" - path: "s3://openpipelines-bio/openpipeline_spatial/resources_test" - dest: "resources_test" - repositories: - - type: "vsh" - name: "openpipeline" - repo: "openpipeline" - tag: "v3.0.0" - viash_version: "0.9.4" - source: "src" - target: "target" - config_mods: - - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n\ - .runners[.type == 'nextflow'].config.script := 'includeConfig(\"nextflow_labels.config\"\ - )'" - - ".engines += { type: \"native\" }" - - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'niche-compass'" - organization: "vsh" - links: - repository: "https://github.com/openpipelines-bio/openpipeline_spatial" - docker_registry: "ghcr.io" diff --git a/target/executable/dataflow/concatenate_h5mu/compress_h5mu.py b/target/executable/dataflow/concatenate_h5mu/compress_h5mu.py deleted file mode 100644 index 4b363ee..0000000 --- a/target/executable/dataflow/concatenate_h5mu/compress_h5mu.py +++ /dev/null @@ -1,87 +0,0 @@ -import shutil -from anndata import AnnData -from mudata import write_h5ad -from h5py import File as H5File -from h5py import Group, Dataset -from pathlib import Path -from typing import Union, Literal -from functools import partial - - -def compress_h5mu( - input_path: Union[str, Path], - output_path: Union[str, Path], - compression: Union[Literal["gzip"], Literal["lzf"]], -): - input_path, output_path = str(input_path), str(output_path) - - def copy_attributes(in_object, out_object): - for key, value in in_object.attrs.items(): - out_object.attrs[key] = value - - def visit_path( - output_h5: H5File, - compression: Union[Literal["gzip"], Literal["lzf"]], - name: str, - object: Union[Group, Dataset], - ): - if isinstance(object, Group): - new_group = output_h5.create_group(name) - copy_attributes(object, new_group) - elif isinstance(object, Dataset): - # Compression only works for non-scalar Dataset objects - # Scalar objects dont have a shape defined - if not object.compression and object.shape not in [None, ()]: - new_dataset = output_h5.create_dataset( - name, data=object, compression=compression - ) - copy_attributes(object, new_dataset) - else: - output_h5.copy(object, name) - else: - raise NotImplementedError( - f"Could not copy element {name}, " - f"type has not been implemented yet: {type(object)}" - ) - - with ( - H5File(input_path, "r") as input_h5, - H5File(output_path, "w", userblock_size=512) as output_h5, - ): - copy_attributes(input_h5, output_h5) - input_h5.visititems(partial(visit_path, output_h5, compression)) - - with open(input_path, "rb") as input_bytes: - # Mudata puts metadata like this in the first 512 bytes: - # MuData (format-version=0.1.0;creator=muon;creator-version=0.2.0) - # See mudata/_core/io.py, read_h5mu() function - starting_metadata = input_bytes.read(100) - # The metadata is padded with extra null bytes up until 512 bytes - truncate_location = starting_metadata.find(b"\x00") - starting_metadata = starting_metadata[:truncate_location] - with open(output_path, "br+") as f: - nbytes = f.write(starting_metadata) - f.write(b"\0" * (512 - nbytes)) - - -def write_h5ad_to_h5mu_with_compression( - output_file: Union[str, Path], - h5mu: Union[str, Path], - modality_name: str, - modality_data: AnnData, - output_compression=None, -): - output_file = Path(output_file) - h5mu = Path(h5mu) - output_file_uncompressed = ( - output_file.with_name(output_file.stem + "_uncompressed.h5mu") - if output_compression - else output_file - ) - shutil.copyfile(h5mu, output_file_uncompressed) - write_h5ad(filename=output_file_uncompressed, mod=modality_name, data=modality_data) - if output_compression: - compress_h5mu( - output_file_uncompressed, output_file, compression=output_compression - ) - output_file_uncompressed.unlink() diff --git a/target/executable/mapping/spaceranger_count/.config.vsh.yaml b/target/executable/mapping/spaceranger_count/.config.vsh.yaml index 7277f9f..6063fd8 100644 --- a/target/executable/mapping/spaceranger_count/.config.vsh.yaml +++ b/target/executable/mapping/spaceranger_count/.config.vsh.yaml @@ -330,7 +330,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" keywords: - "spaceranger" links: @@ -439,7 +439,7 @@ build_info: output: "target/executable/mapping/spaceranger_count" executable: "target/executable/mapping/spaceranger_count/spaceranger_count" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -453,7 +453,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/mapping/spaceranger_count/spaceranger_count b/target/executable/mapping/spaceranger_count/spaceranger_count index 761437c..2373ac6 100755 --- a/target/executable/mapping/spaceranger_count/spaceranger_count +++ b/target/executable/mapping/spaceranger_count/spaceranger_count @@ -453,9 +453,9 @@ apt upgrade -y && apt install -y procps && rm -rf /var/lib/apt/lists/* LABEL org.opencontainers.image.authors="Jakub Majercik" LABEL org.opencontainers.image.description="Companion container for running component mapping spaceranger_count" -LABEL org.opencontainers.image.created="2026-01-26T08:53:42Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:54Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER @@ -1722,7 +1722,7 @@ for par in \${unset_if_false[@]}; do [[ "\$test_val" == "false" ]] && unset \$par done -# just to make sure paths are absolute +# Make sure paths are absolute par_gex_reference=\`realpath \$par_gex_reference\` par_output=\`realpath \$par_output\` par_probe_set=\`realpath \$par_probe_set\` diff --git a/target/executable/neighbors/spatial_neighborhood_graph/.config.vsh.yaml b/target/executable/neighbors/spatial_neighborhood_graph/.config.vsh.yaml index 1742ee6..8c512df 100644 --- a/target/executable/neighbors/spatial_neighborhood_graph/.config.vsh.yaml +++ b/target/executable/neighbors/spatial_neighborhood_graph/.config.vsh.yaml @@ -147,7 +147,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -237,14 +237,15 @@ engines: - type: "python" user: false packages: - - "spatialdata~=0.5.0" - - "pyarrow~=18.0.0" - - "squidpy~=1.6.5" - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "scanpy~=1.10.4" + - "squidpy~=1.7.0" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -269,7 +270,7 @@ build_info: output: "target/executable/neighbors/spatial_neighborhood_graph" executable: "target/executable/neighbors/spatial_neighborhood_graph/spatial_neighborhood_graph" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -283,7 +284,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/neighbors/spatial_neighborhood_graph/spatial_neighborhood_graph b/target/executable/neighbors/spatial_neighborhood_graph/spatial_neighborhood_graph index df78570..5f3d5ad 100755 --- a/target/executable/neighbors/spatial_neighborhood_graph/spatial_neighborhood_graph +++ b/target/executable/neighbors/spatial_neighborhood_graph/spatial_neighborhood_graph @@ -453,14 +453,14 @@ RUN apt-get update && \ rm -rf /var/lib/apt/lists/* RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "spatialdata~=0.5.0" "pyarrow~=18.0.0" "squidpy~=1.6.5" "anndata~=0.11.1" "mudata~=0.3.1" && \ - python -c 'exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)")' + pip install --upgrade --no-cache-dir "scanpy~=1.10.4" "squidpy~=1.7.0" "anndata~=0.12.7" "awkward" "mudata~=0.3.2" && \ + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' LABEL org.opencontainers.image.authors="Dorien Roosen" LABEL org.opencontainers.image.description="Companion container for running component neighbors spatial_neighborhood_graph" -LABEL org.opencontainers.image.created="2026-01-26T08:53:42Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:54Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER diff --git a/target/executable/nichecompass/nichecompass/.config.vsh.yaml b/target/executable/nichecompass/nichecompass/.config.vsh.yaml index ad2769e..3ad029e 100644 --- a/target/executable/nichecompass/nichecompass/.config.vsh.yaml +++ b/target/executable/nichecompass/nichecompass/.config.vsh.yaml @@ -875,7 +875,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -954,18 +954,11 @@ runners: engines: - type: "docker" id: "docker" - image: "nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04" + image: "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime" target_registry: "images.viash-hub.com" target_tag: "niche-compass" namespace_separator: "/" setup: - - type: "apt" - packages: - - "libhdf5-dev" - - "python3-pip" - - "python3-dev" - - "python-is-python3" - interactive: false - type: "docker" run: - "pip install torch --index-url https://download.pytorch.org/whl/cu124 \\\n&&\ @@ -974,11 +967,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true - type: "python" user: false @@ -1003,7 +998,7 @@ build_info: output: "target/executable/nichecompass/nichecompass" executable: "target/executable/nichecompass/nichecompass/nichecompass" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -1017,7 +1012,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/executable/nichecompass/nichecompass/nichecompass b/target/executable/nichecompass/nichecompass/nichecompass index bc33024..a1cc9ca 100755 --- a/target/executable/nichecompass/nichecompass/nichecompass +++ b/target/executable/nichecompass/nichecompass/nichecompass @@ -446,27 +446,23 @@ function ViashDockerfile { if [[ "$engine_id" == "docker" ]]; then cat << 'VIASHDOCKER' -FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04 +FROM pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime ENTRYPOINT [] -RUN apt-get update && \ - DEBIAN_FRONTEND=noninteractive apt-get install -y libhdf5-dev python3-pip python3-dev python-is-python3 && \ - rm -rf /var/lib/apt/lists/* - RUN pip install torch --index-url https://download.pytorch.org/whl/cu124 \ && pip install pyg_lib torch-scatter torch-sparse -f https://data.pyg.org/whl/torch-2.6.0+cu124.html RUN pip install --upgrade pip && \ - pip install --upgrade --no-cache-dir "anndata~=0.11.1" "mudata~=0.3.1" && \ - python -c 'exec("try:\n import awkward\nexcept ModuleNotFoundError:\n exit(0)\nelse: exit(1)")' + pip install --upgrade --no-cache-dir "anndata~=0.12.7" "awkward" "mudata~=0.3.2" && \ + python -c 'exec("try:\n import zarr; from importlib.metadata import version\nexcept ModuleNotFoundError:\n exit(0)\nelse: assert int(version(\"zarr\").partition(\".\")[0]) > 2")' RUN pip install --upgrade pip && \ pip install --upgrade --no-cache-dir "numpy<2" "nichecompass" LABEL org.opencontainers.image.authors="Dorien Roosen" LABEL org.opencontainers.image.description="Companion container for running component nichecompass nichecompass" -LABEL org.opencontainers.image.created="2026-01-26T08:53:41Z" +LABEL org.opencontainers.image.created="2026-01-27T10:47:53Z" LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline_spatial" -LABEL org.opencontainers.image.revision="f91eceb7cf408169b2847c359c6e2acd77856ff7" +LABEL org.opencontainers.image.revision="a4d81924a673566026c204c55add247504ef1c56" LABEL org.opencontainers.image.version="niche-compass" VIASHDOCKER @@ -3112,6 +3108,7 @@ cat > "\$tempscript" << 'VIASHMAIN' import sys import json import mudata as mu +import torch from nichecompass.models import NicheCompass from nichecompass.utils import add_gps_from_gp_dict_to_adata @@ -3220,6 +3217,12 @@ from setup_logger import setup_logger logger = setup_logger() +# Verify torch and CUDA availability +logger.info(f"Torch version: {torch.__version__}") +logger.info(f"CUDA available: {torch.cuda.is_available()}") +logger.info(f"Torch CUDA version: {torch.version.cuda}") +logger.info(f"GPU count: {torch.cuda.device_count()}") + ## Read in data adata = mu.read_h5ad(par["input"], mod=par["modality"]) diff --git a/target/nextflow/convert/from_cells2stats_to_h5mu/.config.vsh.yaml b/target/nextflow/convert/from_cells2stats_to_h5mu/.config.vsh.yaml index 7d5bc9b..87fd38e 100644 --- a/target/nextflow/convert/from_cells2stats_to_h5mu/.config.vsh.yaml +++ b/target/nextflow/convert/from_cells2stats_to_h5mu/.config.vsh.yaml @@ -179,7 +179,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -271,14 +271,16 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" - "pyarrow" git: - "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -301,7 +303,7 @@ build_info: output: "target/nextflow/convert/from_cells2stats_to_h5mu" executable: "target/nextflow/convert/from_cells2stats_to_h5mu/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -315,7 +317,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/convert/from_cells2stats_to_h5mu/main.nf b/target/nextflow/convert/from_cells2stats_to_h5mu/main.nf index 928da0f..0145ea9 100644 --- a/target/nextflow/convert/from_cells2stats_to_h5mu/main.nf +++ b/target/nextflow/convert/from_cells2stats_to_h5mu/main.nf @@ -3246,7 +3246,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3357,15 +3357,16 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", "pyarrow" ], "git" : [ "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3399,7 +3400,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/convert/from_cells2stats_to_h5mu", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3419,7 +3420,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", @@ -3510,7 +3511,7 @@ logger = setup_logger() def assert_matching_order(var_names, count_columns, split_pattern=None): for var, col in zip(var_names, count_columns): - count_var = col if not split_pattern else col.split("_Nuclear")[0] + count_var = col if not split_pattern else col.replace(split_pattern, "") assert var == count_var, "Orders do not match" @@ -3699,8 +3700,8 @@ def main(): df.index_name = None # var and obs names - var_names = [var.split(".")[0] for var in count_columns] - obs_names = df["Cell"].astype(str).tolist() + var_columns = list(count_columns) + obs_columns = df["Cell"].astype(str).tolist() # Count matrix logger.info("Creating count matrix...") @@ -3711,16 +3712,21 @@ def main(): logger.info(f"Creating obs field with columns {obs_columns_fixed}") obs_df = df[obs_columns_fixed].copy() + # Var field + var_df = pd.DataFrame(index=pd.Index(var_columns, dtype=str)) + targets, batches = zip(*(c.rsplit(".", 1) for c in var_columns)) + var_df["target"] = targets + var_df["batch"] = batches + # Create AnnData object logger.info("Creating AnnData object...") adata = ad.AnnData( X=count_matrix_sparse, obs=obs_df, - var=pd.DataFrame(index=var_names), + var=var_df, ) - - adata.obs_names = obs_names - adata.var_names = var_names + adata.obs_names = pd.Index(obs_columns, dtype=str) + adata.var_names = pd.Index(var_columns, dtype=str) # Spatial coordinates coordinate_sets = { @@ -3757,13 +3763,13 @@ def main(): adata.uns[par["obsm_cell_profiler"]] = cell_profiler_columns if par["obsm_unassigned_targets"]: logger.info(f"Adding {par['obsm_unassigned_targets']} to obsm") - adata.obsm["unassigned_targets"] = df[unassigned_columns].copy() - adata.uns["unassigned_targets"] = unassigned_columns + adata.obsm[par["obsm_unassigned_targets"]] = df[unassigned_columns].copy() + adata.uns[par["obsm_unassigned_targets"]] = unassigned_columns # Add (optional) nuclear count layer if par["layer_nuclear_counts"]: assert_matching_order( - var_names, nuclear_count_columns, split_pattern="_Nuclear" + var_columns, nuclear_count_columns, split_pattern="_Nuclear" ) logger.info(f"Adding {par['layer_nuclear_counts']} to layers") nuclear_count_df = df[nuclear_count_columns].copy() diff --git a/target/nextflow/convert/from_cosmx_to_h5mu/.config.vsh.yaml b/target/nextflow/convert/from_cosmx_to_h5mu/.config.vsh.yaml index c12c5b9..9eb9ee1 100644 --- a/target/nextflow/convert/from_cosmx_to_h5mu/.config.vsh.yaml +++ b/target/nextflow/convert/from_cosmx_to_h5mu/.config.vsh.yaml @@ -107,7 +107,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -199,17 +199,18 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "spatialdata~=0.5.0" - - "pyarrow~=18.0.0" - - "squidpy~=1.6.5" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.10.4" + - "squidpy~=1.7.0" - "pyarrow" git: - "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -238,7 +239,7 @@ build_info: output: "target/nextflow/convert/from_cosmx_to_h5mu" executable: "target/nextflow/convert/from_cosmx_to_h5mu/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -252,7 +253,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/convert/from_cosmx_to_h5mu/main.nf b/target/nextflow/convert/from_cosmx_to_h5mu/main.nf index 9fb8978..011d3ad 100644 --- a/target/nextflow/convert/from_cosmx_to_h5mu/main.nf +++ b/target/nextflow/convert/from_cosmx_to_h5mu/main.nf @@ -3184,7 +3184,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3295,18 +3295,18 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "spatialdata~=0.5.0", - "pyarrow~=18.0.0", - "squidpy~=1.6.5", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.10.4", + "squidpy~=1.7.0", "pyarrow" ], "git" : [ "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3350,7 +3350,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/convert/from_cosmx_to_h5mu", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3370,7 +3370,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/nextflow/convert/from_cosmx_to_spatialexperiment/.config.vsh.yaml b/target/nextflow/convert/from_cosmx_to_spatialexperiment/.config.vsh.yaml index 17934ba..5ad4c88 100644 --- a/target/nextflow/convert/from_cosmx_to_spatialexperiment/.config.vsh.yaml +++ b/target/nextflow/convert/from_cosmx_to_spatialexperiment/.config.vsh.yaml @@ -125,7 +125,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -234,7 +234,7 @@ build_info: output: "target/nextflow/convert/from_cosmx_to_spatialexperiment" executable: "target/nextflow/convert/from_cosmx_to_spatialexperiment/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -248,7 +248,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/convert/from_cosmx_to_spatialexperiment/main.nf b/target/nextflow/convert/from_cosmx_to_spatialexperiment/main.nf index 479cf3c..d4f2bf4 100644 --- a/target/nextflow/convert/from_cosmx_to_spatialexperiment/main.nf +++ b/target/nextflow/convert/from_cosmx_to_spatialexperiment/main.nf @@ -3190,7 +3190,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3326,7 +3326,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/convert/from_cosmx_to_spatialexperiment", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3346,7 +3346,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/nextflow/convert/from_h5mu_to_spatialexperiment/.config.vsh.yaml b/target/nextflow/convert/from_h5mu_to_spatialexperiment/.config.vsh.yaml index fdf643c..9323ac7 100644 --- a/target/nextflow/convert/from_h5mu_to_spatialexperiment/.config.vsh.yaml +++ b/target/nextflow/convert/from_h5mu_to_spatialexperiment/.config.vsh.yaml @@ -92,7 +92,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -169,7 +169,7 @@ runners: engines: - type: "docker" id: "docker" - image: "rocker/r2u:22.04" + image: "rocker/r2u:24.04" target_registry: "images.viash-hub.com" target_tag: "niche-compass" namespace_separator: "/" @@ -191,6 +191,7 @@ engines: - type: "docker" env: - "RETICULATE_PYTHON=/usr/bin/python" + - "PIP_BREAK_SYSTEM_PACKAGES=1" - type: "apt" packages: - "python3" @@ -205,13 +206,15 @@ engines: bioc_force_install: false warnings_as_errors: true - type: "python" - user: false + user: true packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true entrypoint: [] cmd: null @@ -224,7 +227,7 @@ build_info: output: "target/nextflow/convert/from_h5mu_to_spatialexperiment" executable: "target/nextflow/convert/from_h5mu_to_spatialexperiment/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -238,7 +241,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/convert/from_h5mu_to_spatialexperiment/main.nf b/target/nextflow/convert/from_h5mu_to_spatialexperiment/main.nf index e07a2eb..3fe6838 100644 --- a/target/nextflow/convert/from_h5mu_to_spatialexperiment/main.nf +++ b/target/nextflow/convert/from_h5mu_to_spatialexperiment/main.nf @@ -3163,7 +3163,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3255,7 +3255,7 @@ meta = [ { "type" : "docker", "id" : "docker", - "image" : "rocker/r2u:22.04", + "image" : "rocker/r2u:24.04", "target_registry" : "images.viash-hub.com", "target_tag" : "niche-compass", "namespace_separator" : "/", @@ -3285,7 +3285,8 @@ meta = [ { "type" : "docker", "env" : [ - "RETICULATE_PYTHON=/usr/bin/python" + "RETICULATE_PYTHON=/usr/bin/python", + "PIP_BREAK_SYSTEM_PACKAGES=1" ] }, { @@ -3309,13 +3310,14 @@ meta = [ }, { "type" : "python", - "user" : false, + "user" : true, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3332,7 +3334,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/convert/from_h5mu_to_spatialexperiment", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3352,7 +3354,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/nextflow/convert/from_spaceranger_to_h5mu/.config.vsh.yaml b/target/nextflow/convert/from_spaceranger_to_h5mu/.config.vsh.yaml new file mode 100644 index 0000000..23684e4 --- /dev/null +++ b/target/nextflow/convert/from_spaceranger_to_h5mu/.config.vsh.yaml @@ -0,0 +1,296 @@ +name: "from_spaceranger_to_h5mu" +namespace: "convert" +version: "niche-compass" +authors: +- name: "Dorien Roosen" + roles: + - "maintainer" + info: + role: "Core Team Member" + links: + email: "dorien@data-intuitive.com" + github: "dorien-er" + linkedin: "dorien-roosen" + organizations: + - name: "Data Intuitive" + href: "https://www.data-intuitive.com" + role: "Data Scientist" +argument_groups: +- name: "Inputs" + arguments: + - type: "file" + name: "--input" + alternatives: + - "-i" + description: "Convert spatial data resulting from Aviti Teton sequencers that\ + \ have been processed by the Element Biosciences cells2stats workflow to H5MU\ + \ format.\n\nThis component processes cells2stats count matrices to create a\ + \ standardized H5MU file for downstream analysis.\n\nThe component reads:\n\ + - Parquet file containing the count matrix and metadata\n- Panel.json with target\ + \ and batch information\n\nAnd outputs an H5MU file with:\n- Count data as the\ + \ main .X matrix\n- Spatial coordinates in obsm\n- Cell Paint intensities in\ + \ obsm (optional)\n- Nuclear count data as a layer (optional)\n- CellProfiler\ + \ morphology metrics in obsm (optional)\n- Unassigned targets in obsm (optional)\n" + info: null + example: + - "spaceranger_output" + must_exist: true + create_parent: true + required: true + direction: "input" + multiple: false + multiple_sep: ";" +- name: "Outputs" + arguments: + - type: "file" + name: "--output" + description: "Output h5mu file." + info: null + example: + - "output.h5mu" + must_exist: true + create_parent: true + required: false + direction: "output" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--modality" + description: "Name of the modality under which to store the data." + info: null + default: + - "rna" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--uns_metrics" + description: "Name of the .uns slot under which to QC metrics (if any)." + info: null + default: + - "metrics_spaceranger" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--uns_probe_set" + description: "Name of the .uns slot under which to store probe set information\ + \ (if any)." + info: null + default: + - "probe_set" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--obsm_coordinates" + description: "Name of the .obsm slot under which to store the cell centroid coordinates." + info: null + default: + - "spatial" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--output_type" + description: "Which Spaceranger output to use for converting to h5mu." + info: null + default: + - "filtered" + required: false + choices: + - "raw" + - "filtered" + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--output_compression" + description: "Compression to use when writing the h5mu file." + info: null + required: false + choices: + - "gzip" + - "lzf" + direction: "input" + multiple: false + multiple_sep: ";" +resources: +- type: "python_script" + path: "script.py" + is_executable: true +- type: "file" + path: "setup_logger.py" +- type: "file" + path: "nextflow_labels.config" + dest: "nextflow_labels.config" +description: "Converts the output bundle from spaceranger into an h5mu file.\n" +test_resources: +- type: "python_script" + path: "test.py" + is_executable: true +- type: "file" + path: "Visium_FFPE_Human_Ovarian_Cancer_tiny_spaceranger" +info: null +status: "enabled" +scope: + image: "public" + target: "public" +repositories: +- type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" +links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" +runners: +- type: "executable" + id: "executable" + docker_setup_strategy: "ifneedbepullelsecachedbuild" +- type: "nextflow" + id: "nextflow" + directives: + label: + - "lowmem" + - "singlecpu" + tag: "$id" + auto: + simplifyInput: true + simplifyOutput: false + transcript: false + publish: false + config: + labels: + mem1gb: "memory = 1000000000.B" + mem2gb: "memory = 2000000000.B" + mem5gb: "memory = 5000000000.B" + mem10gb: "memory = 10000000000.B" + mem20gb: "memory = 20000000000.B" + mem50gb: "memory = 50000000000.B" + mem100gb: "memory = 100000000000.B" + mem200gb: "memory = 200000000000.B" + mem500gb: "memory = 500000000000.B" + mem1tb: "memory = 1000000000000.B" + mem2tb: "memory = 2000000000000.B" + mem5tb: "memory = 5000000000000.B" + mem10tb: "memory = 10000000000000.B" + mem20tb: "memory = 20000000000000.B" + mem50tb: "memory = 50000000000000.B" + mem100tb: "memory = 100000000000000.B" + mem200tb: "memory = 200000000000000.B" + mem500tb: "memory = 500000000000000.B" + mem1gib: "memory = 1073741824.B" + mem2gib: "memory = 2147483648.B" + mem4gib: "memory = 4294967296.B" + mem8gib: "memory = 8589934592.B" + mem16gib: "memory = 17179869184.B" + mem32gib: "memory = 34359738368.B" + mem64gib: "memory = 68719476736.B" + mem128gib: "memory = 137438953472.B" + mem256gib: "memory = 274877906944.B" + mem512gib: "memory = 549755813888.B" + mem1tib: "memory = 1099511627776.B" + mem2tib: "memory = 2199023255552.B" + mem4tib: "memory = 4398046511104.B" + mem8tib: "memory = 8796093022208.B" + mem16tib: "memory = 17592186044416.B" + mem32tib: "memory = 35184372088832.B" + mem64tib: "memory = 70368744177664.B" + mem128tib: "memory = 140737488355328.B" + mem256tib: "memory = 281474976710656.B" + mem512tib: "memory = 562949953421312.B" + 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" + script: + - "includeConfig(\"nextflow_labels.config\")" + debug: false + container: "docker" +engines: +- type: "docker" + id: "docker" + image: "python:3.12-slim" + target_registry: "images.viash-hub.com" + target_tag: "niche-compass" + namespace_separator: "/" + setup: + - type: "apt" + packages: + - "procps" + interactive: false + - type: "python" + user: false + packages: + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "scanpy~=1.10.4" + script: + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" + upgrade: true + test_setup: + - type: "apt" + packages: + - "git" + interactive: false + - type: "python" + user: false + packages: + - "viashpy==0.9.0" + github: + - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" + upgrade: true + entrypoint: [] + cmd: null +- type: "native" + id: "native" +build_info: + config: "src/convert/from_spaceranger_to_h5mu/config.vsh.yaml" + runner: "nextflow" + engine: "docker|native" + output: "target/nextflow/convert/from_spaceranger_to_h5mu" + executable: "target/nextflow/convert/from_spaceranger_to_h5mu/main.nf" + viash_version: "0.9.4" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" + git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" +package_config: + name: "openpipeline_spatial" + version: "niche-compass" + info: + test_resources: + - type: "s3" + path: "s3://openpipelines-bio/openpipeline_spatial/resources_test" + dest: "resources_test" + repositories: + - type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" + viash_version: "0.9.4" + source: "src" + target: "target" + config_mods: + - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n\ + .runners[.type == 'nextflow'].config.script := 'includeConfig(\"nextflow_labels.config\"\ + )'" + - ".engines += { type: \"native\" }" + - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" + - ".engines[.type == 'docker'].target_tag := 'niche-compass'" + organization: "vsh" + links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" diff --git a/target/nextflow/convert/from_spaceranger_to_h5mu/main.nf b/target/nextflow/convert/from_spaceranger_to_h5mu/main.nf new file mode 100644 index 0000000..302ba97 --- /dev/null +++ b/target/nextflow/convert/from_spaceranger_to_h5mu/main.nf @@ -0,0 +1,4082 @@ +// from_spaceranger_to_h5mu niche-compass +// +// This wrapper script is auto-generated by viash 0.9.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. +// +// Component authors: +// * Dorien Roosen (maintainer) + +//////////////////////////// +// VDSL3 helper functions // +//////////////////////////// + +// helper file: 'src/main/resources/io/viash/runners/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. only cast if the value is a GString + if (value instanceof GString) { + value = value as String + } + expectedClass = value instanceof String ? null : "String" + } else if (par.type == "integer") { + // cast to integer if need be + if (value !instanceof Integer) { + try { + value = value as Integer + } catch (NumberFormatException e) { + expectedClass = "Integer" + } + } + } else if (par.type == "long") { + // cast to long if need be + if (value !instanceof Long) { + try { + value = value as Long + } catch (NumberFormatException e) { + expectedClass = "Long" + } + } + } else if (par.type == "double") { + // cast to double if need be + if (value !instanceof Double) { + try { + value = value as Double + } catch (NumberFormatException e) { + expectedClass = "Double" + } + } + } else if (par.type == "float") { + // cast to float if need be + if (value !instanceof Float) { + try { + value = value as Float + } catch (NumberFormatException e) { + expectedClass = "Float" + } + } + } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { + // cast to boolean if need be + if (value !instanceof Boolean) { + try { + value = value as Boolean + } catch (Exception e) { + expectedClass = "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 String) { + try { + value = value as String + } catch (Exception e) { + expectedClass = "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/runners/nextflow/arguments/_processInputValues.nf' +Map _processInputValues(Map inputs, Map config, String id, String key) { + if (!workflow.stubRun) { + config.allArguments.each { arg -> + if (arg.required && arg.direction == "input") { + 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.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/runners/nextflow/arguments/_processOutputValues.nf' +Map _checkValidOutputArgument(Map outputs, Map config, String id, String key) { + if (!workflow.stubRun) { + outputs = outputs.collectEntries { name, value -> + def par = config.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 +} + +void _checkAllRequiredOuputsPresent(Map outputs, Map config, String id, String key) { + if (!workflow.stubRun) { + config.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" + } + } + } +} +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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/runners/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.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/runners/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.name + + /* parse regular parameters (not in param_list) */ + /*************************************************/ + def globalParams = config.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 && !id) { + // if stub run, explicitly add an id if missing + 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.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/runners/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/runners/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.name + + // Get different parameter types (used throughout this function) + def defaultArgs = config.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.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/runners/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] + 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_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/runners/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 runIf_ = args.runIf + def id_ = args.id + + assert !runIf_ || runIf_ instanceof Closure: "runEach: must pass a Closure to runIf." + + 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 chPassthrough = null + def chRun = null + if (runIf_) { + def idRunIfBranch = id_ch.branch{ tup -> + run: runIf_(tup[0], tup[1], comp_) + passthrough: true + } + chPassthrough = idRunIfBranch.passthrough + chRun = idRunIfBranch.run + } else { + chRun = id_ch + chPassthrough = Channel.empty() + } + def data_ch = chRun | 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 + + def return_ch = post_ch + | concat(chPassthrough) + + return_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/runners/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/runners/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/runners/nextflow/config/addGlobalParams.nf' +def addGlobalArguments(config) { + def localConfig = [ + "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/runners/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 + + // 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/runners/nextflow/config/processConfig.nf' +def processConfig(config) { + // set defaults for arguments + config.arguments = + (config.arguments ?: []).collect{_processArgument(it)} + + // set defaults for argument_group arguments + config.argument_groups = + (config.argument_groups ?: []).collect{grp -> + grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} + grp + } + + // create combined arguments list + config.allArguments = + config.arguments + + config.argument_groups.collectMany{it.arguments} + + // add missing argument groups (based on Functionality::allArgumentGroups()) + def argGroups = config.argument_groups + if (argGroups.any{it.name.toLowerCase() == "arguments"}) { + argGroups = argGroups.collect{ grp -> + if (grp.name.toLowerCase() == "arguments") { + grp = grp + [ + arguments: grp.arguments + config.arguments + ] + } + grp + } + } else { + argGroups = argGroups + [ + name: "Arguments", + arguments: config.arguments + ] + } + config.allArgumentGroups = argGroups + + config +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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) { + def _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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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 + } + def 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/runners/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/runners/nextflow/readwrite/readJsonBlob.nf' +def readJsonBlob(str) { + def jsonSlurper = new groovy.json.JsonSlurper() + jsonSlurper.parseText(str) +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/nextflow/readwrite/readYamlBlob.nf' +def readYamlBlob(str) { + def yamlSlurper = new org.yaml.snakeyaml.Yaml() + yamlSlurper.load(str) +} + +// helper file: 'src/main/resources/io/viash/runners/nextflow/readwrite/toJsonBlob.nf' +String toJsonBlob(data) { + return groovy.json.JsonOutput.toJson(data) +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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/runners/nextflow/states/findStates.nf' +def findStates(Map params, Map config) { + def auto_config = deepClone(config) + def auto_params = deepClone(params) + + auto_config = auto_config.clone() + // override arguments + auto_config.argument_groups = [] + auto_config.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', or 'newKey:oldKey;newKey:oldKey' in case of multiple values" + 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/runners/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/runners/nextflow/states/publishFiles.nf' +def publishFiles(Map args) { + def key_ = args.get("key") + + assert key_ != null : "publishFiles: key must be specified" + + workflow publishFilesWf { + 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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() + def inputFiles_ = inputoutputFilenames_[0] + def outputFilenames_ = inputoutputFilenames_[1] + + [id_, inputFiles_, outputFilenames_] + } + | publishFilesProc + emit: input_ch + } + return publishFilesWf +} + +process publishFilesProc { + // todo: check publishpath? + publishDir path: "${getPublishDir()}/", mode: "copy" + tag "$id" + input: + tuple val(id), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) + output: + tuple val(id), path{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 + [] + } + } + """ + 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 publishFilesByConfig(Map args) { + def config = args.get("config") + assert config != null : "publishFilesByConfig: config must be specified" + + def key_ = args.get("key", config.name) + assert key_ != null : "publishFilesByConfig: key must be specified" + + workflow publishFilesSimpleWf { + 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'] + + + // the processed state is a list of [key, value, inputPath, outputFilename] tuples, where + // - key is a String + // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) + // - inputPath is a List[Path] + // - outputFilename is a List[String] + // - (inputPath, outputFilename) are the files that will be copied from src to dest (relative to the state.yaml) + def processedState = + config.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 OR multiple channels were emitted + // and the output was just not added to using the channel + // that is now being parsed + 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 [[inputPath: [], outputFilename: []]] + } + // 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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .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 filename_ix = filename.replace("*", ix.toString()) + def inputPath = val instanceof File ? val.toPath() : val + [inputPath: inputPath, outputFilename: filename_ix] + } + def transposedOutputs = ["inputPath", "outputFilename"].collectEntries{ key -> + [key, outputPerFile.collect{dic -> dic[key]}] + } + return [[key: plainName_] + transposedOutputs] + } else { + def value_ = java.nio.file.Paths.get(filename) + def inputPath = value instanceof File ? value.toPath() : value + return [[inputPath: [inputPath], outputFilename: [filename]]] + } + } + + def inputPaths = processedState.collectMany{it.inputPath} + def outputFilenames = processedState.collectMany{it.outputFilename} + + + [id_, inputPaths, outputFilenames] + } + | publishFilesProc + emit: input_ch + } + return publishFilesSimpleWf +} + + + + +// helper file: 'src/main/resources/io/viash/runners/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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() + + def yamlFilename = yamlTemplate_ + .replaceAll('\\$id', id_) + .replaceAll('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .replaceAll('\\$\\{key\\}', key_) + + // TODO: do the pathnames in state_ match up with the outputFilenames_? + + // convert state to yaml blob + def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) + + [id_, yamlBlob_, yamlFilename] + } + | 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) + output: + tuple val(id), path{[yamlFile]} + script: + """ + mkdir -p "\$(dirname '${yamlFile}')" + echo "Storing state as yaml" + cat > '${yamlFile}' << HERE +${yamlBlob} +HERE + """ +} + + +// 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.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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .replaceAll('\\$\\{key\\}', key_) + def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() + + // the processed state is a list of [key, value] tuples, where + // - key is a String + // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) + // - (key, value) are the tuples that will be saved to the state.yaml file + def processedState = + config.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]] + } + // 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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .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 filename_ix = filename.replace("*", ix.toString()) + def value_ = java.nio.file.Paths.get(filename_ix) + // if id contains a slash + if (yamlDir != null) { + value_ = yamlDir.relativize(value_) + } + return value_ + } + return [["key": plainName_, "value": outputPerFile]] + } else { + def value_ = java.nio.file.Paths.get(filename) + // if id contains a slash + if (yamlDir != null) { + value_ = yamlDir.relativize(value_) + } + def inputPath = value instanceof File ? value.toPath() : value + return [["key": plainName_, value: value_]] + } + } + + + def updatedState_ = processedState.collectEntries{[it.key, it.value]} + + // convert state to yaml blob + def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) + + [id_, yamlBlob_, yamlFilename] + } + | publishStatesProc + emit: input_ch + } + return publishStatesSimpleWf +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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.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_.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/runners/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"] + def multipleArgs = meta.config.allArguments.findAll{ it.multiple }.collect{it.plainName} + + workflow workflowInstance { + take: input_ + + main: + def 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 + if (tuple[0] instanceof GString) { + tuple[0] = tuple[0].toString() + } + 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.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 + } + + + def chRun = null + def chPassthrough = null + if (workflowArgs.runIf) { + def runIfBranch = chModified.branch{ tup -> + run: workflowArgs.runIf(tup[0], tup[1]) + passthrough: true + } + chRun = runIfBranch.run + chPassthrough = runIfBranch.passthrough + } else { + chRun = chModified + chPassthrough = Channel.empty() + } + + def chRunFiltered = workflowArgs.filter ? + chRun | filter{workflowArgs.filter(it)} : + chRun + + def chArgs = workflowArgs.fromState ? + chRunFiltered | map{ + def new_data = workflowArgs.fromState(it.take(2)) + [it[0], new_data] + } : + chRunFiltered | map {tup -> tup.take(2)} + + // fill in defaults + def 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.allArguments + .findAll { it.containsKey("default") } + .collectEntries { [ it.plainName, it.default ] } + + // fetch overrides in params + def paramArgs = meta.config.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.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. + def chInitialOutputMulti = chArgsWithDefaults + | _debug(workflowArgs, "processed") + // run workflow + | innerWorkflowFactory(workflowArgs) + def chInitialOutputList = chInitialOutputMulti instanceof List ? chInitialOutputMulti : [chInitialOutputMulti] + assert chInitialOutputList.size() > 0: "should have emitted at least one output channel" + // Add a channel ID to the events, which designates the channel the event was emitted from as a running number + // This number is used to sort the events later when the events are gathered from across the channels. + def chInitialOutputListWithIndexedEvents = chInitialOutputList.withIndex().collect{channel, channelIndex -> + def newChannel = channel + | map {tuple -> + assert tuple instanceof List : + "Error in module '${key_}': element in output 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()}" + + def newEvent = [channelIndex] + tuple + return newEvent + } + return newChannel + } + // Put the events into 1 channel, cover case where there is only one channel is emitted + def chInitialOutput = chInitialOutputList.size() > 1 ? \ + chInitialOutputListWithIndexedEvents[0].mix(*chInitialOutputListWithIndexedEvents.tail()) : \ + chInitialOutputListWithIndexedEvents[0] + def chInitialOutputProcessed = chInitialOutput + | map { tuple -> + def channelId = tuple[0] + def id_ = tuple[1] + def output_ = tuple[2] + + // 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_ = _checkValidOutputArgument(output_, meta.config, id_, key_) + + [join_id, channelId, id_, output_] + } + // | view{"chInitialOutput: ${it.take(3)}"} + + // join the output [prev_id, channel_id, new_id, output] with the previous state [prev_id, state, ...] + def chPublishWithPreviousState = safeJoin(chInitialOutputProcessed, chRunFiltered, key_) + // input tuple format: [join_id, channel_id, id, output, prev_state, ...] + // output tuple format: [join_id, channel_id, id, new_state, ...] + | map{ tup -> + def new_state = workflowArgs.toState(tup.drop(2).take(3)) + tup.take(3) + [new_state] + tup.drop(5) + } + if (workflowArgs.auto.publish == "state") { + def chPublishFiles = chPublishWithPreviousState + // input tuple format: [join_id, channel_id, id, new_state, ...] + // output tuple format: [join_id, channel_id, id, new_state] + | map{ tup -> + tup.take(4) + } + + safeJoin(chPublishFiles, chArgsWithDefaults, key_) + // input tuple format: [join_id, channel_id, id, new_state, orig_state, ...] + // output tuple format: [id, new_state, orig_state] + | map { tup -> + tup.drop(2).take(3) + } + | publishFilesByConfig(key: key_, config: meta.config) + } + // Join the state from the events that were emitted from different channels + def chJoined = chInitialOutputProcessed + | map {tuple -> + def join_id = tuple[0] + def channel_id = tuple[1] + def id = tuple[2] + def other = tuple.drop(3) + // Below, groupTuple is used to join the events. To make sure resuming a workflow + // keeps working, the output state must be deterministic. This means the state needs to be + // sorted with groupTuple's has a 'sort' argument. This argument can be set to 'hash', + // but hashing the state when it is large can be problematic in terms of performance. + // Therefore, a custom comparator function is provided. We add the channel ID to the + // states so that we can use the channel ID to sort the items. + def stateWithChannelID = [[channel_id] * other.size(), other].transpose() + // A comparator that is provided to groupTuple's 'sort' argument is applied + // to all elements of the event tuple (that is not the 'id'). The comparator + // closure that is used below expects the input to be List. So the join_id and + // channel_id must also be wrapped in a list. + [[join_id], [channel_id], id] + stateWithChannelID + } + | groupTuple(by: 2, sort: {a, b -> a[0] <=> b[0]}, size: chInitialOutputList.size(), remainder: true) + | map {join_ids, _, id, statesWithChannelID -> + // Remove the channel IDs from the states + def states = statesWithChannelID.collect{it[1]} + def newJoinId = join_ids.flatten().unique{a, b -> a <=> b} + assert newJoinId.size() == 1: "Multiple events were emitted for '$id'." + def newJoinIdUnique = newJoinId[0] + + // Merge the states from the different channels + def newState = states.inject([:]){ old_state, state_to_add -> + return old_state + state_to_add.collectEntries{k, v -> + if (!multipleArgs.contains(k)) { + // if the key is not a multiple argument, we expect only one value + if (old_state.containsKey(k)) { + assert old_state[k] == v : "ID $id: multiple entries for argument $k were emitted." + } + [k, v] + } else { + // if the key is a multiple argument, append the different values into one list + def prevValue = old_state.getOrDefault(k, []) + def prevValueAsList = prevValue instanceof List ? prevValue : [prevValue] + [k, prevValueAsList + v] + } + } + } + + _checkAllRequiredOuputsPresent(newState, meta.config, id, key_) + + // simplify output if need be + if (workflowArgs.auto.simplifyOutput && newState.size() == 1) { + newState = newState.values()[0] + } + + return [newJoinIdUnique, id, newState] + } + + // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] + def chNewState = safeJoin(chJoined, chRunFiltered, 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") { + def chPublishStates = chNewState + // input tuple format: [join_id, id, new_state, ...] + // output tuple format: [join_id, id, new_state] + | map{ tup -> + tup.take(3) + } + + safeJoin(chPublishStates, 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) + } + 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('''{ + "name" : "from_spaceranger_to_h5mu", + "namespace" : "convert", + "version" : "niche-compass", + "authors" : [ + { + "name" : "Dorien Roosen", + "roles" : [ + "maintainer" + ], + "info" : { + "role" : "Core Team Member", + "links" : { + "email" : "dorien@data-intuitive.com", + "github" : "dorien-er", + "linkedin" : "dorien-roosen" + }, + "organizations" : [ + { + "name" : "Data Intuitive", + "href" : "https://www.data-intuitive.com", + "role" : "Data Scientist" + } + ] + } + } + ], + "argument_groups" : [ + { + "name" : "Inputs", + "arguments" : [ + { + "type" : "file", + "name" : "--input", + "alternatives" : [ + "-i" + ], + "description" : "Convert spatial data resulting from Aviti Teton sequencers that have been processed by the Element Biosciences cells2stats workflow to H5MU format.\n\nThis component processes cells2stats count matrices to create a standardized H5MU file for downstream analysis.\n\nThe component reads:\n- Parquet file containing the count matrix and metadata\n- Panel.json with target and batch information\n\nAnd outputs an H5MU file with:\n- Count data as the main .X matrix\n- Spatial coordinates in obsm\n- Cell Paint intensities in obsm (optional)\n- Nuclear count data as a layer (optional)\n- CellProfiler morphology metrics in obsm (optional)\n- Unassigned targets in obsm (optional)\n", + "example" : [ + "spaceranger_output" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + }, + { + "name" : "Outputs", + "arguments" : [ + { + "type" : "file", + "name" : "--output", + "description" : "Output h5mu file.", + "example" : [ + "output.h5mu" + ], + "must_exist" : true, + "create_parent" : true, + "required" : false, + "direction" : "output", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--modality", + "description" : "Name of the modality under which to store the data.", + "default" : [ + "rna" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--uns_metrics", + "description" : "Name of the .uns slot under which to QC metrics (if any).", + "default" : [ + "metrics_spaceranger" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--uns_probe_set", + "description" : "Name of the .uns slot under which to store probe set information (if any).", + "default" : [ + "probe_set" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--obsm_coordinates", + "description" : "Name of the .obsm slot under which to store the cell centroid coordinates.", + "default" : [ + "spatial" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--output_type", + "description" : "Which Spaceranger output to use for converting to h5mu.", + "default" : [ + "filtered" + ], + "required" : false, + "choices" : [ + "raw", + "filtered" + ], + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--output_compression", + "description" : "Compression to use when writing the h5mu file.", + "required" : false, + "choices" : [ + "gzip", + "lzf" + ], + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + } + ], + "resources" : [ + { + "type" : "python_script", + "path" : "script.py", + "is_executable" : true + }, + { + "type" : "file", + "path" : "/src/utils/setup_logger.py" + }, + { + "type" : "file", + "path" : "/src/workflows/utils/labels.config", + "dest" : "nextflow_labels.config" + } + ], + "description" : "Converts the output bundle from spaceranger into an h5mu file.\n", + "test_resources" : [ + { + "type" : "python_script", + "path" : "test.py", + "is_executable" : true + }, + { + "type" : "file", + "path" : "/resources_test/visium/Visium_FFPE_Human_Ovarian_Cancer_tiny_spaceranger" + } + ], + "status" : "enabled", + "scope" : { + "image" : "public", + "target" : "public" + }, + "repositories" : [ + { + "type" : "vsh", + "name" : "openpipeline", + "repo" : "openpipeline", + "tag" : "v4.0.0" + } + ], + "links" : { + "repository" : "https://github.com/openpipelines-bio/openpipeline_spatial", + "docker_registry" : "ghcr.io" + }, + "runners" : [ + { + "type" : "executable", + "id" : "executable", + "docker_setup_strategy" : "ifneedbepullelsecachedbuild" + }, + { + "type" : "nextflow", + "id" : "nextflow", + "directives" : { + "label" : [ + "lowmem", + "singlecpu" + ], + "tag" : "$id" + }, + "auto" : { + "simplifyInput" : true, + "simplifyOutput" : false, + "transcript" : false, + "publish" : false + }, + "config" : { + "labels" : { + "mem1gb" : "memory = 1000000000.B", + "mem2gb" : "memory = 2000000000.B", + "mem5gb" : "memory = 5000000000.B", + "mem10gb" : "memory = 10000000000.B", + "mem20gb" : "memory = 20000000000.B", + "mem50gb" : "memory = 50000000000.B", + "mem100gb" : "memory = 100000000000.B", + "mem200gb" : "memory = 200000000000.B", + "mem500gb" : "memory = 500000000000.B", + "mem1tb" : "memory = 1000000000000.B", + "mem2tb" : "memory = 2000000000000.B", + "mem5tb" : "memory = 5000000000000.B", + "mem10tb" : "memory = 10000000000000.B", + "mem20tb" : "memory = 20000000000000.B", + "mem50tb" : "memory = 50000000000000.B", + "mem100tb" : "memory = 100000000000000.B", + "mem200tb" : "memory = 200000000000000.B", + "mem500tb" : "memory = 500000000000000.B", + "mem1gib" : "memory = 1073741824.B", + "mem2gib" : "memory = 2147483648.B", + "mem4gib" : "memory = 4294967296.B", + "mem8gib" : "memory = 8589934592.B", + "mem16gib" : "memory = 17179869184.B", + "mem32gib" : "memory = 34359738368.B", + "mem64gib" : "memory = 68719476736.B", + "mem128gib" : "memory = 137438953472.B", + "mem256gib" : "memory = 274877906944.B", + "mem512gib" : "memory = 549755813888.B", + "mem1tib" : "memory = 1099511627776.B", + "mem2tib" : "memory = 2199023255552.B", + "mem4tib" : "memory = 4398046511104.B", + "mem8tib" : "memory = 8796093022208.B", + "mem16tib" : "memory = 17592186044416.B", + "mem32tib" : "memory = 35184372088832.B", + "mem64tib" : "memory = 70368744177664.B", + "mem128tib" : "memory = 140737488355328.B", + "mem256tib" : "memory = 281474976710656.B", + "mem512tib" : "memory = 562949953421312.B", + "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" + }, + "script" : [ + "includeConfig(\\"nextflow_labels.config\\")" + ] + }, + "debug" : false, + "container" : "docker" + } + ], + "engines" : [ + { + "type" : "docker", + "id" : "docker", + "image" : "python:3.12-slim", + "target_registry" : "images.viash-hub.com", + "target_tag" : "niche-compass", + "namespace_separator" : "/", + "setup" : [ + { + "type" : "apt", + "packages" : [ + "procps" + ], + "interactive" : false + }, + { + "type" : "python", + "user" : false, + "packages" : [ + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "scanpy~=1.10.4" + ], + "script" : [ + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" + ], + "upgrade" : true + } + ], + "test_setup" : [ + { + "type" : "apt", + "packages" : [ + "git" + ], + "interactive" : false + }, + { + "type" : "python", + "user" : false, + "packages" : [ + "viashpy==0.9.0" + ], + "github" : [ + "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" + ], + "upgrade" : true + } + ] + }, + { + "type" : "native", + "id" : "native" + } + ], + "build_info" : { + "config" : "/workdir/root/repo/src/convert/from_spaceranger_to_h5mu/config.vsh.yaml", + "runner" : "nextflow", + "engine" : "docker|native", + "output" : "/workdir/root/repo/target/nextflow/convert/from_spaceranger_to_h5mu", + "viash_version" : "0.9.4", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" + }, + "package_config" : { + "name" : "openpipeline_spatial", + "version" : "niche-compass", + "info" : { + "test_resources" : [ + { + "type" : "s3", + "path" : "s3://openpipelines-bio/openpipeline_spatial/resources_test", + "dest" : "resources_test" + } + ] + }, + "repositories" : [ + { + "type" : "vsh", + "name" : "openpipeline", + "repo" : "openpipeline", + "tag" : "v4.0.0" + } + ], + "viash_version" : "0.9.4", + "source" : "/workdir/root/repo/src", + "target" : "/workdir/root/repo/target", + "config_mods" : [ + ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", + ".engines += { type: \\"native\\" }", + ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", + ".engines[.type == 'docker'].target_tag := 'niche-compass'" + ], + "organization" : "vsh", + "links" : { + "repository" : "https://github.com/openpipelines-bio/openpipeline_spatial", + "docker_registry" : "ghcr.io" + } + } +}''')) +] + +// resolve dependencies dependencies (if any) + + +// inner workflow +// inner workflow hook +def innerWorkflowFactory(args) { + def rawScript = '''set -e +tempscript=".viash_script.py" +cat > "$tempscript" << VIASHMAIN +from pathlib import Path +import mudata +import scanpy as sc +import sys +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 ), + 'modality': $( if [ ! -z ${VIASH_PAR_MODALITY+x} ]; then echo "r'${VIASH_PAR_MODALITY//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), + 'uns_metrics': $( if [ ! -z ${VIASH_PAR_UNS_METRICS+x} ]; then echo "r'${VIASH_PAR_UNS_METRICS//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), + 'uns_probe_set': $( if [ ! -z ${VIASH_PAR_UNS_PROBE_SET+x} ]; then echo "r'${VIASH_PAR_UNS_PROBE_SET//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), + 'obsm_coordinates': $( if [ ! -z ${VIASH_PAR_OBSM_COORDINATES+x} ]; then echo "r'${VIASH_PAR_OBSM_COORDINATES//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), + 'output_type': $( if [ ! -z ${VIASH_PAR_OUTPUT_TYPE+x} ]; then echo "r'${VIASH_PAR_OUTPUT_TYPE//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), + 'output_compression': $( if [ ! -z ${VIASH_PAR_OUTPUT_COMPRESSION+x} ]; then echo "r'${VIASH_PAR_OUTPUT_COMPRESSION//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ) +} +meta = { + 'name': $( if [ ! -z ${VIASH_META_NAME+x} ]; then echo "r'${VIASH_META_NAME//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), + '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 ), + 'memory_kib': $( if [ ! -z ${VIASH_META_MEMORY_KIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_KIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), + 'memory_mib': $( if [ ! -z ${VIASH_META_MEMORY_MIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_MIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), + 'memory_gib': $( if [ ! -z ${VIASH_META_MEMORY_GIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_GIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), + 'memory_tib': $( if [ ! -z ${VIASH_META_MEMORY_TIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_TIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), + 'memory_pib': $( if [ ! -z ${VIASH_META_MEMORY_PIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_PIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ) +} +dep = { + +} + +## VIASH END + +sys.path.append(meta["resources_dir"]) +from setup_logger import setup_logger + +logger = setup_logger() + + +def retrieve_input_data(spaceranger_output_bundle, input_type="filtered"): + # Expected folder structure (showing only relevant files): + # ├── Spatial/ + # │ └── tissue_positions.csv + # ├── filtered_feature_bc_matrix.h5 OR raw_feature_bc_matrix.h5 + # ├── metrics_summary.csv + # └── probe_set.csv + + matrix_pattern = ( + "**/filtered_feature_bc_matrix.h5" + if input_type == "filtered" + else "**/raw_feature_bc_matrix.h5" + ) + spaceranger_file_patterns = { + "count_matrix": matrix_pattern, + "metrics_summary": "**/metrics_summary.csv", + "probe_set": "**/probe_set.csv", + "spatial_coords": "**/spatial/tissue_positions.csv", + } + + spaceranger_output_bundle = Path(spaceranger_output_bundle) + + spaceranger_files = {} + + for key, pattern in spaceranger_file_patterns.items(): + file = list(spaceranger_output_bundle.glob(pattern)) + assert len(file) == 1, ( + f"Expected exactly one file for pattern '{pattern}', found {len(file)}." + ) + spaceranger_files[key] = file[0] + + return spaceranger_files + + +def main(): + spaceranger_files = retrieve_input_data(par["input"], input_type=par["output_type"]) + + logger.info("Reading count matrix...") + adata = sc.read_10x_h5(spaceranger_files["count_matrix"], gex_only=False) + + # set the gene ids as var_names + logger.info("Renaming var columns") + adata.var = adata.var.rename_axis("gene_symbol").reset_index().set_index("gene_ids") + + if par["uns_metrics"]: + logger.info("Reading metrics summary file...") + metrics_summary = pd.read_csv( + spaceranger_files["metrics_summary"], + decimal=".", + quotechar='"', + thousands=",", + ) + + logger.info("Storing metrics summary in .uns slot...") + adata.uns[par["uns_metrics"]] = metrics_summary + + if par["uns_probe_set"]: + logger.info("Reading probe set file...") + + def read_hash_metadata(path): + meta = {} + with open(path, "r", encoding="utf-8") as f: + for i, line in enumerate(f): + if not line.startswith("#"): + break + line = line[1:].strip() + if "=" in line: + k, v = line.split("=", 1) + meta[k.strip()] = v.strip() + return meta + + meta = read_hash_metadata(spaceranger_files["probe_set"]) + probe_set = pd.read_csv(spaceranger_files["probe_set"], comment="#") + + logger.info("Storing probe set in .uns slot...") + adata.uns[par["uns_probe_set"]] = probe_set + adata.uns[par["uns_probe_set"] + "_meta"] = meta + + logger.info("Reading spatial coordinates...") + spatial_coords = pd.read_csv( + spaceranger_files["spatial_coords"], decimal=".", thousands="," + ) + + spatial_coords_aligned = spatial_coords.set_index("barcode").reindex( + adata.obs_names + ) + logger.info("Storing spatial coordinates in .obsm slot...") + adata.obsm[par["obsm_coordinates"]] = spatial_coords_aligned[ + ["pxl_col_in_fullres", "pxl_row_in_fullres"] + ].to_numpy() + + # generate output + logger.info("Convert to mudata") + mdata = mudata.MuData({par["modality"]: adata}) + + # override root .obs and .uns + mdata.obs = adata.obs + mdata.uns = adata.uns + + # write output + logger.info("Writing %s", par["output"]) + mdata.write_h5mu(par["output"], compression=par["output_compression"]) + + +if __name__ == "__main__": + main() +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.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.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('\\$\\{id\\}', id) + .replaceAll('\\$key', key) + .replaceAll('\\$\\{key\\}', key) + } + [parName, val] + } + + [ id ] + inputPaths + [ argsExclInputFiles, meta.resources_dir ] + } + | processObj + | map { output -> + def outputFiles = meta.config.allArguments + .findAll { it.type == "file" && it.direction == "output" } + .indexed() + .collectEntries{ index, par -> + def 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.allArguments + .findAll { it.type == "file" && it.direction == "input" } + .collect { ', path(viash_par_' + it.plainName + ', stageAs: "_viash_par/' + it.plainName + '_?/*")' } + .join() + + def outputPaths = meta.config.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.allArguments + .findAll { it.type == "file" && it.direction == "output" && it.create_parent } + .collect { par -> + def contents = "args[\"${par.plainName}\"] instanceof List ? args[\"${par.plainName}\"].join('\" \"') : args[\"${par.plainName}\"]" + "\${ args.containsKey(\"${par.plainName}\") ? \"mkdir_parent '\" + escapeText(${contents}) + \"'\" : \"\" }" + } + .join("\n") + + // construct inputFileExports + def inputFileExports = meta.config.allArguments + .findAll { it.type == "file" && it.direction.toLowerCase() == "input" } + .collect { par -> + def 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()}='\" + escapeText(${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.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 + | + |def escapeText = { s -> s.toString().replaceAll("'", "'\\\"'\\\"'") } + |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 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}" + |export VIASH_META_TEMP_DIR="${['docker', 'podman', 'charliecloud'].any{ it == workflow.containerEngine } ? '/tmp' : tmpDir}" + |export VIASH_META_NAME="${meta.config.name}" + |# export VIASH_META_EXECUTABLE="\\\$VIASH_META_RESOURCES_DIR/\\\$VIASH_META_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+999) / 1000 )) + | export VIASH_META_MEMORY_MB=\\\$(( (\\\$VIASH_META_MEMORY_KB+999) / 1000 )) + | export VIASH_META_MEMORY_GB=\\\$(( (\\\$VIASH_META_MEMORY_MB+999) / 1000 )) + | export VIASH_META_MEMORY_TB=\\\$(( (\\\$VIASH_META_MEMORY_GB+999) / 1000 )) + | export VIASH_META_MEMORY_PB=\\\$(( (\\\$VIASH_META_MEMORY_TB+999) / 1000 )) + | export VIASH_META_MEMORY_KIB=\\\$(( (\\\$VIASH_META_MEMORY_B+1023) / 1024 )) + | export VIASH_META_MEMORY_MIB=\\\$(( (\\\$VIASH_META_MEMORY_KIB+1023) / 1024 )) + | export VIASH_META_MEMORY_GIB=\\\$(( (\\\$VIASH_META_MEMORY_MIB+1023) / 1024 )) + | export VIASH_META_MEMORY_TIB=\\\$(( (\\\$VIASH_META_MEMORY_GIB+1023) / 1024 )) + | export VIASH_META_MEMORY_PIB=\\\$(( (\\\$VIASH_META_MEMORY_TIB+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######################") + // } + + // write process to temp file + def tempFile = java.nio.file.Files.createTempFile("viash-process-${procKey}-", ".nf") + addShutdownHook { java.nio.file.Files.deleteIfExists(tempFile) } + tempFile.text = procStr + + // create process from temp file + def binding = new nextflow.script.ScriptBinding([:]) + def session = nextflow.Nextflow.getSession() + def parser = _getScriptLoader(session) + .setModule(true) + .setBinding(binding) + def moduleScript = parser.runScript(tempFile) + .getScript() + + // register module in meta + def module = new nextflow.script.IncludeDef.Module(name: procKey) + scriptMeta.addModule(moduleScript, module.name, module.alias) + + // retrieve and return process from meta + return scriptMeta.getProcess(procKey) +} + +// use Reflection to get a ScriptParser / ScriptLoader +// <25.02.0-edge: new nextflow.script.ScriptParser(session) +// >=25.02.0-edge: nextflow.script.ScriptLoaderFactory.create(session) +def _getScriptLoader(nextflow.Session session) { + // try using the old method + try { + Class scriptParserClass = Class.forName('nextflow.script.ScriptParser') + return scriptParserClass.getDeclaredConstructor(nextflow.Session).newInstance(session) + } catch (ClassNotFoundException e) { + // else try with the new method + try { + Class scriptLoaderFactoryClass = Class.forName('nextflow.script.ScriptLoaderFactory') + def createMethod = scriptLoaderFactoryClass.getDeclaredMethod('create', nextflow.Session) + return createMethod.invoke(null, session) // null because create is static + } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | java.lang.reflect.InvocationTargetException e2) { + // Handle the case where neither class is found + throw new Exception("Neither nextflow.script.ScriptParser nor nextflow.script.ScriptLoaderFactory could be found. Is this a compatible Nextflow version?", e2) + } + } +} + +// 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" : "images.viash-hub.com", + "image" : "vsh/openpipeline_spatial/convert/from_spaceranger_to_h5mu", + "tag" : "niche-compass" + }, + "label" : [ + "lowmem", + "singlecpu" + ], + "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.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.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.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/convert/from_spaceranger_to_h5mu/nextflow.config b/target/nextflow/convert/from_spaceranger_to_h5mu/nextflow.config new file mode 100644 index 0000000..43e6906 --- /dev/null +++ b/target/nextflow/convert/from_spaceranger_to_h5mu/nextflow.config @@ -0,0 +1,126 @@ +manifest { + name = 'convert/from_spaceranger_to_h5mu' + mainScript = 'main.nf' + nextflowVersion = '!>=20.12.1-edge' + version = 'niche-compass' + description = 'Converts the output bundle from spaceranger into an h5mu file.\n' + author = 'Dorien Roosen' +} + +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 = 1000000000.B } + withLabel: mem2gb { memory = 2000000000.B } + withLabel: mem5gb { memory = 5000000000.B } + withLabel: mem10gb { memory = 10000000000.B } + withLabel: mem20gb { memory = 20000000000.B } + withLabel: mem50gb { memory = 50000000000.B } + withLabel: mem100gb { memory = 100000000000.B } + withLabel: mem200gb { memory = 200000000000.B } + withLabel: mem500gb { memory = 500000000000.B } + withLabel: mem1tb { memory = 1000000000000.B } + withLabel: mem2tb { memory = 2000000000000.B } + withLabel: mem5tb { memory = 5000000000000.B } + withLabel: mem10tb { memory = 10000000000000.B } + withLabel: mem20tb { memory = 20000000000000.B } + withLabel: mem50tb { memory = 50000000000000.B } + withLabel: mem100tb { memory = 100000000000000.B } + withLabel: mem200tb { memory = 200000000000000.B } + withLabel: mem500tb { memory = 500000000000000.B } + withLabel: mem1gib { memory = 1073741824.B } + withLabel: mem2gib { memory = 2147483648.B } + withLabel: mem4gib { memory = 4294967296.B } + withLabel: mem8gib { memory = 8589934592.B } + withLabel: mem16gib { memory = 17179869184.B } + withLabel: mem32gib { memory = 34359738368.B } + withLabel: mem64gib { memory = 68719476736.B } + withLabel: mem128gib { memory = 137438953472.B } + withLabel: mem256gib { memory = 274877906944.B } + withLabel: mem512gib { memory = 549755813888.B } + withLabel: mem1tib { memory = 1099511627776.B } + withLabel: mem2tib { memory = 2199023255552.B } + withLabel: mem4tib { memory = 4398046511104.B } + withLabel: mem8tib { memory = 8796093022208.B } + withLabel: mem16tib { memory = 17592186044416.B } + withLabel: mem32tib { memory = 35184372088832.B } + withLabel: mem64tib { memory = 70368744177664.B } + withLabel: mem128tib { memory = 140737488355328.B } + withLabel: mem256tib { memory = 281474976710656.B } + withLabel: mem512tib { memory = 562949953421312.B } + 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 } +} + +includeConfig("nextflow_labels.config") diff --git a/target/nextflow/convert/from_spaceranger_to_h5mu/nextflow_labels.config b/target/nextflow/convert/from_spaceranger_to_h5mu/nextflow_labels.config new file mode 100644 index 0000000..541aaad --- /dev/null +++ b/target/nextflow/convert/from_spaceranger_to_h5mu/nextflow_labels.config @@ -0,0 +1,68 @@ +process { + // Default resources for components that hardly do any processing + memory = { 2.GB * task.attempt } + cpus = 1 + + // Retry for exit codes that have something to do with memory issues + errorStrategy = { task.exitStatus in 137..140 ? 'retry' : 'terminate' } + maxRetries = 3 + maxMemory = null + + // CPU resources + withLabel: singlecpu { cpus = 1 } + withLabel: lowcpu { cpus = 4 } + withLabel: midcpu { cpus = 10 } + withLabel: highcpu { cpus = 20 } + + // Memory resources + withLabel: lowmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: midmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: highmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: veryhighmem { memory = { get_memory( 75.GB * task.attempt ) } } + + // Disk space + // Nextflow apparently can't handle empty directives, i.e. + // withLabel: lowdisk {} + // so for that reason we have to add a dummy directive + withLabel: lowdisk { + dummyDirective = "dummyValue" + } + withLabel: middisk { + dummyDirective = "dummyValue" + } + withLabel: highdisk { + dummyDirective = "dummyValue" + } + withLabel: veryhighdisk { + dummyDirective = "dummyValue" + } + // NOTE: The above labels intentionally do not have an effect by default. + // The user should set the disk space requirements by adding the following + // to the compute environment: + // + // withLabel: lowdisk { disk = { 20.GB * task.attempt } } + // withLabel: middisk { disk = { 100.GB * task.attempt } } + // withLabel: highdisk { disk = { 200.GB * task.attempt } } + // withLabel: veryhighdisk { disk = { 500.GB * task.attempt } } +} + +def get_memory(to_compare) { + if (!process.containsKey("maxMemory") || !process.maxMemory) { + return to_compare + } + + try { + if (process.containsKey("maxRetries") && process.maxRetries && task.attempt == (process.maxRetries as int)) { + return process.maxMemory + } + else if (to_compare.compareTo(process.maxMemory as nextflow.util.MemoryUnit) == 1) { + return max_memory as nextflow.util.MemoryUnit + } + else { + return to_compare + } + } catch (all) { + println "Error processing memory resources. Please check that process.maxMemory '${process.maxMemory}' and process.maxRetries '${process.maxRetries}' are valid!" + System.exit(1) + } +} diff --git a/target/nextflow/convert/from_spaceranger_to_h5mu/nextflow_schema.json b/target/nextflow/convert/from_spaceranger_to_h5mu/nextflow_schema.json new file mode 100644 index 0000000..db93bd9 --- /dev/null +++ b/target/nextflow/convert/from_spaceranger_to_h5mu/nextflow_schema.json @@ -0,0 +1,102 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "from_spaceranger_to_h5mu", + "description": "Converts the output bundle from spaceranger into an h5mu file.\n", + "type": "object", + "$defs": { + "inputs": { + "title": "Inputs", + "type": "object", + "description": "No description", + "properties": { + "input": { + "type": "string", + "format": "path", + "exists": true, + "description": "Convert spatial data resulting from Aviti Teton sequencers that have been processed by the Element Biosciences cells2stats workflow to H5MU format.\n\nThis component processes cells2stats count matrices to create a standardized H5MU file for downstream analysis.\n\nThe component reads:\n- Parquet file containing the count matrix and metadata\n- Panel.json with target and batch information\n\nAnd outputs an H5MU file with:\n- Count data as the main .X matrix\n- Spatial coordinates in obsm\n- Cell Paint intensities in obsm (optional)\n- Nuclear count data as a layer (optional)\n- CellProfiler morphology metrics in obsm (optional)\n- Unassigned targets in obsm (optional)\n", + "help_text": "Type: `file`, multiple: `False`, required, direction: `input`, example: `\"spaceranger_output\"`. " + } + } + }, + "outputs": { + "title": "Outputs", + "type": "object", + "description": "No description", + "properties": { + "output": { + "type": "string", + "format": "path", + "description": "Output h5mu file.", + "help_text": "Type: `file`, multiple: `False`, default: `\"$id.$key.output.h5mu\"`, direction: `output`, example: `\"output.h5mu\"`. ", + "default": "$id.$key.output.h5mu" + }, + "modality": { + "type": "string", + "description": "Name of the modality under which to store the data.", + "help_text": "Type: `string`, multiple: `False`, default: `\"rna\"`. ", + "default": "rna" + }, + "uns_metrics": { + "type": "string", + "description": "Name of the .uns slot under which to QC metrics (if any).", + "help_text": "Type: `string`, multiple: `False`, default: `\"metrics_spaceranger\"`. ", + "default": "metrics_spaceranger" + }, + "uns_probe_set": { + "type": "string", + "description": "Name of the .uns slot under which to store probe set information (if any).", + "help_text": "Type: `string`, multiple: `False`, default: `\"probe_set\"`. ", + "default": "probe_set" + }, + "obsm_coordinates": { + "type": "string", + "description": "Name of the .obsm slot under which to store the cell centroid coordinates.", + "help_text": "Type: `string`, multiple: `False`, default: `\"spatial\"`. ", + "default": "spatial" + }, + "output_type": { + "type": "string", + "description": "Which Spaceranger output to use for converting to h5mu.", + "help_text": "Type: `string`, multiple: `False`, default: `\"filtered\"`, choices: ``raw`, `filtered``. ", + "enum": [ + "raw", + "filtered" + ], + "default": "filtered" + }, + "output_compression": { + "type": "string", + "description": "Compression to use when writing the h5mu file.", + "help_text": "Type: `string`, multiple: `False`, choices: ``gzip`, `lzf``. ", + "enum": [ + "gzip", + "lzf" + ] + } + } + }, + "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.", + "help_text": "Type: `string`, multiple: `False`, required, example: `\"output/\"`. " + } + } + } + }, + "allOf": [ + { + "$ref": "#/$defs/inputs" + }, + { + "$ref": "#/$defs/outputs" + }, + { + "$ref": "#/$defs/nextflow input-output arguments" + } + ] +} diff --git a/target/nextflow/convert/from_spaceranger_to_h5mu/setup_logger.py b/target/nextflow/convert/from_spaceranger_to_h5mu/setup_logger.py new file mode 100644 index 0000000..3ca1cdb --- /dev/null +++ b/target/nextflow/convert/from_spaceranger_to_h5mu/setup_logger.py @@ -0,0 +1,12 @@ +def setup_logger(): + import logging + from sys import stdout + + logger = logging.getLogger() + logger.setLevel(logging.INFO) + console_handler = logging.StreamHandler(stdout) + logFormatter = logging.Formatter("%(asctime)s %(levelname)-8s %(message)s") + console_handler.setFormatter(logFormatter) + logger.addHandler(console_handler) + + return logger diff --git a/target/nextflow/convert/from_spatialdata_to_h5mu/.config.vsh.yaml b/target/nextflow/convert/from_spatialdata_to_h5mu/.config.vsh.yaml index ce5489e..4bbc563 100644 --- a/target/nextflow/convert/from_spatialdata_to_h5mu/.config.vsh.yaml +++ b/target/nextflow/convert/from_spatialdata_to_h5mu/.config.vsh.yaml @@ -101,7 +101,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -190,13 +190,15 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - - "spatialdata~=0.5.0" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" + - "spatialdata~=0.6.1" - "pyarrow~=18.0.0" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -221,7 +223,7 @@ build_info: output: "target/nextflow/convert/from_spatialdata_to_h5mu" executable: "target/nextflow/convert/from_spatialdata_to_h5mu/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -235,7 +237,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/convert/from_spatialdata_to_h5mu/main.nf b/target/nextflow/convert/from_spatialdata_to_h5mu/main.nf index e9ae4b7..3ef83f6 100644 --- a/target/nextflow/convert/from_spatialdata_to_h5mu/main.nf +++ b/target/nextflow/convert/from_spatialdata_to_h5mu/main.nf @@ -3180,7 +3180,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3288,13 +3288,14 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", - "spatialdata~=0.5.0", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", + "spatialdata~=0.6.1", "pyarrow~=18.0.0" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3331,7 +3332,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/convert/from_spatialdata_to_h5mu", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3351,7 +3352,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/nextflow/convert/from_xenium_to_h5mu/.config.vsh.yaml b/target/nextflow/convert/from_xenium_to_h5mu/.config.vsh.yaml index aa40d4a..f059155 100644 --- a/target/nextflow/convert/from_xenium_to_h5mu/.config.vsh.yaml +++ b/target/nextflow/convert/from_xenium_to_h5mu/.config.vsh.yaml @@ -121,7 +121,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -213,15 +213,17 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" - "scanpy~=1.10.4" - "pyarrow" git: - "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -244,7 +246,7 @@ build_info: output: "target/nextflow/convert/from_xenium_to_h5mu" executable: "target/nextflow/convert/from_xenium_to_h5mu/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -258,7 +260,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/convert/from_xenium_to_h5mu/main.nf b/target/nextflow/convert/from_xenium_to_h5mu/main.nf index d1269df..771795f 100644 --- a/target/nextflow/convert/from_xenium_to_h5mu/main.nf +++ b/target/nextflow/convert/from_xenium_to_h5mu/main.nf @@ -3194,7 +3194,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3305,8 +3305,9 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2", "scanpy~=1.10.4", "pyarrow" ], @@ -3314,7 +3315,7 @@ meta = [ "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3348,7 +3349,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/convert/from_xenium_to_h5mu", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3368,7 +3369,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/nextflow/convert/from_xenium_to_spatialdata/.config.vsh.yaml b/target/nextflow/convert/from_xenium_to_spatialdata/.config.vsh.yaml index 4a36cb4..82b287a 100644 --- a/target/nextflow/convert/from_xenium_to_spatialdata/.config.vsh.yaml +++ b/target/nextflow/convert/from_xenium_to_spatialdata/.config.vsh.yaml @@ -201,7 +201,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -293,8 +293,8 @@ engines: - type: "python" user: false packages: - - "spatialdata-io~=0.3.0" - - "spatialdata~=0.5.0" + - "spatialdata-io~=0.5.1" + - "spatialdata~=0.6.1" - "pyarrow~=18.0.0" git: - "https://codeberg.org/miurahr/zipfile-inflate64.git@v0.2" @@ -326,7 +326,7 @@ build_info: output: "target/nextflow/convert/from_xenium_to_spatialdata" executable: "target/nextflow/convert/from_xenium_to_spatialdata/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -340,7 +340,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/convert/from_xenium_to_spatialdata/main.nf b/target/nextflow/convert/from_xenium_to_spatialdata/main.nf index d4f595c..dba355b 100644 --- a/target/nextflow/convert/from_xenium_to_spatialdata/main.nf +++ b/target/nextflow/convert/from_xenium_to_spatialdata/main.nf @@ -3283,7 +3283,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3394,8 +3394,8 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "spatialdata-io~=0.3.0", - "spatialdata~=0.5.0", + "spatialdata-io~=0.5.1", + "spatialdata~=0.6.1", "pyarrow~=18.0.0" ], "git" : [ @@ -3443,7 +3443,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/convert/from_xenium_to_spatialdata", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3463,7 +3463,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/nextflow/convert/from_xenium_to_spatialexperiment/.config.vsh.yaml b/target/nextflow/convert/from_xenium_to_spatialexperiment/.config.vsh.yaml index c550dfe..81e000a 100644 --- a/target/nextflow/convert/from_xenium_to_spatialexperiment/.config.vsh.yaml +++ b/target/nextflow/convert/from_xenium_to_spatialexperiment/.config.vsh.yaml @@ -115,7 +115,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -238,7 +238,7 @@ build_info: output: "target/nextflow/convert/from_xenium_to_spatialexperiment" executable: "target/nextflow/convert/from_xenium_to_spatialexperiment/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -252,7 +252,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/convert/from_xenium_to_spatialexperiment/main.nf b/target/nextflow/convert/from_xenium_to_spatialexperiment/main.nf index 3ed6c54..d965a7c 100644 --- a/target/nextflow/convert/from_xenium_to_spatialexperiment/main.nf +++ b/target/nextflow/convert/from_xenium_to_spatialexperiment/main.nf @@ -3179,7 +3179,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3337,7 +3337,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/convert/from_xenium_to_spatialexperiment", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3357,7 +3357,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml b/target/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml deleted file mode 100644 index f41e2a3..0000000 --- a/target/nextflow/dataflow/concatenate_h5mu/.config.vsh.yaml +++ /dev/null @@ -1,333 +0,0 @@ -name: "concatenate_h5mu" -namespace: "dataflow" -version: "niche-compass" -authors: -- name: "Dries Schaumont" - roles: - - "maintainer" - info: - role: "Core Team Member" - links: - email: "dries@data-intuitive.com" - github: "DriesSchaumont" - orcid: "0000-0002-4389-0440" - linkedin: "dries-schaumont" - organizations: - - name: "Data Intuitive" - href: "https://www.data-intuitive.com" - role: "Data Scientist" -argument_groups: -- name: "Arguments" - arguments: - - type: "file" - name: "--input" - alternatives: - - "-i" - description: "Paths to the different samples to be concatenated." - info: null - example: - - "sample_paths" - must_exist: true - create_parent: true - required: true - direction: "input" - multiple: true - multiple_sep: ";" - - type: "string" - name: "--modality" - description: "Only output concatenated objects for the provided modalities. Outputs\ - \ all modalities by default." - info: null - required: false - direction: "input" - multiple: true - multiple_sep: ";" - - type: "string" - name: "--input_id" - description: "Names of the different samples that have to be concatenated. Must\ - \ be specified when using '--mode move'.\nIn this case, the ids will be used\ - \ for the columns names of the dataframes registring the conflicts.\nIf specified,\ - \ must be of same length as `--input`.\n" - info: null - required: false - direction: "input" - multiple: true - multiple_sep: ";" - - type: "file" - name: "--output" - alternatives: - - "-o" - description: "Output location for the concatenated MuData object file.\n" - info: null - example: - - "output.h5mu" - must_exist: true - create_parent: true - required: false - direction: "output" - multiple: false - multiple_sep: ";" - - type: "string" - name: "--obs_sample_name" - description: "Name of the .obs key under which to add the sample names." - info: null - default: - - "sample_id" - required: false - direction: "input" - multiple: false - multiple_sep: ";" - - type: "string" - name: "--other_axis_mode" - description: "How to handle the merging of other axis (var, obs, ...).\n\n -\ - \ None: keep no data\n - same: only keep elements of the matrices which are\ - \ the same in each of the samples\n - unique: only keep elements for which\ - \ there is only 1 possible value (1 value that can occur in multiple samples)\n\ - \ - first: keep the annotation from the first sample\n - only: keep elements\ - \ that show up in only one of the objects (1 unique element in only 1 sample)\n\ - \ - move: identical to 'same', but moving the conflicting values to .varm or\ - \ .obsm\n" - info: null - default: - - "move" - required: false - choices: - - "same" - - "unique" - - "first" - - "only" - - "concat" - - "move" - direction: "input" - multiple: false - multiple_sep: ";" - - type: "string" - name: "--uns_merge_mode" - description: "How to handle the merging of .uns across modalities\n - None: keep\ - \ no data\n - same: only keep elements of the matrices which are the same in\ - \ each of the samples\n - unique: only keep elements for which there is only\ - \ 1 possible value (1 value that can occur in multiple samples)\n - first:\ - \ keep the annotation from the first sample\n - only: keep elements that show\ - \ up in only one of the objects (1 unique element in only 1 sample)\n - make_unique:\ - \ identical to 'unique', but keys which are not unique are made unique by prefixing\ - \ them with the sample id.\n" - info: null - default: - - "make_unique" - required: false - choices: - - "same" - - "unique" - - "first" - - "only" - - "make_unique" - direction: "input" - multiple: false - multiple_sep: ";" - - type: "string" - name: "--obsp_keys" - description: "List of `.obsp` keys for which block-diagonal concatenation should\ - \ be performed.\nIf not provided, no `.obsp` keys will be concatenated.\nProvided\ - \ keys must be present in all samples for block concatenation to be performed.\n" - info: null - required: false - direction: "input" - multiple: true - multiple_sep: ";" - - type: "string" - name: "--output_compression" - description: "Compression format to use for the output AnnData and/or Mudata objects.\n\ - By default no compression is applied.\n" - info: null - example: - - "gzip" - required: false - choices: - - "gzip" - - "lzf" - direction: "input" - multiple: false - multiple_sep: ";" -resources: -- type: "python_script" - path: "script.py" - is_executable: true -- type: "file" - path: "setup_logger.py" -- type: "file" - path: "compress_h5mu.py" -- type: "file" - path: "nextflow_labels.config" - dest: "nextflow_labels.config" -description: "Concatenate observations from samples in several (uni- and/or multi-modal)\ - \ MuData files into a single file.\n" -test_resources: -- type: "python_script" - path: "test.py" - is_executable: true -- type: "file" - path: "e18_mouse_brain_fresh_5k_filtered_feature_bc_matrix_subset_unique_obs.h5mu" -- type: "file" - path: "human_brain_3k_filtered_feature_bc_matrix_subset_unique_obs.h5mu" -info: null -status: "enabled" -scope: - image: "public" - target: "public" -repositories: -- type: "vsh" - name: "openpipeline" - repo: "openpipeline" - tag: "v3.0.0" -links: - repository: "https://github.com/openpipelines-bio/openpipeline_spatial" - docker_registry: "ghcr.io" -runners: -- type: "executable" - id: "executable" - docker_setup_strategy: "ifneedbepullelsecachedbuild" -- type: "nextflow" - id: "nextflow" - directives: - label: - - "midcpu" - - "highmem" - tag: "$id" - auto: - simplifyInput: true - simplifyOutput: false - transcript: false - publish: false - config: - labels: - mem1gb: "memory = 1000000000.B" - mem2gb: "memory = 2000000000.B" - mem5gb: "memory = 5000000000.B" - mem10gb: "memory = 10000000000.B" - mem20gb: "memory = 20000000000.B" - mem50gb: "memory = 50000000000.B" - mem100gb: "memory = 100000000000.B" - mem200gb: "memory = 200000000000.B" - mem500gb: "memory = 500000000000.B" - mem1tb: "memory = 1000000000000.B" - mem2tb: "memory = 2000000000000.B" - mem5tb: "memory = 5000000000000.B" - mem10tb: "memory = 10000000000000.B" - mem20tb: "memory = 20000000000000.B" - mem50tb: "memory = 50000000000000.B" - mem100tb: "memory = 100000000000000.B" - mem200tb: "memory = 200000000000000.B" - mem500tb: "memory = 500000000000000.B" - mem1gib: "memory = 1073741824.B" - mem2gib: "memory = 2147483648.B" - mem4gib: "memory = 4294967296.B" - mem8gib: "memory = 8589934592.B" - mem16gib: "memory = 17179869184.B" - mem32gib: "memory = 34359738368.B" - mem64gib: "memory = 68719476736.B" - mem128gib: "memory = 137438953472.B" - mem256gib: "memory = 274877906944.B" - mem512gib: "memory = 549755813888.B" - mem1tib: "memory = 1099511627776.B" - mem2tib: "memory = 2199023255552.B" - mem4tib: "memory = 4398046511104.B" - mem8tib: "memory = 8796093022208.B" - mem16tib: "memory = 17592186044416.B" - mem32tib: "memory = 35184372088832.B" - mem64tib: "memory = 70368744177664.B" - mem128tib: "memory = 140737488355328.B" - mem256tib: "memory = 281474976710656.B" - mem512tib: "memory = 562949953421312.B" - 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" - script: - - "includeConfig(\"nextflow_labels.config\")" - debug: false - container: "docker" -engines: -- type: "docker" - id: "docker" - image: "python:3.13-slim" - target_registry: "images.viash-hub.com" - target_tag: "niche-compass" - namespace_separator: "/" - setup: - - type: "apt" - packages: - - "procps" - interactive: false - - type: "python" - user: false - packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" - script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" - upgrade: true - test_setup: - - type: "apt" - packages: - - "git" - interactive: false - - type: "python" - user: false - packages: - - "viashpy==0.9.0" - github: - - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" - upgrade: true - - type: "python" - user: false - packages: - - "viashpy==0.9.0" - - "pytest-benchmark" - upgrade: true - entrypoint: [] - cmd: null -- type: "native" - id: "native" -build_info: - config: "src/dataflow/concatenate_h5mu/config.vsh.yaml" - runner: "nextflow" - engine: "docker|native" - output: "target/nextflow/dataflow/concatenate_h5mu" - executable: "target/nextflow/dataflow/concatenate_h5mu/main.nf" - viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" - git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" -package_config: - name: "openpipeline_spatial" - version: "niche-compass" - info: - test_resources: - - type: "s3" - path: "s3://openpipelines-bio/openpipeline_spatial/resources_test" - dest: "resources_test" - repositories: - - type: "vsh" - name: "openpipeline" - repo: "openpipeline" - tag: "v3.0.0" - viash_version: "0.9.4" - source: "src" - target: "target" - config_mods: - - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n\ - .runners[.type == 'nextflow'].config.script := 'includeConfig(\"nextflow_labels.config\"\ - )'" - - ".engines += { type: \"native\" }" - - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" - - ".engines[.type == 'docker'].target_tag := 'niche-compass'" - organization: "vsh" - links: - repository: "https://github.com/openpipelines-bio/openpipeline_spatial" - docker_registry: "ghcr.io" diff --git a/target/nextflow/dataflow/concatenate_h5mu/compress_h5mu.py b/target/nextflow/dataflow/concatenate_h5mu/compress_h5mu.py deleted file mode 100644 index 4b363ee..0000000 --- a/target/nextflow/dataflow/concatenate_h5mu/compress_h5mu.py +++ /dev/null @@ -1,87 +0,0 @@ -import shutil -from anndata import AnnData -from mudata import write_h5ad -from h5py import File as H5File -from h5py import Group, Dataset -from pathlib import Path -from typing import Union, Literal -from functools import partial - - -def compress_h5mu( - input_path: Union[str, Path], - output_path: Union[str, Path], - compression: Union[Literal["gzip"], Literal["lzf"]], -): - input_path, output_path = str(input_path), str(output_path) - - def copy_attributes(in_object, out_object): - for key, value in in_object.attrs.items(): - out_object.attrs[key] = value - - def visit_path( - output_h5: H5File, - compression: Union[Literal["gzip"], Literal["lzf"]], - name: str, - object: Union[Group, Dataset], - ): - if isinstance(object, Group): - new_group = output_h5.create_group(name) - copy_attributes(object, new_group) - elif isinstance(object, Dataset): - # Compression only works for non-scalar Dataset objects - # Scalar objects dont have a shape defined - if not object.compression and object.shape not in [None, ()]: - new_dataset = output_h5.create_dataset( - name, data=object, compression=compression - ) - copy_attributes(object, new_dataset) - else: - output_h5.copy(object, name) - else: - raise NotImplementedError( - f"Could not copy element {name}, " - f"type has not been implemented yet: {type(object)}" - ) - - with ( - H5File(input_path, "r") as input_h5, - H5File(output_path, "w", userblock_size=512) as output_h5, - ): - copy_attributes(input_h5, output_h5) - input_h5.visititems(partial(visit_path, output_h5, compression)) - - with open(input_path, "rb") as input_bytes: - # Mudata puts metadata like this in the first 512 bytes: - # MuData (format-version=0.1.0;creator=muon;creator-version=0.2.0) - # See mudata/_core/io.py, read_h5mu() function - starting_metadata = input_bytes.read(100) - # The metadata is padded with extra null bytes up until 512 bytes - truncate_location = starting_metadata.find(b"\x00") - starting_metadata = starting_metadata[:truncate_location] - with open(output_path, "br+") as f: - nbytes = f.write(starting_metadata) - f.write(b"\0" * (512 - nbytes)) - - -def write_h5ad_to_h5mu_with_compression( - output_file: Union[str, Path], - h5mu: Union[str, Path], - modality_name: str, - modality_data: AnnData, - output_compression=None, -): - output_file = Path(output_file) - h5mu = Path(h5mu) - output_file_uncompressed = ( - output_file.with_name(output_file.stem + "_uncompressed.h5mu") - if output_compression - else output_file - ) - shutil.copyfile(h5mu, output_file_uncompressed) - write_h5ad(filename=output_file_uncompressed, mod=modality_name, data=modality_data) - if output_compression: - compress_h5mu( - output_file_uncompressed, output_file, compression=output_compression - ) - output_file_uncompressed.unlink() diff --git a/target/nextflow/dataflow/concatenate_h5mu/main.nf b/target/nextflow/dataflow/concatenate_h5mu/main.nf deleted file mode 100644 index 4780844..0000000 --- a/target/nextflow/dataflow/concatenate_h5mu/main.nf +++ /dev/null @@ -1,4387 +0,0 @@ -// concatenate_h5mu niche-compass -// -// This wrapper script is auto-generated by viash 0.9.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. -// -// Component authors: -// * Dries Schaumont (maintainer) - -//////////////////////////// -// VDSL3 helper functions // -//////////////////////////// - -// helper file: 'src/main/resources/io/viash/runners/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. only cast if the value is a GString - if (value instanceof GString) { - value = value as String - } - expectedClass = value instanceof String ? null : "String" - } else if (par.type == "integer") { - // cast to integer if need be - if (value !instanceof Integer) { - try { - value = value as Integer - } catch (NumberFormatException e) { - expectedClass = "Integer" - } - } - } else if (par.type == "long") { - // cast to long if need be - if (value !instanceof Long) { - try { - value = value as Long - } catch (NumberFormatException e) { - expectedClass = "Long" - } - } - } else if (par.type == "double") { - // cast to double if need be - if (value !instanceof Double) { - try { - value = value as Double - } catch (NumberFormatException e) { - expectedClass = "Double" - } - } - } else if (par.type == "float") { - // cast to float if need be - if (value !instanceof Float) { - try { - value = value as Float - } catch (NumberFormatException e) { - expectedClass = "Float" - } - } - } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { - // cast to boolean if need be - if (value !instanceof Boolean) { - try { - value = value as Boolean - } catch (Exception e) { - expectedClass = "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 String) { - try { - value = value as String - } catch (Exception e) { - expectedClass = "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/runners/nextflow/arguments/_processInputValues.nf' -Map _processInputValues(Map inputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.allArguments.each { arg -> - if (arg.required && arg.direction == "input") { - 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.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/runners/nextflow/arguments/_processOutputValues.nf' -Map _checkValidOutputArgument(Map outputs, Map config, String id, String key) { - if (!workflow.stubRun) { - outputs = outputs.collectEntries { name, value -> - def par = config.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 -} - -void _checkAllRequiredOuputsPresent(Map outputs, Map config, String id, String key) { - if (!workflow.stubRun) { - config.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" - } - } - } -} -// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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/runners/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.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/runners/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.name - - /* parse regular parameters (not in param_list) */ - /*************************************************/ - def globalParams = config.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 && !id) { - // if stub run, explicitly add an id if missing - 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.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/runners/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/runners/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.name - - // Get different parameter types (used throughout this function) - def defaultArgs = config.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.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/runners/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] - 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_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/runners/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 runIf_ = args.runIf - def id_ = args.id - - assert !runIf_ || runIf_ instanceof Closure: "runEach: must pass a Closure to runIf." - - 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 chPassthrough = null - def chRun = null - if (runIf_) { - def idRunIfBranch = id_ch.branch{ tup -> - run: runIf_(tup[0], tup[1], comp_) - passthrough: true - } - chPassthrough = idRunIfBranch.passthrough - chRun = idRunIfBranch.run - } else { - chRun = id_ch - chPassthrough = Channel.empty() - } - def data_ch = chRun | 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 - - def return_ch = post_ch - | concat(chPassthrough) - - return_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/runners/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/runners/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/runners/nextflow/config/addGlobalParams.nf' -def addGlobalArguments(config) { - def localConfig = [ - "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/runners/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 - - // 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/runners/nextflow/config/processConfig.nf' -def processConfig(config) { - // set defaults for arguments - config.arguments = - (config.arguments ?: []).collect{_processArgument(it)} - - // set defaults for argument_group arguments - config.argument_groups = - (config.argument_groups ?: []).collect{grp -> - grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} - grp - } - - // create combined arguments list - config.allArguments = - config.arguments + - config.argument_groups.collectMany{it.arguments} - - // add missing argument groups (based on Functionality::allArgumentGroups()) - def argGroups = config.argument_groups - if (argGroups.any{it.name.toLowerCase() == "arguments"}) { - argGroups = argGroups.collect{ grp -> - if (grp.name.toLowerCase() == "arguments") { - grp = grp + [ - arguments: grp.arguments + config.arguments - ] - } - grp - } - } else { - argGroups = argGroups + [ - name: "Arguments", - arguments: config.arguments - ] - } - config.allArgumentGroups = argGroups - - config -} - -// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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) { - def _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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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 - } - def 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/runners/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/runners/nextflow/readwrite/readJsonBlob.nf' -def readJsonBlob(str) { - def jsonSlurper = new groovy.json.JsonSlurper() - jsonSlurper.parseText(str) -} - -// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/nextflow/readwrite/readYamlBlob.nf' -def readYamlBlob(str) { - def yamlSlurper = new org.yaml.snakeyaml.Yaml() - yamlSlurper.load(str) -} - -// helper file: 'src/main/resources/io/viash/runners/nextflow/readwrite/toJsonBlob.nf' -String toJsonBlob(data) { - return groovy.json.JsonOutput.toJson(data) -} - -// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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/runners/nextflow/states/findStates.nf' -def findStates(Map params, Map config) { - def auto_config = deepClone(config) - def auto_params = deepClone(params) - - auto_config = auto_config.clone() - // override arguments - auto_config.argument_groups = [] - auto_config.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', or 'newKey:oldKey;newKey:oldKey' in case of multiple values" - 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/runners/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/runners/nextflow/states/publishFiles.nf' -def publishFiles(Map args) { - def key_ = args.get("key") - - assert key_ != null : "publishFiles: key must be specified" - - workflow publishFilesWf { - 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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() - def inputFiles_ = inputoutputFilenames_[0] - def outputFilenames_ = inputoutputFilenames_[1] - - [id_, inputFiles_, outputFilenames_] - } - | publishFilesProc - emit: input_ch - } - return publishFilesWf -} - -process publishFilesProc { - // todo: check publishpath? - publishDir path: "${getPublishDir()}/", mode: "copy" - tag "$id" - input: - tuple val(id), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) - output: - tuple val(id), path{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 - [] - } - } - """ - 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 publishFilesByConfig(Map args) { - def config = args.get("config") - assert config != null : "publishFilesByConfig: config must be specified" - - def key_ = args.get("key", config.name) - assert key_ != null : "publishFilesByConfig: key must be specified" - - workflow publishFilesSimpleWf { - 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'] - - - // the processed state is a list of [key, value, inputPath, outputFilename] tuples, where - // - key is a String - // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) - // - inputPath is a List[Path] - // - outputFilename is a List[String] - // - (inputPath, outputFilename) are the files that will be copied from src to dest (relative to the state.yaml) - def processedState = - config.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 OR multiple channels were emitted - // and the output was just not added to using the channel - // that is now being parsed - 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 [[inputPath: [], outputFilename: []]] - } - // 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('\\$\\{id\\}', id_) - .replaceAll('\\$key', key_) - .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 filename_ix = filename.replace("*", ix.toString()) - def inputPath = val instanceof File ? val.toPath() : val - [inputPath: inputPath, outputFilename: filename_ix] - } - def transposedOutputs = ["inputPath", "outputFilename"].collectEntries{ key -> - [key, outputPerFile.collect{dic -> dic[key]}] - } - return [[key: plainName_] + transposedOutputs] - } else { - def value_ = java.nio.file.Paths.get(filename) - def inputPath = value instanceof File ? value.toPath() : value - return [[inputPath: [inputPath], outputFilename: [filename]]] - } - } - - def inputPaths = processedState.collectMany{it.inputPath} - def outputFilenames = processedState.collectMany{it.outputFilename} - - - [id_, inputPaths, outputFilenames] - } - | publishFilesProc - emit: input_ch - } - return publishFilesSimpleWf -} - - - - -// helper file: 'src/main/resources/io/viash/runners/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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() - - def yamlFilename = yamlTemplate_ - .replaceAll('\\$id', id_) - .replaceAll('\\$\\{id\\}', id_) - .replaceAll('\\$key', key_) - .replaceAll('\\$\\{key\\}', key_) - - // TODO: do the pathnames in state_ match up with the outputFilenames_? - - // convert state to yaml blob - def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) - - [id_, yamlBlob_, yamlFilename] - } - | 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) - output: - tuple val(id), path{[yamlFile]} - script: - """ - mkdir -p "\$(dirname '${yamlFile}')" - echo "Storing state as yaml" - cat > '${yamlFile}' << HERE -${yamlBlob} -HERE - """ -} - - -// 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.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('\\$\\{id\\}', id_) - .replaceAll('\\$key', key_) - .replaceAll('\\$\\{key\\}', key_) - def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() - - // the processed state is a list of [key, value] tuples, where - // - key is a String - // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) - // - (key, value) are the tuples that will be saved to the state.yaml file - def processedState = - config.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]] - } - // 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('\\$\\{id\\}', id_) - .replaceAll('\\$key', key_) - .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 filename_ix = filename.replace("*", ix.toString()) - def value_ = java.nio.file.Paths.get(filename_ix) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - return value_ - } - return [["key": plainName_, "value": outputPerFile]] - } else { - def value_ = java.nio.file.Paths.get(filename) - // if id contains a slash - if (yamlDir != null) { - value_ = yamlDir.relativize(value_) - } - def inputPath = value instanceof File ? value.toPath() : value - return [["key": plainName_, value: value_]] - } - } - - - def updatedState_ = processedState.collectEntries{[it.key, it.value]} - - // convert state to yaml blob - def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) - - [id_, yamlBlob_, yamlFilename] - } - | publishStatesProc - emit: input_ch - } - return publishStatesSimpleWf -} - -// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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.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_.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/runners/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"] - def multipleArgs = meta.config.allArguments.findAll{ it.multiple }.collect{it.plainName} - - workflow workflowInstance { - take: input_ - - main: - def 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 - if (tuple[0] instanceof GString) { - tuple[0] = tuple[0].toString() - } - 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.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 - } - - - def chRun = null - def chPassthrough = null - if (workflowArgs.runIf) { - def runIfBranch = chModified.branch{ tup -> - run: workflowArgs.runIf(tup[0], tup[1]) - passthrough: true - } - chRun = runIfBranch.run - chPassthrough = runIfBranch.passthrough - } else { - chRun = chModified - chPassthrough = Channel.empty() - } - - def chRunFiltered = workflowArgs.filter ? - chRun | filter{workflowArgs.filter(it)} : - chRun - - def chArgs = workflowArgs.fromState ? - chRunFiltered | map{ - def new_data = workflowArgs.fromState(it.take(2)) - [it[0], new_data] - } : - chRunFiltered | map {tup -> tup.take(2)} - - // fill in defaults - def 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.allArguments - .findAll { it.containsKey("default") } - .collectEntries { [ it.plainName, it.default ] } - - // fetch overrides in params - def paramArgs = meta.config.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.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. - def chInitialOutputMulti = chArgsWithDefaults - | _debug(workflowArgs, "processed") - // run workflow - | innerWorkflowFactory(workflowArgs) - def chInitialOutputList = chInitialOutputMulti instanceof List ? chInitialOutputMulti : [chInitialOutputMulti] - assert chInitialOutputList.size() > 0: "should have emitted at least one output channel" - // Add a channel ID to the events, which designates the channel the event was emitted from as a running number - // This number is used to sort the events later when the events are gathered from across the channels. - def chInitialOutputListWithIndexedEvents = chInitialOutputList.withIndex().collect{channel, channelIndex -> - def newChannel = channel - | map {tuple -> - assert tuple instanceof List : - "Error in module '${key_}': element in output 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()}" - - def newEvent = [channelIndex] + tuple - return newEvent - } - return newChannel - } - // Put the events into 1 channel, cover case where there is only one channel is emitted - def chInitialOutput = chInitialOutputList.size() > 1 ? \ - chInitialOutputListWithIndexedEvents[0].mix(*chInitialOutputListWithIndexedEvents.tail()) : \ - chInitialOutputListWithIndexedEvents[0] - def chInitialOutputProcessed = chInitialOutput - | map { tuple -> - def channelId = tuple[0] - def id_ = tuple[1] - def output_ = tuple[2] - - // 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_ = _checkValidOutputArgument(output_, meta.config, id_, key_) - - [join_id, channelId, id_, output_] - } - // | view{"chInitialOutput: ${it.take(3)}"} - - // join the output [prev_id, channel_id, new_id, output] with the previous state [prev_id, state, ...] - def chPublishWithPreviousState = safeJoin(chInitialOutputProcessed, chRunFiltered, key_) - // input tuple format: [join_id, channel_id, id, output, prev_state, ...] - // output tuple format: [join_id, channel_id, id, new_state, ...] - | map{ tup -> - def new_state = workflowArgs.toState(tup.drop(2).take(3)) - tup.take(3) + [new_state] + tup.drop(5) - } - if (workflowArgs.auto.publish == "state") { - def chPublishFiles = chPublishWithPreviousState - // input tuple format: [join_id, channel_id, id, new_state, ...] - // output tuple format: [join_id, channel_id, id, new_state] - | map{ tup -> - tup.take(4) - } - - safeJoin(chPublishFiles, chArgsWithDefaults, key_) - // input tuple format: [join_id, channel_id, id, new_state, orig_state, ...] - // output tuple format: [id, new_state, orig_state] - | map { tup -> - tup.drop(2).take(3) - } - | publishFilesByConfig(key: key_, config: meta.config) - } - // Join the state from the events that were emitted from different channels - def chJoined = chInitialOutputProcessed - | map {tuple -> - def join_id = tuple[0] - def channel_id = tuple[1] - def id = tuple[2] - def other = tuple.drop(3) - // Below, groupTuple is used to join the events. To make sure resuming a workflow - // keeps working, the output state must be deterministic. This means the state needs to be - // sorted with groupTuple's has a 'sort' argument. This argument can be set to 'hash', - // but hashing the state when it is large can be problematic in terms of performance. - // Therefore, a custom comparator function is provided. We add the channel ID to the - // states so that we can use the channel ID to sort the items. - def stateWithChannelID = [[channel_id] * other.size(), other].transpose() - // A comparator that is provided to groupTuple's 'sort' argument is applied - // to all elements of the event tuple (that is not the 'id'). The comparator - // closure that is used below expects the input to be List. So the join_id and - // channel_id must also be wrapped in a list. - [[join_id], [channel_id], id] + stateWithChannelID - } - | groupTuple(by: 2, sort: {a, b -> a[0] <=> b[0]}, size: chInitialOutputList.size(), remainder: true) - | map {join_ids, _, id, statesWithChannelID -> - // Remove the channel IDs from the states - def states = statesWithChannelID.collect{it[1]} - def newJoinId = join_ids.flatten().unique{a, b -> a <=> b} - assert newJoinId.size() == 1: "Multiple events were emitted for '$id'." - def newJoinIdUnique = newJoinId[0] - - // Merge the states from the different channels - def newState = states.inject([:]){ old_state, state_to_add -> - return old_state + state_to_add.collectEntries{k, v -> - if (!multipleArgs.contains(k)) { - // if the key is not a multiple argument, we expect only one value - if (old_state.containsKey(k)) { - assert old_state[k] == v : "ID $id: multiple entries for argument $k were emitted." - } - [k, v] - } else { - // if the key is a multiple argument, append the different values into one list - def prevValue = old_state.getOrDefault(k, []) - def prevValueAsList = prevValue instanceof List ? prevValue : [prevValue] - [k, prevValueAsList + v] - } - } - } - - _checkAllRequiredOuputsPresent(newState, meta.config, id, key_) - - // simplify output if need be - if (workflowArgs.auto.simplifyOutput && newState.size() == 1) { - newState = newState.values()[0] - } - - return [newJoinIdUnique, id, newState] - } - - // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] - def chNewState = safeJoin(chJoined, chRunFiltered, 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") { - def chPublishStates = chNewState - // input tuple format: [join_id, id, new_state, ...] - // output tuple format: [join_id, id, new_state] - | map{ tup -> - tup.take(3) - } - - safeJoin(chPublishStates, 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) - } - 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('''{ - "name" : "concatenate_h5mu", - "namespace" : "dataflow", - "version" : "niche-compass", - "authors" : [ - { - "name" : "Dries Schaumont", - "roles" : [ - "maintainer" - ], - "info" : { - "role" : "Core Team Member", - "links" : { - "email" : "dries@data-intuitive.com", - "github" : "DriesSchaumont", - "orcid" : "0000-0002-4389-0440", - "linkedin" : "dries-schaumont" - }, - "organizations" : [ - { - "name" : "Data Intuitive", - "href" : "https://www.data-intuitive.com", - "role" : "Data Scientist" - } - ] - } - } - ], - "argument_groups" : [ - { - "name" : "Arguments", - "arguments" : [ - { - "type" : "file", - "name" : "--input", - "alternatives" : [ - "-i" - ], - "description" : "Paths to the different samples to be concatenated.", - "example" : [ - "sample_paths" - ], - "must_exist" : true, - "create_parent" : true, - "required" : true, - "direction" : "input", - "multiple" : true, - "multiple_sep" : ";" - }, - { - "type" : "string", - "name" : "--modality", - "description" : "Only output concatenated objects for the provided modalities. Outputs all modalities by default.", - "required" : false, - "direction" : "input", - "multiple" : true, - "multiple_sep" : ";" - }, - { - "type" : "string", - "name" : "--input_id", - "description" : "Names of the different samples that have to be concatenated. Must be specified when using '--mode move'.\nIn this case, the ids will be used for the columns names of the dataframes registring the conflicts.\nIf specified, must be of same length as `--input`.\n", - "required" : false, - "direction" : "input", - "multiple" : true, - "multiple_sep" : ";" - }, - { - "type" : "file", - "name" : "--output", - "alternatives" : [ - "-o" - ], - "description" : "Output location for the concatenated MuData object file.\n", - "example" : [ - "output.h5mu" - ], - "must_exist" : true, - "create_parent" : true, - "required" : false, - "direction" : "output", - "multiple" : false, - "multiple_sep" : ";" - }, - { - "type" : "string", - "name" : "--obs_sample_name", - "description" : "Name of the .obs key under which to add the sample names.", - "default" : [ - "sample_id" - ], - "required" : false, - "direction" : "input", - "multiple" : false, - "multiple_sep" : ";" - }, - { - "type" : "string", - "name" : "--other_axis_mode", - "description" : "How to handle the merging of other axis (var, obs, ...).\n\n - None: keep no data\n - same: only keep elements of the matrices which are the same in each of the samples\n - unique: only keep elements for which there is only 1 possible value (1 value that can occur in multiple samples)\n - first: keep the annotation from the first sample\n - only: keep elements that show up in only one of the objects (1 unique element in only 1 sample)\n - move: identical to 'same', but moving the conflicting values to .varm or .obsm\n", - "default" : [ - "move" - ], - "required" : false, - "choices" : [ - "same", - "unique", - "first", - "only", - "concat", - "move" - ], - "direction" : "input", - "multiple" : false, - "multiple_sep" : ";" - }, - { - "type" : "string", - "name" : "--uns_merge_mode", - "description" : "How to handle the merging of .uns across modalities\n - None: keep no data\n - same: only keep elements of the matrices which are the same in each of the samples\n - unique: only keep elements for which there is only 1 possible value (1 value that can occur in multiple samples)\n - first: keep the annotation from the first sample\n - only: keep elements that show up in only one of the objects (1 unique element in only 1 sample)\n - make_unique: identical to 'unique', but keys which are not unique are made unique by prefixing them with the sample id.\n", - "default" : [ - "make_unique" - ], - "required" : false, - "choices" : [ - "same", - "unique", - "first", - "only", - "make_unique" - ], - "direction" : "input", - "multiple" : false, - "multiple_sep" : ";" - }, - { - "type" : "string", - "name" : "--obsp_keys", - "description" : "List of `.obsp` keys for which block-diagonal concatenation should be performed.\nIf not provided, no `.obsp` keys will be concatenated.\nProvided keys must be present in all samples for block concatenation to be performed.\n", - "required" : false, - "direction" : "input", - "multiple" : true, - "multiple_sep" : ";" - }, - { - "type" : "string", - "name" : "--output_compression", - "description" : "Compression format to use for the output AnnData and/or Mudata objects.\nBy default no compression is applied.\n", - "example" : [ - "gzip" - ], - "required" : false, - "choices" : [ - "gzip", - "lzf" - ], - "direction" : "input", - "multiple" : false, - "multiple_sep" : ";" - } - ] - } - ], - "resources" : [ - { - "type" : "python_script", - "path" : "script.py", - "is_executable" : true - }, - { - "type" : "file", - "path" : "/src/utils/setup_logger.py" - }, - { - "type" : "file", - "path" : "/src/utils/compress_h5mu.py" - }, - { - "type" : "file", - "path" : "/src/workflows/utils/labels.config", - "dest" : "nextflow_labels.config" - } - ], - "description" : "Concatenate observations from samples in several (uni- and/or multi-modal) MuData files into a single file.\n", - "test_resources" : [ - { - "type" : "python_script", - "path" : "test.py", - "is_executable" : true - }, - { - "type" : "file", - "path" : "/resources_test/concat_test_data/e18_mouse_brain_fresh_5k_filtered_feature_bc_matrix_subset_unique_obs.h5mu" - }, - { - "type" : "file", - "path" : "/resources_test/concat_test_data/human_brain_3k_filtered_feature_bc_matrix_subset_unique_obs.h5mu" - } - ], - "status" : "enabled", - "scope" : { - "image" : "public", - "target" : "public" - }, - "repositories" : [ - { - "type" : "vsh", - "name" : "openpipeline", - "repo" : "openpipeline", - "tag" : "v3.0.0" - } - ], - "links" : { - "repository" : "https://github.com/openpipelines-bio/openpipeline_spatial", - "docker_registry" : "ghcr.io" - }, - "runners" : [ - { - "type" : "executable", - "id" : "executable", - "docker_setup_strategy" : "ifneedbepullelsecachedbuild" - }, - { - "type" : "nextflow", - "id" : "nextflow", - "directives" : { - "label" : [ - "midcpu", - "highmem" - ], - "tag" : "$id" - }, - "auto" : { - "simplifyInput" : true, - "simplifyOutput" : false, - "transcript" : false, - "publish" : false - }, - "config" : { - "labels" : { - "mem1gb" : "memory = 1000000000.B", - "mem2gb" : "memory = 2000000000.B", - "mem5gb" : "memory = 5000000000.B", - "mem10gb" : "memory = 10000000000.B", - "mem20gb" : "memory = 20000000000.B", - "mem50gb" : "memory = 50000000000.B", - "mem100gb" : "memory = 100000000000.B", - "mem200gb" : "memory = 200000000000.B", - "mem500gb" : "memory = 500000000000.B", - "mem1tb" : "memory = 1000000000000.B", - "mem2tb" : "memory = 2000000000000.B", - "mem5tb" : "memory = 5000000000000.B", - "mem10tb" : "memory = 10000000000000.B", - "mem20tb" : "memory = 20000000000000.B", - "mem50tb" : "memory = 50000000000000.B", - "mem100tb" : "memory = 100000000000000.B", - "mem200tb" : "memory = 200000000000000.B", - "mem500tb" : "memory = 500000000000000.B", - "mem1gib" : "memory = 1073741824.B", - "mem2gib" : "memory = 2147483648.B", - "mem4gib" : "memory = 4294967296.B", - "mem8gib" : "memory = 8589934592.B", - "mem16gib" : "memory = 17179869184.B", - "mem32gib" : "memory = 34359738368.B", - "mem64gib" : "memory = 68719476736.B", - "mem128gib" : "memory = 137438953472.B", - "mem256gib" : "memory = 274877906944.B", - "mem512gib" : "memory = 549755813888.B", - "mem1tib" : "memory = 1099511627776.B", - "mem2tib" : "memory = 2199023255552.B", - "mem4tib" : "memory = 4398046511104.B", - "mem8tib" : "memory = 8796093022208.B", - "mem16tib" : "memory = 17592186044416.B", - "mem32tib" : "memory = 35184372088832.B", - "mem64tib" : "memory = 70368744177664.B", - "mem128tib" : "memory = 140737488355328.B", - "mem256tib" : "memory = 281474976710656.B", - "mem512tib" : "memory = 562949953421312.B", - "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" - }, - "script" : [ - "includeConfig(\\"nextflow_labels.config\\")" - ] - }, - "debug" : false, - "container" : "docker" - } - ], - "engines" : [ - { - "type" : "docker", - "id" : "docker", - "image" : "python:3.13-slim", - "target_registry" : "images.viash-hub.com", - "target_tag" : "niche-compass", - "namespace_separator" : "/", - "setup" : [ - { - "type" : "apt", - "packages" : [ - "procps" - ], - "interactive" : false - }, - { - "type" : "python", - "user" : false, - "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" - ], - "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" - ], - "upgrade" : true - } - ], - "test_setup" : [ - { - "type" : "apt", - "packages" : [ - "git" - ], - "interactive" : false - }, - { - "type" : "python", - "user" : false, - "packages" : [ - "viashpy==0.9.0" - ], - "github" : [ - "openpipelines-bio/core#subdirectory=packages/python/openpipeline_testutils" - ], - "upgrade" : true - }, - { - "type" : "python", - "user" : false, - "packages" : [ - "viashpy==0.9.0", - "pytest-benchmark" - ], - "upgrade" : true - } - ] - }, - { - "type" : "native", - "id" : "native" - } - ], - "build_info" : { - "config" : "/workdir/root/repo/src/dataflow/concatenate_h5mu/config.vsh.yaml", - "runner" : "nextflow", - "engine" : "docker|native", - "output" : "/workdir/root/repo/target/nextflow/dataflow/concatenate_h5mu", - "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", - "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" - }, - "package_config" : { - "name" : "openpipeline_spatial", - "version" : "niche-compass", - "info" : { - "test_resources" : [ - { - "type" : "s3", - "path" : "s3://openpipelines-bio/openpipeline_spatial/resources_test", - "dest" : "resources_test" - } - ] - }, - "repositories" : [ - { - "type" : "vsh", - "name" : "openpipeline", - "repo" : "openpipeline", - "tag" : "v3.0.0" - } - ], - "viash_version" : "0.9.4", - "source" : "/workdir/root/repo/src", - "target" : "/workdir/root/repo/target", - "config_mods" : [ - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", - ".engines += { type: \\"native\\" }", - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", - ".engines[.type == 'docker'].target_tag := 'niche-compass'" - ], - "organization" : "vsh", - "links" : { - "repository" : "https://github.com/openpipelines-bio/openpipeline_spatial", - "docker_registry" : "ghcr.io" - } - } -}''')) -] - -// resolve dependencies dependencies (if any) - - -// inner workflow -// inner workflow hook -def innerWorkflowFactory(args) { - def rawScript = '''set -e -tempscript=".viash_script.py" -cat > "$tempscript" << VIASHMAIN -from __future__ import annotations -import sys -import anndata -import mudata as mu -import pandas as pd -import numpy as np -from collections.abc import Iterable -from multiprocessing import Pool -from pathlib import Path -from h5py import File as H5File -from typing import Literal -import shutil - -### 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\\'}'.split(';')"; else echo None; fi ), - 'modality': $( if [ ! -z ${VIASH_PAR_MODALITY+x} ]; then echo "r'${VIASH_PAR_MODALITY//\\'/\\'\\"\\'\\"r\\'}'.split(';')"; else echo None; fi ), - 'input_id': $( if [ ! -z ${VIASH_PAR_INPUT_ID+x} ]; then echo "r'${VIASH_PAR_INPUT_ID//\\'/\\'\\"\\'\\"r\\'}'.split(';')"; else echo None; fi ), - 'output': $( if [ ! -z ${VIASH_PAR_OUTPUT+x} ]; then echo "r'${VIASH_PAR_OUTPUT//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'obs_sample_name': $( if [ ! -z ${VIASH_PAR_OBS_SAMPLE_NAME+x} ]; then echo "r'${VIASH_PAR_OBS_SAMPLE_NAME//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'other_axis_mode': $( if [ ! -z ${VIASH_PAR_OTHER_AXIS_MODE+x} ]; then echo "r'${VIASH_PAR_OTHER_AXIS_MODE//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'uns_merge_mode': $( if [ ! -z ${VIASH_PAR_UNS_MERGE_MODE+x} ]; then echo "r'${VIASH_PAR_UNS_MERGE_MODE//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - 'obsp_keys': $( if [ ! -z ${VIASH_PAR_OBSP_KEYS+x} ]; then echo "r'${VIASH_PAR_OBSP_KEYS//\\'/\\'\\"\\'\\"r\\'}'.split(';')"; else echo None; fi ), - 'output_compression': $( if [ ! -z ${VIASH_PAR_OUTPUT_COMPRESSION+x} ]; then echo "r'${VIASH_PAR_OUTPUT_COMPRESSION//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ) -} -meta = { - 'name': $( if [ ! -z ${VIASH_META_NAME+x} ]; then echo "r'${VIASH_META_NAME//\\'/\\'\\"\\'\\"r\\'}'"; else echo None; fi ), - '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 ), - 'memory_kib': $( if [ ! -z ${VIASH_META_MEMORY_KIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_KIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_mib': $( if [ ! -z ${VIASH_META_MEMORY_MIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_MIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_gib': $( if [ ! -z ${VIASH_META_MEMORY_GIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_GIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_tib': $( if [ ! -z ${VIASH_META_MEMORY_TIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_TIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ), - 'memory_pib': $( if [ ! -z ${VIASH_META_MEMORY_PIB+x} ]; then echo "int(r'${VIASH_META_MEMORY_PIB//\\'/\\'\\"\\'\\"r\\'}')"; else echo None; fi ) -} -dep = { - -} - -### VIASH END - -sys.path.append(meta["resources_dir"]) -from compress_h5mu import compress_h5mu -from setup_logger import setup_logger - -logger = setup_logger() - - -def nunique(row): - unique = pd.unique(row) - unique_without_na = pd.core.dtypes.missing.remove_na_arraylike(unique) - return len(unique_without_na) > 1 - - -def any_row_contains_duplicate_values(n_processes: int, frame: pd.DataFrame) -> bool: - """ - Check if any row contains duplicate values, that are not NA. - """ - numpy_array = frame.to_numpy() - with Pool(n_processes) as pool: - is_duplicated = pool.map(nunique, iter(numpy_array)) - return any(is_duplicated) - - -def concatenate_matrices( - n_processes: int, matrices: dict[str, pd.DataFrame], align_to: pd.Index -) -> tuple[ - dict[str, pd.DataFrame], pd.DataFrame | None, dict[str, pd.core.dtypes.dtypes.Dtype] -]: - """ - Merge matrices by combining columns that have the same name. - Columns that contain conflicting values (e.i. the columns have different values), - are not merged, but instead moved to a new dataframe. - """ - column_names = set(column_name for var in matrices.values() for column_name in var) - logger.debug("Trying to concatenate columns: %s.", ",".join(column_names)) - if not column_names: - return {}, pd.DataFrame(index=align_to) - conflicts, concatenated_matrix = split_conflicts_and_concatenated_columns( - n_processes, matrices, column_names, align_to - ) - concatenated_matrix = cast_to_writeable_dtype(concatenated_matrix) - conflicts = { - conflict_name: cast_to_writeable_dtype(conflict_df) - for conflict_name, conflict_df in conflicts.items() - } - return conflicts, concatenated_matrix - - -def get_first_non_na_value_vector(df): - numpy_arr = df.to_numpy() - n_rows, n_cols = numpy_arr.shape - col_index = pd.isna(numpy_arr).argmin(axis=1) - flat_index = n_cols * np.arange(n_rows) + col_index - return pd.Series(numpy_arr.ravel()[flat_index], index=df.index, name=df.columns[0]) - - -def make_uns_keys_unique(mod_data, concatenated_data): - """ - Check if the uns keys across samples are unique before adding them - to the final concatenated object. If a conflict occurs between the samples, - add the sample ID to make the key unique again. - """ - all_uns_keys = {} - for sample_id, mod in mod_data.items(): - for uns_key, _ in mod.uns.items(): - all_uns_keys.setdefault(uns_key, []).append(sample_id) - for uns_key, samples_ids in all_uns_keys.items(): - assert samples_ids - if len(samples_ids) == 1: - sample_id = samples_ids[0] - concatenated_data.uns[uns_key] = mod_data[sample_id].uns[uns_key] - else: - for sample_id in samples_ids: - concatenated_data.uns[f"{sample_id}_{uns_key}"] = mod_data[ - sample_id - ].uns[uns_key] - return concatenated_data - - -def split_conflicts_and_concatenated_columns( - n_processes: int, - matrices: dict[str, pd.DataFrame], - column_names: Iterable[str], - align_to: pd.Index, -) -> tuple[dict[str, pd.DataFrame], pd.DataFrame]: - """ - Retrieve columns with the same name from a list of dataframes which are - identical across all the frames (ignoring NA values). - Columns which are not the same are regarded as 'conflicts', - which are stored in seperate dataframes, one per columns - with the same name that store conflicting values. - """ - conflicts = {} - concatenated_matrix = [] - for column_name in column_names: - columns = { - input_id: var[column_name] - for input_id, var in matrices.items() - if column_name in var - } - assert columns, "Some columns should have been found." - concatenated_columns = pd.concat( - columns.values(), axis=1, join="outer", sort=False - ) - if any_row_contains_duplicate_values(n_processes, concatenated_columns): - concatenated_columns.columns = ( - columns.keys() - ) # Use the sample id as column name - concatenated_columns = concatenated_columns.reindex(align_to, copy=False) - conflicts[f"conflict_{column_name}"] = concatenated_columns - else: - unique_values = get_first_non_na_value_vector(concatenated_columns) - concatenated_matrix.append(unique_values) - if not concatenated_matrix: - return conflicts, pd.DataFrame(index=align_to) - concatenated_matrix = pd.concat( - concatenated_matrix, join="outer", axis=1, sort=False - ) - concatenated_matrix = concatenated_matrix.reindex(align_to, copy=False) - return conflicts, concatenated_matrix - - -def cast_to_writeable_dtype(result: pd.DataFrame) -> pd.DataFrame: - """ - Cast the dataframe to dtypes that can be written by mudata. - """ - # dtype inferral workfs better with np.nan - result = result.replace({pd.NA: np.nan}) - - # MuData supports nullable booleans and ints - # ie. \\`IntegerArray\\` and \\`BooleanArray\\` - result = result.convert_dtypes( - infer_objects=True, - convert_integer=True, - convert_string=False, - convert_boolean=True, - convert_floating=False, - ) - - # Convert leftover 'object' columns to string - # However, na values are supported, so convert all values except NA's to string - object_cols = result.select_dtypes(include="object").columns.values - for obj_col in object_cols: - result[obj_col] = ( - result[obj_col] - .where(result[obj_col].isna(), result[obj_col].astype(str)) - .astype("category") - ) - return result - - -def split_conflicts_modalities( - n_processes: int, samples: dict[str, anndata.AnnData], output: anndata.AnnData -) -> anndata.AnnData: - """ - Merge .var and .obs matrices of the anndata objects. Columns are merged - when the values (excl NA) are the same in each of the matrices. - Conflicting columns are moved to a separate dataframe (one dataframe for each column, - containing all the corresponding column from each sample). - """ - matrices_to_parse = ("var", "obs") - for matrix_name in matrices_to_parse: - matrices = { - sample_id: getattr(sample, matrix_name) - for sample_id, sample in samples.items() - } - output_index = getattr(output, matrix_name).index - conflicts, concatenated_matrix = concatenate_matrices( - n_processes, matrices, output_index - ) - if concatenated_matrix.empty: - concatenated_matrix.index = output_index - - # Even though we did not touch the varm and obsm matrices that were already present, - # the joining of observations might have caused a dtype change in these matrices as well - # so these also need to be casted to a writable dtype... - for multidim_name, multidim_data in getattr(output, f"{matrix_name}m").items(): - new_data = ( - cast_to_writeable_dtype(multidim_data) - if isinstance(multidim_data, pd.DataFrame) - else multidim_data - ) - getattr(output, f"{matrix_name}m")[multidim_name] = new_data - - # Write the conflicts to the output - for conflict_name, conflict_data in conflicts.items(): - getattr(output, f"{matrix_name}m")[conflict_name] = conflict_data - - # Set other annotation matrices in the output - setattr(output, matrix_name, concatenated_matrix) - - return output - - -def concatenate_modality( - n_processes: int, - mod: str | None, - input_files: Iterable[str | Path], - other_axis_mode: str, - uns_merge_mode: str, - input_ids: tuple[str], -) -> anndata.AnnData: - concat_modes = { - "move": "unique", - } - other_axis_mode_to_apply = concat_modes.get(other_axis_mode, other_axis_mode) - - uns_merge_modes = {"make_unique": None} - uns_merge_mode_to_apply = uns_merge_modes.get(uns_merge_mode, uns_merge_mode) - - mod_data = {} - mod_indices_combined = pd.Index([]) - for input_id, input_file in zip(input_ids, input_files): - if mod is not None: - try: - data = mu.read_h5ad(input_file, mod=mod) - - # Remove obsp keys that are not in par["obsp_keys"] - if par["obsp_keys"]: - # Keep only the obsp keys that are specified in par["obsp_keys"] - keys_to_remove = set(data.obsp.keys()) - set(par["obsp_keys"]) - for key in keys_to_remove: - del data.obsp[key] - - mod_data[input_id] = data - mod_indices_combined = mod_indices_combined.append(data.obs.index) - except KeyError as e: # Modality does not exist for this sample, skip it - if ( - f"Unable to synchronously open object (object '{mod}' doesn't exist)" - not in str(e) - ): - raise e - pass - else: # When mod=None, process the 'global' h5mu state - with H5File(input_file, "r") as input_h5: - if "uns" in input_h5.keys(): - uns_data = anndata.experimental.read_elem(input_h5["uns"]) - if uns_data: - mod_data[input_id] = anndata.AnnData(uns=uns_data) - - if not mod_indices_combined.is_unique: - raise ValueError("Observations are not unique across samples.") - - if not mod_data: - return anndata.AnnData() - - concatenated_data = anndata.concat( - mod_data.values(), - join="outer", - pairwise=True if par["obsp_keys"] else False, - merge=other_axis_mode_to_apply, - uns_merge=uns_merge_mode_to_apply, - ) - - if other_axis_mode == "move": - concatenated_data = split_conflicts_modalities( - n_processes, mod_data, concatenated_data - ) - - if uns_merge_mode == "make_unique": - concatenated_data = make_uns_keys_unique(mod_data, concatenated_data) - - return concatenated_data - - -def concatenate_modalities( - n_processes: int, - modalities: list[str], - input_files: Path | str, - other_axis_mode: str, - uns_merge_mode: str, - output_file: Path | str, - compression: Literal["gzip"] | Literal["lzf"], - input_ids: tuple[str] | None = None, -) -> None: - """ - Join the modalities together into a single multimodal sample. - """ - logger.info("Concatenating samples.") - output_file, input_files = ( - Path(output_file), - [Path(input_file) for input_file in input_files], - ) - output_file_uncompressed = output_file.with_name( - output_file.stem + "_uncompressed.h5mu" - ) - output_file_uncompressed.touch() - # Create empty mudata file - mdata = mu.MuData({modality: anndata.AnnData() for modality in modalities}) - mdata.write(output_file_uncompressed, compression=compression) - - # Use "None" for the global slots (not assigned to any modality) - for mod_name in modalities + [ - None, - ]: - new_mod = concatenate_modality( - n_processes, - mod_name, - input_files, - other_axis_mode, - uns_merge_mode, - input_ids, - ) - if mod_name is None: - if new_mod.uns: - with H5File(output_file_uncompressed, "r+") as open_h5mu_file: - anndata.experimental.write_elem( - open_h5mu_file, "uns", dict(new_mod.uns) - ) - continue - logger.info( - "Writing out modality '%s' to '%s' with compression '%s'.", - mod_name, - output_file_uncompressed, - compression, - ) - mu.write_h5ad(output_file_uncompressed, data=new_mod, mod=mod_name) - - if compression: - compress_h5mu(output_file_uncompressed, output_file, compression=compression) - output_file_uncompressed.unlink() - else: - shutil.move(output_file_uncompressed, output_file) - - logger.info("Concatenation successful.") - - -def main() -> None: - # Get a list of all possible modalities - mods = set() - for path in par["input"]: - try: - with H5File(path, "r") as f_root: - mods = mods | set(f_root["mod"].keys()) - except OSError: - raise OSError(f"Failed to load {path}. Is it a valid h5 file?") - - input_ids = None - if par["input_id"]: - input_ids: tuple[str] = tuple(i.strip() for i in par["input_id"]) - if len(input_ids) != len(par["input"]): - raise ValueError( - "The number of sample names must match the number of sample files." - ) - - if len(set(input_ids)) != len(input_ids): - raise ValueError("The sample names should be unique.") - - logger.info("\\\\nConcatenating data from paths:\\\\n\\\\t%s", "\\\\n\\\\t".join(par["input"])) - - if par["other_axis_mode"] == "move" and not input_ids: - raise ValueError("--mode 'move' requires --input_ids.") - - n_processes = meta["cpus"] if meta["cpus"] else 1 - - if par["modality"]: - par["modality"] = set(par["modality"]) - if not par["modality"].issubset(mods): - mods_joined, input_mods_joined = ", ".join(mods), ", ".join(par["modality"]) - raise ValueError( - f"One of the modalities provided ({input_mods_joined}) is not available in the input data {mods_joined}" - ) - mods = par["modality"] - - concatenate_modalities( - n_processes, - list(mods), - par["input"], - par["other_axis_mode"], - par["uns_merge_mode"], - par["output"], - par["output_compression"], - input_ids=input_ids, - ) - - -if __name__ == "__main__": - main() -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.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.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('\\$\\{id\\}', id) - .replaceAll('\\$key', key) - .replaceAll('\\$\\{key\\}', key) - } - [parName, val] - } - - [ id ] + inputPaths + [ argsExclInputFiles, meta.resources_dir ] - } - | processObj - | map { output -> - def outputFiles = meta.config.allArguments - .findAll { it.type == "file" && it.direction == "output" } - .indexed() - .collectEntries{ index, par -> - def 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.allArguments - .findAll { it.type == "file" && it.direction == "input" } - .collect { ', path(viash_par_' + it.plainName + ', stageAs: "_viash_par/' + it.plainName + '_?/*")' } - .join() - - def outputPaths = meta.config.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.allArguments - .findAll { it.type == "file" && it.direction == "output" && it.create_parent } - .collect { par -> - def contents = "args[\"${par.plainName}\"] instanceof List ? args[\"${par.plainName}\"].join('\" \"') : args[\"${par.plainName}\"]" - "\${ args.containsKey(\"${par.plainName}\") ? \"mkdir_parent '\" + escapeText(${contents}) + \"'\" : \"\" }" - } - .join("\n") - - // construct inputFileExports - def inputFileExports = meta.config.allArguments - .findAll { it.type == "file" && it.direction.toLowerCase() == "input" } - .collect { par -> - def 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()}='\" + escapeText(${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.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 - | - |def escapeText = { s -> s.toString().replaceAll("'", "'\\\"'\\\"'") } - |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 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}" - |export VIASH_META_TEMP_DIR="${['docker', 'podman', 'charliecloud'].any{ it == workflow.containerEngine } ? '/tmp' : tmpDir}" - |export VIASH_META_NAME="${meta.config.name}" - |# export VIASH_META_EXECUTABLE="\\\$VIASH_META_RESOURCES_DIR/\\\$VIASH_META_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+999) / 1000 )) - | export VIASH_META_MEMORY_MB=\\\$(( (\\\$VIASH_META_MEMORY_KB+999) / 1000 )) - | export VIASH_META_MEMORY_GB=\\\$(( (\\\$VIASH_META_MEMORY_MB+999) / 1000 )) - | export VIASH_META_MEMORY_TB=\\\$(( (\\\$VIASH_META_MEMORY_GB+999) / 1000 )) - | export VIASH_META_MEMORY_PB=\\\$(( (\\\$VIASH_META_MEMORY_TB+999) / 1000 )) - | export VIASH_META_MEMORY_KIB=\\\$(( (\\\$VIASH_META_MEMORY_B+1023) / 1024 )) - | export VIASH_META_MEMORY_MIB=\\\$(( (\\\$VIASH_META_MEMORY_KIB+1023) / 1024 )) - | export VIASH_META_MEMORY_GIB=\\\$(( (\\\$VIASH_META_MEMORY_MIB+1023) / 1024 )) - | export VIASH_META_MEMORY_TIB=\\\$(( (\\\$VIASH_META_MEMORY_GIB+1023) / 1024 )) - | export VIASH_META_MEMORY_PIB=\\\$(( (\\\$VIASH_META_MEMORY_TIB+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######################") - // } - - // write process to temp file - def tempFile = java.nio.file.Files.createTempFile("viash-process-${procKey}-", ".nf") - addShutdownHook { java.nio.file.Files.deleteIfExists(tempFile) } - tempFile.text = procStr - - // create process from temp file - def binding = new nextflow.script.ScriptBinding([:]) - def session = nextflow.Nextflow.getSession() - def parser = _getScriptLoader(session) - .setModule(true) - .setBinding(binding) - def moduleScript = parser.runScript(tempFile) - .getScript() - - // register module in meta - def module = new nextflow.script.IncludeDef.Module(name: procKey) - scriptMeta.addModule(moduleScript, module.name, module.alias) - - // retrieve and return process from meta - return scriptMeta.getProcess(procKey) -} - -// use Reflection to get a ScriptParser / ScriptLoader -// <25.02.0-edge: new nextflow.script.ScriptParser(session) -// >=25.02.0-edge: nextflow.script.ScriptLoaderFactory.create(session) -def _getScriptLoader(nextflow.Session session) { - // try using the old method - try { - Class scriptParserClass = Class.forName('nextflow.script.ScriptParser') - return scriptParserClass.getDeclaredConstructor(nextflow.Session).newInstance(session) - } catch (ClassNotFoundException e) { - // else try with the new method - try { - Class scriptLoaderFactoryClass = Class.forName('nextflow.script.ScriptLoaderFactory') - def createMethod = scriptLoaderFactoryClass.getDeclaredMethod('create', nextflow.Session) - return createMethod.invoke(null, session) // null because create is static - } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | java.lang.reflect.InvocationTargetException e2) { - // Handle the case where neither class is found - throw new Exception("Neither nextflow.script.ScriptParser nor nextflow.script.ScriptLoaderFactory could be found. Is this a compatible Nextflow version?", e2) - } - } -} - -// 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" : "images.viash-hub.com", - "image" : "vsh/openpipeline_spatial/dataflow/concatenate_h5mu", - "tag" : "niche-compass" - }, - "label" : [ - "midcpu", - "highmem" - ], - "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.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.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.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/mapping/spaceranger_count/.config.vsh.yaml b/target/nextflow/mapping/spaceranger_count/.config.vsh.yaml index 5285377..1f5147b 100644 --- a/target/nextflow/mapping/spaceranger_count/.config.vsh.yaml +++ b/target/nextflow/mapping/spaceranger_count/.config.vsh.yaml @@ -330,7 +330,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" keywords: - "spaceranger" links: @@ -439,7 +439,7 @@ build_info: output: "target/nextflow/mapping/spaceranger_count" executable: "target/nextflow/mapping/spaceranger_count/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -453,7 +453,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/mapping/spaceranger_count/main.nf b/target/nextflow/mapping/spaceranger_count/main.nf index f9652c0..7c8803a 100644 --- a/target/nextflow/mapping/spaceranger_count/main.nf +++ b/target/nextflow/mapping/spaceranger_count/main.nf @@ -3433,7 +3433,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "keywords" : [ @@ -3569,7 +3569,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/mapping/spaceranger_count", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3589,7 +3589,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", @@ -3681,7 +3681,7 @@ for par in \\${unset_if_false[@]}; do [[ "\\$test_val" == "false" ]] && unset \\$par done -# just to make sure paths are absolute +# Make sure paths are absolute par_gex_reference=\\`realpath \\$par_gex_reference\\` par_output=\\`realpath \\$par_output\\` par_probe_set=\\`realpath \\$par_probe_set\\` diff --git a/target/nextflow/neighbors/spatial_neighborhood_graph/.config.vsh.yaml b/target/nextflow/neighbors/spatial_neighborhood_graph/.config.vsh.yaml index b166100..3c16722 100644 --- a/target/nextflow/neighbors/spatial_neighborhood_graph/.config.vsh.yaml +++ b/target/nextflow/neighbors/spatial_neighborhood_graph/.config.vsh.yaml @@ -147,7 +147,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -237,14 +237,15 @@ engines: - type: "python" user: false packages: - - "spatialdata~=0.5.0" - - "pyarrow~=18.0.0" - - "squidpy~=1.6.5" - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "scanpy~=1.10.4" + - "squidpy~=1.7.0" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true test_setup: - type: "apt" @@ -269,7 +270,7 @@ build_info: output: "target/nextflow/neighbors/spatial_neighborhood_graph" executable: "target/nextflow/neighbors/spatial_neighborhood_graph/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -283,7 +284,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/neighbors/spatial_neighborhood_graph/main.nf b/target/nextflow/neighbors/spatial_neighborhood_graph/main.nf index 2a3e1c8..0cd0651 100644 --- a/target/nextflow/neighbors/spatial_neighborhood_graph/main.nf +++ b/target/nextflow/neighbors/spatial_neighborhood_graph/main.nf @@ -3220,7 +3220,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3329,14 +3329,14 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "spatialdata~=0.5.0", - "pyarrow~=18.0.0", - "squidpy~=1.6.5", - "anndata~=0.11.1", - "mudata~=0.3.1" + "scanpy~=1.10.4", + "squidpy~=1.7.0", + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true } @@ -3373,7 +3373,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/neighbors/spatial_neighborhood_graph", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3393,7 +3393,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", diff --git a/target/nextflow/nichecompass/nichecompass/.config.vsh.yaml b/target/nextflow/nichecompass/nichecompass/.config.vsh.yaml index 0fe4078..1f4bb8b 100644 --- a/target/nextflow/nichecompass/nichecompass/.config.vsh.yaml +++ b/target/nextflow/nichecompass/nichecompass/.config.vsh.yaml @@ -875,7 +875,7 @@ repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -954,18 +954,11 @@ runners: engines: - type: "docker" id: "docker" - image: "nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04" + image: "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime" target_registry: "images.viash-hub.com" target_tag: "niche-compass" namespace_separator: "/" setup: - - type: "apt" - packages: - - "libhdf5-dev" - - "python3-pip" - - "python3-dev" - - "python-is-python3" - interactive: false - type: "docker" run: - "pip install torch --index-url https://download.pytorch.org/whl/cu124 \\\n&&\ @@ -974,11 +967,13 @@ engines: - type: "python" user: false packages: - - "anndata~=0.11.1" - - "mudata~=0.3.1" + - "anndata~=0.12.7" + - "awkward" + - "mudata~=0.3.2" script: - - "exec(\"try:\\n import awkward\\nexcept ModuleNotFoundError:\\n exit(0)\\\ - nelse: exit(1)\")" + - "exec(\"try:\\n import zarr; from importlib.metadata import version\\nexcept\ + \ ModuleNotFoundError:\\n exit(0)\\nelse: assert int(version(\\\"zarr\\\"\ + ).partition(\\\".\\\")[0]) > 2\")" upgrade: true - type: "python" user: false @@ -1003,7 +998,7 @@ build_info: output: "target/nextflow/nichecompass/nichecompass" executable: "target/nextflow/nichecompass/nichecompass/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" package_config: name: "openpipeline_spatial" @@ -1017,7 +1012,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/nichecompass/nichecompass/main.nf b/target/nextflow/nichecompass/nichecompass/main.nf index 4834a51..c0e1c62 100644 --- a/target/nextflow/nichecompass/nichecompass/main.nf +++ b/target/nextflow/nichecompass/nichecompass/main.nf @@ -3979,7 +3979,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -4073,21 +4073,11 @@ meta = [ { "type" : "docker", "id" : "docker", - "image" : "nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04", + "image" : "pytorch/pytorch:2.6.0-cuda12.4-cudnn9-runtime", "target_registry" : "images.viash-hub.com", "target_tag" : "niche-compass", "namespace_separator" : "/", "setup" : [ - { - "type" : "apt", - "packages" : [ - "libhdf5-dev", - "python3-pip", - "python3-dev", - "python-is-python3" - ], - "interactive" : false - }, { "type" : "docker", "run" : [ @@ -4098,11 +4088,12 @@ meta = [ "type" : "python", "user" : false, "packages" : [ - "anndata~=0.11.1", - "mudata~=0.3.1" + "anndata~=0.12.7", + "awkward", + "mudata~=0.3.2" ], "script" : [ - "exec(\\"try:\\\\n import awkward\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: exit(1)\\")" + "exec(\\"try:\\\\n import zarr; from importlib.metadata import version\\\\nexcept ModuleNotFoundError:\\\\n exit(0)\\\\nelse: assert int(version(\\\\\\"zarr\\\\\\").partition(\\\\\\".\\\\\\")[0]) > 2\\")" ], "upgrade" : true }, @@ -4138,7 +4129,7 @@ meta = [ "engine" : "docker|native", "output" : "/workdir/root/repo/target/nextflow/nichecompass/nichecompass", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -4158,7 +4149,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", @@ -4191,6 +4182,7 @@ cat > "$tempscript" << VIASHMAIN import sys import json import mudata as mu +import torch from nichecompass.models import NicheCompass from nichecompass.utils import add_gps_from_gp_dict_to_adata @@ -4299,6 +4291,12 @@ from setup_logger import setup_logger logger = setup_logger() +# Verify torch and CUDA availability +logger.info(f"Torch version: {torch.__version__}") +logger.info(f"CUDA available: {torch.cuda.is_available()}") +logger.info(f"Torch CUDA version: {torch.version.cuda}") +logger.info(f"GPU count: {torch.cuda.device_count()}") + ## Read in data adata = mu.read_h5ad(par["input"], mod=par["modality"]) diff --git a/target/nextflow/workflows/ingestion/spaceranger_mapping/.config.vsh.yaml b/target/nextflow/workflows/ingestion/spaceranger_mapping/.config.vsh.yaml new file mode 100644 index 0000000..a06a25a --- /dev/null +++ b/target/nextflow/workflows/ingestion/spaceranger_mapping/.config.vsh.yaml @@ -0,0 +1,511 @@ +name: "spaceranger_mapping" +namespace: "workflows/ingestion" +version: "niche-compass" +authors: +- name: "Dorien Roosen" + roles: + - "maintainer" + info: + role: "Core Team Member" + links: + email: "dorien@data-intuitive.com" + github: "dorien-er" + linkedin: "dorien-roosen" + organizations: + - name: "Data Intuitive" + href: "https://www.data-intuitive.com" + role: "Data Scientist" +- name: "Weiwei Schultz" + roles: + - "contributor" + info: + role: "Contributor" + organizations: + - name: "Janssen R&D US" + role: "Associate Director Data Sciences" +argument_groups: +- name: "Inputs" + arguments: + - type: "string" + name: "--id" + description: "ID of the sample." + info: null + example: + - "foo" + required: true + direction: "input" + multiple: false + multiple_sep: ";" + - type: "file" + name: "--input" + description: "The fastq.gz files to align. Can also be a single directory containing\ + \ fastq.gz files.\n\nIndividual FASTQ files should follow the naming convention\ + \ of 10x Genomics:\n[Sample Name]_S[Sample Number]_L[Lane Number]_[Read Type]_001.fastq.gz\n\ + \nWhere:\n[Sample Name] is the name assigned during sample preparation/sequencing\n\ + S[Sample Number] is the sample index (usually S1, S2, etc.)\nL[Lane Number]\ + \ identifies the sequencing lane (L001, L002, etc.)\n\n[Read Type] will be one\ + \ of:\nR1 - Read 1 (contains the spatial barcode and UMI)\nR2 - Read 2 (contains\ + \ the actual cDNA sequence)\n" + info: null + example: + - "sample_S1_L001_R1_001.fastq.gz" + - "sample_S1_L001_R2_001.fastq.gz" + must_exist: true + create_parent: true + required: true + direction: "input" + multiple: true + multiple_sep: ";" + - type: "file" + name: "--gex_reference" + description: "Path of folder containing 10x-compatible reference" + info: null + example: + - "/path/to/refdata-gex-GRCh38-2020-A" + must_exist: true + create_parent: true + required: true + direction: "input" + multiple: false + multiple_sep: ";" + - type: "file" + name: "--probe_set" + description: "CSV file specifying the probe set used" + info: null + example: + - "Visium_Human_Transcriptome_Probe_Set_v2.0_GRCh38-2020-A.csv" + must_exist: true + create_parent: true + required: true + direction: "input" + multiple: false + multiple_sep: ";" + - type: "file" + name: "--cytaimage" + description: "Brightfield image generated by the CytAssist instrument. \nWhen\ + \ using CytAssist workflow, either this or --image must be provided.\n" + info: null + example: + - "cyta_image.tif" + must_exist: true + create_parent: true + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "file" + name: "--image" + description: "H&E or fluorescence microscope image in TIFF or JPG format. \nRequired\ + \ for standard Visium workflow, optional when using --cytaimage for CytAssist\ + \ workflow.\n" + info: null + example: + - "brightfield.tif" + must_exist: true + create_parent: true + required: false + direction: "input" + multiple: false + multiple_sep: ";" +- name: "Outputs" + arguments: + - type: "file" + name: "--output_raw" + description: "Location where the output folder from Cell Ranger will be stored." + info: null + example: + - "output_dir" + must_exist: true + create_parent: true + required: true + direction: "output" + multiple: false + multiple_sep: ";" + - type: "file" + name: "--output_h5mu" + description: "The output from Cell Ranger, converted to h5mu." + info: null + example: + - "output.h5mu" + must_exist: true + create_parent: true + required: true + direction: "output" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--output_type" + description: "Which Cell Ranger output to use for converting to h5mu." + info: null + default: + - "raw" + required: false + choices: + - "raw" + - "filtered" + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--uns_metrics" + description: "Name of the .uns slot under which to QC metrics (if any)." + info: null + default: + - "metrics_summary" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--uns_probe_set" + description: "Name of the .uns slot under which to store probe set information\ + \ (if any)." + info: null + default: + - "probe_set" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--obsm_coordinates" + description: "Name of the .obsm slot under which to store the cell centroid coordinates." + info: null + default: + - "spatial" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--output_compression" + description: "Compression to use when writing the h5mu file." + info: null + required: false + choices: + - "gzip" + - "lzf" + direction: "input" + multiple: false + multiple_sep: ";" +- name: "Image Options" + arguments: + - type: "file" + name: "--darkimage" + description: "Multi-channel, dark-background fluorescence image" + info: null + example: + - "fluorescence.tif" + must_exist: true + create_parent: true + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "file" + name: "--colorizedimage" + description: "Color image representing pre-colored dark-background fluorescence\ + \ images" + info: null + example: + - "colored_fluorescence.tif" + must_exist: true + create_parent: true + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "integer" + name: "--dapi_index" + description: "Index of DAPI channel (1-indexed) of fluorescence image" + info: null + example: + - 1 + required: false + min: 1 + direction: "input" + multiple: false + multiple_sep: ";" + - type: "double" + name: "--image_scale" + description: "Microns per microscope image pixel" + info: null + example: + - 0.65 + required: false + min: 0.01 + max: 10.0 + direction: "input" + multiple: false + multiple_sep: ";" + - type: "boolean" + name: "--reorient_images" + description: "Whether to rotate and mirror image to align fiducial pattern" + info: null + default: + - true + required: false + direction: "input" + multiple: false + multiple_sep: ";" +- name: "Slide Information" + arguments: + - type: "string" + name: "--slide" + description: "Visium slide serial number (e.g., 'V10J25-015')" + info: null + example: + - "V10J25-015" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--area" + description: "Visium capture area identifier (e.g., 'A1')" + info: null + example: + - "A1" + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "string" + name: "--unknown_slide" + description: "Use this option if the slide serial number and area were entered\ + \ incorrectly on the CytAssist \ninstrument and the correct values are unknown.\ + \ Not compatible with --slide, --area, or \n--slide-file options\n" + info: null + required: false + choices: + - "visium-1" + - "visium-2" + - "visium-2-large" + - "visium-hd" + direction: "input" + multiple: false + multiple_sep: ";" + - type: "file" + name: "--slidefile" + description: "Slide design file for offline use" + info: null + example: + - "slide_design.gpr" + must_exist: true + create_parent: true + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "boolean_true" + name: "--override_id" + description: "Overrides the slide serial number and capture area provided in the\ + \ Cytassist image metadata" + info: null + direction: "input" +- name: "SpaceRanger arguments" + arguments: + - type: "boolean" + name: "--create_bam" + description: "Enable or disable BAM file generation" + info: null + default: + - true + required: true + direction: "input" + multiple: false + multiple_sep: ";" + - type: "boolean_true" + name: "--nosecondary" + description: "Disable secondary analysis (e.g., clustering)" + info: null + direction: "input" + - type: "integer" + name: "--r1_length" + description: "Hard trim the input Read 1 to this length before analysis" + info: null + required: false + min: 1 + direction: "input" + multiple: false + multiple_sep: ";" + - type: "integer" + name: "--r2_length" + description: "Hard trim the input Read 2 to this length before analysis" + info: null + required: false + min: 1 + direction: "input" + multiple: false + multiple_sep: ";" + - type: "boolean" + name: "--filter_probes" + description: "Whether to filter the probe set using the \"included\" column" + info: null + default: + - true + required: false + direction: "input" + multiple: false + multiple_sep: ";" + - type: "integer" + name: "--custom_bin_size" + description: "Bin Visium HD data to specified size in microns (4-100, even values\ + \ only) in addition to the standard binning size (2 µm, 8 µm, 16 µm)" + info: null + required: false + min: 4 + max: 100 + direction: "input" + multiple: false + multiple_sep: ";" +resources: +- type: "nextflow_script" + path: "main.nf" + is_executable: true + entrypoint: "run_wf" +- type: "file" + path: "utils" +- type: "file" + path: "nextflow_labels.config" + dest: "nextflow_labels.config" +description: "A pipeline for running SpaceRanger mapping." +test_resources: +- type: "nextflow_script" + path: "test.nf" + is_executable: true + entrypoint: "test_wf" +- type: "file" + path: "visium" +- type: "file" + path: "GRCh38" +info: + name: "SpaceRanger mapping" + test_dependencies: + - name: "spaceranger_mapping_test" + namespace: "test_workflows/ingestion" +status: "enabled" +scope: + image: "public" + target: "public" +dependencies: +- name: "mapping/spaceranger_count" + repository: + type: "local" +- name: "convert/from_spaceranger_to_h5mu" + repository: + type: "local" +repositories: +- type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" +links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" +runners: +- type: "nextflow" + id: "nextflow" + directives: + tag: "$id" + auto: + simplifyInput: true + simplifyOutput: false + transcript: false + publish: false + config: + labels: + mem1gb: "memory = 1000000000.B" + mem2gb: "memory = 2000000000.B" + mem5gb: "memory = 5000000000.B" + mem10gb: "memory = 10000000000.B" + mem20gb: "memory = 20000000000.B" + mem50gb: "memory = 50000000000.B" + mem100gb: "memory = 100000000000.B" + mem200gb: "memory = 200000000000.B" + mem500gb: "memory = 500000000000.B" + mem1tb: "memory = 1000000000000.B" + mem2tb: "memory = 2000000000000.B" + mem5tb: "memory = 5000000000000.B" + mem10tb: "memory = 10000000000000.B" + mem20tb: "memory = 20000000000000.B" + mem50tb: "memory = 50000000000000.B" + mem100tb: "memory = 100000000000000.B" + mem200tb: "memory = 200000000000000.B" + mem500tb: "memory = 500000000000000.B" + mem1gib: "memory = 1073741824.B" + mem2gib: "memory = 2147483648.B" + mem4gib: "memory = 4294967296.B" + mem8gib: "memory = 8589934592.B" + mem16gib: "memory = 17179869184.B" + mem32gib: "memory = 34359738368.B" + mem64gib: "memory = 68719476736.B" + mem128gib: "memory = 137438953472.B" + mem256gib: "memory = 274877906944.B" + mem512gib: "memory = 549755813888.B" + mem1tib: "memory = 1099511627776.B" + mem2tib: "memory = 2199023255552.B" + mem4tib: "memory = 4398046511104.B" + mem8tib: "memory = 8796093022208.B" + mem16tib: "memory = 17592186044416.B" + mem32tib: "memory = 35184372088832.B" + mem64tib: "memory = 70368744177664.B" + mem128tib: "memory = 140737488355328.B" + mem256tib: "memory = 281474976710656.B" + mem512tib: "memory = 562949953421312.B" + 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" + script: + - "includeConfig(\"nextflow_labels.config\")" + debug: false + container: "docker" +engines: +- type: "native" + id: "native" +build_info: + config: "src/workflows/ingestion/spaceranger_mapping/config.vsh.yaml" + runner: "nextflow" + engine: "native" + output: "target/nextflow/workflows/ingestion/spaceranger_mapping" + executable: "target/nextflow/workflows/ingestion/spaceranger_mapping/main.nf" + viash_version: "0.9.4" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" + git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" + dependencies: + - "target/nextflow/mapping/spaceranger_count" + - "target/nextflow/convert/from_spaceranger_to_h5mu" +package_config: + name: "openpipeline_spatial" + version: "niche-compass" + info: + test_resources: + - type: "s3" + path: "s3://openpipelines-bio/openpipeline_spatial/resources_test" + dest: "resources_test" + repositories: + - type: "vsh" + name: "openpipeline" + repo: "openpipeline" + tag: "v4.0.0" + viash_version: "0.9.4" + source: "src" + target: "target" + config_mods: + - ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n\ + .runners[.type == 'nextflow'].config.script := 'includeConfig(\"nextflow_labels.config\"\ + )'" + - ".engines += { type: \"native\" }" + - ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'" + - ".engines[.type == 'docker'].target_tag := 'niche-compass'" + organization: "vsh" + links: + repository: "https://github.com/openpipelines-bio/openpipeline_spatial" + docker_registry: "ghcr.io" diff --git a/target/nextflow/workflows/ingestion/spaceranger_mapping/main.nf b/target/nextflow/workflows/ingestion/spaceranger_mapping/main.nf new file mode 100644 index 0000000..9955eba --- /dev/null +++ b/target/nextflow/workflows/ingestion/spaceranger_mapping/main.nf @@ -0,0 +1,3864 @@ +// spaceranger_mapping niche-compass +// +// This wrapper script is auto-generated by viash 0.9.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. +// +// Component authors: +// * Dorien Roosen (maintainer) +// * Weiwei Schultz (contributor) + +//////////////////////////// +// VDSL3 helper functions // +//////////////////////////// + +// helper file: 'src/main/resources/io/viash/runners/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. only cast if the value is a GString + if (value instanceof GString) { + value = value as String + } + expectedClass = value instanceof String ? null : "String" + } else if (par.type == "integer") { + // cast to integer if need be + if (value !instanceof Integer) { + try { + value = value as Integer + } catch (NumberFormatException e) { + expectedClass = "Integer" + } + } + } else if (par.type == "long") { + // cast to long if need be + if (value !instanceof Long) { + try { + value = value as Long + } catch (NumberFormatException e) { + expectedClass = "Long" + } + } + } else if (par.type == "double") { + // cast to double if need be + if (value !instanceof Double) { + try { + value = value as Double + } catch (NumberFormatException e) { + expectedClass = "Double" + } + } + } else if (par.type == "float") { + // cast to float if need be + if (value !instanceof Float) { + try { + value = value as Float + } catch (NumberFormatException e) { + expectedClass = "Float" + } + } + } else if (par.type == "boolean" | par.type == "boolean_true" | par.type == "boolean_false") { + // cast to boolean if need be + if (value !instanceof Boolean) { + try { + value = value as Boolean + } catch (Exception e) { + expectedClass = "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 String) { + try { + value = value as String + } catch (Exception e) { + expectedClass = "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/runners/nextflow/arguments/_processInputValues.nf' +Map _processInputValues(Map inputs, Map config, String id, String key) { + if (!workflow.stubRun) { + config.allArguments.each { arg -> + if (arg.required && arg.direction == "input") { + 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.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/runners/nextflow/arguments/_processOutputValues.nf' +Map _checkValidOutputArgument(Map outputs, Map config, String id, String key) { + if (!workflow.stubRun) { + outputs = outputs.collectEntries { name, value -> + def par = config.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 +} + +void _checkAllRequiredOuputsPresent(Map outputs, Map config, String id, String key) { + if (!workflow.stubRun) { + config.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" + } + } + } +} +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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/runners/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.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/runners/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.name + + /* parse regular parameters (not in param_list) */ + /*************************************************/ + def globalParams = config.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 && !id) { + // if stub run, explicitly add an id if missing + 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.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/runners/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/runners/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.name + + // Get different parameter types (used throughout this function) + def defaultArgs = config.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.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/runners/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] + 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_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/runners/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 runIf_ = args.runIf + def id_ = args.id + + assert !runIf_ || runIf_ instanceof Closure: "runEach: must pass a Closure to runIf." + + 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 chPassthrough = null + def chRun = null + if (runIf_) { + def idRunIfBranch = id_ch.branch{ tup -> + run: runIf_(tup[0], tup[1], comp_) + passthrough: true + } + chPassthrough = idRunIfBranch.passthrough + chRun = idRunIfBranch.run + } else { + chRun = id_ch + chPassthrough = Channel.empty() + } + def data_ch = chRun | 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 + + def return_ch = post_ch + | concat(chPassthrough) + + return_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/runners/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/runners/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/runners/nextflow/config/addGlobalParams.nf' +def addGlobalArguments(config) { + def localConfig = [ + "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/runners/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 + + // 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/runners/nextflow/config/processConfig.nf' +def processConfig(config) { + // set defaults for arguments + config.arguments = + (config.arguments ?: []).collect{_processArgument(it)} + + // set defaults for argument_group arguments + config.argument_groups = + (config.argument_groups ?: []).collect{grp -> + grp.arguments = (grp.arguments ?: []).collect{_processArgument(it)} + grp + } + + // create combined arguments list + config.allArguments = + config.arguments + + config.argument_groups.collectMany{it.arguments} + + // add missing argument groups (based on Functionality::allArgumentGroups()) + def argGroups = config.argument_groups + if (argGroups.any{it.name.toLowerCase() == "arguments"}) { + argGroups = argGroups.collect{ grp -> + if (grp.name.toLowerCase() == "arguments") { + grp = grp + [ + arguments: grp.arguments + config.arguments + ] + } + grp + } + } else { + argGroups = argGroups + [ + name: "Arguments", + arguments: config.arguments + ] + } + config.allArgumentGroups = argGroups + + config +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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) { + def _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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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/runners/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 + } + def 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/runners/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/runners/nextflow/readwrite/readJsonBlob.nf' +def readJsonBlob(str) { + def jsonSlurper = new groovy.json.JsonSlurper() + jsonSlurper.parseText(str) +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/nextflow/readwrite/readYamlBlob.nf' +def readYamlBlob(str) { + def yamlSlurper = new org.yaml.snakeyaml.Yaml() + yamlSlurper.load(str) +} + +// helper file: 'src/main/resources/io/viash/runners/nextflow/readwrite/toJsonBlob.nf' +String toJsonBlob(data) { + return groovy.json.JsonOutput.toJson(data) +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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/runners/nextflow/states/findStates.nf' +def findStates(Map params, Map config) { + def auto_config = deepClone(config) + def auto_params = deepClone(params) + + auto_config = auto_config.clone() + // override arguments + auto_config.argument_groups = [] + auto_config.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', or 'newKey:oldKey;newKey:oldKey' in case of multiple values" + 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/runners/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/runners/nextflow/states/publishFiles.nf' +def publishFiles(Map args) { + def key_ = args.get("key") + + assert key_ != null : "publishFiles: key must be specified" + + workflow publishFilesWf { + 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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() + def inputFiles_ = inputoutputFilenames_[0] + def outputFilenames_ = inputoutputFilenames_[1] + + [id_, inputFiles_, outputFilenames_] + } + | publishFilesProc + emit: input_ch + } + return publishFilesWf +} + +process publishFilesProc { + // todo: check publishpath? + publishDir path: "${getPublishDir()}/", mode: "copy" + tag "$id" + input: + tuple val(id), path(inputFiles, stageAs: "_inputfile?/*"), val(outputFiles) + output: + tuple val(id), path{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 + [] + } + } + """ + 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 publishFilesByConfig(Map args) { + def config = args.get("config") + assert config != null : "publishFilesByConfig: config must be specified" + + def key_ = args.get("key", config.name) + assert key_ != null : "publishFilesByConfig: key must be specified" + + workflow publishFilesSimpleWf { + 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'] + + + // the processed state is a list of [key, value, inputPath, outputFilename] tuples, where + // - key is a String + // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) + // - inputPath is a List[Path] + // - outputFilename is a List[String] + // - (inputPath, outputFilename) are the files that will be copied from src to dest (relative to the state.yaml) + def processedState = + config.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 OR multiple channels were emitted + // and the output was just not added to using the channel + // that is now being parsed + 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 [[inputPath: [], outputFilename: []]] + } + // 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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .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 filename_ix = filename.replace("*", ix.toString()) + def inputPath = val instanceof File ? val.toPath() : val + [inputPath: inputPath, outputFilename: filename_ix] + } + def transposedOutputs = ["inputPath", "outputFilename"].collectEntries{ key -> + [key, outputPerFile.collect{dic -> dic[key]}] + } + return [[key: plainName_] + transposedOutputs] + } else { + def value_ = java.nio.file.Paths.get(filename) + def inputPath = value instanceof File ? value.toPath() : value + return [[inputPath: [inputPath], outputFilename: [filename]]] + } + } + + def inputPaths = processedState.collectMany{it.inputPath} + def outputFilenames = processedState.collectMany{it.outputFilename} + + + [id_, inputPaths, outputFilenames] + } + | publishFilesProc + emit: input_ch + } + return publishFilesSimpleWf +} + + + + +// helper file: 'src/main/resources/io/viash/runners/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 inputoutputFilenames_ = collectInputOutputPaths(state_, id_ + "." + key_).transpose() + + def yamlFilename = yamlTemplate_ + .replaceAll('\\$id', id_) + .replaceAll('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .replaceAll('\\$\\{key\\}', key_) + + // TODO: do the pathnames in state_ match up with the outputFilenames_? + + // convert state to yaml blob + def yamlBlob_ = toRelativeTaggedYamlBlob([id: id_] + state_, java.nio.file.Paths.get(yamlFilename)) + + [id_, yamlBlob_, yamlFilename] + } + | 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) + output: + tuple val(id), path{[yamlFile]} + script: + """ + mkdir -p "\$(dirname '${yamlFile}')" + echo "Storing state as yaml" + cat > '${yamlFile}' << HERE +${yamlBlob} +HERE + """ +} + + +// 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.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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .replaceAll('\\$\\{key\\}', key_) + def yamlDir = java.nio.file.Paths.get(yamlFilename).getParent() + + // the processed state is a list of [key, value] tuples, where + // - key is a String + // - value is any object that can be serialized to a Yaml (so a String/Integer/Long/Double/Boolean, a List, a Map, or a Path) + // - (key, value) are the tuples that will be saved to the state.yaml file + def processedState = + config.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]] + } + // 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('\\$\\{id\\}', id_) + .replaceAll('\\$key', key_) + .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 filename_ix = filename.replace("*", ix.toString()) + def value_ = java.nio.file.Paths.get(filename_ix) + // if id contains a slash + if (yamlDir != null) { + value_ = yamlDir.relativize(value_) + } + return value_ + } + return [["key": plainName_, "value": outputPerFile]] + } else { + def value_ = java.nio.file.Paths.get(filename) + // if id contains a slash + if (yamlDir != null) { + value_ = yamlDir.relativize(value_) + } + def inputPath = value instanceof File ? value.toPath() : value + return [["key": plainName_, value: value_]] + } + } + + + def updatedState_ = processedState.collectEntries{[it.key, it.value]} + + // convert state to yaml blob + def yamlBlob_ = toTaggedYamlBlob([id: id_] + updatedState_) + + [id_, yamlBlob_, yamlFilename] + } + | publishStatesProc + emit: input_ch + } + return publishStatesSimpleWf +} + +// helper file: 'src/main/resources/io/viash/runners/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/runners/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/runners/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/runners/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.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.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.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_.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/runners/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"] + def multipleArgs = meta.config.allArguments.findAll{ it.multiple }.collect{it.plainName} + + workflow workflowInstance { + take: input_ + + main: + def 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 + if (tuple[0] instanceof GString) { + tuple[0] = tuple[0].toString() + } + 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.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 + } + + + def chRun = null + def chPassthrough = null + if (workflowArgs.runIf) { + def runIfBranch = chModified.branch{ tup -> + run: workflowArgs.runIf(tup[0], tup[1]) + passthrough: true + } + chRun = runIfBranch.run + chPassthrough = runIfBranch.passthrough + } else { + chRun = chModified + chPassthrough = Channel.empty() + } + + def chRunFiltered = workflowArgs.filter ? + chRun | filter{workflowArgs.filter(it)} : + chRun + + def chArgs = workflowArgs.fromState ? + chRunFiltered | map{ + def new_data = workflowArgs.fromState(it.take(2)) + [it[0], new_data] + } : + chRunFiltered | map {tup -> tup.take(2)} + + // fill in defaults + def 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.allArguments + .findAll { it.containsKey("default") } + .collectEntries { [ it.plainName, it.default ] } + + // fetch overrides in params + def paramArgs = meta.config.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.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. + def chInitialOutputMulti = chArgsWithDefaults + | _debug(workflowArgs, "processed") + // run workflow + | innerWorkflowFactory(workflowArgs) + def chInitialOutputList = chInitialOutputMulti instanceof List ? chInitialOutputMulti : [chInitialOutputMulti] + assert chInitialOutputList.size() > 0: "should have emitted at least one output channel" + // Add a channel ID to the events, which designates the channel the event was emitted from as a running number + // This number is used to sort the events later when the events are gathered from across the channels. + def chInitialOutputListWithIndexedEvents = chInitialOutputList.withIndex().collect{channel, channelIndex -> + def newChannel = channel + | map {tuple -> + assert tuple instanceof List : + "Error in module '${key_}': element in output 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()}" + + def newEvent = [channelIndex] + tuple + return newEvent + } + return newChannel + } + // Put the events into 1 channel, cover case where there is only one channel is emitted + def chInitialOutput = chInitialOutputList.size() > 1 ? \ + chInitialOutputListWithIndexedEvents[0].mix(*chInitialOutputListWithIndexedEvents.tail()) : \ + chInitialOutputListWithIndexedEvents[0] + def chInitialOutputProcessed = chInitialOutput + | map { tuple -> + def channelId = tuple[0] + def id_ = tuple[1] + def output_ = tuple[2] + + // 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_ = _checkValidOutputArgument(output_, meta.config, id_, key_) + + [join_id, channelId, id_, output_] + } + // | view{"chInitialOutput: ${it.take(3)}"} + + // join the output [prev_id, channel_id, new_id, output] with the previous state [prev_id, state, ...] + def chPublishWithPreviousState = safeJoin(chInitialOutputProcessed, chRunFiltered, key_) + // input tuple format: [join_id, channel_id, id, output, prev_state, ...] + // output tuple format: [join_id, channel_id, id, new_state, ...] + | map{ tup -> + def new_state = workflowArgs.toState(tup.drop(2).take(3)) + tup.take(3) + [new_state] + tup.drop(5) + } + if (workflowArgs.auto.publish == "state") { + def chPublishFiles = chPublishWithPreviousState + // input tuple format: [join_id, channel_id, id, new_state, ...] + // output tuple format: [join_id, channel_id, id, new_state] + | map{ tup -> + tup.take(4) + } + + safeJoin(chPublishFiles, chArgsWithDefaults, key_) + // input tuple format: [join_id, channel_id, id, new_state, orig_state, ...] + // output tuple format: [id, new_state, orig_state] + | map { tup -> + tup.drop(2).take(3) + } + | publishFilesByConfig(key: key_, config: meta.config) + } + // Join the state from the events that were emitted from different channels + def chJoined = chInitialOutputProcessed + | map {tuple -> + def join_id = tuple[0] + def channel_id = tuple[1] + def id = tuple[2] + def other = tuple.drop(3) + // Below, groupTuple is used to join the events. To make sure resuming a workflow + // keeps working, the output state must be deterministic. This means the state needs to be + // sorted with groupTuple's has a 'sort' argument. This argument can be set to 'hash', + // but hashing the state when it is large can be problematic in terms of performance. + // Therefore, a custom comparator function is provided. We add the channel ID to the + // states so that we can use the channel ID to sort the items. + def stateWithChannelID = [[channel_id] * other.size(), other].transpose() + // A comparator that is provided to groupTuple's 'sort' argument is applied + // to all elements of the event tuple (that is not the 'id'). The comparator + // closure that is used below expects the input to be List. So the join_id and + // channel_id must also be wrapped in a list. + [[join_id], [channel_id], id] + stateWithChannelID + } + | groupTuple(by: 2, sort: {a, b -> a[0] <=> b[0]}, size: chInitialOutputList.size(), remainder: true) + | map {join_ids, _, id, statesWithChannelID -> + // Remove the channel IDs from the states + def states = statesWithChannelID.collect{it[1]} + def newJoinId = join_ids.flatten().unique{a, b -> a <=> b} + assert newJoinId.size() == 1: "Multiple events were emitted for '$id'." + def newJoinIdUnique = newJoinId[0] + + // Merge the states from the different channels + def newState = states.inject([:]){ old_state, state_to_add -> + return old_state + state_to_add.collectEntries{k, v -> + if (!multipleArgs.contains(k)) { + // if the key is not a multiple argument, we expect only one value + if (old_state.containsKey(k)) { + assert old_state[k] == v : "ID $id: multiple entries for argument $k were emitted." + } + [k, v] + } else { + // if the key is a multiple argument, append the different values into one list + def prevValue = old_state.getOrDefault(k, []) + def prevValueAsList = prevValue instanceof List ? prevValue : [prevValue] + [k, prevValueAsList + v] + } + } + } + + _checkAllRequiredOuputsPresent(newState, meta.config, id, key_) + + // simplify output if need be + if (workflowArgs.auto.simplifyOutput && newState.size() == 1) { + newState = newState.values()[0] + } + + return [newJoinIdUnique, id, newState] + } + + // join the output [prev_id, new_id, output] with the previous state [prev_id, state, ...] + def chNewState = safeJoin(chJoined, chRunFiltered, 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") { + def chPublishStates = chNewState + // input tuple format: [join_id, id, new_state, ...] + // output tuple format: [join_id, id, new_state] + | map{ tup -> + tup.take(3) + } + + safeJoin(chPublishStates, 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) + } + 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('''{ + "name" : "spaceranger_mapping", + "namespace" : "workflows/ingestion", + "version" : "niche-compass", + "authors" : [ + { + "name" : "Dorien Roosen", + "roles" : [ + "maintainer" + ], + "info" : { + "role" : "Core Team Member", + "links" : { + "email" : "dorien@data-intuitive.com", + "github" : "dorien-er", + "linkedin" : "dorien-roosen" + }, + "organizations" : [ + { + "name" : "Data Intuitive", + "href" : "https://www.data-intuitive.com", + "role" : "Data Scientist" + } + ] + } + }, + { + "name" : "Weiwei Schultz", + "roles" : [ + "contributor" + ], + "info" : { + "role" : "Contributor", + "organizations" : [ + { + "name" : "Janssen R&D US", + "role" : "Associate Director Data Sciences" + } + ] + } + } + ], + "argument_groups" : [ + { + "name" : "Inputs", + "arguments" : [ + { + "type" : "string", + "name" : "--id", + "description" : "ID of the sample.", + "example" : [ + "foo" + ], + "required" : true, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "file", + "name" : "--input", + "description" : "The fastq.gz files to align. Can also be a single directory containing fastq.gz files.\n\nIndividual FASTQ files should follow the naming convention of 10x Genomics:\n[Sample Name]_S[Sample Number]_L[Lane Number]_[Read Type]_001.fastq.gz\n\nWhere:\n[Sample Name] is the name assigned during sample preparation/sequencing\nS[Sample Number] is the sample index (usually S1, S2, etc.)\nL[Lane Number] identifies the sequencing lane (L001, L002, etc.)\n\n[Read Type] will be one of:\nR1 - Read 1 (contains the spatial barcode and UMI)\nR2 - Read 2 (contains the actual cDNA sequence)\n", + "example" : [ + "sample_S1_L001_R1_001.fastq.gz", + "sample_S1_L001_R2_001.fastq.gz" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "input", + "multiple" : true, + "multiple_sep" : ";" + }, + { + "type" : "file", + "name" : "--gex_reference", + "description" : "Path of folder containing 10x-compatible reference", + "example" : [ + "/path/to/refdata-gex-GRCh38-2020-A" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "file", + "name" : "--probe_set", + "description" : "CSV file specifying the probe set used", + "example" : [ + "Visium_Human_Transcriptome_Probe_Set_v2.0_GRCh38-2020-A.csv" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "file", + "name" : "--cytaimage", + "description" : "Brightfield image generated by the CytAssist instrument. \nWhen using CytAssist workflow, either this or --image must be provided.\n", + "example" : [ + "cyta_image.tif" + ], + "must_exist" : true, + "create_parent" : true, + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "file", + "name" : "--image", + "description" : "H&E or fluorescence microscope image in TIFF or JPG format. \nRequired for standard Visium workflow, optional when using --cytaimage for CytAssist workflow.\n", + "example" : [ + "brightfield.tif" + ], + "must_exist" : true, + "create_parent" : true, + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + }, + { + "name" : "Outputs", + "arguments" : [ + { + "type" : "file", + "name" : "--output_raw", + "description" : "Location where the output folder from Cell Ranger will be stored.", + "example" : [ + "output_dir" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "output", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "file", + "name" : "--output_h5mu", + "description" : "The output from Cell Ranger, converted to h5mu.", + "example" : [ + "output.h5mu" + ], + "must_exist" : true, + "create_parent" : true, + "required" : true, + "direction" : "output", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--output_type", + "description" : "Which Cell Ranger output to use for converting to h5mu.", + "default" : [ + "raw" + ], + "required" : false, + "choices" : [ + "raw", + "filtered" + ], + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--uns_metrics", + "description" : "Name of the .uns slot under which to QC metrics (if any).", + "default" : [ + "metrics_summary" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--uns_probe_set", + "description" : "Name of the .uns slot under which to store probe set information (if any).", + "default" : [ + "probe_set" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--obsm_coordinates", + "description" : "Name of the .obsm slot under which to store the cell centroid coordinates.", + "default" : [ + "spatial" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--output_compression", + "description" : "Compression to use when writing the h5mu file.", + "required" : false, + "choices" : [ + "gzip", + "lzf" + ], + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + }, + { + "name" : "Image Options", + "arguments" : [ + { + "type" : "file", + "name" : "--darkimage", + "description" : "Multi-channel, dark-background fluorescence image", + "example" : [ + "fluorescence.tif" + ], + "must_exist" : true, + "create_parent" : true, + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "file", + "name" : "--colorizedimage", + "description" : "Color image representing pre-colored dark-background fluorescence images", + "example" : [ + "colored_fluorescence.tif" + ], + "must_exist" : true, + "create_parent" : true, + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "integer", + "name" : "--dapi_index", + "description" : "Index of DAPI channel (1-indexed) of fluorescence image", + "example" : [ + 1 + ], + "required" : false, + "min" : 1, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "double", + "name" : "--image_scale", + "description" : "Microns per microscope image pixel", + "example" : [ + 0.65 + ], + "required" : false, + "min" : 0.01, + "max" : 10.0, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "boolean", + "name" : "--reorient_images", + "description" : "Whether to rotate and mirror image to align fiducial pattern", + "default" : [ + true + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + }, + { + "name" : "Slide Information", + "arguments" : [ + { + "type" : "string", + "name" : "--slide", + "description" : "Visium slide serial number (e.g., 'V10J25-015')", + "example" : [ + "V10J25-015" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--area", + "description" : "Visium capture area identifier (e.g., 'A1')", + "example" : [ + "A1" + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "string", + "name" : "--unknown_slide", + "description" : "Use this option if the slide serial number and area were entered incorrectly on the CytAssist \ninstrument and the correct values are unknown. Not compatible with --slide, --area, or \n--slide-file options\n", + "required" : false, + "choices" : [ + "visium-1", + "visium-2", + "visium-2-large", + "visium-hd" + ], + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "file", + "name" : "--slidefile", + "description" : "Slide design file for offline use", + "example" : [ + "slide_design.gpr" + ], + "must_exist" : true, + "create_parent" : true, + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "boolean_true", + "name" : "--override_id", + "description" : "Overrides the slide serial number and capture area provided in the Cytassist image metadata", + "direction" : "input" + } + ] + }, + { + "name" : "SpaceRanger arguments", + "arguments" : [ + { + "type" : "boolean", + "name" : "--create_bam", + "description" : "Enable or disable BAM file generation", + "default" : [ + true + ], + "required" : true, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "boolean_true", + "name" : "--nosecondary", + "description" : "Disable secondary analysis (e.g., clustering)", + "direction" : "input" + }, + { + "type" : "integer", + "name" : "--r1_length", + "description" : "Hard trim the input Read 1 to this length before analysis", + "required" : false, + "min" : 1, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "integer", + "name" : "--r2_length", + "description" : "Hard trim the input Read 2 to this length before analysis", + "required" : false, + "min" : 1, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "boolean", + "name" : "--filter_probes", + "description" : "Whether to filter the probe set using the \\"included\\" column", + "default" : [ + true + ], + "required" : false, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + }, + { + "type" : "integer", + "name" : "--custom_bin_size", + "description" : "Bin Visium HD data to specified size in microns (4-100, even values only) in addition to the standard binning size (2 µm, 8 µm, 16 µm)", + "required" : false, + "min" : 4, + "max" : 100, + "direction" : "input", + "multiple" : false, + "multiple_sep" : ";" + } + ] + } + ], + "resources" : [ + { + "type" : "nextflow_script", + "path" : "main.nf", + "is_executable" : true, + "entrypoint" : "run_wf" + }, + { + "type" : "file", + "path" : "/src/workflows/utils/" + }, + { + "type" : "file", + "path" : "/src/workflows/utils/labels.config", + "dest" : "nextflow_labels.config" + } + ], + "description" : "A pipeline for running SpaceRanger mapping.", + "test_resources" : [ + { + "type" : "nextflow_script", + "path" : "test.nf", + "is_executable" : true, + "entrypoint" : "test_wf" + }, + { + "type" : "file", + "path" : "/resources_test/visium" + }, + { + "type" : "file", + "path" : "/resources_test/GRCh38" + } + ], + "info" : { + "name" : "SpaceRanger mapping", + "test_dependencies" : [ + { + "name" : "spaceranger_mapping_test", + "namespace" : "test_workflows/ingestion" + } + ] + }, + "status" : "enabled", + "scope" : { + "image" : "public", + "target" : "public" + }, + "dependencies" : [ + { + "name" : "mapping/spaceranger_count", + "repository" : { + "type" : "local" + } + }, + { + "name" : "convert/from_spaceranger_to_h5mu", + "repository" : { + "type" : "local" + } + } + ], + "repositories" : [ + { + "type" : "vsh", + "name" : "openpipeline", + "repo" : "openpipeline", + "tag" : "v4.0.0" + } + ], + "links" : { + "repository" : "https://github.com/openpipelines-bio/openpipeline_spatial", + "docker_registry" : "ghcr.io" + }, + "runners" : [ + { + "type" : "nextflow", + "id" : "nextflow", + "directives" : { + "tag" : "$id" + }, + "auto" : { + "simplifyInput" : true, + "simplifyOutput" : false, + "transcript" : false, + "publish" : false + }, + "config" : { + "labels" : { + "mem1gb" : "memory = 1000000000.B", + "mem2gb" : "memory = 2000000000.B", + "mem5gb" : "memory = 5000000000.B", + "mem10gb" : "memory = 10000000000.B", + "mem20gb" : "memory = 20000000000.B", + "mem50gb" : "memory = 50000000000.B", + "mem100gb" : "memory = 100000000000.B", + "mem200gb" : "memory = 200000000000.B", + "mem500gb" : "memory = 500000000000.B", + "mem1tb" : "memory = 1000000000000.B", + "mem2tb" : "memory = 2000000000000.B", + "mem5tb" : "memory = 5000000000000.B", + "mem10tb" : "memory = 10000000000000.B", + "mem20tb" : "memory = 20000000000000.B", + "mem50tb" : "memory = 50000000000000.B", + "mem100tb" : "memory = 100000000000000.B", + "mem200tb" : "memory = 200000000000000.B", + "mem500tb" : "memory = 500000000000000.B", + "mem1gib" : "memory = 1073741824.B", + "mem2gib" : "memory = 2147483648.B", + "mem4gib" : "memory = 4294967296.B", + "mem8gib" : "memory = 8589934592.B", + "mem16gib" : "memory = 17179869184.B", + "mem32gib" : "memory = 34359738368.B", + "mem64gib" : "memory = 68719476736.B", + "mem128gib" : "memory = 137438953472.B", + "mem256gib" : "memory = 274877906944.B", + "mem512gib" : "memory = 549755813888.B", + "mem1tib" : "memory = 1099511627776.B", + "mem2tib" : "memory = 2199023255552.B", + "mem4tib" : "memory = 4398046511104.B", + "mem8tib" : "memory = 8796093022208.B", + "mem16tib" : "memory = 17592186044416.B", + "mem32tib" : "memory = 35184372088832.B", + "mem64tib" : "memory = 70368744177664.B", + "mem128tib" : "memory = 140737488355328.B", + "mem256tib" : "memory = 281474976710656.B", + "mem512tib" : "memory = 562949953421312.B", + "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" + }, + "script" : [ + "includeConfig(\\"nextflow_labels.config\\")" + ] + }, + "debug" : false, + "container" : "docker" + } + ], + "engines" : [ + { + "type" : "native", + "id" : "native" + } + ], + "build_info" : { + "config" : "/workdir/root/repo/src/workflows/ingestion/spaceranger_mapping/config.vsh.yaml", + "runner" : "nextflow", + "engine" : "native", + "output" : "/workdir/root/repo/target/nextflow/workflows/ingestion/spaceranger_mapping", + "viash_version" : "0.9.4", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", + "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" + }, + "package_config" : { + "name" : "openpipeline_spatial", + "version" : "niche-compass", + "info" : { + "test_resources" : [ + { + "type" : "s3", + "path" : "s3://openpipelines-bio/openpipeline_spatial/resources_test", + "dest" : "resources_test" + } + ] + }, + "repositories" : [ + { + "type" : "vsh", + "name" : "openpipeline", + "repo" : "openpipeline", + "tag" : "v4.0.0" + } + ], + "viash_version" : "0.9.4", + "source" : "/workdir/root/repo/src", + "target" : "/workdir/root/repo/target", + "config_mods" : [ + ".resources += {path: '/src/workflows/utils/labels.config', dest: 'nextflow_labels.config'}\n.runners[.type == 'nextflow'].config.script := 'includeConfig(\\"nextflow_labels.config\\")'", + ".engines += { type: \\"native\\" }", + ".engines[.type == 'docker'].target_registry := 'images.viash-hub.com'", + ".engines[.type == 'docker'].target_tag := 'niche-compass'" + ], + "organization" : "vsh", + "links" : { + "repository" : "https://github.com/openpipelines-bio/openpipeline_spatial", + "docker_registry" : "ghcr.io" + } + } +}''')) +] + +// resolve dependencies dependencies (if any) +meta["root_dir"] = getRootDir() +include { spaceranger_count } from "${meta.resources_dir}/../../../../nextflow/mapping/spaceranger_count/main.nf" +include { from_spaceranger_to_h5mu } from "${meta.resources_dir}/../../../../nextflow/convert/from_spaceranger_to_h5mu/main.nf" + +// inner workflow +// user-provided Nextflow code +workflow run_wf { + take: + input_ch + + main: + output_ch = input_ch + | spaceranger_count.run( + fromState: { id, state -> [ + "input": state.input, + "gex_reference": state.gex_reference, + "probe_set": state.probe_set, + "cytaimage": state.cytaimage, + "image": state.image, + "slide": state.slide, + "area": state.area, + "unkown_slide": state.unkown_slide, + "slidefile": state.slidefile, + "override_id": state.override_id, + "darkimage": state.darkimage, + "colorizedimage": state.colorizedimage, + "dapi_index": state.dapi_index, + "image_scale": state.image_scale, + "reorient_images": state.reorient_images, + "create_bam": state.create_bam, + "nosecondary": state.nosecondary, + "r1_length": state.r1_length, + "r2_length": state.r2_length, + "filter_probes": state.filter_probes, + "custom_bin_size": state.custom_bin_size, + "output": state.output_raw, + ]}, + toState: [ + "input": "output", + "output_raw": "output" + ] + ) + // convert to h5mu + | from_spaceranger_to_h5mu.run( + fromState: {id, state -> + [ + "input": state.input, + "output_compression": state.output_compression, + "output": state.output_h5mu, + "uns_metrics": state.uns_metrics, + "uns_probe_set": state.uns_probe_set, + "obsm_coordinates": state.obsm_coordinates, + "output_type": state.output_type, + "output_compression": state.output_compression, + ] + }, + toState: ["output_h5mu": "output"] + ) + | setState(["output_raw", "output_h5mu"]) + + 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.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.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.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/workflows/ingestion/spaceranger_mapping/nextflow.config b/target/nextflow/workflows/ingestion/spaceranger_mapping/nextflow.config new file mode 100644 index 0000000..9530017 --- /dev/null +++ b/target/nextflow/workflows/ingestion/spaceranger_mapping/nextflow.config @@ -0,0 +1,126 @@ +manifest { + name = 'workflows/ingestion/spaceranger_mapping' + mainScript = 'main.nf' + nextflowVersion = '!>=20.12.1-edge' + version = 'niche-compass' + description = 'A pipeline for running SpaceRanger mapping.' + author = 'Dorien Roosen, Weiwei Schultz' +} + +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 = 1000000000.B } + withLabel: mem2gb { memory = 2000000000.B } + withLabel: mem5gb { memory = 5000000000.B } + withLabel: mem10gb { memory = 10000000000.B } + withLabel: mem20gb { memory = 20000000000.B } + withLabel: mem50gb { memory = 50000000000.B } + withLabel: mem100gb { memory = 100000000000.B } + withLabel: mem200gb { memory = 200000000000.B } + withLabel: mem500gb { memory = 500000000000.B } + withLabel: mem1tb { memory = 1000000000000.B } + withLabel: mem2tb { memory = 2000000000000.B } + withLabel: mem5tb { memory = 5000000000000.B } + withLabel: mem10tb { memory = 10000000000000.B } + withLabel: mem20tb { memory = 20000000000000.B } + withLabel: mem50tb { memory = 50000000000000.B } + withLabel: mem100tb { memory = 100000000000000.B } + withLabel: mem200tb { memory = 200000000000000.B } + withLabel: mem500tb { memory = 500000000000000.B } + withLabel: mem1gib { memory = 1073741824.B } + withLabel: mem2gib { memory = 2147483648.B } + withLabel: mem4gib { memory = 4294967296.B } + withLabel: mem8gib { memory = 8589934592.B } + withLabel: mem16gib { memory = 17179869184.B } + withLabel: mem32gib { memory = 34359738368.B } + withLabel: mem64gib { memory = 68719476736.B } + withLabel: mem128gib { memory = 137438953472.B } + withLabel: mem256gib { memory = 274877906944.B } + withLabel: mem512gib { memory = 549755813888.B } + withLabel: mem1tib { memory = 1099511627776.B } + withLabel: mem2tib { memory = 2199023255552.B } + withLabel: mem4tib { memory = 4398046511104.B } + withLabel: mem8tib { memory = 8796093022208.B } + withLabel: mem16tib { memory = 17592186044416.B } + withLabel: mem32tib { memory = 35184372088832.B } + withLabel: mem64tib { memory = 70368744177664.B } + withLabel: mem128tib { memory = 140737488355328.B } + withLabel: mem256tib { memory = 281474976710656.B } + withLabel: mem512tib { memory = 562949953421312.B } + 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 } +} + +includeConfig("nextflow_labels.config") diff --git a/target/nextflow/workflows/ingestion/spaceranger_mapping/nextflow_labels.config b/target/nextflow/workflows/ingestion/spaceranger_mapping/nextflow_labels.config new file mode 100644 index 0000000..541aaad --- /dev/null +++ b/target/nextflow/workflows/ingestion/spaceranger_mapping/nextflow_labels.config @@ -0,0 +1,68 @@ +process { + // Default resources for components that hardly do any processing + memory = { 2.GB * task.attempt } + cpus = 1 + + // Retry for exit codes that have something to do with memory issues + errorStrategy = { task.exitStatus in 137..140 ? 'retry' : 'terminate' } + maxRetries = 3 + maxMemory = null + + // CPU resources + withLabel: singlecpu { cpus = 1 } + withLabel: lowcpu { cpus = 4 } + withLabel: midcpu { cpus = 10 } + withLabel: highcpu { cpus = 20 } + + // Memory resources + withLabel: lowmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: midmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: highmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: veryhighmem { memory = { get_memory( 75.GB * task.attempt ) } } + + // Disk space + // Nextflow apparently can't handle empty directives, i.e. + // withLabel: lowdisk {} + // so for that reason we have to add a dummy directive + withLabel: lowdisk { + dummyDirective = "dummyValue" + } + withLabel: middisk { + dummyDirective = "dummyValue" + } + withLabel: highdisk { + dummyDirective = "dummyValue" + } + withLabel: veryhighdisk { + dummyDirective = "dummyValue" + } + // NOTE: The above labels intentionally do not have an effect by default. + // The user should set the disk space requirements by adding the following + // to the compute environment: + // + // withLabel: lowdisk { disk = { 20.GB * task.attempt } } + // withLabel: middisk { disk = { 100.GB * task.attempt } } + // withLabel: highdisk { disk = { 200.GB * task.attempt } } + // withLabel: veryhighdisk { disk = { 500.GB * task.attempt } } +} + +def get_memory(to_compare) { + if (!process.containsKey("maxMemory") || !process.maxMemory) { + return to_compare + } + + try { + if (process.containsKey("maxRetries") && process.maxRetries && task.attempt == (process.maxRetries as int)) { + return process.maxMemory + } + else if (to_compare.compareTo(process.maxMemory as nextflow.util.MemoryUnit) == 1) { + return max_memory as nextflow.util.MemoryUnit + } + else { + return to_compare + } + } catch (all) { + println "Error processing memory resources. Please check that process.maxMemory '${process.maxMemory}' and process.maxRetries '${process.maxRetries}' are valid!" + System.exit(1) + } +} diff --git a/target/nextflow/workflows/ingestion/spaceranger_mapping/nextflow_schema.json b/target/nextflow/workflows/ingestion/spaceranger_mapping/nextflow_schema.json new file mode 100644 index 0000000..c809a18 --- /dev/null +++ b/target/nextflow/workflows/ingestion/spaceranger_mapping/nextflow_schema.json @@ -0,0 +1,261 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "spaceranger_mapping", + "description": "A pipeline for running SpaceRanger mapping.", + "type": "object", + "$defs": { + "inputs": { + "title": "Inputs", + "type": "object", + "description": "No description", + "properties": { + "id": { + "type": "string", + "description": "ID of the sample.", + "help_text": "Type: `string`, multiple: `False`, required, example: `\"foo\"`. " + }, + "input": { + "type": "array", + "items": { + "type": "string" + }, + "format": "path", + "exists": true, + "description": "The fastq.gz files to align", + "help_text": "Type: `file`, multiple: `True`, required, direction: `input`, example: `[\"sample_S1_L001_R1_001.fastq.gz\";\"sample_S1_L001_R2_001.fastq.gz\"]`. " + }, + "gex_reference": { + "type": "string", + "format": "path", + "exists": true, + "description": "Path of folder containing 10x-compatible reference", + "help_text": "Type: `file`, multiple: `False`, required, direction: `input`, example: `\"/path/to/refdata-gex-GRCh38-2020-A\"`. " + }, + "probe_set": { + "type": "string", + "format": "path", + "exists": true, + "description": "CSV file specifying the probe set used", + "help_text": "Type: `file`, multiple: `False`, required, direction: `input`, example: `\"Visium_Human_Transcriptome_Probe_Set_v2.0_GRCh38-2020-A.csv\"`. " + }, + "cytaimage": { + "type": "string", + "format": "path", + "description": "Brightfield image generated by the CytAssist instrument", + "help_text": "Type: `file`, multiple: `False`, direction: `input`, example: `\"cyta_image.tif\"`. " + }, + "image": { + "type": "string", + "format": "path", + "description": "H&E or fluorescence microscope image in TIFF or JPG format", + "help_text": "Type: `file`, multiple: `False`, direction: `input`, example: `\"brightfield.tif\"`. " + } + } + }, + "outputs": { + "title": "Outputs", + "type": "object", + "description": "No description", + "properties": { + "output_raw": { + "type": "string", + "format": "path", + "description": "Location where the output folder from Cell Ranger will be stored.", + "help_text": "Type: `file`, multiple: `False`, required, default: `\"$id.$key.output_raw\"`, direction: `output`, example: `\"output_dir\"`. ", + "default": "$id.$key.output_raw" + }, + "output_h5mu": { + "type": "string", + "format": "path", + "description": "The output from Cell Ranger, converted to h5mu.", + "help_text": "Type: `file`, multiple: `False`, required, default: `\"$id.$key.output_h5mu.h5mu\"`, direction: `output`, example: `\"output.h5mu\"`. ", + "default": "$id.$key.output_h5mu.h5mu" + }, + "output_type": { + "type": "string", + "description": "Which Cell Ranger output to use for converting to h5mu.", + "help_text": "Type: `string`, multiple: `False`, default: `\"raw\"`, choices: ``raw`, `filtered``. ", + "enum": [ + "raw", + "filtered" + ], + "default": "raw" + }, + "uns_metrics": { + "type": "string", + "description": "Name of the .uns slot under which to QC metrics (if any).", + "help_text": "Type: `string`, multiple: `False`, default: `\"metrics_summary\"`. ", + "default": "metrics_summary" + }, + "uns_probe_set": { + "type": "string", + "description": "Name of the .uns slot under which to store probe set information (if any).", + "help_text": "Type: `string`, multiple: `False`, default: `\"probe_set\"`. ", + "default": "probe_set" + }, + "obsm_coordinates": { + "type": "string", + "description": "Name of the .obsm slot under which to store the cell centroid coordinates.", + "help_text": "Type: `string`, multiple: `False`, default: `\"spatial\"`. ", + "default": "spatial" + }, + "output_compression": { + "type": "string", + "description": "Compression to use when writing the h5mu file.", + "help_text": "Type: `string`, multiple: `False`, choices: ``gzip`, `lzf``. ", + "enum": [ + "gzip", + "lzf" + ] + } + } + }, + "image options": { + "title": "Image Options", + "type": "object", + "description": "No description", + "properties": { + "darkimage": { + "type": "string", + "format": "path", + "description": "Multi-channel, dark-background fluorescence image", + "help_text": "Type: `file`, multiple: `False`, direction: `input`, example: `\"fluorescence.tif\"`. " + }, + "colorizedimage": { + "type": "string", + "format": "path", + "description": "Color image representing pre-colored dark-background fluorescence images", + "help_text": "Type: `file`, multiple: `False`, direction: `input`, example: `\"colored_fluorescence.tif\"`. " + }, + "dapi_index": { + "type": "integer", + "description": "Index of DAPI channel (1-indexed) of fluorescence image", + "help_text": "Type: `integer`, multiple: `False`, example: `1`. " + }, + "image_scale": { + "type": "number", + "description": "Microns per microscope image pixel", + "help_text": "Type: `double`, multiple: `False`, example: `0.65`. " + }, + "reorient_images": { + "type": "boolean", + "description": "Whether to rotate and mirror image to align fiducial pattern", + "help_text": "Type: `boolean`, multiple: `False`, default: `true`. ", + "default": true + } + } + }, + "slide information": { + "title": "Slide Information", + "type": "object", + "description": "No description", + "properties": { + "slide": { + "type": "string", + "description": "Visium slide serial number (e.g., 'V10J25-015')", + "help_text": "Type: `string`, multiple: `False`, example: `\"V10J25-015\"`. " + }, + "area": { + "type": "string", + "description": "Visium capture area identifier (e.g., 'A1')", + "help_text": "Type: `string`, multiple: `False`, example: `\"A1\"`. " + }, + "unknown_slide": { + "type": "string", + "description": "Use this option if the slide serial number and area were entered incorrectly on the CytAssist \ninstrument and the correct values are unknown", + "help_text": "Type: `string`, multiple: `False`, choices: ``visium-1`, `visium-2`, `visium-2-large`, `visium-hd``. ", + "enum": [ + "visium-1", + "visium-2", + "visium-2-large", + "visium-hd" + ] + }, + "slidefile": { + "type": "string", + "format": "path", + "description": "Slide design file for offline use", + "help_text": "Type: `file`, multiple: `False`, direction: `input`, example: `\"slide_design.gpr\"`. " + }, + "override_id": { + "type": "boolean", + "description": "Overrides the slide serial number and capture area provided in the Cytassist image metadata", + "help_text": "Type: `boolean_true`, multiple: `False`, default: `false`. ", + "default": false + } + } + }, + "spaceranger arguments": { + "title": "SpaceRanger arguments", + "type": "object", + "description": "No description", + "properties": { + "create_bam": { + "type": "boolean", + "description": "Enable or disable BAM file generation", + "help_text": "Type: `boolean`, multiple: `False`, required, default: `true`. ", + "default": true + }, + "nosecondary": { + "type": "boolean", + "description": "Disable secondary analysis (e.g., clustering)", + "help_text": "Type: `boolean_true`, multiple: `False`, default: `false`. ", + "default": false + }, + "r1_length": { + "type": "integer", + "description": "Hard trim the input Read 1 to this length before analysis", + "help_text": "Type: `integer`, multiple: `False`. " + }, + "r2_length": { + "type": "integer", + "description": "Hard trim the input Read 2 to this length before analysis", + "help_text": "Type: `integer`, multiple: `False`. " + }, + "filter_probes": { + "type": "boolean", + "description": "Whether to filter the probe set using the \"included\" column", + "help_text": "Type: `boolean`, multiple: `False`, default: `true`. ", + "default": true + }, + "custom_bin_size": { + "type": "integer", + "description": "Bin Visium HD data to specified size in microns (4-100, even values only) in addition to the standard binning size (2 µm, 8 µm, 16 µm)", + "help_text": "Type: `integer`, multiple: `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.", + "help_text": "Type: `string`, multiple: `False`, required, example: `\"output/\"`. " + } + } + } + }, + "allOf": [ + { + "$ref": "#/$defs/inputs" + }, + { + "$ref": "#/$defs/outputs" + }, + { + "$ref": "#/$defs/image options" + }, + { + "$ref": "#/$defs/slide information" + }, + { + "$ref": "#/$defs/spaceranger arguments" + }, + { + "$ref": "#/$defs/nextflow input-output arguments" + } + ] +} diff --git a/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/integration_tests.config b/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/integration_tests.config new file mode 100644 index 0000000..59d5b09 --- /dev/null +++ b/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/integration_tests.config @@ -0,0 +1,36 @@ +profiles { + + // detect tempdir + tempDir = java.nio.file.Paths.get( + System.getenv('NXF_TEMP') ?: + System.getenv('VIASH_TEMP') ?: + System.getenv('TEMPDIR') ?: + System.getenv('TMPDIR') ?: + '/tmp' + ).toAbsolutePath() + + mount_temp { + docker.temp = tempDir + podman.temp = tempDir + charliecloud.temp = tempDir + } + + no_publish { + process { + withName: '.*' { + publishDir = [ + enabled: false + ] + } + } + } + + docker { + docker.enabled = true + // docker.userEmulation = true + singularity.enabled = false + podman.enabled = false + shifter.enabled = false + charliecloud.enabled = false + } +} \ No newline at end of file diff --git a/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/labels.config b/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/labels.config new file mode 100644 index 0000000..541aaad --- /dev/null +++ b/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/labels.config @@ -0,0 +1,68 @@ +process { + // Default resources for components that hardly do any processing + memory = { 2.GB * task.attempt } + cpus = 1 + + // Retry for exit codes that have something to do with memory issues + errorStrategy = { task.exitStatus in 137..140 ? 'retry' : 'terminate' } + maxRetries = 3 + maxMemory = null + + // CPU resources + withLabel: singlecpu { cpus = 1 } + withLabel: lowcpu { cpus = 4 } + withLabel: midcpu { cpus = 10 } + withLabel: highcpu { cpus = 20 } + + // Memory resources + withLabel: lowmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: midmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: highmem { memory = { get_memory( 50.GB * task.attempt ) } } + withLabel: veryhighmem { memory = { get_memory( 75.GB * task.attempt ) } } + + // Disk space + // Nextflow apparently can't handle empty directives, i.e. + // withLabel: lowdisk {} + // so for that reason we have to add a dummy directive + withLabel: lowdisk { + dummyDirective = "dummyValue" + } + withLabel: middisk { + dummyDirective = "dummyValue" + } + withLabel: highdisk { + dummyDirective = "dummyValue" + } + withLabel: veryhighdisk { + dummyDirective = "dummyValue" + } + // NOTE: The above labels intentionally do not have an effect by default. + // The user should set the disk space requirements by adding the following + // to the compute environment: + // + // withLabel: lowdisk { disk = { 20.GB * task.attempt } } + // withLabel: middisk { disk = { 100.GB * task.attempt } } + // withLabel: highdisk { disk = { 200.GB * task.attempt } } + // withLabel: veryhighdisk { disk = { 500.GB * task.attempt } } +} + +def get_memory(to_compare) { + if (!process.containsKey("maxMemory") || !process.maxMemory) { + return to_compare + } + + try { + if (process.containsKey("maxRetries") && process.maxRetries && task.attempt == (process.maxRetries as int)) { + return process.maxMemory + } + else if (to_compare.compareTo(process.maxMemory as nextflow.util.MemoryUnit) == 1) { + return max_memory as nextflow.util.MemoryUnit + } + else { + return to_compare + } + } catch (all) { + println "Error processing memory resources. Please check that process.maxMemory '${process.maxMemory}' and process.maxRetries '${process.maxRetries}' are valid!" + System.exit(1) + } +} diff --git a/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/labels_ci.config b/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/labels_ci.config new file mode 100644 index 0000000..7a1c7d3 --- /dev/null +++ b/target/nextflow/workflows/ingestion/spaceranger_mapping/utils/labels_ci.config @@ -0,0 +1,105 @@ +process { + withLabel: lowmem { memory = 13.Gb } + withLabel: lowcpu { cpus = 4 } + withLabel: midmem { memory = 13.Gb } + withLabel: midcpu { cpus = 4 } + withLabel: highmem { memory = 13.Gb } + withLabel: highcpu { cpus = 4 } + withLabel: veryhighmem { memory = 13.Gb } + withLabel: lowdisk { + disk = {process.disk ? process.disk : null} + } + withLabel: middisk { + disk = {process.disk ? process.disk : null} + } + withLabel: highdisk { + disk = {process.disk ? process.disk : null} + } + withLabel: veryhighdisk { + disk = {process.disk ? process.disk : null} + } +} + +env.NUMBA_CACHE_DIR = '/tmp' + +trace { + enabled = true + overwrite = true +} +dag { + overwrite = true +} + +process.maxForks = 1 + +profiles { + // detect tempdir + tempDir = java.nio.file.Paths.get( + System.getenv('NXF_TEMP') ?: + System.getenv('VIASH_TEMP') ?: + System.getenv('TEMPDIR') ?: + System.getenv('TMPDIR') ?: + '/tmp' + ).toAbsolutePath() + + mount_temp { + docker.temp = tempDir + podman.temp = tempDir + charliecloud.temp = tempDir + } + + no_publish { + process { + withName: '.*' { + publishDir = [ + enabled: false + ] + } + } + } + + docker { + docker.fixOwnership = true + docker.enabled = true + singularity.enabled = false + podman.enabled = false + shifter.enabled = false + charliecloud.enabled = false + } + + local { + // This config is for local processing. + process { + maxMemory = 25.GB + withLabel: verylowcpu { cpus = 2 } + withLabel: lowcpu { cpus = 4 } + withLabel: midcpu { cpus = 6 } + withLabel: highcpu { cpus = 12 } + + withLabel: lowmem { memory = { get_memory( 8.GB * task.attempt ) } } + withLabel: midmem { memory = { get_memory( 12.GB * task.attempt ) } } + withLabel: highmem { memory = { get_memory( 20.GB * task.attempt ) } } + } + } +} + +def get_memory(to_compare) { + if (!process.containsKey("maxMemory") || !process.maxMemory) { + return to_compare + } + + try { + if (process.containsKey("maxRetries") && process.maxRetries && task.attempt == (process.maxRetries as int)) { + return process.maxMemory + } + else if (to_compare.compareTo(process.maxMemory as nextflow.util.MemoryUnit) == 1) { + return max_memory as nextflow.util.MemoryUnit + } + else { + return to_compare + } + } catch (all) { + println "Error processing memory resources. Please check that process.maxMemory '${process.maxMemory}' and process.maxRetries '${process.maxRetries}' are valid!" + System.exit(1) + } +} diff --git a/target/nextflow/workflows/multiomics/spatial_process_samples/.config.vsh.yaml b/target/nextflow/workflows/multiomics/spatial_process_samples/.config.vsh.yaml index 6c2175e..9cbd8fb 100644 --- a/target/nextflow/workflows/multiomics/spatial_process_samples/.config.vsh.yaml +++ b/target/nextflow/workflows/multiomics/spatial_process_samples/.config.vsh.yaml @@ -557,12 +557,12 @@ dependencies: repository: type: "vsh" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -640,10 +640,10 @@ build_info: output: "target/nextflow/workflows/multiomics/spatial_process_samples" executable: "target/nextflow/workflows/multiomics/spatial_process_samples/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" dependencies: - - "target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples" + - "target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples" package_config: name: "openpipeline_spatial" version: "niche-compass" @@ -656,7 +656,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/workflows/multiomics/spatial_process_samples/main.nf b/target/nextflow/workflows/multiomics/spatial_process_samples/main.nf index 2c61f9d..3503d8f 100644 --- a/target/nextflow/workflows/multiomics/spatial_process_samples/main.nf +++ b/target/nextflow/workflows/multiomics/spatial_process_samples/main.nf @@ -3707,7 +3707,7 @@ meta = [ "repository" : { "type" : "vsh", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } } ], @@ -3716,7 +3716,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3807,7 +3807,7 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/multiomics/spatial_process_samples", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3827,7 +3827,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", @@ -3850,7 +3850,7 @@ meta = [ // resolve dependencies dependencies (if any) meta["root_dir"] = getRootDir() -include { process_samples as spatial_sample_processing_viashalias } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/process_samples/main.nf" +include { process_samples as spatial_sample_processing_viashalias } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/process_samples/main.nf" spatial_sample_processing = spatial_sample_processing_viashalias.run(key: "spatial_sample_processing") // inner workflow diff --git a/target/nextflow/workflows/niche/nichecompass_leiden/.config.vsh.yaml b/target/nextflow/workflows/niche/nichecompass_leiden/.config.vsh.yaml index 8ab1503..f958830 100644 --- a/target/nextflow/workflows/niche/nichecompass_leiden/.config.vsh.yaml +++ b/target/nextflow/workflows/niche/nichecompass_leiden/.config.vsh.yaml @@ -696,7 +696,9 @@ scope: dependencies: - name: "dataflow/concatenate_h5mu" repository: - type: "local" + type: "vsh" + repo: "openpipeline" + tag: "v4.0.0" - name: "neighbors/spatial_neighborhood_graph" repository: type: "local" @@ -707,17 +709,17 @@ dependencies: repository: type: "vsh" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" - name: "workflows/multiomics/neighbors_leiden_umap" repository: type: "vsh" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -795,14 +797,14 @@ build_info: output: "target/nextflow/workflows/niche/nichecompass_leiden" executable: "target/nextflow/workflows/niche/nichecompass_leiden/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" dependencies: - - "target/nextflow/dataflow/concatenate_h5mu" + - "target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu" - "target/nextflow/neighbors/spatial_neighborhood_graph" - "target/nextflow/nichecompass/nichecompass" - - "target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu" - - "target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap" + - "target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu" + - "target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap" package_config: name: "openpipeline_spatial" version: "niche-compass" @@ -815,7 +817,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/workflows/niche/nichecompass_leiden/main.nf b/target/nextflow/workflows/niche/nichecompass_leiden/main.nf index e330b73..a3fbf9e 100644 --- a/target/nextflow/workflows/niche/nichecompass_leiden/main.nf +++ b/target/nextflow/workflows/niche/nichecompass_leiden/main.nf @@ -3820,7 +3820,9 @@ meta = [ { "name" : "dataflow/concatenate_h5mu", "repository" : { - "type" : "local" + "type" : "vsh", + "repo" : "openpipeline", + "tag" : "v4.0.0" } }, { @@ -3840,7 +3842,7 @@ meta = [ "repository" : { "type" : "vsh", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } }, { @@ -3848,7 +3850,7 @@ meta = [ "repository" : { "type" : "vsh", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } } ], @@ -3857,7 +3859,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3948,7 +3950,7 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/niche/nichecompass_leiden", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3968,7 +3970,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", @@ -3991,11 +3993,11 @@ meta = [ // resolve dependencies dependencies (if any) meta["root_dir"] = getRootDir() -include { concatenate_h5mu } from "${meta.resources_dir}/../../../../nextflow/dataflow/concatenate_h5mu/main.nf" +include { concatenate_h5mu } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/concatenate_h5mu/main.nf" include { spatial_neighborhood_graph } from "${meta.resources_dir}/../../../../nextflow/neighbors/spatial_neighborhood_graph/main.nf" include { nichecompass } from "${meta.resources_dir}/../../../../nextflow/nichecompass/nichecompass/main.nf" -include { split_h5mu } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/dataflow/split_h5mu/main.nf" -include { neighbors_leiden_umap } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf" +include { split_h5mu } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/dataflow/split_h5mu/main.nf" +include { neighbors_leiden_umap } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/multiomics/neighbors_leiden_umap/main.nf" // inner workflow // user-provided Nextflow code diff --git a/target/nextflow/workflows/qc/spatial_qc/.config.vsh.yaml b/target/nextflow/workflows/qc/spatial_qc/.config.vsh.yaml index 693c479..6a45277 100644 --- a/target/nextflow/workflows/qc/spatial_qc/.config.vsh.yaml +++ b/target/nextflow/workflows/qc/spatial_qc/.config.vsh.yaml @@ -304,12 +304,12 @@ dependencies: repository: type: "vsh" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" repositories: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" links: repository: "https://github.com/openpipelines-bio/openpipeline_spatial" docker_registry: "ghcr.io" @@ -387,10 +387,10 @@ build_info: output: "target/nextflow/workflows/qc/spatial_qc" executable: "target/nextflow/workflows/qc/spatial_qc/main.nf" viash_version: "0.9.4" - git_commit: "f91eceb7cf408169b2847c359c6e2acd77856ff7" + git_commit: "a4d81924a673566026c204c55add247504ef1c56" git_remote: "https://github.com/openpipelines-bio/openpipeline_spatial" dependencies: - - "target/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc" + - "target/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc" package_config: name: "openpipeline_spatial" version: "niche-compass" @@ -403,7 +403,7 @@ package_config: - type: "vsh" name: "openpipeline" repo: "openpipeline" - tag: "v3.0.0" + tag: "v4.0.0" viash_version: "0.9.4" source: "src" target: "target" diff --git a/target/nextflow/workflows/qc/spatial_qc/main.nf b/target/nextflow/workflows/qc/spatial_qc/main.nf index 5792ed1..4375273 100644 --- a/target/nextflow/workflows/qc/spatial_qc/main.nf +++ b/target/nextflow/workflows/qc/spatial_qc/main.nf @@ -3405,7 +3405,7 @@ meta = [ "repository" : { "type" : "vsh", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } } ], @@ -3414,7 +3414,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "links" : { @@ -3505,7 +3505,7 @@ meta = [ "engine" : "native", "output" : "/workdir/root/repo/target/nextflow/workflows/qc/spatial_qc", "viash_version" : "0.9.4", - "git_commit" : "f91eceb7cf408169b2847c359c6e2acd77856ff7", + "git_commit" : "a4d81924a673566026c204c55add247504ef1c56", "git_remote" : "https://github.com/openpipelines-bio/openpipeline_spatial" }, "package_config" : { @@ -3525,7 +3525,7 @@ meta = [ "type" : "vsh", "name" : "openpipeline", "repo" : "openpipeline", - "tag" : "v3.0.0" + "tag" : "v4.0.0" } ], "viash_version" : "0.9.4", @@ -3548,7 +3548,7 @@ meta = [ // resolve dependencies dependencies (if any) meta["root_dir"] = getRootDir() -include { qc as spatial_qc_workflow_viashalias } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v3.0.0/nextflow/workflows/qc/qc/main.nf" +include { qc as spatial_qc_workflow_viashalias } from "${meta.root_dir}/dependencies/vsh/vsh/openpipeline/v4.0.0/nextflow/workflows/qc/qc/main.nf" spatial_qc_workflow = spatial_qc_workflow_viashalias.run(key: "spatial_qc_workflow") // inner workflow