diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index ea27a58..b290e09 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -2,6 +2,7 @@ "name": "nfcore", "image": "nfcore/gitpod:latest", "remoteUser": "gitpod", + "runArgs": ["--privileged"], // Configure tool-specific properties. "customizations": { @@ -9,15 +10,7 @@ "vscode": { // Set *default* container specific settings.json values on container create. "settings": { - "python.defaultInterpreterPath": "/opt/conda/bin/python", - "python.linting.enabled": true, - "python.linting.pylintEnabled": true, - "python.formatting.autopep8Path": "/opt/conda/bin/autopep8", - "python.formatting.yapfPath": "/opt/conda/bin/yapf", - "python.linting.flake8Path": "/opt/conda/bin/flake8", - "python.linting.pycodestylePath": "/opt/conda/bin/pycodestyle", - "python.linting.pydocstylePath": "/opt/conda/bin/pydocstyle", - "python.linting.pylintPath": "/opt/conda/bin/pylint" + "python.defaultInterpreterPath": "/opt/conda/bin/python" }, // Add the IDs of extensions you want installed when the container is created. diff --git a/.editorconfig b/.editorconfig index b6b3190..72dda28 100644 --- a/.editorconfig +++ b/.editorconfig @@ -18,7 +18,16 @@ end_of_line = unset insert_final_newline = unset trim_trailing_whitespace = unset indent_style = unset -indent_size = unset +[/subworkflows/nf-core/**] +charset = unset +end_of_line = unset +insert_final_newline = unset +trim_trailing_whitespace = unset +indent_style = unset [/assets/email*] indent_size = unset + +# ignore python and markdown +[*.{py,md}] +indent_style = unset diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index ea3ff5f..b986314 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -9,6 +9,7 @@ Please use the pre-filled template to save time. However, don't be put off by this template - other more general issues and suggestions are welcome! Contributions to the code are even more welcome ;) +> [!NOTE] > If you need help using or modifying nf-core/epitopeprediction then the best place to ask is on the nf-core Slack [#epitopeprediction](https://nfcore.slack.com/channels/epitopeprediction) channel ([join our Slack here](https://nf-co.re/join/slack)). ## Contribution workflow @@ -18,13 +19,19 @@ If you'd like to write some code for nf-core/epitopeprediction, the standard wor 1. Check that there isn't already an issue about your idea in the [nf-core/epitopeprediction issues](https://github.com/nf-core/epitopeprediction/issues) to avoid duplicating work. If there isn't one already, please create one so that others know you're working on this 2. [Fork](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) the [nf-core/epitopeprediction repository](https://github.com/nf-core/epitopeprediction) to your GitHub account 3. Make the necessary changes / additions within your forked repository following [Pipeline conventions](#pipeline-contribution-conventions) -4. Use `nf-core schema build` and add any new parameters to the pipeline JSON schema (requires [nf-core tools](https://github.com/nf-core/tools) >= 1.10). +4. Use `nf-core pipelines schema build` and add any new parameters to the pipeline JSON schema (requires [nf-core tools](https://github.com/nf-core/tools) >= 1.10). 5. Submit a Pull Request against the `dev` branch and wait for the code to be reviewed and merged If you're not used to this workflow with git, you can start with some [docs from GitHub](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests) or even their [excellent `git` resources](https://try.github.io/). ## Tests +You have the option to test your changes locally by running the pipeline. For receiving warnings about process selectors and other `debug` information, it is recommended to use the debug profile. Execute all the tests with the following command: + +```bash +nf-test test --profile debug,test,docker --verbose +``` + When you create a pull request with changes, [GitHub Actions](https://github.com/features/actions) will run automatic tests. Typically, pull-requests are only fully reviewed when these tests are passing, though of course we can help out before then. @@ -33,7 +40,7 @@ There are typically two types of tests that run: ### Lint tests `nf-core` has a [set of guidelines](https://nf-co.re/developers/guidelines) which all pipelines must adhere to. -To enforce these and ensure that all pipelines stay in sync, we have developed a helper tool which runs checks on the pipeline code. This is in the [nf-core/tools repository](https://github.com/nf-core/tools) and once installed can be run locally with the `nf-core lint ` command. +To enforce these and ensure that all pipelines stay in sync, we have developed a helper tool which runs checks on the pipeline code. This is in the [nf-core/tools repository](https://github.com/nf-core/tools) and once installed can be run locally with the `nf-core pipelines lint ` command. If any failures or warnings are encountered, please follow the listed URL for more documentation. @@ -68,7 +75,7 @@ If you wish to contribute a new step, please use the following coding standards: 2. Write the process block (see below). 3. Define the output channel if needed (see below). 4. Add any new parameters to `nextflow.config` with a default (see below). -5. Add any new parameters to `nextflow_schema.json` with help text (via the `nf-core schema build` tool). +5. Add any new parameters to `nextflow_schema.json` with help text (via the `nf-core pipelines schema build` tool). 6. Add sanity checks and validation for all relevant parameters. 7. Perform local tests to validate that the new code works as expected. 8. If applicable, add a new test command in `.github/workflow/ci.yml`. @@ -79,13 +86,13 @@ If you wish to contribute a new step, please use the following coding standards: Parameters should be initialised / defined with default values in `nextflow.config` under the `params` scope. -Once there, use `nf-core schema build` to add to `nextflow_schema.json`. +Once there, use `nf-core pipelines schema build` to add to `nextflow_schema.json`. ### Default processes resource requirements -Sensible defaults for process resource requirements (CPUs / memory / time) for a process should be defined in `conf/base.config`. These should generally be specified generic with `withLabel:` selectors so they can be shared across multiple processes/steps of the pipeline. A nf-core standard set of labels that should be followed where possible can be seen in the [nf-core pipeline template](https://github.com/nf-core/tools/blob/master/nf_core/pipeline-template/conf/base.config), which has the default process as a single core-process, and then different levels of multi-core configurations for increasingly large memory requirements defined with standardised labels. +Sensible defaults for process resource requirements (CPUs / memory / time) for a process should be defined in `conf/base.config`. These should generally be specified generic with `withLabel:` selectors so they can be shared across multiple processes/steps of the pipeline. A nf-core standard set of labels that should be followed where possible can be seen in the [nf-core pipeline template](https://github.com/nf-core/tools/blob/main/nf_core/pipeline-template/conf/base.config), which has the default process as a single core-process, and then different levels of multi-core configurations for increasingly large memory requirements defined with standardised labels. -The process resources can be passed on to the tool dynamically within the process with the `${task.cpu}` and `${task.memory}` variables in the `script:` block. +The process resources can be passed on to the tool dynamically within the process with the `${task.cpus}` and `${task.memory}` variables in the `script:` block. ### Naming schemes @@ -96,7 +103,7 @@ Please use the following naming schemes, to make it easy to understand what is g ### Nextflow version bumping -If you are using a new feature from core Nextflow, you may bump the minimum required version of nextflow in the pipeline with: `nf-core bump-version --nextflow . [min-nf-version]` +If you are using a new feature from core Nextflow, you may bump the minimum required version of nextflow in the pipeline with: `nf-core pipelines bump-version --nextflow . [min-nf-version]` ### Images and figures diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 5f925ad..eb0a50d 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -17,8 +17,9 @@ Learn more about contributing: [CONTRIBUTING.md](https://github.com/nf-core/epit - [ ] If you've fixed a bug or added code that should be tested, add tests! - [ ] If you've added a new tool - have you followed the pipeline conventions in the [contribution docs](https://github.com/nf-core/epitopeprediction/tree/master/.github/CONTRIBUTING.md) - [ ] If necessary, also make a PR on the nf-core/epitopeprediction _branch_ on the [nf-core/test-datasets](https://github.com/nf-core/test-datasets) repository. -- [ ] Make sure your code lints (`nf-core lint`). +- [ ] Make sure your code lints (`nf-core pipelines lint`). - [ ] Ensure the test suite passes (`nextflow run . -profile test,docker --outdir `). +- [ ] Check for unexpected warnings in debug mode (`nextflow run . -profile debug,test,docker --outdir `). - [ ] Usage Documentation in `docs/usage.md` is updated. - [ ] Output Documentation in `docs/output.md` is updated. - [ ] `CHANGELOG.md` is updated. diff --git a/.github/workflows/awsfulltest.yml b/.github/workflows/awsfulltest.yml index 469824a..59db64d 100644 --- a/.github/workflows/awsfulltest.yml +++ b/.github/workflows/awsfulltest.yml @@ -1,19 +1,36 @@ name: nf-core AWS full size tests -# This workflow is triggered on published releases. +# This workflow is triggered on PRs opened against the master branch. # It can be additionally triggered manually with GitHub actions workflow dispatch button. # It runs the -profile 'test_full' on AWS batch on: - release: - types: [published] + pull_request: + branches: + - master workflow_dispatch: + pull_request_review: + types: [submitted] + jobs: - run-tower: + run-platform: name: Run AWS full tests - if: github.repository == 'nf-core/epitopeprediction' + # run only if the PR is approved by at least 2 reviewers and against the master branch or manually triggered + if: github.repository == 'nf-core/epitopeprediction' && github.event.review.state == 'approved' && github.event.pull_request.base.ref == 'master' || github.event_name == 'workflow_dispatch' runs-on: ubuntu-latest steps: - - name: Launch workflow via tower + - uses: octokit/request-action@v2.x + id: check_approvals + with: + route: GET /repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/reviews + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - id: test_variables + if: github.event_name != 'workflow_dispatch' + run: | + JSON_RESPONSE='${{ steps.check_approvals.outputs.data }}' + CURRENT_APPROVALS_COUNT=$(echo $JSON_RESPONSE | jq -c '[.[] | select(.state | contains("APPROVED")) ] | length') + test $CURRENT_APPROVALS_COUNT -ge 2 || exit 1 # At least 2 approvals are required + - name: Launch workflow via Seqera Platform uses: seqeralabs/action-tower-launch@v2 with: workspace_id: ${{ secrets.TOWER_WORKSPACE_ID }} @@ -28,9 +45,9 @@ jobs: } profiles: test_full - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: - name: Tower debug log file + name: Seqera Platform debug log file path: | - tower_action_*.log - tower_action_*.json + seqera_platform_action_*.log + seqera_platform_action_*.json diff --git a/.github/workflows/awstest.yml b/.github/workflows/awstest.yml index eee9395..91beaea 100644 --- a/.github/workflows/awstest.yml +++ b/.github/workflows/awstest.yml @@ -5,13 +5,13 @@ name: nf-core AWS test on: workflow_dispatch: jobs: - run-tower: + run-platform: name: Run AWS tests if: github.repository == 'nf-core/epitopeprediction' runs-on: ubuntu-latest steps: - # Launch workflow using Tower CLI tool action - - name: Launch workflow via tower + # Launch workflow using Seqera Platform CLI tool action + - name: Launch workflow via Seqera Platform uses: seqeralabs/action-tower-launch@v2 with: workspace_id: ${{ secrets.TOWER_WORKSPACE_ID }} @@ -25,9 +25,9 @@ jobs: } profiles: test - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 with: - name: Tower debug log file + name: Seqera Platform debug log file path: | - tower_action_*.log - tower_action_*.json + seqera_platform_action_*.log + seqera_platform_action_*.json diff --git a/.github/workflows/branch.yml b/.github/workflows/branch.yml index 1abbb9b..a468112 100644 --- a/.github/workflows/branch.yml +++ b/.github/workflows/branch.yml @@ -19,7 +19,7 @@ jobs: # NOTE - this doesn't currently work if the PR is coming from a fork, due to limitations in GitHub actions secrets - name: Post PR comment if: failure() - uses: mshick/add-pr-comment@v1 + uses: mshick/add-pr-comment@b8f338c590a895d50bcbfa6c5859251edc8952fc # v2 with: message: | ## This PR is against the `master` branch :x: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7694cb2..296c816 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,9 +7,12 @@ on: pull_request: release: types: [published] + workflow_dispatch: env: NXF_ANSI_LOG: false + NXF_SINGULARITY_CACHEDIR: ${{ github.workspace }}/.singularity + NXF_SINGULARITY_LIBRARYDIR: ${{ github.workspace }}/.singularity concurrency: group: "${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}" @@ -17,24 +20,66 @@ concurrency: jobs: test: - name: Run pipeline with test data + name: "Run pipeline with test data (${{ matrix.NXF_VER }} | ${{ matrix.test_name }} | ${{ matrix.profile }})" # Only run on push if this is the nf-core dev branch (merged PRs) if: "${{ github.event_name != 'push' || (github.event_name == 'push' && github.repository == 'nf-core/epitopeprediction') }}" runs-on: ubuntu-latest strategy: matrix: NXF_VER: - - "23.04.0" + - "24.04.2" - "latest-everything" + profile: + - "conda" + - "docker" + - "singularity" + test_name: + - "test" + isMaster: + - ${{ github.base_ref == 'master' }} + # Exclude conda and singularity on dev + exclude: + - isMaster: false + profile: "conda" + - isMaster: false + profile: "singularity" steps: - name: Check out pipeline code - uses: actions/checkout@v3 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4 - - name: Install Nextflow - uses: nf-core/setup-nextflow@v1 + - name: Set up Nextflow + uses: nf-core/setup-nextflow@v2 with: version: "${{ matrix.NXF_VER }}" + - name: Set up Apptainer + if: matrix.profile == 'singularity' + uses: eWaterCycle/setup-apptainer@main + + - name: Set up Singularity + if: matrix.profile == 'singularity' + run: | + mkdir -p $NXF_SINGULARITY_CACHEDIR + mkdir -p $NXF_SINGULARITY_LIBRARYDIR + + - name: Set up Miniconda + if: matrix.profile == 'conda' + uses: conda-incubator/setup-miniconda@a4260408e20b96e80095f42ff7f1a15b27dd94ca # v3 + with: + miniconda-version: "latest" + auto-update-conda: true + conda-solver: libmamba + channels: conda-forge,bioconda + + - name: Set up Conda + if: matrix.profile == 'conda' + run: | + echo $(realpath $CONDA)/condabin >> $GITHUB_PATH + echo $(realpath python) >> $GITHUB_PATH + + - name: Clean up Disk space + uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be # v1.3.1 + - name: Run pipeline with test data run: | nextflow run ${GITHUB_WORKSPACE} -profile test,docker --outdir ./results @@ -42,40 +87,22 @@ jobs: name: Run profile tests if: ${{ github.event_name != 'push' || (github.event_name == 'push' && github.repository == 'nf-core/epitopeprediction') }} runs-on: ubuntu-latest - env: - NXF_VER: ${{ matrix.nxf_ver }} - NXF_ANSI_LOG: false strategy: matrix: - include: - # Test pipeline minimum Nextflow version - - NXF_VER: "22.10.1" - NXF_EDGE: "" - # Test latest edge release of Nextflow - - NXF_VER: "" - NXF_EDGE: "1" + NXF_VER: + - "24.04.2" + - "latest-everything" tests: - [ - "test_variant_tsv", - "test_grch38_variant_tsv", - "test_peptides", - "test_peptides_h2", - "test_proteins", - "test_mhcnuggets", - "test_mhcflurry", - ] + ["test_grch38", "test_peptides", "test_peptides_h2", "test_proteins", "test_mhcnuggets", "test_mhcflurry"] steps: - name: Check out pipeline code - uses: actions/checkout@v2 + uses: actions/checkout@v3 + - name: Install Nextflow - env: - NXF_VER: ${{ matrix.NXF_VER }} - # Uncomment only if the edge release is more recent than the latest stable release - # See https://github.com/nextflow-io/nextflow/issues/2467 - # NXF_EDGE: ${{ matrix.NXF_EDGE }} - run: | - wget -qO- get.nextflow.io | bash - sudo mv nextflow /usr/local/bin/ + uses: nf-core/setup-nextflow@v1 + with: + version: "${{ matrix.NXF_VER }}" + - name: Run pipeline with profile ${{ matrix.tests }} run: | nextflow run ${GITHUB_WORKSPACE} -profile ${{ matrix.tests }},docker --outdir ./results @@ -84,20 +111,14 @@ jobs: name: Run NetMHC tool family tests if: ${{ ( github.event_name == 'push' && github.repository == 'nf-core/epitopeprediction' ) || github.event.pull_request.head.repo.full_name == 'nf-core/epitopeprediction' }} runs-on: ubuntu-latest - env: - NXF_VER: ${{ matrix.nxf_ver }} strategy: matrix: - include: - # Test pipeline minimum Nextflow version - - NXF_VER: "22.10.1" - NXF_EDGE: "" - # Test latest edge release of Nextflow - - NXF_VER: "" - NXF_EDGE: "1" + NXF_VER: + - "24.04.2" + - "latest-everything" steps: - name: Check out pipeline code - uses: actions/checkout@v2 + uses: actions/checkout@v3 - name: Install non-free software env: @@ -107,14 +128,10 @@ jobs: curl -L https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/software/non-free-software.tar.gpg | ${GITHUB_WORKSPACE}/bin/decrypt | tar -C non-free -v -x - name: Install Nextflow - env: - NXF_VER: ${{ matrix.NXF_VER }} - # Uncomment only if the edge release is more recent than the latest stable release - # See https://github.com/nextflow-io/nextflow/issues/2467 - # NXF_EDGE: ${{ matrix.NXF_EDGE }} - run: | - wget -qO- get.nextflow.io | bash - sudo mv nextflow /usr/local/bin/ + uses: nf-core/setup-nextflow@v1 + with: + version: "${{ matrix.NXF_VER }}" + - name: Run pipeline with NetMHC run: | nextflow run ${GITHUB_WORKSPACE} -profile test_netmhc,docker --outdir ./results diff --git a/.github/workflows/clean-up.yml b/.github/workflows/clean-up.yml index 694e90e..0b6b1f2 100644 --- a/.github/workflows/clean-up.yml +++ b/.github/workflows/clean-up.yml @@ -10,7 +10,7 @@ jobs: issues: write pull-requests: write steps: - - uses: actions/stale@v7 + - uses: actions/stale@28ca1036281a5e5922ead5184a1bbf96e5fc984e # v9 with: stale-issue-message: "This issue has been tagged as awaiting-changes or awaiting-feedback by an nf-core contributor. Remove stale label or add a comment otherwise this issue will be closed in 20 days." stale-pr-message: "This PR has been tagged as awaiting-changes or awaiting-feedback by an nf-core contributor. Remove stale label or add a comment if it is still useful." diff --git a/.github/workflows/download_pipeline.yml b/.github/workflows/download_pipeline.yml new file mode 100644 index 0000000..713dc3e --- /dev/null +++ b/.github/workflows/download_pipeline.yml @@ -0,0 +1,119 @@ +name: Test successful pipeline download with 'nf-core pipelines download' + +# Run the workflow when: +# - dispatched manually +# - when a PR is opened or reopened to master branch +# - the head branch of the pull request is updated, i.e. if fixes for a release are pushed last minute to dev. +on: + workflow_dispatch: + inputs: + testbranch: + description: "The specific branch you wish to utilize for the test execution of nf-core pipelines download." + required: true + default: "dev" + pull_request: + types: + - opened + - edited + - synchronize + branches: + - master + pull_request_target: + branches: + - master + +env: + NXF_ANSI_LOG: false + +jobs: + download: + runs-on: ubuntu-latest + steps: + - name: Install Nextflow + uses: nf-core/setup-nextflow@v2 + + - name: Disk space cleanup + uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be # v1.3.1 + + - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5 + with: + python-version: "3.12" + architecture: "x64" + + - name: Setup Apptainer + uses: eWaterCycle/setup-apptainer@4bb22c52d4f63406c49e94c804632975787312b3 # v2.0.0 + with: + apptainer-version: 1.3.4 + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install git+https://github.com/nf-core/tools.git@dev + + - name: Get the repository name and current branch set as environment variable + run: | + echo "REPO_LOWERCASE=${GITHUB_REPOSITORY,,}" >> ${GITHUB_ENV} + echo "REPOTITLE_LOWERCASE=$(basename ${GITHUB_REPOSITORY,,})" >> ${GITHUB_ENV} + echo "REPO_BRANCH=${{ github.event.inputs.testbranch || 'dev' }}" >> ${GITHUB_ENV} + + - name: Make a cache directory for the container images + run: | + mkdir -p ./singularity_container_images + + - name: Download the pipeline + env: + NXF_SINGULARITY_CACHEDIR: ./singularity_container_images + run: | + nf-core pipelines download ${{ env.REPO_LOWERCASE }} \ + --revision ${{ env.REPO_BRANCH }} \ + --outdir ./${{ env.REPOTITLE_LOWERCASE }} \ + --compress "none" \ + --container-system 'singularity' \ + --container-library "quay.io" -l "docker.io" -l "community.wave.seqera.io" \ + --container-cache-utilisation 'amend' \ + --download-configuration 'yes' + + - name: Inspect download + run: tree ./${{ env.REPOTITLE_LOWERCASE }} + + - name: Count the downloaded number of container images + id: count_initial + run: | + image_count=$(ls -1 ./singularity_container_images | wc -l | xargs) + echo "Initial container image count: $image_count" + echo "IMAGE_COUNT_INITIAL=$image_count" >> ${GITHUB_ENV} + + - name: Run the downloaded pipeline (stub) + id: stub_run_pipeline + continue-on-error: true + env: + NXF_SINGULARITY_CACHEDIR: ./singularity_container_images + NXF_SINGULARITY_HOME_MOUNT: true + run: nextflow run ./${{ env.REPOTITLE_LOWERCASE }}/$( sed 's/\W/_/g' <<< ${{ env.REPO_BRANCH }}) -stub -profile test,singularity --outdir ./results + - name: Run the downloaded pipeline (stub run not supported) + id: run_pipeline + if: ${{ job.steps.stub_run_pipeline.status == failure() }} + env: + NXF_SINGULARITY_CACHEDIR: ./singularity_container_images + NXF_SINGULARITY_HOME_MOUNT: true + run: nextflow run ./${{ env.REPOTITLE_LOWERCASE }}/$( sed 's/\W/_/g' <<< ${{ env.REPO_BRANCH }}) -profile test,singularity --outdir ./results + + - name: Count the downloaded number of container images + id: count_afterwards + run: | + image_count=$(ls -1 ./singularity_container_images | wc -l | xargs) + echo "Post-pipeline run container image count: $image_count" + echo "IMAGE_COUNT_AFTER=$image_count" >> ${GITHUB_ENV} + + - name: Compare container image counts + run: | + if [ "${{ env.IMAGE_COUNT_INITIAL }}" -ne "${{ env.IMAGE_COUNT_AFTER }}" ]; then + initial_count=${{ env.IMAGE_COUNT_INITIAL }} + final_count=${{ env.IMAGE_COUNT_AFTER }} + difference=$((final_count - initial_count)) + echo "$difference additional container images were \n downloaded at runtime . The pipeline has no support for offline runs!" + tree ./singularity_container_images + exit 1 + else + echo "The pipeline can be downloaded successfully!" + fi diff --git a/.github/workflows/fix-linting.yml b/.github/workflows/fix-linting.yml index 9ebf496..91f4948 100644 --- a/.github/workflows/fix-linting.yml +++ b/.github/workflows/fix-linting.yml @@ -4,7 +4,7 @@ on: types: [created] jobs: - deploy: + fix-linting: # Only run if comment is on a PR with the main repo, and if it contains the magic keywords if: > contains(github.event.comment.html_url, '/pull/') && @@ -13,10 +13,17 @@ jobs: runs-on: ubuntu-latest steps: # Use the @nf-core-bot token to check out so we can push later - - uses: actions/checkout@v3 + - uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4 with: token: ${{ secrets.nf_core_bot_auth_token }} + # indication that the linting is being fixed + - name: React on comment + uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043 # v4 + with: + comment-id: ${{ github.event.comment.id }} + reactions: eyes + # Action runs on the issue comment, so we don't get the PR by default # Use the gh cli to check out the PR - name: Checkout Pull Request @@ -24,32 +31,59 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.nf_core_bot_auth_token }} - - uses: actions/setup-node@v3 + # Install and run pre-commit + - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5 + with: + python-version: "3.12" - - name: Install Prettier - run: npm install -g prettier @prettier/plugin-php + - name: Install pre-commit + run: pip install pre-commit - # Check that we actually need to fix something - - name: Run 'prettier --check' - id: prettier_status - run: | - if prettier --check ${GITHUB_WORKSPACE}; then - echo "result=pass" >> $GITHUB_OUTPUT - else - echo "result=fail" >> $GITHUB_OUTPUT - fi + - name: Run pre-commit + id: pre-commit + run: pre-commit run --all-files + continue-on-error: true - - name: Run 'prettier --write' - if: steps.prettier_status.outputs.result == 'fail' - run: prettier --write ${GITHUB_WORKSPACE} + # indication that the linting has finished + - name: react if linting finished succesfully + if: steps.pre-commit.outcome == 'success' + uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043 # v4 + with: + comment-id: ${{ github.event.comment.id }} + reactions: "+1" - name: Commit & push changes - if: steps.prettier_status.outputs.result == 'fail' + id: commit-and-push + if: steps.pre-commit.outcome == 'failure' run: | git config user.email "core@nf-co.re" git config user.name "nf-core-bot" git config push.default upstream git add . git status - git commit -m "[automated] Fix linting with Prettier" + git commit -m "[automated] Fix code linting" git push + + - name: react if linting errors were fixed + id: react-if-fixed + if: steps.commit-and-push.outcome == 'success' + uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043 # v4 + with: + comment-id: ${{ github.event.comment.id }} + reactions: hooray + + - name: react if linting errors were not fixed + if: steps.commit-and-push.outcome == 'failure' + uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043 # v4 + with: + comment-id: ${{ github.event.comment.id }} + reactions: confused + + - name: react if linting errors were not fixed + if: steps.commit-and-push.outcome == 'failure' + uses: peter-evans/create-or-update-comment@71345be0265236311c031f5c7866368bd1eff043 # v4 + with: + issue-number: ${{ github.event.issue.number }} + body: | + @${{ github.actor }} I tried to fix the linting errors, but it didn't work. Please fix them manually. + See [CI log](https://github.com/nf-core/epitopeprediction/actions/runs/${{ github.run_id }}) for more details. diff --git a/.github/workflows/linting.yml b/.github/workflows/linting.yml index 888cb4b..a502573 100644 --- a/.github/workflows/linting.yml +++ b/.github/workflows/linting.yml @@ -1,6 +1,6 @@ name: nf-core linting # This workflow is triggered on pushes and PRs to the repository. -# It runs the `nf-core lint` and markdown lint tests to ensure +# It runs the `nf-core pipelines lint` and markdown lint tests to ensure # that the code meets the nf-core guidelines. on: push: @@ -11,87 +11,62 @@ on: types: [published] jobs: - EditorConfig: + pre-commit: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4 - - uses: actions/setup-node@v3 - - - name: Install editorconfig-checker - run: npm install -g editorconfig-checker - - - name: Run ECLint check - run: editorconfig-checker -exclude README.md $(find .* -type f | grep -v '.git\|.py\|.md\|json\|yml\|yaml\|html\|css\|work\|.nextflow\|build\|nf_core.egg-info\|log.txt\|Makefile') - - Prettier: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - uses: actions/setup-node@v3 - - - name: Install Prettier - run: npm install -g prettier - - - name: Run Prettier --check - run: prettier --check ${GITHUB_WORKSPACE} - - PythonBlack: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Check code lints with Black - uses: psf/black@stable - - # If the above check failed, post a comment on the PR explaining the failure - - name: Post PR comment - if: failure() - uses: mshick/add-pr-comment@v1 + - name: Set up Python 3.12 + uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5 with: - message: | - ## Python linting (`black`) is failing - - To keep the code consistent with lots of contributors, we run automated code consistency checks. - To fix this CI test, please run: - - * Install [`black`](https://black.readthedocs.io/en/stable/): `pip install black` - * Fix formatting errors in your pipeline: `black .` + python-version: "3.12" - Once you push these changes the test should pass, and you can hide this comment :+1: + - name: Install pre-commit + run: pip install pre-commit - We highly recommend setting up Black in your code editor so that this formatting is done automatically on save. Ask about it on Slack for help! - - Thanks again for your contribution! - repo-token: ${{ secrets.GITHUB_TOKEN }} - allow-repeats: false + - name: Run pre-commit + run: pre-commit run --all-files nf-core: runs-on: ubuntu-latest steps: - name: Check out pipeline code - uses: actions/checkout@v3 + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4 - name: Install Nextflow - uses: nf-core/setup-nextflow@v1 + uses: nf-core/setup-nextflow@v2 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5 with: - python-version: "3.8" + python-version: "3.12" architecture: "x64" + - name: read .nf-core.yml + uses: pietrobolcato/action-read-yaml@1.1.0 + id: read_yml + with: + config: ${{ github.workspace }}/.nf-core.yml + - name: Install dependencies run: | python -m pip install --upgrade pip - pip install nf-core + pip install nf-core==${{ steps.read_yml.outputs['nf_core_version'] }} + + - name: Run nf-core pipelines lint + if: ${{ github.base_ref != 'master' }} + env: + GITHUB_COMMENTS_URL: ${{ github.event.pull_request.comments_url }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_PR_COMMIT: ${{ github.event.pull_request.head.sha }} + run: nf-core -l lint_log.txt pipelines lint --dir ${GITHUB_WORKSPACE} --markdown lint_results.md - - name: Run nf-core lint + - name: Run nf-core pipelines lint --release + if: ${{ github.base_ref == 'master' }} env: GITHUB_COMMENTS_URL: ${{ github.event.pull_request.comments_url }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_PR_COMMIT: ${{ github.event.pull_request.head.sha }} - run: nf-core -l lint_log.txt lint --dir ${GITHUB_WORKSPACE} --markdown lint_results.md + run: nf-core -l lint_log.txt pipelines lint --release --dir ${GITHUB_WORKSPACE} --markdown lint_results.md - name: Save PR number if: ${{ always() }} @@ -99,7 +74,7 @@ jobs: - name: Upload linting log file artifact if: ${{ always() }} - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 # v4 with: name: linting-logs path: | diff --git a/.github/workflows/linting_comment.yml b/.github/workflows/linting_comment.yml index 0bbcd30..42e519b 100644 --- a/.github/workflows/linting_comment.yml +++ b/.github/workflows/linting_comment.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Download lint results - uses: dawidd6/action-download-artifact@v2 + uses: dawidd6/action-download-artifact@bf251b5aa9c2f7eeb574a96ee720e24f801b7c11 # v6 with: workflow: linting.yml workflow_conclusion: completed @@ -21,7 +21,7 @@ jobs: run: echo "pr_number=$(cat linting-logs/PR_number.txt)" >> $GITHUB_OUTPUT - name: Post PR comment - uses: marocchino/sticky-pull-request-comment@v2 + uses: marocchino/sticky-pull-request-comment@331f8f5b4215f0445d3c07b4967662a32a2d3e31 # v2 with: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} number: ${{ steps.pr_number.outputs.pr_number }} diff --git a/.github/workflows/release-announcements.yml b/.github/workflows/release-announcements.yml new file mode 100644 index 0000000..c6ba35d --- /dev/null +++ b/.github/workflows/release-announcements.yml @@ -0,0 +1,75 @@ +name: release-announcements +# Automatic release toot and tweet anouncements +on: + release: + types: [published] + workflow_dispatch: + +jobs: + toot: + runs-on: ubuntu-latest + steps: + - name: get topics and convert to hashtags + id: get_topics + run: | + echo "topics=$(curl -s https://nf-co.re/pipelines.json | jq -r '.remote_workflows[] | select(.full_name == "${{ github.repository }}") | .topics[]' | awk '{print "#"$0}' | tr '\n' ' ')" | sed 's/-//g' >> $GITHUB_OUTPUT + + - uses: rzr/fediverse-action@master + with: + access-token: ${{ secrets.MASTODON_ACCESS_TOKEN }} + host: "mstdn.science" # custom host if not "mastodon.social" (default) + # GitHub event payload + # https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#release + message: | + Pipeline release! ${{ github.repository }} v${{ github.event.release.tag_name }} - ${{ github.event.release.name }}! + + Please see the changelog: ${{ github.event.release.html_url }} + + ${{ steps.get_topics.outputs.topics }} #nfcore #openscience #nextflow #bioinformatics + + send-tweet: + runs-on: ubuntu-latest + + steps: + - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5 + with: + python-version: "3.10" + - name: Install dependencies + run: pip install tweepy==4.14.0 + - name: Send tweet + shell: python + run: | + import os + import tweepy + + client = tweepy.Client( + access_token=os.getenv("TWITTER_ACCESS_TOKEN"), + access_token_secret=os.getenv("TWITTER_ACCESS_TOKEN_SECRET"), + consumer_key=os.getenv("TWITTER_CONSUMER_KEY"), + consumer_secret=os.getenv("TWITTER_CONSUMER_SECRET"), + ) + tweet = os.getenv("TWEET") + client.create_tweet(text=tweet) + env: + TWEET: | + Pipeline release! ${{ github.repository }} v${{ github.event.release.tag_name }} - ${{ github.event.release.name }}! + + Please see the changelog: ${{ github.event.release.html_url }} + TWITTER_CONSUMER_KEY: ${{ secrets.TWITTER_CONSUMER_KEY }} + TWITTER_CONSUMER_SECRET: ${{ secrets.TWITTER_CONSUMER_SECRET }} + TWITTER_ACCESS_TOKEN: ${{ secrets.TWITTER_ACCESS_TOKEN }} + TWITTER_ACCESS_TOKEN_SECRET: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} + + bsky-post: + runs-on: ubuntu-latest + steps: + - uses: zentered/bluesky-post-action@80dbe0a7697de18c15ad22f4619919ceb5ccf597 # v0.1.0 + with: + post: | + Pipeline release! ${{ github.repository }} v${{ github.event.release.tag_name }} - ${{ github.event.release.name }}! + + Please see the changelog: ${{ github.event.release.html_url }} + env: + BSKY_IDENTIFIER: ${{ secrets.BSKY_IDENTIFIER }} + BSKY_PASSWORD: ${{ secrets.BSKY_PASSWORD }} + # diff --git a/.github/workflows/template_version_comment.yml b/.github/workflows/template_version_comment.yml new file mode 100644 index 0000000..e8aafe4 --- /dev/null +++ b/.github/workflows/template_version_comment.yml @@ -0,0 +1,46 @@ +name: nf-core template version comment +# This workflow is triggered on PRs to check if the pipeline template version matches the latest nf-core version. +# It posts a comment to the PR, even if it comes from a fork. + +on: pull_request_target + +jobs: + template_version: + runs-on: ubuntu-latest + steps: + - name: Check out pipeline code + uses: actions/checkout@0ad4b8fadaa221de15dcec353f45205ec38ea70b # v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + + - name: Read template version from .nf-core.yml + uses: nichmor/minimal-read-yaml@v0.0.2 + id: read_yml + with: + config: ${{ github.workspace }}/.nf-core.yml + + - name: Install nf-core + run: | + python -m pip install --upgrade pip + pip install nf-core==${{ steps.read_yml.outputs['nf_core_version'] }} + + - name: Check nf-core outdated + id: nf_core_outdated + run: echo "OUTPUT=$(pip list --outdated | grep nf-core)" >> ${GITHUB_ENV} + + - name: Post nf-core template version comment + uses: mshick/add-pr-comment@b8f338c590a895d50bcbfa6c5859251edc8952fc # v2 + if: | + contains(env.OUTPUT, 'nf-core') + with: + repo-token: ${{ secrets.NF_CORE_BOT_AUTH_TOKEN }} + allow-repeats: false + message: | + > [!WARNING] + > Newer version of the nf-core template is available. + > + > Your pipeline is using an old version of the nf-core template: ${{ steps.read_yml.outputs['nf_core_version'] }}. + > Please update your pipeline to the latest version. + > + > For more documentation on how to update your pipeline, please see the [nf-core documentation](https://github.com/nf-core/tools?tab=readme-ov-file#sync-a-pipeline-with-the-template) and [Synchronisation documentation](https://nf-co.re/docs/contributing/sync). + # diff --git a/.gitignore b/.gitignore index 5124c9a..a42ce01 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ results/ testing/ testing* *.pyc +null/ diff --git a/.gitpod.yml b/.gitpod.yml index 25488dc..4611863 100644 --- a/.gitpod.yml +++ b/.gitpod.yml @@ -7,13 +7,11 @@ tasks: vscode: extensions: # based on nf-core.nf-core-extensionpack - - codezombiech.gitignore # Language support for .gitignore files - # - cssho.vscode-svgviewer # SVG viewer - - esbenp.prettier-vscode # Markdown/CommonMark linting and style checking for Visual Studio Code - - eamodio.gitlens # Quickly glimpse into whom, why, and when a line or code block was changed + #- esbenp.prettier-vscode # Markdown/CommonMark linting and style checking for Visual Studio Code - EditorConfig.EditorConfig # override user/workspace settings with settings found in .editorconfig files - Gruntfuggly.todo-tree # Display TODO and FIXME in a tree view in the activity bar - mechatroner.rainbow-csv # Highlight columns in csv files in different colors - # - nextflow.nextflow # Nextflow syntax highlighting + - nextflow.nextflow # Nextflow syntax highlighting - oderwat.indent-rainbow # Highlight indentation level - streetsidesoftware.code-spell-checker # Spelling checker for source code + - charliermarsh.ruff # Code linter Ruff diff --git a/.nf-core.yml b/.nf-core.yml index 3805dc8..a4de20e 100644 --- a/.nf-core.yml +++ b/.nf-core.yml @@ -1 +1,20 @@ +bump_version: null +lint: + files_unchanged: + - assets/nf-core-epitopeprediction_logo_light.png + - docs/images/nf-core-epitopeprediction_logo_light.png + - docs/images/nf-core-epitopeprediction_logo_dark.png +nf_core_version: 3.0.2 +org_path: null repository_type: pipeline +template: + author: Christopher Mohr, Jonas Scheid + description: A fully reproducible and state of the art epitope prediction pipeline. + force: false + is_nfcore: true + name: epitopeprediction + org: nf-core + outdir: . + skip_features: null + version: 2.3.1 +update: null diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 0c31cdb..9e9f0e1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,5 +1,13 @@ repos: - repo: https://github.com/pre-commit/mirrors-prettier - rev: "v2.7.1" + rev: "v3.1.0" hooks: - id: prettier + additional_dependencies: + - prettier@3.2.5 + + - repo: https://github.com/editorconfig-checker/editorconfig-checker.python + rev: "3.0.3" + hooks: + - id: editorconfig-checker + alias: ec diff --git a/CHANGELOG.md b/CHANGELOG.md index ba344ec..9651fa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,14 +3,43 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## v2.2.2dev - 2023-08-29 +## v2.4.0dev [date] ### `Changed` -- [203](https://github.com/nf-core/epitopeprediction/pull/203) - Update to nf-core template `2.9` -- [203](https://github.com/nf-core/epitopeprediction/pull/203) - Update to nf-core template `2.8` +- [#247](https://github.com/nf-core/epitopeprediction/pull/247) - Update to nf-core template `3.0.2` + +## v2.3.1 - Oesterberg - 2024-05-17 + +### `Changed` + +- [#243](https://github.com/nf-core/epitopeprediction/pull/243) - Update to nf-core template `2.14.1` +- [#237](https://github.com/nf-core/epitopeprediction/pull/237) - Update to nf-core template `2.13.1` + +### `Fixed` + +- [#243](https://github.com/nf-core/epitopeprediction/pull/243) - Add check for protein map to prevent failure if no information is available + +## v2.3.0 - Oesterberg - 2024-02-26 + +### `Changed` + +- [#233](https://github.com/nf-core/epitopeprediction/pull/233) - Update to nf-core template `2.13` +- [#228](https://github.com/nf-core/epitopeprediction/pull/228) - Update to nf-core template `2.12` +- [#227](https://github.com/nf-core/epitopeprediction/pull/227) Prevent crash if no transcript is found (in splitted vcf) +- [#220](https://github.com/nf-core/epitopeprediction/pull/220) - Switch to nf-validation to parse samplesheet +- [#213](https://github.com/nf-core/epitopeprediction/pull/213) - Update epytope and Ensembl reference handling and update to nf-core template `2.10` - [#206](https://github.com/nf-core/epitopeprediction/issues/206) - Update the row checker class. -- [#205](https://github.com/nf-core/epitopeprediction/issues/205) - Update general structure of MHC binding subworkflow +- [#203](https://github.com/nf-core/epitopeprediction/pull/203) - Update to nf-core template `2.9`, rename param `genome_version` to `genome_reference`, add functionality to handle BioMart archive urls + +### `Fixed` + +- [#219](https://github.com/nf-core/epitopeprediction/pull/219) - Fix `EXTERNAL_TOOLS_IMPORT`` container registry and bump version +- [#227](https://github.com/nf-core/epitopeprediction/pull/227) - Prevent crash if no transcript is found (in splitted vcf) + +### `Removed` + +- [#221](https://github.com/nf-core/epitopeprediction/pull/221) - Remove support of `GSvar` and variant `tsv` input files ## v2.2.1 - WaldhaeuserOst Hotfix - 2023-03-16 diff --git a/CITATIONS.md b/CITATIONS.md index 5466f3b..a23fa19 100644 --- a/CITATIONS.md +++ b/CITATIONS.md @@ -10,9 +10,13 @@ ## Pipeline tools +- [FastQC](https://www.bioinformatics.babraham.ac.uk/projects/fastqc/) + +> Andrews, S. (2010). FastQC: A Quality Control Tool for High Throughput Sequence Data [Online]. + - [MultiQC](https://pubmed.ncbi.nlm.nih.gov/27312411/) - > Ewels P, Magnusson M, Lundin S, Käller M. MultiQC: summarize analysis results for multiple tools and samples in a single report. Bioinformatics. 2016 Oct 1;32(19):3047-8. doi: 10.1093/bioinformatics/btw354. Epub 2016 Jun 16. PubMed PMID: 27312411; PubMed Central PMCID: PMC5039924. +> Ewels P, Magnusson M, Lundin S, Käller M. MultiQC: summarize analysis results for multiple tools and samples in a single report. Bioinformatics. 2016 Oct 1;32(19):3047-8. doi: 10.1093/bioinformatics/btw354. Epub 2016 Jun 16. PubMed PMID: 27312411; PubMed Central PMCID: PMC5039924. - [SnpSift](https://dx.doi.org/10.3389/fgene.2012.00035) diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index f4fd052..c089ec7 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,18 +1,20 @@ -# Code of Conduct at nf-core (v1.0) +# Code of Conduct at nf-core (v1.4) ## Our Pledge -In the interest of fostering an open, collaborative, and welcoming environment, we as contributors and maintainers of nf-core, pledge to making participation in our projects and community a harassment-free experience for everyone, regardless of: +In the interest of fostering an open, collaborative, and welcoming environment, we as contributors and maintainers of nf-core pledge to making participation in our projects and community a harassment-free experience for everyone, regardless of: - Age +- Ability - Body size +- Caste - Familial status - Gender identity and expression - Geographical location - Level of experience - Nationality and national origins - Native language -- Physical and neurological ability +- Neurodiversity - Race or ethnicity - Religion - Sexual identity and orientation @@ -22,80 +24,133 @@ Please note that the list above is alphabetised and is therefore not ranked in a ## Preamble -> Note: This Code of Conduct (CoC) has been drafted by the nf-core Safety Officer and been edited after input from members of the nf-core team and others. "We", in this document, refers to the Safety Officer and members of the nf-core core team, both of whom are deemed to be members of the nf-core community and are therefore required to abide by this Code of Conduct. This document will amended periodically to keep it up-to-date, and in case of any dispute, the most current version will apply. +:::note +This Code of Conduct (CoC) has been drafted by Renuka Kudva, Cris Tuñí, and Michael Heuer, with input from the nf-core Core Team and Susanna Marquez from the nf-core community. "We", in this document, refers to the Safety Officers and members of the nf-core Core Team, both of whom are deemed to be members of the nf-core community and are therefore required to abide by this Code of Conduct. This document will be amended periodically to keep it up-to-date. In case of any dispute, the most current version will apply. +::: -An up-to-date list of members of the nf-core core team can be found [here](https://nf-co.re/about). Our current safety officer is Renuka Kudva. +An up-to-date list of members of the nf-core core team can be found [here](https://nf-co.re/about). + +Our Safety Officers are Saba Nafees, Cris Tuñí, and Michael Heuer. nf-core is a young and growing community that welcomes contributions from anyone with a shared vision for [Open Science Policies](https://www.fosteropenscience.eu/taxonomy/term/8). Open science policies encompass inclusive behaviours and we strive to build and maintain a safe and inclusive environment for all individuals. -We have therefore adopted this code of conduct (CoC), which we require all members of our community and attendees in nf-core events to adhere to in all our workspaces at all times. Workspaces include but are not limited to Slack, meetings on Zoom, Jitsi, YouTube live etc. +We have therefore adopted this CoC, which we require all members of our community and attendees of nf-core events to adhere to in all our workspaces at all times. Workspaces include, but are not limited to, Slack, meetings on Zoom, gather.town, YouTube live etc. -Our CoC will be strictly enforced and the nf-core team reserve the right to exclude participants who do not comply with our guidelines from our workspaces and future nf-core activities. +Our CoC will be strictly enforced and the nf-core team reserves the right to exclude participants who do not comply with our guidelines from our workspaces and future nf-core activities. -We ask all members of our community to help maintain a supportive and productive workspace and to avoid behaviours that can make individuals feel unsafe or unwelcome. Please help us maintain and uphold this CoC. +We ask all members of our community to help maintain supportive and productive workspaces and to avoid behaviours that can make individuals feel unsafe or unwelcome. Please help us maintain and uphold this CoC. -Questions, concerns or ideas on what we can include? Contact safety [at] nf-co [dot] re +Questions, concerns, or ideas on what we can include? Contact members of the Safety Team on Slack or email safety [at] nf-co [dot] re. ## Our Responsibilities -The safety officer is responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behaviour. +Members of the Safety Team (the Safety Officers) are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behaviour. -The safety officer in consultation with the nf-core core team have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. +The Safety Team, in consultation with the nf-core core team, have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this CoC, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. -Members of the core team or the safety officer who violate the CoC will be required to recuse themselves pending investigation. They will not have access to any reports of the violations and be subject to the same actions as others in violation of the CoC. +Members of the core team or the Safety Team who violate the CoC will be required to recuse themselves pending investigation. They will not have access to any reports of the violations and will be subject to the same actions as others in violation of the CoC. -## When are where does this Code of Conduct apply? +## When and where does this Code of Conduct apply? -Participation in the nf-core community is contingent on following these guidelines in all our workspaces and events. This includes but is not limited to the following listed alphabetically and therefore in no order of preference: +Participation in the nf-core community is contingent on following these guidelines in all our workspaces and events, such as hackathons, workshops, bytesize, and collaborative workspaces on gather.town. These guidelines include, but are not limited to, the following (listed alphabetically and therefore in no order of preference): - Communicating with an official project email address. - Communicating with community members within the nf-core Slack channel. - Participating in hackathons organised by nf-core (both online and in-person events). -- Participating in collaborative work on GitHub, Google Suite, community calls, mentorship meetings, email correspondence. -- Participating in workshops, training, and seminar series organised by nf-core (both online and in-person events). This applies to events hosted on web-based platforms such as Zoom, Jitsi, YouTube live etc. +- Participating in collaborative work on GitHub, Google Suite, community calls, mentorship meetings, email correspondence, and on the nf-core gather.town workspace. +- Participating in workshops, training, and seminar series organised by nf-core (both online and in-person events). This applies to events hosted on web-based platforms such as Zoom, gather.town, Jitsi, YouTube live etc. - Representing nf-core on social media. This includes both official and personal accounts. ## nf-core cares 😊 -nf-core's CoC and expectations of respectful behaviours for all participants (including organisers and the nf-core team) include but are not limited to the following (listed in alphabetical order): +nf-core's CoC and expectations of respectful behaviours for all participants (including organisers and the nf-core team) include, but are not limited to, the following (listed in alphabetical order): - Ask for consent before sharing another community member’s personal information (including photographs) on social media. - Be respectful of differing viewpoints and experiences. We are all here to learn from one another and a difference in opinion can present a good learning opportunity. -- Celebrate your accomplishments at events! (Get creative with your use of emojis 🎉 🥳 💯 🙌 !) +- Celebrate your accomplishments! (Get creative with your use of emojis 🎉 🥳 💯 🙌 !) - Demonstrate empathy towards other community members. (We don’t all have the same amount of time to dedicate to nf-core. If tasks are pending, don’t hesitate to gently remind members of your team. If you are leading a task, ask for help if you feel overwhelmed.) - Engage with and enquire after others. (This is especially important given the geographically remote nature of the nf-core community, so let’s do this the best we can) - Focus on what is best for the team and the community. (When in doubt, ask) -- Graciously accept constructive criticism, yet be unafraid to question, deliberate, and learn. +- Accept feedback, yet be unafraid to question, deliberate, and learn. - Introduce yourself to members of the community. (We’ve all been outsiders and we know that talking to strangers can be hard for some, but remember we’re interested in getting to know you and your visions for open science!) -- Show appreciation and **provide clear feedback**. (This is especially important because we don’t see each other in person and it can be harder to interpret subtleties. Also remember that not everyone understands a certain language to the same extent as you do, so **be clear in your communications to be kind.**) +- Show appreciation and **provide clear feedback**. (This is especially important because we don’t see each other in person and it can be harder to interpret subtleties. Also remember that not everyone understands a certain language to the same extent as you do, so **be clear in your communication to be kind.**) - Take breaks when you feel like you need them. -- Using welcoming and inclusive language. (Participants are encouraged to display their chosen pronouns on Zoom or in communication on Slack.) +- Use welcoming and inclusive language. (Participants are encouraged to display their chosen pronouns on Zoom or in communication on Slack) ## nf-core frowns on 😕 -The following behaviours from any participants within the nf-core community (including the organisers) will be considered unacceptable under this code of conduct. Engaging or advocating for any of the following could result in expulsion from nf-core workspaces. +The following behaviours from any participants within the nf-core community (including the organisers) will be considered unacceptable under this CoC. Engaging or advocating for any of the following could result in expulsion from nf-core workspaces: - Deliberate intimidation, stalking or following and sustained disruption of communication among participants of the community. This includes hijacking shared screens through actions such as using the annotate tool in conferencing software such as Zoom. - “Doxing” i.e. posting (or threatening to post) another person’s personal identifying information online. - Spamming or trolling of individuals on social media. -- Use of sexual or discriminatory imagery, comments, or jokes and unwelcome sexual attention. -- Verbal and text comments that reinforce social structures of domination related to gender, gender identity and expression, sexual orientation, ability, physical appearance, body size, race, age, religion or work experience. +- Use of sexual or discriminatory imagery, comments, jokes, or unwelcome sexual attention. +- Verbal and text comments that reinforce social structures of domination related to gender, gender identity and expression, sexual orientation, ability, physical appearance, body size, race, age, religion, or work experience. ### Online Trolling -The majority of nf-core interactions and events are held online. Unfortunately, holding events online comes with the added issue of online trolling. This is unacceptable, reports of such behaviour will be taken very seriously, and perpetrators will be excluded from activities immediately. +The majority of nf-core interactions and events are held online. Unfortunately, holding events online comes with the risk of online trolling. This is unacceptable — reports of such behaviour will be taken very seriously and perpetrators will be excluded from activities immediately. -All community members are required to ask members of the group they are working within for explicit consent prior to taking screenshots of individuals during video calls. +All community members are **required** to ask members of the group they are working with for explicit consent prior to taking screenshots of individuals during video calls. -## Procedures for Reporting CoC violations +## Procedures for reporting CoC violations If someone makes you feel uncomfortable through their behaviours or actions, report it as soon as possible. -You can reach out to members of the [nf-core core team](https://nf-co.re/about) and they will forward your concerns to the safety officer(s). +You can reach out to members of the Safety Team (Saba Nafees, Cris Tuñí, and Michael Heuer) on Slack. Alternatively, contact a member of the nf-core core team [nf-core core team](https://nf-co.re/about), and they will forward your concerns to the Safety Team. + +Issues directly concerning members of the Core Team or the Safety Team will be dealt with by other members of the core team and the safety manager — possible conflicts of interest will be taken into account. nf-core is also in discussions about having an ombudsperson and details will be shared in due course. + +All reports will be handled with the utmost discretion and confidentiality. + +You can also report any CoC violations to safety [at] nf-co [dot] re. In your email report, please do your best to include: + +- Your contact information. +- Identifying information (e.g. names, nicknames, pseudonyms) of the participant who has violated the Code of Conduct. +- The behaviour that was in violation and the circumstances surrounding the incident. +- The approximate time of the behaviour (if different than the time the report was made). +- Other people involved in the incident, if applicable. +- If you believe the incident is ongoing. +- If there is a publicly available record (e.g. mailing list record, a screenshot). +- Any additional information. + +After you file a report, one or more members of our Safety Team will contact you to follow up on your report. + +## Who will read and handle reports + +All reports will be read and handled by the members of the Safety Team at nf-core. + +If members of the Safety Team are deemed to have a conflict of interest with a report, they will be required to recuse themselves as per our Code of Conduct and will not have access to any follow-ups. + +To keep this first report confidential from any of the Safety Team members, please submit your first report by direct messaging on Slack/direct email to any of the nf-core members you are comfortable disclosing the information to, and be explicit about which member(s) you do not consent to sharing the information with. + +## Reviewing reports + +After receiving the report, members of the Safety Team will review the incident report to determine whether immediate action is required, for example, whether there is immediate threat to participants’ safety. + +The Safety Team, in consultation with members of the nf-core core team, will assess the information to determine whether the report constitutes a Code of Conduct violation, for them to decide on a course of action. + +In the case of insufficient information, one or more members of the Safety Team may contact the reporter, the reportee, or any other attendees to obtain more information. -Issues directly concerning members of the core team will be dealt with by other members of the core team and the safety manager, and possible conflicts of interest will be taken into account. nf-core is also in discussions about having an ombudsperson, and details will be shared in due course. +Once additional information is gathered, the Safety Team will collectively review and decide on the best course of action to take, if any. The Safety Team reserves the right to not act on a report. -All reports will be handled with utmost discretion and confidentially. +## Confidentiality + +All reports, and any additional information included, are only shared with the team of safety officers (and possibly members of the core team, in case the safety officer is in violation of the CoC). We will respect confidentiality requests for the purpose of protecting victims of abuse. + +We will not name harassment victims, beyond discussions between the safety officer and members of the nf-core team, without the explicit consent of the individuals involved. + +## Enforcement + +Actions taken by the nf-core’s Safety Team may include, but are not limited to: + +- Asking anyone to stop a behaviour. +- Asking anyone to leave the event and online spaces either temporarily, for the remainder of the event, or permanently. +- Removing access to the gather.town and Slack, either temporarily or permanently. +- Communicating to all participants to reinforce our expectations for conduct and remind what is unacceptable behaviour; this may be public for practical reasons. +- Communicating to all participants that an incident has taken place and how we will act or have acted — this may be for the purpose of letting event participants know we are aware of and dealing with the incident. +- Banning anyone from participating in nf-core-managed spaces, future events, and activities, either temporarily or permanently. +- No action. ## Attribution and Acknowledgements @@ -106,6 +161,22 @@ All reports will be handled with utmost discretion and confidentially. ## Changelog -### v1.0 - March 12th, 2021 +### v1.4 - February 8th, 2022 + +- Included a new member of the Safety Team. Corrected a typographical error in the text. + +### v1.3 - December 10th, 2021 + +- Added a statement that the CoC applies to nf-core gather.town workspaces. Corrected typographical errors in the text. + +### v1.2 - November 12th, 2021 + +- Removed information specific to reporting CoC violations at the Hackathon in October 2021. + +### v1.1 - October 14th, 2021 + +- Updated with names of new Safety Officers and specific information for the hackathon in October 2021. + +### v1.0 - March 15th, 2021 - Complete rewrite from original [Contributor Covenant](http://contributor-covenant.org/) CoC. diff --git a/README.md b/README.md index e931fa9..ac2f76a 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,19 @@ -# ![nf-core/epitopeprediction](docs/images/nf-core-epitopeprediction_logo_light.png#gh-light-mode-only) ![nf-core/epitopeprediction](docs/images/nf-core-epitopeprediction_logo_dark.png#gh-dark-mode-only) - -[![GitHub Actions CI Status](https://github.com/nf-core/epitopeprediction/workflows/nf-core%20CI/badge.svg)](https://github.com/nf-core/epitopeprediction/actions?query=workflow%3A%22nf-core+CI%22) -[![GitHub Actions Linting Status](https://github.com/nf-core/epitopeprediction/workflows/nf-core%20linting/badge.svg)](https://github.com/nf-core/epitopeprediction/actions?query=workflow%3A%22nf-core+linting%22) -[![AWS CI](https://img.shields.io/badge/CI%20tests-full%20size-FF9900?labelColor=000000&logo=Amazon%20AWS)](https://nf-co.re/epitopeprediction/results) -[![Cite with Zenodo](http://img.shields.io/badge/DOI-10.5281/zenodo.3564666-1073c8?labelColor=000000)](https://doi.org/10.5281/zenodo.3564666) - -[![Nextflow](https://img.shields.io/badge/nextflow%20DSL2-%E2%89%A523.04.0-23aa62.svg)](https://www.nextflow.io/) +

+ + + nf-core/epitopeprediction + +

+ +[![GitHub Actions CI Status](https://github.com/nf-core/epitopeprediction/actions/workflows/ci.yml/badge.svg)](https://github.com/nf-core/epitopeprediction/actions/workflows/ci.yml) +[![GitHub Actions Linting Status](https://github.com/nf-core/epitopeprediction/actions/workflows/linting.yml/badge.svg)](https://github.com/nf-core/epitopeprediction/actions/workflows/linting.yml)[![AWS CI](https://img.shields.io/badge/CI%20tests-full%20size-FF9900?labelColor=000000&logo=Amazon%20AWS)](https://nf-co.re/epitopeprediction/results)[![Cite with Zenodo](http://img.shields.io/badge/DOI-10.5281/zenodo.3564666-1073c8?labelColor=000000)](https://doi.org/10.5281/zenodo.3564666) +[![nf-test](https://img.shields.io/badge/unit_tests-nf--test-337ab7.svg)](https://www.nf-test.com) + +[![Nextflow](https://img.shields.io/badge/nextflow%20DSL2-%E2%89%A524.04.2-23aa62.svg)](https://www.nextflow.io/) [![run with conda](http://img.shields.io/badge/run%20with-conda-3EB049?labelColor=000000&logo=anaconda)](https://docs.conda.io/en/latest/) [![run with docker](https://img.shields.io/badge/run%20with-docker-0db7ed?labelColor=000000&logo=docker)](https://www.docker.com/) [![run with singularity](https://img.shields.io/badge/run%20with-singularity-1d355c.svg?labelColor=000000)](https://sylabs.io/docs/) -[![Launch on Nextflow Tower](https://img.shields.io/badge/Launch%20%F0%9F%9A%80-Nextflow%20Tower-%234256e7?labelColor=000000)](https://tower.nf/launch?pipeline=https://github.com/nf-core/epitopeprediction) +[![Launch on Seqera Platform](https://img.shields.io/badge/Launch%20%F0%9F%9A%80-Seqera%20Platform-%234256e7)](https://cloud.seqera.io/launch?pipeline=https://github.com/nf-core/epitopeprediction) [![Get help on Slack](http://img.shields.io/badge/slack-nf--core%20%23epitopeprediction-4A154B?labelColor=000000&logo=slack)](https://nfcore.slack.com/channels/epitopeprediction)[![Follow on Twitter](http://img.shields.io/badge/twitter-%40nf__core-1DA1F2?labelColor=000000&logo=twitter)](https://twitter.com/nf_core)[![Follow on Mastodon](https://img.shields.io/badge/mastodon-nf__core-6364ff?labelColor=FFFFFF&logo=mastodon)](https://mstdn.science/@nf_core)[![Watch on YouTube](http://img.shields.io/badge/youtube-nf--core-FF0000?labelColor=000000&logo=youtube)](https://www.youtube.com/c/nf-core) @@ -18,6 +22,17 @@ **nf-core/epitopeprediction** is a bioinformatics best-practice analysis pipeline for epitope prediction and annotation. The pipeline performs epitope predictions for a given set of variants or peptides directly using state of the art prediction tools. Additionally, resulting prediction results can be annotated with metadata. +Supported prediction tools: + +- `syfpeithi` +- `mhcflurry` +- `mhcnuggets-class-1` +- `mhcnuggets-class-2` +- `netmhcpan-4.0` +- `netmhcpan-4.1` +- `netmhc-4.0` +- `netmhciipan-4.1` + The pipeline is built using [Nextflow](https://www.nextflow.io), a workflow tool to run tasks across multiple compute infrastructures in a very portable manner. It uses Docker/Singularity containers making installation trivial and results highly reproducible. The [Nextflow DSL2](https://www.nextflow.io/docs/latest/dsl2.html) implementation of this pipeline uses one container per process which makes it easier to maintain and update software dependencies. Where possible, these processes have been submitted to and installed from [nf-core/modules](https://github.com/nf-core/modules) in order to make them available to all nf-core pipelines, and to everyone within the Nextflow community! On release, automated continuous integration tests run the pipeline on a full-sized dataset on the AWS cloud infrastructure. This ensures that the pipeline runs on AWS, has sensible resource allocation defaults set to run on real-world datasets, and permits the persistent storage of results to benchmark between pipeline releases and other analysis sources.The results obtained from the full-sized test can be viewed on the [nf-core website](https://nf-co.re/epitopeprediction/results). @@ -28,37 +43,32 @@ On release, automated continuous integration tests run the pipeline on a full-si 2. Generate peptides from variants or proteins or use peptides directly 3. Predict HLA-binding peptides for the given set of HLA alleles -## Usage - -> **Note** -> If you are new to Nextflow and nf-core, please refer to [this page](https://nf-co.re/docs/usage/installation) on how -> to set-up Nextflow. Make sure to [test your setup](https://nf-co.re/docs/usage/introduction#how-to-run-a-pipeline) -> with `-profile test` before running the workflow on actual data. +> [!NOTE] +> If you are new to Nextflow and nf-core, please refer to [this page](https://nf-co.re/docs/usage/installation) on how to set-up Nextflow. Make sure to [test your setup](https://nf-co.re/docs/usage/introduction#how-to-run-a-pipeline) with `-profile test` before running the workflow on actual data. First, prepare a samplesheet with your input data that looks as follows: `samplesheet.csv`: -````csv +```csv sample,alleles,mhc_class,filename GBM_1,A*01:01;A*02:01;B*07:02;B*24:02;C*03:01;C*04:01,I,gbm_1_variants.vcf GBM_1,A*02:01;A*24:01;B*07:02;B*08:01;C*04:01;C*07:01,I,gbm_1_peptides.vcf +``` Each row represents a sample with associated HLA alleles and input data (variants/peptides/proteins). ---> +Now, you can run the pipeline using: ```bash nextflow run nf-core/epitopeprediction \ -profile \ --input samplesheet.csv \ --outdir -```` +``` -> **Warning:** -> Please provide pipeline parameters via the CLI or Nextflow `-params-file` option. Custom config files including those -> provided by the `-c` Nextflow option can be used to provide any configuration _**except for parameters**_; -> see [docs](https://nf-co.re/usage/configuration#custom-configuration-files). +> [!WARNING] +> Please provide pipeline parameters via the CLI or Nextflow `-params-file` option. Custom config files including those provided by the `-c` Nextflow option can be used to provide any configuration _**except for parameters**_; see [docs](https://nf-co.re/docs/usage/getting_started/configuration#custom-configuration-files). For more details and further functionality, please refer to the [usage documentation](https://nf-co.re/epitopeprediction/usage) and the [parameter documentation](https://nf-co.re/epitopeprediction/parameters). diff --git a/assets/email_template.html b/assets/email_template.html index 08d9a41..251ba8c 100644 --- a/assets/email_template.html +++ b/assets/email_template.html @@ -12,7 +12,7 @@ -

nf-core/epitopeprediction v${version}

+

nf-core/epitopeprediction ${version}

Run Name: $runName

<% if (!success){ diff --git a/assets/email_template.txt b/assets/email_template.txt index 8b39053..9d39536 100644 --- a/assets/email_template.txt +++ b/assets/email_template.txt @@ -4,7 +4,7 @@ |\\ | |__ __ / ` / \\ |__) |__ } { | \\| | \\__, \\__/ | \\ |___ \\`-._,-`-, `._,._,' - nf-core/epitopeprediction v${version} + nf-core/epitopeprediction ${version} ---------------------------------------------------- Run Name: $runName diff --git a/assets/external_tools_meta.json b/assets/external_tools_meta.json index 828f5d7..df320b2 100644 --- a/assets/external_tools_meta.json +++ b/assets/external_tools_meta.json @@ -56,6 +56,11 @@ "data_url": "https://services.healthtech.dtu.dk/services/NetMHCIIpan-4.0/data.tar.gz", "data_md5": "ec3032cb66aee20ff0f53ff7f1795f47", "binary_name": "netMHCIIpan" + }, + "4.3": { + "version": 4.3, + "software_md5": "477d65f92b6b217fdec2d3af65c2df79", + "binary_name": "netMHCIIpan" } }, "netmhciipan_darwin": { diff --git a/assets/multiqc_config.yml b/assets/multiqc_config.yml index 8a6b9e8..0065922 100644 --- a/assets/multiqc_config.yml +++ b/assets/multiqc_config.yml @@ -1,12 +1,7 @@ report_comment: > - This report has been generated by the nf-core/epitopeprediction + This report has been generated by the nf-core/epitopeprediction analysis pipeline. For information about how to interpret these results, please see the - documentation. - -custom_logo: "nf-core-epitopeprediction_logo_light.png" -custom_logo_url: https://github.com/nf-core/epitopeprediction/ -custom_logo_title: "nf-core/epitopeprediction" - + documentation. report_section_order: "nf-core-epitopeprediction-methods-description": order: -1000 @@ -16,3 +11,5 @@ report_section_order: order: -1002 export_plots: true + +disable_version_detection: true diff --git a/assets/nf-core-epitopeprediction_logo_light.png b/assets/nf-core-epitopeprediction_logo_light.png index 40ba75d..998876a 100644 Binary files a/assets/nf-core-epitopeprediction_logo_light.png and b/assets/nf-core-epitopeprediction_logo_light.png differ diff --git a/assets/schema_input.json b/assets/schema_input.json index b564a5c..1fa236a 100644 --- a/assets/schema_input.json +++ b/assets/schema_input.json @@ -1,5 +1,5 @@ { - "$schema": "http://json-schema.org/draft-07/schema", + "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://raw.githubusercontent.com/nf-core/epitopeprediction/master/assets/schema_input.json", "title": "nf-core/epitopeprediction pipeline - params.input schema", "description": "Schema for the file provided with params.input", @@ -10,7 +10,8 @@ "sample": { "type": "string", "pattern": "^\\S+$", - "errorMessage": "Sample name must be provided and cannot contain spaces" + "errorMessage": "Sample name must be provided and cannot contain spaces", + "meta": ["sample"] }, "alleles": { "anyOf": [ @@ -20,20 +21,35 @@ }, { "type": "string", - "pattern": "(^[A-Z][*][0-9][0-9][:][0-9][0-9])$" + "pattern": "^([A-E]{1}[*][0-9]{2}[:][0-9]{2})(;[A-E]{1}[*][0-9]{2}[:][0-9]{2})*$" + }, + { + "type": "string", + "pattern": "^((DR|DP|DQ)[AB][0-9][*][0-9]{2}[:][0-9]{2})(;(DR|DP|DQ)[AB][0-9][*][0-9]{2}[:][0-9]{2})*$" + }, + { + "type": "string", + "pattern": "^((DR|DP|DQ)[AB][0-9][*][0-9]{2}[:][0-9]{2}[-](DR|DP|DQ)[AB][0-9][*][0-9]{2}[:][0-9]{2})(;((DR|DP|DQ)[AB][0-9][*][0-9]{2}[:][0-9]{2}[-](DR|DP|DQ)[AB][0-9][*][0-9]{2}[:][0-9]{2}))*$" + }, + { + "type": "string", + "pattern": "^[H][-][2][-][A-Za-z]{2,3}$" } ], - "errorMessage": "Alleles must be provided as string or file with extension '.txt''" + "errorMessage": "Alleles must be provided as string or file with extension '.txt'. Please check the documentation for more information.", + "meta": ["alleles"] }, "mhc_class": { "type": "string", "pattern": "^(I|II|H-2)$", - "errorMessage": "The MHC class must be provided. Valid values: " + "errorMessage": "The MHC class must be provided. Valid values: 'I', 'II' or 'H-2'", + "meta": ["mhc_class"] }, "filename": { "type": "string", - "pattern": "^\\S+\\.(vcf|tsv|fasta|fa|txt)$", - "errorMessage": "Variants/proteins/peptides for sample must be provided and have one of the following extensions: '.vcf', '.tsv', '.fasta', '.fa', '.txt'" + "pattern": "^\\S+\\.(vcf|vcf.gz|tsv|fasta|fa)$", + "errorMessage": "Variants/proteins/peptides of a sample must be provided and have one of the following extensions: '.vcf', '.vcf.gz', '.tsv', '.fasta', '.fa'", + "exists": true } }, "required": ["sample", "alleles", "mhc_class", "filename"] diff --git a/assets/slackreport.json b/assets/slackreport.json index 80b50b7..f27f64a 100644 --- a/assets/slackreport.json +++ b/assets/slackreport.json @@ -3,7 +3,7 @@ { "fallback": "Plain-text summary of the attachment.", "color": "<% if (success) { %>good<% } else { %>danger<%} %>", - "author_name": "nf-core/epitopeprediction v${version} - ${runName}", + "author_name": "nf-core/epitopeprediction ${version} - ${runName}", "author_icon": "https://www.nextflow.io/docs/latest/_static/favicon.ico", "text": "<% if (success) { %>Pipeline completed successfully!<% } else { %>Pipeline completed with errors<% } %>", "fields": [ diff --git a/bin/check_requested_models.py b/bin/check_requested_models.py index bc7a485..845666d 100755 --- a/bin/check_requested_models.py +++ b/bin/check_requested_models.py @@ -2,15 +2,14 @@ # Written by Sabrina Krakau, Christopher Mohr and released under the MIT license. -import sys -import csv import argparse +import csv import logging +import sys import urllib.request from epytope.Core.Allele import Allele from epytope.Core.Peptide import Peptide -from epytope.IO import FileReader from epytope.EpitopePrediction import EpitopePredictorFactory # instantiate global logger object @@ -25,7 +24,7 @@ def read_peptide_input(filename): peptides = [] """expected columns (min required): id sequence""" - with open(filename, "r") as peptide_input: + with open(filename) as peptide_input: # enable listing of protein names for each peptide csv.field_size_limit(600000) reader = csv.DictReader(peptide_input, delimiter="\t") @@ -54,7 +53,7 @@ def __main__(): "Write out information about supported models by epytope for installed predictor tool versions." ) parser.add_argument("-p", "--peptides", help="File with one peptide per line") - parser.add_argument("-c", "--mhcclass", default=1, help="MHC class I or II") + parser.add_argument("-c", "--mhc_class", default=1, help="MHC class I or II") parser.add_argument("-l", "--max_length", help="Maximum peptide length", type=int) parser.add_argument("-ml", "--min_length", help="Minimum peptide length", type=int) parser.add_argument("-a", "--alleles", help=" MHC Alleles", required=True, type=str) @@ -62,7 +61,7 @@ def __main__(): parser.add_argument("-v", "--versions", help=" File with used software versions.", required=True) args = parser.parse_args() selected_methods = [item.split("-")[0] if "mhcnuggets" not in item else item for item in args.tools.split(",")] - with open(args.versions, "r") as versions_file: + with open(args.versions) as versions_file: tool_version = [(row[0].split()[0], str(row[1])) for row in csv.reader(versions_file, delimiter=":")] # NOTE this needs to be updated, if a newer version will be available via epytope and should be used in the future tool_version.append(("syfpeithi", "1.0")) # how to handle this? @@ -75,12 +74,7 @@ def __main__(): } # get the alleles - if args.alleles.startswith("http"): - alleles = [Allele(a) for a in urllib.request.urlopen(args.alleles).read().decode("utf-8").splitlines()] - elif args.alleles.endswith(".txt"): - alleles = [Allele(a) for a in open(args.alleles, "r").read().splitlines()] - else: - alleles = [Allele(a) for a in args.alleles.split(";")] + alleles = [Allele(a) for a in args.alleles.split(";")] peptide_lengths = [] if args.peptides: diff --git a/bin/check_samplesheet.py b/bin/check_samplesheet.py deleted file mode 100755 index 97f66c6..0000000 --- a/bin/check_samplesheet.py +++ /dev/null @@ -1,294 +0,0 @@ -#!/usr/bin/env python -# Written by Jonas Scheid, Christopher Mohr and released under the MIT license. - -import argparse -import logging -import os -import re -import sys -import errno -import re -import csv -from pathlib import Path -import urllib.request - - -class RowChecker: - """ - Define a service that can validate and transform each given row. - - Attributes: - rows (list): A list of dicts, where each dict corresponds to a previously - validated and transformed row. The order of rows is maintained. - - """ - - VALID_FORMATS = (".tsv", ".fasta", ".vcf", "GSvar") - - def __init__( - self, - sample_col=0, - alleles_col=1, - mhc_class_col=2, - filename_col=3, - **kwargs, - ): - """ - Initialize the row checker with the expected column names. - - Args: - sample_col (str): The name of the column that contains the sample name - (default "sample"). - alleles_col (str): The name of the column that contains the MHC alleles. - mhc_class_col (str): The name of the column that contains the MHC class. - filename_col (str): The name of the column that contains the filename. - - """ - super().__init__(**kwargs) - self._sample_col = sample_col - self._alleles_col = alleles_col - self._mhc_class_col = mhc_class_col - self._filename_col = filename_col - self._seen = set() - self.rows = [] - - def validate(self, row): - """ - Perform all validations on the given row. - - Args: - row (dict): A mapping from column headers (keys) to elements of that row - (values). - - """ - self._validate_row_length(row) - self._validate_sample(row) - self._validate_allele(row) - self._validate_mhc_class(row) - self._validate_file(row[self._filename_col]) - self._seen.add( - (row[self._sample_col], row[self._alleles_col], row[self._mhc_class_col], row[self._filename_col]) - ) - self.rows.append(row) - self._validate_unique_row() - self._validate_unique_sample() - - def _validate_sample(self, row): - """Assert that the sample name exists and convert spaces to underscores.""" - if len(row[self._sample_col]) <= 0: - raise AssertionError(f"Sample input is required.\nLine: {row}") - - def _validate_allele(self, row): - """Assert that the alleles have the right format.""" - valid_class1_loci = ["A*", "B*", "C*", "E*", "G*"] - valid_class2_loci = ["DR", "DP", "DQ"] - - if len(row[self._alleles_col]) <= 0: - raise AssertionError(f"No alleles specified.\nLine: {row}") - if ( - not os.path.isfile(row[self._alleles_col]) - and ( - row[self._mhc_class_col] == "I" - and any(substring in row[self._alleles_col] for substring in valid_class2_loci) - ) - or ( - row[self._mhc_class_col] == "II" - and any(substring in row[self._alleles_col] for substring in valid_class1_loci) - ) - ): - raise AssertionError( - f"Samplesheet contains invalid mhc class and allele combination!\nLine: {row} \ - \nValid loci: {valid_class1_loci if row[self._mhc_class_col] == 'I' else valid_class2_loci}" - ) - - def _validate_mhc_class(self, row): - """Assert that the mhc_class has the right format.""" - valid_classes = ["I", "II", "H-2"] - if row[self._mhc_class_col] not in valid_classes: - raise AssertionError(f"MHC class must be one of: {valid_classes}\nLine: {row}") - - def _validate_file(self, filename): - """Assert that a given filename has one of the expected FASTQ extensions.""" - if not any(filename.endswith(extension) for extension in self.VALID_FORMATS): - raise AssertionError( - f"The input file has an unrecognized extension: {filename}\n" - f"It should be one of: {', '.join(self.VALID_FORMATS)}" - ) - - def _validate_row_length(self, row): - """Assert the row length.""" - if len(row) != 4: - raise AssertionError(f"Invalid row length: {len(row)}\nLine: {row}.") - - def _validate_unique_row(self): - """Assert that the combination of sample name, alleles, mhc_class and filename is unique.""" - if len(self._seen) != len(self.rows) and len(self.rows) > 1: - raise AssertionError(f"Duplicate row found: {self.rows[-1]}") - - def _validate_unique_sample(self): - """Assert that the combination sample names are unique.""" - sample_names = [row[self._sample_col] for row in self.rows] - if len(set(sample_names)) != len(sample_names): - raise AssertionError(f"Duplicate sample name found: {self.rows[-1]}") - - -def get_file_type(file): - """Read file extension and return file type""" - extension = file.split(".")[-1] - # check input file is empty - # it needs to be distinguished if there's a given local file or internet address - if str(file).startswith("http"): - with urllib.request.urlopen(file) as response: - file = response.read().decode("utf-8").split("\n") - if len(file) == 0: - raise AssertionError(f"Input file {file} is empty.") - else: - file = open(file, "r").readlines() - if file == 0: - raise AssertionError(f"Input file {file} is empty.") - - try: - if extension == "vcf.gz": - file_type = "compressed_variant" - elif extension == "vcf": - file_type = "variant" - elif extension == "fasta": - file_type = "protein" - elif extension in ["tsv", "GSvar"]: - # Check if the file is a variant annotation file or a peptide file - header_columns = [col.strip() for col in file[0].split("\t")] - - required_variant_columns = ["#chr", "start", "end"] - - file_type = "peptide" - - if all(col in header_columns for col in required_variant_columns): - file_type = "variant" - elif "sequence" not in header_columns: - raise AssertionError("Peptide input file does not contain mandatory column 'sequence'") - - return file_type - - except Exception as e: - raise AssertionError( - f"Error with checking samplesheet: {e}. Check correct format for input file {file} in documentation." - ) - - -def parse_args(argv=None): - """Define and immediately parse command line arguments.""" - parser = argparse.ArgumentParser( - description="Validate and transform a tabular samplesheet.", - epilog="Example: python check_samplesheet.py samplesheet.csv samplesheet.valid.csv", - ) - parser.add_argument( - "file_in", - metavar="FILE_IN", - type=Path, - help="Tabular input samplesheet in CSV or TSV format.", - ) - parser.add_argument( - "file_out", - metavar="FILE_OUT", - type=Path, - help="Transformed output samplesheet in CSV format.", - ) - parser.add_argument( - "-l", - "--log-level", - help="The desired log level (default WARNING).", - choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"), - default="WARNING", - ) - return parser.parse_args(argv) - - -def check_allele_nomenclature(allele): - pattern = re.compile("(^[A-Z][\*][0-9][0-9][:][0-9][0-9])$") - return pattern.match(allele) is not None - - -def make_dir(path): - if len(path) > 0: - try: - os.makedirs(path) - except OSError as exception: - if exception.errno != errno.EEXIST: - raise exception - - -def check_samplesheet(file_in, file_out): - """ - sample,alleles,mhc_class,filename - GBM_1,A*01:01;A*02:01;B*07:02;B*24:02;C*03:01;C*04:01,I,gbm_1_anno.vcf|gbm_1_peps.tsv|gbm_1_prot.fasta - GBM_2,A*02:01;A*24:01;B*07:02;B*08:01;C*04:01;C*07:01,I,gbm_2_anno.vcf|gbm_2_peps.tsv|gbm_2_prot.fasta - - or - - sample,alleles,mhc_class,filename - GBM_1,gbm_1_alleles.txt,I,gbm_1_anno.vcf|gbm_1_peps.tsv|gbm_1_prot.fasta - GBM_2,gbm_2_alleles.txt,I,gbm_2_anno.vcf|gbm_2_peps.tsv|gbm_2_prot.fasta - - - where the FileName column contains EITHER a vcf/tsv file with genomic variants, a tsv file (peptides), or a fasta file (proteins) - and the Alleles column contains EITHER a string of alleles separated by semicolon or the path to a text file - containing one allele per line (no header) - - Further examples: - - Class2 allele format => https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/alleles/alleles.DRB1_01_01.txt - - Mouse allele format => https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/alleles/alleles.H2.txt - - Peptide format => https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/peptides/peptides.tsv - - Variant TSV format => https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/variants/variants.tsv - - Variant VCF format => https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/variants/variants.vcf - """ - - with open( - file_in, - newline="", - ) as samplesheet: - reader = csv.reader(samplesheet) - - ## Check header - valid_header = ["sample", "alleles", "mhc_class", "filename"] - header = [x.strip('"') for x in samplesheet.readline().strip().split(",")] - if len(header) != 4: - raise ValueError( - f"Invalid number of header columns! Make sure the samplesheet is properly comma-separated." - ) - elif header != valid_header: - raise AssertionError(f"Invalid samplesheet header (valid = {valid_header})!") - - ## Check samplesheet entries - checker = RowChecker() - rows = [] - for i, row in enumerate(reader): - checker.validate(row) - # here an allele check with mhcgnomes would be suitable - row.append(get_file_type(row[3])) - rows.append(row) - - if len(checker.rows) == 0: - raise AssertionError("Samplesheet contains no entries!") - - ## Write validated samplesheet with appropriate columns - out_dir = os.path.dirname(file_out) - make_dir(out_dir) - with open(file_out, "w") as fout: - valid_header.append("inputtype") - fout.write(",".join(valid_header) + "\n") - for row in rows: - fout.write(",".join(row) + "\n") - - -def main(argv=None): - """Coordinate argument parsing and program execution.""" - args = parse_args(argv) - logging.basicConfig(level=args.log_level, format="[%(levelname)s] %(message)s") - if not args.file_in.is_file(): - raise AssertionError(f"The given input file {args.file_in} does not exist!") - args.file_out.parent.mkdir(parents=True, exist_ok=True) - check_samplesheet(args.file_in, args.file_out) - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/bin/check_supported_models.py b/bin/check_supported_models.py index 8edc5ba..61c4801 100755 --- a/bin/check_supported_models.py +++ b/bin/check_supported_models.py @@ -2,9 +2,8 @@ # Written by Sabrina Krakau, Christopher Mohr and released under the MIT license. -import sys -import csv import argparse +import csv from epytope.EpitopePrediction import EpitopePredictorFactory @@ -30,7 +29,7 @@ def __main__(): # NOTE this needs to be updated manually, if other methods should be used in the future available_methods = ["syfpeithi", "mhcflurry", "mhcnuggets-class-1", "mhcnuggets-class-2"] - with open(args.versions, "r") as versions_file: + with open(args.versions) as versions_file: tool_version = [(row[0].split()[0], str(row[1])) for row in csv.reader(versions_file, delimiter=":")] # NOTE this needs to be updated, if a newer version will be available via Fred2 and should be used in the future tool_version.append(("syfpeithi", "1.0")) diff --git a/bin/epaa.py b/bin/epaa.py index 2603b9f..cd838ae 100755 --- a/bin/epaa.py +++ b/bin/epaa.py @@ -1,31 +1,29 @@ #!/usr/bin/env python # Written by Christopher Mohr and released under the MIT license (2022). -import os -import sys -import logging -import csv -import re -import vcf import argparse -import urllib +import csv import itertools -import pandas as pd -import numpy as np -import epytope.Core.Generator as generator -import math import json -import urllib.request +import logging +import math +import os +import re +import sys +from datetime import datetime -from epytope.IO.MartsAdapter import MartsAdapter -from epytope.Core.Variant import Variant, VariationType, MutationSyntax +import epytope.Core.Generator as generator +import numpy as np +import pandas as pd +import vcf +from Bio import SeqUtils +from epytope.Core.Allele import Allele +from epytope.Core.Peptide import Peptide +from epytope.Core.Variant import MutationSyntax, Variant, VariationType from epytope.EpitopePrediction import EpitopePredictorFactory from epytope.IO.ADBAdapter import EIdentifierTypes +from epytope.IO.MartsAdapter import MartsAdapter from epytope.IO.UniProtAdapter import UniProtDB -from epytope.Core.Allele import Allele -from epytope.Core.Peptide import Peptide -from Bio import SeqUtils -from datetime import datetime __author__ = "Christopher Mohr" VERSION = "1.1" @@ -41,7 +39,7 @@ logger.addHandler(handler) ID_SYSTEM_USED = EIdentifierTypes.ENSEMBL -transcriptProteinMap = {} +transcriptProteinTable = {} transcriptSwissProtMap = {} @@ -70,26 +68,6 @@ def get_epytope_annotation(vt, p, r, alt): return position, reference, alternative -def check_min_req_GSvar(row): - """ - checking the presence of mandatory columns - :param row: dictionary of a GSvar row - :return: boolean, True if min req met - """ - if ( - "#chr" in row.keys() - and "start" in row.keys() - and "end" in row.keys() - and "ref" in row.keys() - and "obs" in row.keys() - and ( - "coding_and_splicing_details" in row.keys() or "coding" in row.keys() or "coding_and_splicing" in row.keys() - ) - ): - return True - return False - - def determine_variant_type(record, alternative): vt = VariationType.UNKNOWN if record.is_snp: @@ -129,154 +107,6 @@ def determine_zygosity(record): return isHomozygous -def read_GSvar(filename, pass_only=True): - """ - reads GSvar and tsv files (tab sep files in context of genetic variants), omitting and warning about rows missing - mandatory columns - :param filename: /path/to/file - :return: list epytope variants - """ - global ID_SYSTEM_USED - RE = re.compile("(\w+):([\w.]+):([&\w]+):\w*:exon(\d+)\D*\d*:(c.\D*([_\d]+)\D*):(p.\D*(\d+)\w*)") - - # list of mandatory (meta)data - exclusion_list = [ - "start", - "end", - "#chr", - "ref", - "obs", - "gene", - "tumour_genotype", - "coding_and_splicing_details", - "variant_details", - "variant_type", - "coding_and_splicing", - ] - - list_vars = list() - lines = list() - transcript_ids = [] - dict_vars = {} - - cases = 0 - - with open(filename, "rt") as tsvfile: - tsvreader = csv.DictReader((row for row in tsvfile if not row.startswith("##")), delimiter="\t") - for row in tsvreader: - if not check_min_req_GSvar(row): - logger.warning("read_GSvar: Omitted row! Mandatory columns not present in: \n" + str(row) + ".") - continue - lines.append(row) - - # get list of additional metadata - metadata_list = set(tsvreader.fieldnames) - set(exclusion_list) - - for mut_id, line in enumerate(lines): - if "filter" in line and pass_only and line["filter"].strip(): - continue - genome_start = int(line["start"]) - 1 - genome_stop = int(line["end"]) - 1 - chrom = line["#chr"] - ref = line["ref"] - alt = line["obs"] - gene = line.get("gene", "") - - isHomozygous = ( - True - if ( - ("tumour_genotype" in line) - and (line["tumour_genotype"].split("/")[0] == line["tumour_genotype"].split("/")[1]) - ) - else False - ) - - # old GSvar version - if "coding_and_splicing_details" in line: - mut_type = line.get("variant_details", "") - annots = RE.findall(line["coding_and_splicing_details"]) - else: - mut_type = line.get("variant_type", "") - # Gene, transcript number, type, impact, exon/intron number, HGVS.c, HGVS.p, Pfam - annots = RE.findall(line["coding_and_splicing"]) - isyn = mut_type == "synonymous_variant" - - """ - Enum for variation types: - type.SNP, type.DEL, type.INS, type.FSDEL, type.FSINS, type.UNKNOWN - """ - vt = VariationType.UNKNOWN - if mut_type == "missense_variant" or "missense_variant" in mut_type: - vt = VariationType.SNP - elif mut_type == "frameshift_variant": - if (ref == "-") or (len(ref) < len(alt)): - vt = VariationType.FSINS - else: - vt = VariationType.FSDEL - elif mut_type == "inframe_deletion": - vt = VariationType.DEL - elif mut_type == "inframe_insertion": - vt = VariationType.INS - - coding = dict() - - for annot in annots: - a_gene, transcript_id, a_mut_type, exon, trans_coding, trans_pos, prot_coding, prot_start = annot - if "NM" in transcript_id: - ID_SYSTEM_USED = EIdentifierTypes.REFSEQ - if "stop_gained" not in mut_type: - if not gene: - gene = a_gene - if not mut_type: - mut_type = a_mut_type - - # TODO with the next epytope release we can deal with transcript id version - transcript_id = transcript_id.split(".")[0] - - coding[transcript_id] = MutationSyntax( - transcript_id, int(trans_pos.split("_")[0]) - 1, int(prot_start) - 1, trans_coding, prot_coding - ) - transcript_ids.append(transcript_id) - if coding: - var = Variant( - mut_id, - vt, - chrom.strip("chr"), - int(genome_start), - ref.upper(), - alt.upper(), - coding, - isHomozygous, - isSynonymous=isyn, - ) - var.gene = gene - - # metadata logging - for meta_name in metadata_list: - var.log_metadata(meta_name, line.get(meta_name, "")) - - dict_vars[var] = var - list_vars.append(var) - - transToVar = {} - - # fix because of memory/timing issues due to combinatorial explosion - for variant in list_vars: - for trans_id in variant.coding.keys(): - transToVar.setdefault(trans_id, []).append(variant) - - for tId, vs in transToVar.items(): - if len(vs) > 10: - cases += 1 - for v in vs: - vs_new = Variant(v.id, v.type, v.chrom, v.genomePos, v.ref, v.obs, v.coding, True, v.isSynonymous) - vs_new.gene = v.gene - for m in metadata_list: - vs_new.log_metadata(m, v.get_metadata(m)[0]) - dict_vars[v] = vs_new - return dict_vars.values(), transcript_ids, metadata_list - - def read_vcf(filename, pass_only=True): """ reads vcf files @@ -319,7 +149,7 @@ def read_vcf(filename, pass_only=True): SNPEFF_KEY = "ANN" variants = list() - with open(filename, "rt") as tsvfile: + with open(filename) as tsvfile: vcf_reader = vcf.Reader(tsvfile) variants = [r for r in vcf_reader] @@ -365,8 +195,7 @@ def read_vcf(filename, pass_only=True): SNP => seq[pos] = OBS (replace) INSERTION => seqp[pos:pos] = obs (insert at that position) - DELETION => s = slice(pos, pos+len(ref)) (create slice that will be removed) - del seq[s] (remove) + DELETION => s = slice(pos, pos+len(ref)) (create slice that will be removed) del seq[s] (remove) """ for alt in alternative_list: isHomozygous = determine_zygosity(record) @@ -420,8 +249,7 @@ def read_vcf(filename, pass_only=True): positions = re.findall(r"\d+", prot_coding) tpos = int(positions[0]) - 1 - # TODO with the new epytope release we will support transcript IDs with version - transcript_id = transcript_id.split(".")[0] + # with the latest epytope release (3.3.1), we can now handle full transcript IDs if "NM" in transcript_id: ID_SYSTEM_USED = EIdentifierTypes.REFSEQ @@ -452,7 +280,6 @@ def read_vcf(filename, pass_only=True): split_coding_c[0] if split_coding_c[0] else split_annotation[vep_fields["feature"]] ) transcript_id = transcript_id.split(".")[0] - tpos = int(cds_pos.split("/")[0].split("-")[0]) - 1 if split_annotation[vep_fields["protein_position"]]: ppos = ( @@ -488,12 +315,10 @@ def read_vcf(filename, pass_only=True): for format_key in format_list: if getattr(sample.data, format_key, None) is None: logger.warning( - "FORMAT entry {entry} not defined for {genotype}. Skipping.".format( - entry=format_key, genotype=sample.sample - ) + f"FORMAT entry {format_key} not defined for {sample.sample}. Skipping." ) continue - format_header = "{}.{}".format(sample.sample, format_key) + format_header = f"{sample.sample}.{format_key}" final_metadata_list.append(format_header) if isinstance(sample[format_key], list): format_value = ",".join([str(i) for i in sample[format_key]]) @@ -532,7 +357,7 @@ def read_peptide_input(filename): metadata = [] """expected columns (min required): id sequence""" - with open(filename, "r") as peptide_input: + with open(filename) as peptide_input: # enable listing of protein names for each peptide csv.field_size_limit(600000) reader = csv.DictReader(peptide_input, delimiter="\t") @@ -554,7 +379,7 @@ def read_protein_quant(filename): # protein id: sample1: intensity, sample2: intensity: intensities = {} - with open(filename, "r") as inp: + with open(filename) as inp: inpreader = csv.DictReader(inp, delimiter="\t") for row in inpreader: if "REV" in row["Protein IDs"]: @@ -575,7 +400,7 @@ def read_diff_expression_values(filename): # feature id: log2fold changes fold_changes = {} - with open(filename, "r") as inp: + with open(filename) as inp: inp.readline() for row in inp: values = row.strip().split("\t") @@ -589,7 +414,7 @@ def read_lig_ID_values(filename): # sequence: score median intensity intensities = {} - with open(filename, "r") as inp: + with open(filename) as inp: reader = csv.DictReader(inp, delimiter=",") for row in reader: seq = re.sub("[\(].*?[\)]", "", row["sequence"]) @@ -599,13 +424,22 @@ def read_lig_ID_values(filename): def create_protein_column_value(pep): + # retrieve Ensembl protein ID for given transcript IDs, if we want to provide additional protein ID types, adapt here + # we have to catch cases where no protein information is available, e.g. if there are issues on BioMart side + if transcriptProteinTable is None: + logger.warning(f"Protein mapping not available for peptide {str(pep)}") + return "" + all_proteins = [ - transcriptProteinMap[transcript.transcript_id.split(":")[0]] for transcript in set(pep.get_all_transcripts()) + # split by : otherwise epytope generator suffix included + transcriptProteinTable.query(f'transcript_id == "{transcript.transcript_id.split(":")[0]}"')["ensembl_id"] + for transcript in set(pep.get_all_transcripts()) ] return ",".join(set([item for sublist in all_proteins for item in sublist])) def create_transcript_column_value(pep): + # split by : otherwise epytope generator suffix included return ",".join(set([transcript.transcript_id.split(":")[0] for transcript in set(pep.get_all_transcripts())])) @@ -630,11 +464,11 @@ def create_gene_column_value(pep, pep_dictionary): def create_variant_pos_column_value(pep, pep_dictionary): - return ",".join(set(["{}".format(variant.genomePos) for variant in set(pep_dictionary[pep])])) + return ",".join(set([f"{variant.genomePos}" for variant in set(pep_dictionary[pep])])) def create_variant_chr_column_value(pep, pep_dictionary): - return ",".join(set(["{}".format(variant.chrom) for variant in set(pep_dictionary[pep])])) + return ",".join(set([f"{variant.chrom}" for variant in set(pep_dictionary[pep])])) def create_variant_type_column_value(pep, pep_dictionary): @@ -662,7 +496,7 @@ def create_metadata_column_value(pep, c, pep_dictionary): if len(variant.get_metadata(c)) != 0 ] ) - if len(meta) is 0: + if len(meta) == 0: return np.nan else: return ",".join(meta) @@ -677,7 +511,7 @@ def create_wt_seq_column_value(pep, wtseqs): if bool(transcript.vars) and "{}_{}".format(str(pep["sequence"]), transcript.transcript_id) in wtseqs ] ) - if len(wild_type) is 0: + if len(wild_type) == 0: return np.nan else: return ",".join(wild_type) @@ -736,13 +570,11 @@ def create_expression_column_value_for_result(row, dict, deseq, gene_id_lengths) ) ) logger.warning( - "FKPM value will be based on transcript length for {gene}. Because gene could not be found in the DB".format( - gene=t - ) + f"FKPM value will be based on transcript length for {t}. Because gene could not be found in the DB" ) else: values.append(np.nan) - values = ["{0:.2f}".format(value) for value in values] + values = [f"{value:.2f}" for value in values] return ",".join(values) @@ -756,7 +588,7 @@ def create_quant_column_value_for_result(row, dict, swissProtDict, key): values.append(math.log(int(dict[p][key]), 2)) else: values.append(int(dict[p][key])) - if len(values) is 0: + if len(values) == 0: return np.nan else: return ",".join(set([str(v) for v in values])) @@ -773,91 +605,6 @@ def create_ligandomics_column_value_for_result(row, lig_id, val, wild_type): return "" -def get_protein_ids_for_transcripts(idtype, transcripts, ensembl_url, reference): - result = {} - result_swissProt = {} - - biomart_url = "{}/biomart/martservice?query=".format(ensembl_url) - biomart_head = """ - - - - - """.strip() - biomart_tail = """ - - - """.strip() - biomart_filter = """""" - biomart_attribute = """""" - - ENSEMBL = False - if idtype == EIdentifierTypes.ENSEMBL: - idname = "ensembl_transcript_id" - ENSEMBL = True - elif idtype == EIdentifierTypes.REFSEQ: - idname = "refseq_mrna" - - input_lists = [] - - # too long requests will fail - if len(transcripts) > 200: - input_lists = [transcripts[i : i + 3] for i in range(0, len(transcripts), 3)] - - else: - input_lists += [transcripts] - - attribut_swissprot = "uniprot_swissprot_accession" if reference == "GRCh37" else "uniprotswissprot" - - tsvselect = [] - for l in input_lists: - rq_n = ( - biomart_head % ("hsapiens_gene_ensembl", "default") - + biomart_filter % (idname, ",".join(l)) - + biomart_attribute % ("ensembl_peptide_id") - + biomart_attribute % (attribut_swissprot) - + biomart_attribute % ("refseq_peptide") - + biomart_attribute % (idname) - + biomart_tail - ) - - # DictReader returns byte object that is transformed into a string by '.decode('utf-8')' - tsvreader = csv.DictReader( - urllib.request.urlopen(biomart_url + urllib.parse.quote(rq_n)).read().decode("utf-8").splitlines(), - dialect="excel-tab", - ) - - tsvselect += [x for x in tsvreader] - - swissProtKey = "UniProt/SwissProt Accession" if reference == "GRCh37" else "UniProtKB/Swiss-Prot ID" - - if ENSEMBL: - key = "Ensembl Transcript ID" if reference == "GRCh37" else "Transcript stable ID" - protein_key = "Ensembl Protein ID" if reference == "GRCh37" else "Protein stable ID" - for dic in tsvselect: - if dic[key] in result: - merged = result[dic[key]] + [dic[protein_key]] - merged_swissProt = result_swissProt[dic[key]] + [dic[swissProtKey]] - result[dic[key]] = merged - result_swissProt[dic[key]] = merged_swissProt - else: - result[dic[key]] = [dic[protein_key]] - result_swissProt[dic[key]] = [dic[swissProtKey]] - else: - key = "RefSeq mRNA [e.g. NM_001195597]" - for dic in tsvselect: - if dic[key] in result: - merged = result[dic[key]] + [dic["RefSeq Protein ID [e.g. NP_001005353]"]] - merged_swissProt = result_swissProt[dic[key]] + [dic[swissProtKey]] - result[dic[key]] = merged - result_swissProt[dic[key]] = merged_swissProt - else: - result[dic[key]] = [dic["RefSeq Protein ID [e.g. NP_001005353]"]] - result_swissProt[dic[key]] = [dic[swissProtKey]] - - return result, result_swissProt - - def get_matrix_max_score(allele, length): allele_model = "%s_%i" % (allele, length) try: @@ -927,9 +674,9 @@ def generate_wt_seqs(peptides): wt = SeqUtils.seq1(m.groups()[0]) mut_seq[key] = wt if not_available: - wt_dict["{}_{}".format(str(x), t.transcript_id)] = np.nan + wt_dict[f"{str(x)}_{t.transcript_id}"] = np.nan elif variant_available: - wt_dict["{}_{}".format(str(x), t.transcript_id)] = "".join(mut_seq) + wt_dict[f"{str(x)}_{t.transcript_id}"] = "".join(mut_seq) return wt_dict @@ -945,25 +692,6 @@ def create_peptide_variant_dictionary(peptides): return pep_to_variants -# TODO replace by epytope function once released -def is_created_by_variant(peptide): - transcript_ids = [x.transcript_id for x in set(peptide.get_all_transcripts())] - for t in transcript_ids: - p = peptide.proteins[t] - varmap = p.vars - for pos, vars in varmap.items(): - for var in vars: - if var.type in [VariationType.FSDEL, VariationType.FSINS]: - if peptide.proteinPos[t][0] + len(peptide) > pos: - return True - else: - for start_pos in peptide.proteinPos[t]: - positions = list(range(start_pos, start_pos + len(peptide))) - if pos in positions: - return True - return False - - def make_predictions_from_variants( variants_all, methods, @@ -976,7 +704,7 @@ def make_predictions_from_variants( protein_db, identifier, metadata, - transcriptProteinMap, + transcriptProteinTable, ): # list for all peptides and filtered peptides all_peptides = [] @@ -988,7 +716,6 @@ def make_predictions_from_variants( # list to hold dataframes for all predictions pred_dataframes = [] - prots = [ p for p in generator.generate_proteins_from_transcripts( @@ -1000,7 +727,7 @@ def make_predictions_from_variants( peptide_gen = generator.generate_peptides_from_proteins(prots, peplen) peptides_var = [x for x in peptide_gen] - peptides = [p for p in peptides_var if is_created_by_variant(p)] + peptides = [p for p in peptides_var if p.is_created_by_variant()] # filter out self peptides selfies = [str(p) for p in peptides if protein_db.exists(str(p))] @@ -1266,11 +993,10 @@ def __main__(): parser.add_argument("-a", "--alleles", help=" MHC Alleles", required=True, type=str) parser.add_argument( "-r", - "--reference", + "--genome_reference", help="Reference, retrieved information will be based on this ensembl version", required=False, - default="GRCh37", - choices=["GRCh37", "GRCh38"], + default="https://grch37.ensembl.org/", ) parser.add_argument( "-f", "--filter_self", help="Filter peptides against human proteom", required=False, action="store_true" @@ -1304,7 +1030,7 @@ def __main__(): parser.print_help() sys.exit("Provide at least one argument to epaa.py.") - filehandler = logging.FileHandler("{}_prediction.log".format(args.identifier)) + filehandler = logging.FileHandler(f"{args.identifier}_prediction.log") filehandler.setLevel(logging.DEBUG) filehandler.setFormatter(formatter) logger.addHandler(filehandler) @@ -1314,37 +1040,29 @@ def __main__(): metadata = [] proteins = [] - references = {"GRCh37": "http://feb2014.archive.ensembl.org", "GRCh38": "http://apr2018.archive.ensembl.org"} - global transcriptProteinMap + global transcriptProteinTable global transcriptSwissProtMap + # initialize MartsAdapter + # in previous version, these were the defaults "GRCh37": "http://feb2014.archive.ensembl.org" (broken) + # "GRCh38": "http://apr2018.archive.ensembl.org" (different dataset table scheme, could potentially be fixed on BiomartAdapter level if needed ) + ma = MartsAdapter(biomart=args.genome_reference) + # read in variants or peptides if args.peptides: logger.info("Running epaa for peptides...") peptides, metadata = read_peptide_input(args.peptides) else: - if args.somatic_mutations.endswith(".GSvar") or args.somatic_mutations.endswith(".tsv"): - logger.info("Running epaa for variants...") - variant_list, transcripts, metadata = read_GSvar(args.somatic_mutations) - elif args.somatic_mutations.endswith(".vcf"): + logger.info("Running epaa for variants...") + if args.somatic_mutations.endswith(".vcf"): variant_list, transcripts, metadata = read_vcf(args.somatic_mutations) - - transcripts = list(set(transcripts)) - transcriptProteinMap, transcriptSwissProtMap = get_protein_ids_for_transcripts( - ID_SYSTEM_USED, transcripts, references[args.reference], args.reference - ) + transcripts = list(set(transcripts)) + else: + raise ValueError("File is not in VCF format. Please provide a VCF file.") # get the alleles - if args.alleles.startswith("http"): - alleles = [Allele(a) for a in urllib.request.urlopen(args.alleles).read().decode("utf-8").splitlines()] - elif args.alleles.endswith(".txt"): - alleles = [Allele(a) for a in open(args.alleles, "r").read().splitlines()] - else: - alleles = [Allele(a) for a in args.alleles.split(";")] - - # initialize MartsAdapter, GRCh37 or GRCh38 based - ma = MartsAdapter(biomart=references[args.reference]) + alleles = [Allele(a) for a in args.alleles.split(";")] # create protein db instance for filtering self-peptides up_db = UniProtDB("sp") @@ -1359,7 +1077,7 @@ def __main__(): up_db.read_seqs(args.reference_proteome) selected_methods = [item.split("-")[0] if "mhcnuggets" not in item else item for item in args.tools.split(",")] - with open(args.versions, "r") as versions_file: + with open(args.versions) as versions_file: tool_version = [(row[0].split()[0], str(row[1])) for row in csv.reader(versions_file, delimiter=":")] # NOTE this needs to be updated, if a newer version will be available via epytope and should be used in the future tool_version.append(("syfpeithi", "1.0")) @@ -1391,7 +1109,7 @@ def __main__(): thresholds.update({"netmhc": 2, "netmhcpan": 2, "netmhcii": 10, "netmhciipan": 5}) if args.tool_thresholds: - with open(args.tool_thresholds, "r") as json_file: + with open(args.tool_thresholds) as json_file: threshold_file = json.load(json_file) for tool, thresh in threshold_file.items(): if tool in thresholds.keys(): @@ -1404,7 +1122,15 @@ def __main__(): pred_dataframes, statistics = make_predictions_from_peptides( peptides, methods, thresholds, args.use_affinity_thresholds, alleles, up_db, args.identifier, metadata ) + elif len(transcripts) == 0: + logger.warning(f"No transcripts found for variants in {args.somatic_mutations}") + pred_dataframes = [] + statistics = {} + all_peptides_filtered = [] + proteins = [] else: + # use function provided by epytope to retrieve protein IDs (different systems) for transcript IDs + transcriptProteinTable = ma.get_protein_ids_from_transcripts(transcripts, type=EIdentifierTypes.ENSEMBL) pred_dataframes, statistics, all_peptides_filtered, proteins = make_predictions_from_variants( variant_list, methods, @@ -1417,7 +1143,7 @@ def __main__(): up_db, args.identifier, metadata, - transcriptProteinMap, + transcriptProteinTable, ) # concat dataframes for all peptide lengths @@ -1496,7 +1222,7 @@ def __main__(): protein_quant = read_protein_quant(args.protein_quantification) first_entry = protein_quant[protein_quant.keys()[0]] for k in first_entry.keys(): - complete_df["{} log2 protein LFQ intensity".format(k)] = complete_df.apply( + complete_df[f"{k} log2 protein LFQ intensity"] = complete_df.apply( lambda row: create_quant_column_value_for_result(row, protein_quant, transcriptSwissProtMap, k), axis=1 ) # parse (differential) expression analysis results, annotate features (genes/transcripts) @@ -1505,7 +1231,7 @@ def __main__(): gene_id_lengths = {} col_name = "RNA expression (RPKM)" - with open(args.gene_reference, "r") as gene_list: + with open(args.gene_reference) as gene_list: for l in gene_list: ids = l.split("\t") gene_id_in_df = complete_df.iloc[1]["gene"] @@ -1548,7 +1274,7 @@ def __main__(): ) # write mutated protein sequences to fasta file if args.fasta_output and predictions_available: - with open("{}_prediction_proteins.fasta".format(args.identifier), "w") as protein_outfile: + with open(f"{args.identifier}_prediction_proteins.fasta", "w") as protein_outfile: for p in proteins: variants = [] for v in p.vars: @@ -1557,15 +1283,15 @@ def __main__(): cf = list(itertools.chain.from_iterable(c)) cds = ",".join([y.cdsMutationSyntax for y in set(cf)]) aas = ",".join([y.aaMutationSyntax for y in set(cf)]) - protein_outfile.write(">{}:{}:{}\n".format(p.transcript_id, aas, cds)) - protein_outfile.write("{}\n".format(str(p))) + protein_outfile.write(f">{p.transcript_id}:{aas}:{cds}\n") + protein_outfile.write(f"{str(p)}\n") complete_df["binder"] = complete_df[[col for col in complete_df.columns if "binder" in col]].any(axis=1) # write dataframe to tsv complete_df.fillna("") if predictions_available: - complete_df.to_csv("{}_prediction_result.tsv".format(args.identifier), "\t", index=False) + complete_df.to_csv(f"{args.identifier}_prediction_result.tsv", "\t", index=False) statistics["tool_thresholds"] = thresholds statistics["number_of_predictions"] = len(complete_df) @@ -1574,7 +1300,7 @@ def __main__(): statistics["number_of_unique_binders"] = list(set(binders)) statistics["number_of_unique_nonbinders"] = list(set(non_binders) - set(binders)) - with open("{}_report.json".format(args.identifier), "w") as json_out: + with open(f"{args.identifier}_report.json", "w") as json_out: json.dump(statistics, json_out) logger.info("Finished predictions at " + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) diff --git a/bin/gen_peptides.py b/bin/gen_peptides.py index 50613a0..d962ed3 100755 --- a/bin/gen_peptides.py +++ b/bin/gen_peptides.py @@ -1,13 +1,11 @@ #!/usr/bin/env python # Written by Sabrina Krakau, Christopher Mohr and released under the MIT license (2022). -import sys import argparse -import pandas as pd +import pandas as pd from Bio.SeqIO.FastaIO import SimpleFastaParser -from epytope.Core import Allele, Peptide, Protein, generate_peptides_from_proteins - +from epytope.Core import Protein, generate_peptides_from_proteins parser = argparse.ArgumentParser("Generating peptides from protein sequences.") parser.add_argument( diff --git a/bin/merge_jsons.py b/bin/merge_jsons.py index 75330ce..f6ebd34 100755 --- a/bin/merge_jsons.py +++ b/bin/merge_jsons.py @@ -2,10 +2,10 @@ # Written by Sabrina Krakau, Christopher Mohr, Gisela Gabernet and released under the MIT license (2022). +import argparse +import json import os import sys -import json -import argparse def __main__(): @@ -43,14 +43,14 @@ def combine_dicts(a, b): # read in json reports data = dict() if args.single_input: - with open(args.single_input, "r") as infile: + with open(args.single_input) as infile: json_content = json.load(infile) data = combine_dicts(data, json_content) else: for file in os.listdir(args.input): if file.endswith(".json"): - with open(os.path.join(args.input, file), "r") as infile: + with open(os.path.join(args.input, file)) as infile: json_content = json.load(infile) data = combine_dicts(data, json_content) @@ -69,7 +69,7 @@ def combine_dicts(a, b): data["number_of_predictions"] = sum(list(flatten(data["number_of_predictions"]))) data["number_of_variants"] = sum(list(flatten(data["number_of_variants"]))) - with open("{}_prediction_report.json".format(args.prefix), "w") as outfile: + with open(f"{args.prefix}_prediction_report.json", "w") as outfile: json.dump(data, outfile) diff --git a/bin/split_peptides.py b/bin/split_peptides.py index 5c96dad..4e31134 100755 --- a/bin/split_peptides.py +++ b/bin/split_peptides.py @@ -2,9 +2,8 @@ # Written by Sabrina Krakau, Christopher Mohr and released under the MIT license (2022). -import math import argparse - +import math parser = argparse.ArgumentParser("Split peptides input file.") parser.add_argument("-i", "--input", metavar="FILE", type=str, help="Input file containing peptides.") @@ -17,13 +16,13 @@ ) args = parser.parse_args() -with open(args.input, "r") as infile: +with open(args.input) as infile: tot_size = sum([1 for _ in infile]) - 1 n = int(min(math.ceil(float(tot_size) / args.min_size), args.max_chunks)) h = int(max(args.min_size, math.ceil(float(tot_size) / n))) -with open(args.input, "r") as infile: +with open(args.input) as infile: header = next(infile) for chunk in range(n): with open(args.output_base + ".chunk_" + str(chunk) + ".tsv", "w") as outfile: diff --git a/bin/split_vcf_by_variants.py b/bin/split_vcf_by_variants.py index 5c389f1..fade55e 100755 --- a/bin/split_vcf_by_variants.py +++ b/bin/split_vcf_by_variants.py @@ -2,14 +2,13 @@ # Written by Christopher Mohr and released under the MIT license (2022). import argparse -import logging import csv +import logging import os -from typing import Optional def determine_split_size(input_file, size): - with open(input_file, "r") as variants: + with open(input_file) as variants: input_lines = variants.readlines() num_variants = sum(1 for i in input_lines if not i.startswith("#")) if not size: @@ -57,7 +56,7 @@ def main(): metadata = "" var_group = "" - with open(args.input, "r") as input_file: + with open(args.input) as input_file: vcf_file = csv.reader(input_file, delimiter="\t") for line in vcf_file: diff --git a/conf/base.config b/conf/base.config index 80b52ab..899e529 100644 --- a/conf/base.config +++ b/conf/base.config @@ -11,9 +11,9 @@ process { - cpus = { check_max( 1 * task.attempt, 'cpus' ) } - memory = { check_max( 7.GB * task.attempt, 'memory' ) } - time = { check_max( 4.h * task.attempt, 'time' ) } + cpus = { 1 * task.attempt } + memory = { 6.GB * task.attempt } + time = { 4.h * task.attempt } errorStrategy = { task.exitStatus in ((130..145) + 104) ? 'retry' : 'finish' } maxRetries = 3 @@ -21,30 +21,30 @@ process { // Process-specific resource requirements withLabel:process_single { - cpus = { check_max( 1 , 'cpus' ) } - memory = { check_max( 6.GB * task.attempt, 'memory' ) } - time = { check_max( 4.h * task.attempt, 'time' ) } + cpus = { 1 } + memory = { 6.GB * task.attempt } + time = { 4.h * task.attempt } } withLabel:process_low { - cpus = { check_max( 2 * task.attempt, 'cpus' ) } - memory = { check_max( 12.GB * task.attempt, 'memory' ) } - time = { check_max( 4.h * task.attempt, 'time' ) } + cpus = { 2 * task.attempt } + memory = { 12.GB * task.attempt } + time = { 4.h * task.attempt } } withLabel:process_medium { - cpus = { check_max( 6 * task.attempt, 'cpus' ) } - memory = { check_max( 36.GB * task.attempt, 'memory' ) } - time = { check_max( 8.h * task.attempt, 'time' ) } + cpus = { 6 * task.attempt } + memory = { 36.GB * task.attempt } + time = { 8.h * task.attempt } } withLabel:process_high { - cpus = { check_max( 12 * task.attempt, 'cpus' ) } - memory = { check_max( 72.GB * task.attempt, 'memory' ) } - time = { check_max( 16.h * task.attempt, 'time' ) } + cpus = { 12 * task.attempt } + memory = { 72.GB * task.attempt } + time = { 16.h * task.attempt } } withLabel:process_long { - time = { check_max( 20.h * task.attempt, 'time' ) } + time = { 20.h * task.attempt } } withLabel:process_high_memory { - memory = { check_max( 200.GB * task.attempt, 'memory' ) } + memory = { 200.GB * task.attempt } } withLabel:error_ignore { errorStrategy = 'ignore' @@ -53,7 +53,4 @@ process { errorStrategy = 'retry' maxRetries = 2 } - withName:CUSTOM_DUMPSOFTWAREVERSIONS { - cache = false - } } diff --git a/conf/igenomes_ignored.config b/conf/igenomes_ignored.config new file mode 100644 index 0000000..b4034d8 --- /dev/null +++ b/conf/igenomes_ignored.config @@ -0,0 +1,9 @@ +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Nextflow config file for iGenomes paths +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + Empty genomes dictionary to use when igenomes is ignored. +---------------------------------------------------------------------------------------- +*/ + +params.genomes = [:] diff --git a/conf/modules.config b/conf/modules.config index e655c5a..fd11ac3 100644 --- a/conf/modules.config +++ b/conf/modules.config @@ -10,6 +10,8 @@ ---------------------------------------------------------------------------------------- */ +def genome_reference = params.genome_reference.toLowerCase() + process { publishDir = [ @@ -18,26 +20,15 @@ process { saveAs: { filename -> filename.equals('versions.yml') ? null : filename } ] - withName: MULTIQC { - ext.args = '' - } - - withName: SAMPLESHEET_CHECK { + withName: 'MULTIQC' { + ext.args = { params.multiqc_title ? "--title \"$params.multiqc_title\"" : '' } publishDir = [ - path: { "${params.outdir}/pipeline_info" }, + path: { "${params.outdir}/multiqc" }, mode: params.publish_dir_mode, saveAs: { filename -> filename.equals('versions.yml') ? null : filename } ] } - withName: CUSTOM_DUMPSOFTWAREVERSIONS { - publishDir = [ - path: { "${params.outdir}/pipeline_info" }, - mode: params.publish_dir_mode, - pattern: '*_versions.yml' - ] - } - withName: EPYTOPE_CHECK_REQUESTED_MODELS { publishDir = [ path: { "${params.outdir}/reports" }, @@ -99,30 +90,45 @@ process { } withName: EPYTOPE_PEPTIDE_PREDICTION_PROTEIN { + // Argument list needs to end with --peptides + ext.args = [ + genome_reference != 'grch37' & genome_reference != 'grch38' ? "--genome_reference '${genome_reference}'" : '', + genome_reference == 'grch37' ? "--genome_reference 'https://grch37.ensembl.org/'" : '', + genome_reference == 'grch38' ? "--genome_reference 'https://www.ensembl.org'" : '', + '--peptides' + ].join(' ').trim() publishDir = [ path: { "${params.outdir}/split_predictions/${meta.sample}" }, mode: params.publish_dir_mode ] - // Argument list needs to end with --peptides - ext.args = "--reference ${params.genome_version} --peptides" } withName: EPYTOPE_PEPTIDE_PREDICTION_PEP { + // Argument list needs to end with --peptides + ext.args = [ + genome_reference != 'grch37' & genome_reference != 'grch38' ? "--genome_reference '${genome_reference}'" : '', + genome_reference == 'grch37' ? "--genome_reference 'https://grch37.ensembl.org/'" : '', + genome_reference == 'grch38' ? "--genome_reference 'https://www.ensembl.org'" : '', + '--peptides' + ].join(' ').trim() publishDir = [ path: { "${params.outdir}/split_predictions/${meta.sample}" }, mode: params.publish_dir_mode ] - // Argument list needs to end with --peptides - ext.args = "--reference ${params.genome_version} --peptides" } withName: EPYTOPE_PEPTIDE_PREDICTION_VAR { + // Argument list needs to end with --somatic_mutation + ext.args = [ + genome_reference != 'grch37' & genome_reference != 'grch38' ? "--genome_reference '${genome_reference}'" : '', + genome_reference == 'grch37' ? "--genome_reference 'https://grch37.ensembl.org/'" : '', + genome_reference == 'grch38' ? "--genome_reference 'https://www.ensembl.org'" : '', + '--somatic_mutation' + ].join(' ').trim() publishDir = [ path: { "${params.outdir}/split_predictions/${meta.sample}" }, mode: params.publish_dir_mode ] - // Argument list needs to end with --somatic_mutation - ext.args = "--reference ${params.genome_version} --somatic_mutation" } withName: MERGE_JSON_SINGLE { @@ -154,13 +160,6 @@ process { ] } - withName: CSVTK_SPLIT { - publishDir = [ - path: { "${params.outdir}/split_input/${meta.sample}" }, - mode: params.publish_dir_mode - ] - } - withName: GET_PREDICTION_VERSIONS { publishDir = [ path: { "${params.outdir}/reports" }, @@ -208,4 +207,5 @@ process { mode: params.publish_dir_mode ] } + } diff --git a/conf/test.config b/conf/test.config index 681012d..af711be 100644 --- a/conf/test.config +++ b/conf/test.config @@ -10,18 +10,20 @@ ---------------------------------------------------------------------------------------- */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '2.h' + ] +} + params { config_profile_name = 'Test profile' config_profile_description = 'Minimal test dataset to check pipeline function' // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_variants.csv' - schema_ignore_params = 'genomes,input_paths' - - // Limit resources so that this can run on GitHub Actions - max_cpus = 2 - max_memory = '6.GB' - max_time = '6.h' + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_variants.csv' } diff --git a/conf/test_full.config b/conf/test_full.config index f1fa9ef..0ed2aa9 100644 --- a/conf/test_full.config +++ b/conf/test_full.config @@ -15,7 +15,7 @@ params { config_profile_description = 'Full test dataset to check pipeline function' // Input data for full size test - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_full_test.csv' - schema_ignore_params = 'genomes,input_paths' + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_full_test.csv' tools = 'syfpeithi,mhcflurry,mhcnuggets-class-1,mhcnuggets-class-2' + } diff --git a/conf/test_grch38.config b/conf/test_grch38.config new file mode 100644 index 0000000..8f81a1d --- /dev/null +++ b/conf/test_grch38.config @@ -0,0 +1,24 @@ +/* + * ------------------------------------------------- + * Nextflow config file for running tests + * ------------------------------------------------- + * Defines bundled input files and everything required + * to run a fast and simple test. Use as follows: + * nextflow run nf-core/epitopeprediction -profile test_grch38, --outdir + */ + +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + +params { + config_profile_name = 'Test GRCh38 profile' + config_profile_description = 'Minimal test dataset to check pipeline function' + + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_variants.csv' + genome_reference = 'grch38' +} diff --git a/conf/test_grch38_variant_tsv.config b/conf/test_grch38_variant_tsv.config deleted file mode 100644 index 61d804a..0000000 --- a/conf/test_grch38_variant_tsv.config +++ /dev/null @@ -1,18 +0,0 @@ -/* - * ------------------------------------------------- - * Nextflow config file for running tests - * ------------------------------------------------- - * Defines bundled input files and everything required - * to run a fast and simple test. Use as follows: - * nextflow run nf-core/epitopeprediction -profile test_grch38_variant_tsv, --outdir - */ - -params { - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h - - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_variants_tab.csv' - genome_version = 'GRCh38' -} diff --git a/conf/test_mhcflurry.config b/conf/test_mhcflurry.config index 7558693..7d92a48 100644 --- a/conf/test_mhcflurry.config +++ b/conf/test_mhcflurry.config @@ -7,15 +7,18 @@ * nextflow run nf-core/epitopeprediction -profile test_mhcflurry, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { config_profile_name = 'Test MHCflurry profile' config_profile_description = 'Minimal test dataset to check pipeline function' - // Limit resources so that this can run on GitHub Actions - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_variants.csv' + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_variants.csv' tools = 'mhcflurry' } diff --git a/conf/test_mhcnuggets.config b/conf/test_mhcnuggets.config index 90774b5..2f3287e 100644 --- a/conf/test_mhcnuggets.config +++ b/conf/test_mhcnuggets.config @@ -7,15 +7,18 @@ * nextflow run nf-core/epitopeprediction -profile test_mhcnuggets, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { config_profile_name = 'Test MHCnuggets profile' config_profile_description = 'Minimal test dataset to check pipeline function' - // Limit resources so that this can run on GitHub Actions - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_variants_class1_and_2.csv' + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_variants_class1_and_2.csv' tools = 'mhcnuggets-class-1,mhcnuggets-class-2' } diff --git a/conf/test_netmhc.config b/conf/test_netmhc.config index 1ad878a..cc34d05 100644 --- a/conf/test_netmhc.config +++ b/conf/test_netmhc.config @@ -7,17 +7,19 @@ * nextflow run nf-core/epitopeprediction -profile test_netmhc, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { config_profile_name = 'NetMHC Test Profile' config_profile_description = 'Peptide list based test profile for NetMHC' - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h - - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_peptides.csv' - + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_peptides.csv' tools = 'netmhc-4.0' netmhc_path = './non-free/netmhc.tar.gz' } diff --git a/conf/test_netmhcii.config b/conf/test_netmhcii.config index 2cc2804..4c60aa8 100644 --- a/conf/test_netmhcii.config +++ b/conf/test_netmhcii.config @@ -7,17 +7,19 @@ * nextflow run nf-core/epitopeprediction -profile test_netmhcii, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { config_profile_name = 'NetMHCII Test Profile' config_profile_description = 'Peptide list based test profile for NetMHCII' - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h - - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_peptides_class2.csv' - + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_peptides_class2.csv' tools = 'netmhcii-2.2' netmhcii_path = './non-free/netmhcii.tar.Z' } diff --git a/conf/test_netmhciipan.config b/conf/test_netmhciipan.config index 07b2781..fa9cec1 100644 --- a/conf/test_netmhciipan.config +++ b/conf/test_netmhciipan.config @@ -7,17 +7,19 @@ * nextflow run nf-core/epitopeprediction -profile test_netmhciipan, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { config_profile_name = 'NetMHCIIpan Test Profile' config_profile_description = 'Peptide list based test profile for NetMHCIIpan' - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h - - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_peptides_class2.csv' - + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_peptides_class2.csv' tools = 'netmhciipan-4.1' netmhciipan_path = './non-free/netmhciipan.tar.gz' } diff --git a/conf/test_netmhcpan.config b/conf/test_netmhcpan.config index 2e9fb4f..38b669b 100644 --- a/conf/test_netmhcpan.config +++ b/conf/test_netmhcpan.config @@ -7,17 +7,19 @@ * nextflow run nf-core/epitopeprediction -profile test_netmhcpan, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { config_profile_name = 'NetMHCpan Test Profile' config_profile_description = 'Peptide list based test profile for NetMHCpan' - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h - - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_peptides.csv' - + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_peptides.csv' tools = 'netmhcpan-4.0' netmhcpan_path = './non-free/netmhcpan.tar.gz' } diff --git a/conf/test_peptides.config b/conf/test_peptides.config index 74c98f3..dac6f25 100644 --- a/conf/test_peptides.config +++ b/conf/test_peptides.config @@ -7,11 +7,17 @@ * nextflow run nf-core/epitopeprediction -profile test_peptides, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h + config_profile_name = 'Test Profile of peptide list input' + config_profile_description = 'Peptide list based test profile for mouse alleles by SYFPEITHI (default)' - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_peptides.csv' + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_peptides.csv' } diff --git a/conf/test_peptides_h2.config b/conf/test_peptides_h2.config index 26a4e00..65adc49 100644 --- a/conf/test_peptides_h2.config +++ b/conf/test_peptides_h2.config @@ -7,12 +7,18 @@ * nextflow run nf-core/epitopeprediction -profile test_peptides_h2, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h + config_profile_name = 'Test Profile of mouse MHC binding predictions' + config_profile_description = 'Peptide list based test profile for mouse alleles by MHCnuggets' - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_peptides_mouse.csv' + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_peptides_mouse.csv' tools = 'mhcnuggets-class-1' } diff --git a/conf/test_proteins.config b/conf/test_proteins.config index 7515999..31690e0 100644 --- a/conf/test_proteins.config +++ b/conf/test_proteins.config @@ -7,11 +7,17 @@ * nextflow run nf-core/epitopeprediction -profile test_proteins, --outdir */ +process { + resourceLimits = [ + cpus: 2, + memory: '6.GB', + time: '48.h' + ] +} + params { - max_cpus = 2 - max_memory = 6.GB - max_time = 4.h + config_profile_name = 'Test Profile of protein input' + config_profile_description = 'Protein input test profile' - // Input data - input = 'https://github.com/nf-core/test-datasets/raw/epitopeprediction/testdata/sample_sheets/sample_sheet_proteins.csv' + input = params.pipelines_testdata_base_path + 'epitopeprediction/testdata/sample_sheets/sample_sheet_proteins.csv' } diff --git a/conf/test_variant_tsv.config b/conf/test_variant_tsv.config deleted file mode 100644 index f54d1bc..0000000 --- a/conf/test_variant_tsv.config +++ /dev/null @@ -1,17 +0,0 @@ -/* - * ------------------------------------------------- - * Nextflow config file for running tests - * ------------------------------------------------- - * Defines bundled input files and everything required - * to run a fast and simple test. Use as follows: - * nextflow run nf-core/epitopeprediction -profile test_variant_tsv, --outdir - */ - -params { - max_cpus = 2 - max_memory = 6.GB - max_time = 48.h - - // Input data - input = 'https://raw.githubusercontent.com/nf-core/test-datasets/epitopeprediction/testdata/sample_sheets/sample_sheet_variants_tab.csv' -} diff --git a/docs/images/mqc_fastqc_adapter.png b/docs/images/mqc_fastqc_adapter.png deleted file mode 100755 index 361d0e4..0000000 Binary files a/docs/images/mqc_fastqc_adapter.png and /dev/null differ diff --git a/docs/images/mqc_fastqc_counts.png b/docs/images/mqc_fastqc_counts.png deleted file mode 100755 index cb39ebb..0000000 Binary files a/docs/images/mqc_fastqc_counts.png and /dev/null differ diff --git a/docs/images/mqc_fastqc_quality.png b/docs/images/mqc_fastqc_quality.png deleted file mode 100755 index a4b89bf..0000000 Binary files a/docs/images/mqc_fastqc_quality.png and /dev/null differ diff --git a/docs/images/nf-core-epitopeprediction_logo_dark.png b/docs/images/nf-core-epitopeprediction_logo_dark.png index 7c16270..42629eb 100644 Binary files a/docs/images/nf-core-epitopeprediction_logo_dark.png and b/docs/images/nf-core-epitopeprediction_logo_dark.png differ diff --git a/docs/images/nf-core-epitopeprediction_logo_light.png b/docs/images/nf-core-epitopeprediction_logo_light.png index 40ba75d..bbaf60a 100644 Binary files a/docs/images/nf-core-epitopeprediction_logo_light.png and b/docs/images/nf-core-epitopeprediction_logo_light.png differ diff --git a/docs/output.md b/docs/output.md index ebb2f96..bda154a 100644 --- a/docs/output.md +++ b/docs/output.md @@ -97,6 +97,7 @@ When running the pipeline using the `--show_supported_models` parameter, informa - Reports generated by Nextflow: `execution_report.html`, `execution_timeline.html`, `execution_trace.txt` and `pipeline_dag.dot`/`pipeline_dag.svg`. - Reports generated by the pipeline: `pipeline_report.html`, `pipeline_report.txt` and `software_versions.yml`. The `pipeline_report*` files will only be present if the `--email` / `--email_on_fail` parameter's are used when running the pipeline. - Reformatted samplesheet files used as input to the pipeline: `samplesheet.valid.csv`. + - Parameters used by the pipeline run: `params.json`. diff --git a/docs/usage.md b/docs/usage.md index a6a0025..b29a587 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -16,12 +16,15 @@ You will need to create a samplesheet with information about the samples you wou ### Input Formats -The pipeline currently accepts three different types of input that are genomic variants, peptides and proteins. The supported file formats for genomic variants are `.vcf`, `.vcf.gz` and `tsv`. - -:warning: Please note that genomic variants have to be annotated. Currently, we support variants that have been annotated using [SnpEff](http://pcingola.github.io/SnpEff/). Support for [VEP](https://www.ensembl.org/info/docs/tools/vep/index.html) will be available with one of the upcoming versions. +The pipeline currently accepts three different types of input that are genomic variants, peptides and proteins. #### Genomic variants +The supported file formats for genomic variants are `.vcf`, `.vcf.gz`. + +> [!IMPORTANT] +> Please note that genomic variants have to be annotated. Currently, we support variants that have been annotated using [SnpEff](http://pcingola.> github.io/SnpEff/) and [VEP](https://www.ensembl.org/info/docs/tools/vep/index.html). + `tsv` files with genomic variants have to provide the following columns: ```console @@ -32,6 +35,13 @@ chr1 12954870 12954870 C T . 0 NORMAL:414,TUMOR:8 . missense_variant 0.5 transcr ``` +For genomic variants, reference information from `Ensembl BioMart` is used. The default database version is the most recent `GRCh37` version. If you want to do the predictions based on `GRCh38` as the reference genome, please specify `--genome_reference grch38` in your pipeline call. + +You can also specify valid `Ensembl BioMart` archive version urls as `--genome_reference` value, e.g. [the archive version of December 2021](http://dec2021.archive.ensembl.org/). + +> [!IMPORTANT] +> Please note that old archive versions are regularly retired, therefore it might be possible that a used version is not available anymore at a later point. + #### Peptide sequences Peptide sequences have to be provided in `tsv` format with two mandatory columns `id` and `sequence`. Additional columns will be added as metadata to results. @@ -72,7 +82,7 @@ GBM_2,alleles.txt,I,gbm_2_variants.vcf | `sample` | Custom sample name. This entry will be identical for multiple sequencing libraries/runs from the same sample. Spaces in sample names are automatically converted to underscores (`_`). | | `alleles` | A string that consists of the patient's alleles (separated by ";"), or a full path to a allele ".txt" file where each allele is saved on a row. | | `mhc_class` | Specifies the MHC class for which the prediction should be performed. Valid values are: `I`, `II` and `H-2` (mouse). | -| `filename` | Full path to a variant/peptide or protein file (".vcf", ".vcf.gz", "tsv", "fasta", or "GSvar"). | +| `filename` | Full path to a variant/peptide or protein file (".vcf", ".vcf.gz", "tsv" or "fasta"). | An [example samplesheet](../assets/samplesheet.csv) has been provided with the pipeline. @@ -81,7 +91,7 @@ An [example samplesheet](../assets/samplesheet.csv) has been provided with the p The typical command for running the pipeline is as follows: ```bash -nextflow run nf-core/epitopeprediction --input ./samplesheet.csv --outdir ./results --genome GRCh37 -profile docker +nextflow run nf-core/epitopeprediction --input ./samplesheet.csv --outdir ./results -profile docker ``` This will launch the pipeline with the `docker` configuration profile and default options (`syfpeithi` by default). See below for more information about profiles. @@ -99,7 +109,8 @@ If you wish to repeatedly use the same parameters for multiple runs, rather than Pipeline settings can be provided in a `yaml` or `json` file via `-params-file `. -> ⚠️ Do not use `-c ` to specify parameters as this will result in errors. Custom config files specified with `-c` must only be used for [tuning process resource specifications](https://nf-co.re/docs/usage/configuration#tuning-workflow-resources), other infrastructural tweaks (such as output directories), or module arguments (args). +> [!WARNING] +> Do not use `-c ` to specify parameters as this will result in errors. Custom config files specified with `-c` must only be used for [tuning process resource specifications](https://nf-co.re/docs/usage/configuration#tuning-workflow-resources), other infrastructural tweaks (such as output directories), or module arguments (args). The above pipeline run specified with a params file in yaml format: @@ -107,12 +118,11 @@ The above pipeline run specified with a params file in yaml format: nextflow run nf-core/epitopeprediction -profile docker -params-file params.yaml ``` -with `params.yaml` containing: +with: -```yaml +```yaml title="params.yaml" input: './samplesheet.csv' outdir: './results/' -genome: 'GRCh37' <...> ``` @@ -147,13 +157,16 @@ First, go to the [nf-core/epitopeprediction releases page](https://github.com/nf This version number will be logged in reports when you run the pipeline, so that you'll know what you used when you look back in the future. For example, at the bottom of the MultiQC reports. -To further assist in reproducbility, you can use share and re-use [parameter files](#running-the-pipeline) to repeat pipeline runs with the same settings without having to write out a command with every single parameter. +To further assist in reproducibility, you can use share and re-use [parameter files](#running-the-pipeline) to repeat pipeline runs with the same settings without having to write out a command with every single parameter. -> 💡 If you wish to share such profile (such as upload as supplementary material for academic publications), make sure to NOT include cluster specific paths to files, nor institutional specific profiles. +:::tip +If you wish to share such profile (such as upload as supplementary material for academic publications), make sure to NOT include cluster specific paths to files, nor institutional specific profiles. +::: ## Core Nextflow arguments -> **NB:** These options are part of Nextflow and use a _single_ hyphen (pipeline parameters use a double-hyphen). +> [!NOTE] +> These options are part of Nextflow and use a _single_ hyphen (pipeline parameters use a double-hyphen). ### `-profile` @@ -161,7 +174,9 @@ Use this parameter to choose a configuration profile. Profiles can give configur Several generic profiles are bundled with the pipeline which instruct the pipeline to use software packaged using different methods (Docker, Singularity, Podman, Shifter, Charliecloud, Apptainer, Conda) - see below. -> We highly recommend the use of Docker or Singularity containers for full pipeline reproducibility, however, Conda is also supported as an alternative. +:::info +We highly recommend the use of Docker or Singularity containers for full pipeline reproducibility, however when this is not possible, Conda is also supported. +::: The pipeline dynamically loads configurations from [https://github.com/nf-core/configs](https://github.com/nf-core/configs) when it runs, making multiple config profiles for various institutional clusters available at run time. For more information, and to see if your system is available in these configs, please see the [nf-core/configs documentation](https://github.com/nf-core/configs#documentation). @@ -185,6 +200,8 @@ If `-profile` is not specified, the pipeline will run locally and expect all sof - A generic configuration profile to be used with [Charliecloud](https://hpc.github.io/charliecloud/) - `apptainer` - A generic configuration profile to be used with [Apptainer](https://apptainer.org/) +- `wave` + - A generic configuration profile to enable [Wave](https://seqera.io/wave/) containers. Use together with one of the above (requires Nextflow ` 24.03.0-edge` or later). - `conda` - A generic configuration profile to be used with [Conda](https://conda.io/docs/). Please only use Conda as a last resort i.e. when it's not possible to run the pipeline with Docker, Singularity, Podman, Shifter, Charliecloud, or Apptainer. @@ -226,14 +243,6 @@ See the main [Nextflow documentation](https://www.nextflow.io/docs/latest/config If you have any questions or issues, please send us a message on [Slack](https://nf-co.re/join/slack) on the [`#configs` channel](https://nfcore.slack.com/channels/configs). -## Azure Resource Requests - -To be used with the `azurebatch` profile by specifying the `-profile azurebatch`. -We recommend providing a compute `params.vm_type` of `Standard_D16_v3` VMs by default but these options can be changed if required. - -Note that the choice of VM size depends on your quota and the overall workload during the analysis. -For a thorough list, please refer the [Azure Sizes for virtual machines in Azure](https://docs.microsoft.com/en-us/azure/virtual-machines/sizes). - ## Running in the background Nextflow handles job submissions and supervises the running jobs. The Nextflow process must run until the pipeline is finished. diff --git a/lib/NfcoreTemplate.groovy b/lib/NfcoreTemplate.groovy deleted file mode 100755 index 408951a..0000000 --- a/lib/NfcoreTemplate.groovy +++ /dev/null @@ -1,336 +0,0 @@ -// -// This file holds several functions used within the nf-core pipeline template. -// - -import org.yaml.snakeyaml.Yaml - -class NfcoreTemplate { - - // - // Check AWS Batch related parameters have been specified correctly - // - public static void awsBatch(workflow, params) { - if (workflow.profile.contains('awsbatch')) { - // Check params.awsqueue and params.awsregion have been set if running on AWSBatch - assert (params.awsqueue && params.awsregion) : "Specify correct --awsqueue and --awsregion parameters on AWSBatch!" - // Check outdir paths to be S3 buckets if running on AWSBatch - assert params.outdir.startsWith('s3:') : "Outdir not on S3 - specify S3 Bucket to run on AWSBatch!" - } - } - - // - // Warn if a -profile or Nextflow config has not been provided to run the pipeline - // - public static void checkConfigProvided(workflow, log) { - if (workflow.profile == 'standard' && workflow.configFiles.size() <= 1) { - log.warn "[$workflow.manifest.name] You are attempting to run the pipeline without any custom configuration!\n\n" + - "This will be dependent on your local compute environment but can be achieved via one or more of the following:\n" + - " (1) Using an existing pipeline profile e.g. `-profile docker` or `-profile singularity`\n" + - " (2) Using an existing nf-core/configs for your Institution e.g. `-profile crick` or `-profile uppmax`\n" + - " (3) Using your own local custom config e.g. `-c /path/to/your/custom.config`\n\n" + - "Please refer to the quick start section and usage docs for the pipeline.\n " - } - } - - // - // Generate version string - // - public static String version(workflow) { - String version_string = "" - - if (workflow.manifest.version) { - def prefix_v = workflow.manifest.version[0] != 'v' ? 'v' : '' - version_string += "${prefix_v}${workflow.manifest.version}" - } - - if (workflow.commitId) { - def git_shortsha = workflow.commitId.substring(0, 7) - version_string += "-g${git_shortsha}" - } - - return version_string - } - - // - // Construct and send completion email - // - public static void email(workflow, params, summary_params, projectDir, log, multiqc_report=[]) { - - // Set up the e-mail variables - def subject = "[$workflow.manifest.name] Successful: $workflow.runName" - if (!workflow.success) { - subject = "[$workflow.manifest.name] FAILED: $workflow.runName" - } - - def summary = [:] - for (group in summary_params.keySet()) { - summary << summary_params[group] - } - - def misc_fields = [:] - misc_fields['Date Started'] = workflow.start - misc_fields['Date Completed'] = workflow.complete - misc_fields['Pipeline script file path'] = workflow.scriptFile - misc_fields['Pipeline script hash ID'] = workflow.scriptId - if (workflow.repository) misc_fields['Pipeline repository Git URL'] = workflow.repository - if (workflow.commitId) misc_fields['Pipeline repository Git Commit'] = workflow.commitId - if (workflow.revision) misc_fields['Pipeline Git branch/tag'] = workflow.revision - misc_fields['Nextflow Version'] = workflow.nextflow.version - misc_fields['Nextflow Build'] = workflow.nextflow.build - misc_fields['Nextflow Compile Timestamp'] = workflow.nextflow.timestamp - - def email_fields = [:] - email_fields['version'] = NfcoreTemplate.version(workflow) - email_fields['runName'] = workflow.runName - email_fields['success'] = workflow.success - email_fields['dateComplete'] = workflow.complete - email_fields['duration'] = workflow.duration - email_fields['exitStatus'] = workflow.exitStatus - email_fields['errorMessage'] = (workflow.errorMessage ?: 'None') - email_fields['errorReport'] = (workflow.errorReport ?: 'None') - email_fields['commandLine'] = workflow.commandLine - email_fields['projectDir'] = workflow.projectDir - email_fields['summary'] = summary << misc_fields - - // On success try attach the multiqc report - def mqc_report = null - try { - if (workflow.success) { - mqc_report = multiqc_report.getVal() - if (mqc_report.getClass() == ArrayList && mqc_report.size() >= 1) { - if (mqc_report.size() > 1) { - log.warn "[$workflow.manifest.name] Found multiple reports from process 'MULTIQC', will use only one" - } - mqc_report = mqc_report[0] - } - } - } catch (all) { - if (multiqc_report) { - log.warn "[$workflow.manifest.name] Could not attach MultiQC report to summary email" - } - } - - // Check if we are only sending emails on failure - def email_address = params.email - if (!params.email && params.email_on_fail && !workflow.success) { - email_address = params.email_on_fail - } - - // Render the TXT template - def engine = new groovy.text.GStringTemplateEngine() - def tf = new File("$projectDir/assets/email_template.txt") - def txt_template = engine.createTemplate(tf).make(email_fields) - def email_txt = txt_template.toString() - - // Render the HTML template - def hf = new File("$projectDir/assets/email_template.html") - def html_template = engine.createTemplate(hf).make(email_fields) - def email_html = html_template.toString() - - // Render the sendmail template - def max_multiqc_email_size = (params.containsKey('max_multiqc_email_size') ? params.max_multiqc_email_size : 0) as nextflow.util.MemoryUnit - def smail_fields = [ email: email_address, subject: subject, email_txt: email_txt, email_html: email_html, projectDir: "$projectDir", mqcFile: mqc_report, mqcMaxSize: max_multiqc_email_size.toBytes() ] - def sf = new File("$projectDir/assets/sendmail_template.txt") - def sendmail_template = engine.createTemplate(sf).make(smail_fields) - def sendmail_html = sendmail_template.toString() - - // Send the HTML e-mail - Map colors = logColours(params.monochrome_logs) - if (email_address) { - try { - if (params.plaintext_email) { throw GroovyException('Send plaintext e-mail, not HTML') } - // Try to send HTML e-mail using sendmail - [ 'sendmail', '-t' ].execute() << sendmail_html - log.info "-${colors.purple}[$workflow.manifest.name]${colors.green} Sent summary e-mail to $email_address (sendmail)-" - } catch (all) { - // Catch failures and try with plaintext - def mail_cmd = [ 'mail', '-s', subject, '--content-type=text/html', email_address ] - if ( mqc_report.size() <= max_multiqc_email_size.toBytes() ) { - mail_cmd += [ '-A', mqc_report ] - } - mail_cmd.execute() << email_html - log.info "-${colors.purple}[$workflow.manifest.name]${colors.green} Sent summary e-mail to $email_address (mail)-" - } - } - - // Write summary e-mail HTML to a file - def output_d = new File("${params.outdir}/pipeline_info/") - if (!output_d.exists()) { - output_d.mkdirs() - } - def output_hf = new File(output_d, "pipeline_report.html") - output_hf.withWriter { w -> w << email_html } - def output_tf = new File(output_d, "pipeline_report.txt") - output_tf.withWriter { w -> w << email_txt } - } - - // - // Construct and send a notification to a web server as JSON - // e.g. Microsoft Teams and Slack - // - public static void IM_notification(workflow, params, summary_params, projectDir, log) { - def hook_url = params.hook_url - - def summary = [:] - for (group in summary_params.keySet()) { - summary << summary_params[group] - } - - def misc_fields = [:] - misc_fields['start'] = workflow.start - misc_fields['complete'] = workflow.complete - misc_fields['scriptfile'] = workflow.scriptFile - misc_fields['scriptid'] = workflow.scriptId - if (workflow.repository) misc_fields['repository'] = workflow.repository - if (workflow.commitId) misc_fields['commitid'] = workflow.commitId - if (workflow.revision) misc_fields['revision'] = workflow.revision - misc_fields['nxf_version'] = workflow.nextflow.version - misc_fields['nxf_build'] = workflow.nextflow.build - misc_fields['nxf_timestamp'] = workflow.nextflow.timestamp - - def msg_fields = [:] - msg_fields['version'] = NfcoreTemplate.version(workflow) - msg_fields['runName'] = workflow.runName - msg_fields['success'] = workflow.success - msg_fields['dateComplete'] = workflow.complete - msg_fields['duration'] = workflow.duration - msg_fields['exitStatus'] = workflow.exitStatus - msg_fields['errorMessage'] = (workflow.errorMessage ?: 'None') - msg_fields['errorReport'] = (workflow.errorReport ?: 'None') - msg_fields['commandLine'] = workflow.commandLine.replaceFirst(/ +--hook_url +[^ ]+/, "") - msg_fields['projectDir'] = workflow.projectDir - msg_fields['summary'] = summary << misc_fields - - // Render the JSON template - def engine = new groovy.text.GStringTemplateEngine() - // Different JSON depending on the service provider - // Defaults to "Adaptive Cards" (https://adaptivecards.io), except Slack which has its own format - def json_path = hook_url.contains("hooks.slack.com") ? "slackreport.json" : "adaptivecard.json" - def hf = new File("$projectDir/assets/${json_path}") - def json_template = engine.createTemplate(hf).make(msg_fields) - def json_message = json_template.toString() - - // POST - def post = new URL(hook_url).openConnection(); - post.setRequestMethod("POST") - post.setDoOutput(true) - post.setRequestProperty("Content-Type", "application/json") - post.getOutputStream().write(json_message.getBytes("UTF-8")); - def postRC = post.getResponseCode(); - if (! postRC.equals(200)) { - log.warn(post.getErrorStream().getText()); - } - } - - // - // Print pipeline summary on completion - // - public static void summary(workflow, params, log) { - Map colors = logColours(params.monochrome_logs) - if (workflow.success) { - if (workflow.stats.ignoredCount == 0) { - log.info "-${colors.purple}[$workflow.manifest.name]${colors.green} Pipeline completed successfully${colors.reset}-" - } else { - log.info "-${colors.purple}[$workflow.manifest.name]${colors.yellow} Pipeline completed successfully, but with errored process(es) ${colors.reset}-" - } - } else { - log.info "-${colors.purple}[$workflow.manifest.name]${colors.red} Pipeline completed with errors${colors.reset}-" - } - } - - // - // ANSII Colours used for terminal logging - // - public static Map logColours(Boolean monochrome_logs) { - Map colorcodes = [:] - - // Reset / Meta - colorcodes['reset'] = monochrome_logs ? '' : "\033[0m" - colorcodes['bold'] = monochrome_logs ? '' : "\033[1m" - colorcodes['dim'] = monochrome_logs ? '' : "\033[2m" - colorcodes['underlined'] = monochrome_logs ? '' : "\033[4m" - colorcodes['blink'] = monochrome_logs ? '' : "\033[5m" - colorcodes['reverse'] = monochrome_logs ? '' : "\033[7m" - colorcodes['hidden'] = monochrome_logs ? '' : "\033[8m" - - // Regular Colors - colorcodes['black'] = monochrome_logs ? '' : "\033[0;30m" - colorcodes['red'] = monochrome_logs ? '' : "\033[0;31m" - colorcodes['green'] = monochrome_logs ? '' : "\033[0;32m" - colorcodes['yellow'] = monochrome_logs ? '' : "\033[0;33m" - colorcodes['blue'] = monochrome_logs ? '' : "\033[0;34m" - colorcodes['purple'] = monochrome_logs ? '' : "\033[0;35m" - colorcodes['cyan'] = monochrome_logs ? '' : "\033[0;36m" - colorcodes['white'] = monochrome_logs ? '' : "\033[0;37m" - - // Bold - colorcodes['bblack'] = monochrome_logs ? '' : "\033[1;30m" - colorcodes['bred'] = monochrome_logs ? '' : "\033[1;31m" - colorcodes['bgreen'] = monochrome_logs ? '' : "\033[1;32m" - colorcodes['byellow'] = monochrome_logs ? '' : "\033[1;33m" - colorcodes['bblue'] = monochrome_logs ? '' : "\033[1;34m" - colorcodes['bpurple'] = monochrome_logs ? '' : "\033[1;35m" - colorcodes['bcyan'] = monochrome_logs ? '' : "\033[1;36m" - colorcodes['bwhite'] = monochrome_logs ? '' : "\033[1;37m" - - // Underline - colorcodes['ublack'] = monochrome_logs ? '' : "\033[4;30m" - colorcodes['ured'] = monochrome_logs ? '' : "\033[4;31m" - colorcodes['ugreen'] = monochrome_logs ? '' : "\033[4;32m" - colorcodes['uyellow'] = monochrome_logs ? '' : "\033[4;33m" - colorcodes['ublue'] = monochrome_logs ? '' : "\033[4;34m" - colorcodes['upurple'] = monochrome_logs ? '' : "\033[4;35m" - colorcodes['ucyan'] = monochrome_logs ? '' : "\033[4;36m" - colorcodes['uwhite'] = monochrome_logs ? '' : "\033[4;37m" - - // High Intensity - colorcodes['iblack'] = monochrome_logs ? '' : "\033[0;90m" - colorcodes['ired'] = monochrome_logs ? '' : "\033[0;91m" - colorcodes['igreen'] = monochrome_logs ? '' : "\033[0;92m" - colorcodes['iyellow'] = monochrome_logs ? '' : "\033[0;93m" - colorcodes['iblue'] = monochrome_logs ? '' : "\033[0;94m" - colorcodes['ipurple'] = monochrome_logs ? '' : "\033[0;95m" - colorcodes['icyan'] = monochrome_logs ? '' : "\033[0;96m" - colorcodes['iwhite'] = monochrome_logs ? '' : "\033[0;97m" - - // Bold High Intensity - colorcodes['biblack'] = monochrome_logs ? '' : "\033[1;90m" - colorcodes['bired'] = monochrome_logs ? '' : "\033[1;91m" - colorcodes['bigreen'] = monochrome_logs ? '' : "\033[1;92m" - colorcodes['biyellow'] = monochrome_logs ? '' : "\033[1;93m" - colorcodes['biblue'] = monochrome_logs ? '' : "\033[1;94m" - colorcodes['bipurple'] = monochrome_logs ? '' : "\033[1;95m" - colorcodes['bicyan'] = monochrome_logs ? '' : "\033[1;96m" - colorcodes['biwhite'] = monochrome_logs ? '' : "\033[1;97m" - - return colorcodes - } - - // - // Does what is says on the tin - // - public static String dashedLine(monochrome_logs) { - Map colors = logColours(monochrome_logs) - return "-${colors.dim}----------------------------------------------------${colors.reset}-" - } - - // - // nf-core logo - // - public static String logo(workflow, monochrome_logs) { - Map colors = logColours(monochrome_logs) - String workflow_version = NfcoreTemplate.version(workflow) - String.format( - """\n - ${dashedLine(monochrome_logs)} - ${colors.green},--.${colors.black}/${colors.green},-.${colors.reset} - ${colors.blue} ___ __ __ __ ___ ${colors.green}/,-._.--~\'${colors.reset} - ${colors.blue} |\\ | |__ __ / ` / \\ |__) |__ ${colors.yellow}} {${colors.reset} - ${colors.blue} | \\| | \\__, \\__/ | \\ |___ ${colors.green}\\`-._,-`-,${colors.reset} - ${colors.green}`._,._,\'${colors.reset} - ${colors.purple} ${workflow.manifest.name} ${workflow_version}${colors.reset} - ${dashedLine(monochrome_logs)} - """.stripIndent() - ) - } -} diff --git a/lib/Utils.groovy b/lib/Utils.groovy deleted file mode 100644 index 8d030f4..0000000 --- a/lib/Utils.groovy +++ /dev/null @@ -1,47 +0,0 @@ -// -// This file holds several Groovy functions that could be useful for any Nextflow pipeline -// - -import org.yaml.snakeyaml.Yaml - -class Utils { - - // - // When running with -profile conda, warn if channels have not been set-up appropriately - // - public static void checkCondaChannels(log) { - Yaml parser = new Yaml() - def channels = [] - try { - def config = parser.load("conda config --show channels".execute().text) - channels = config.channels - } catch(NullPointerException | IOException e) { - log.warn "Could not verify conda channel configuration." - return - } - - // Check that all channels are present - // This channel list is ordered by required channel priority. - def required_channels_in_order = ['conda-forge', 'bioconda', 'defaults'] - def channels_missing = ((required_channels_in_order as Set) - (channels as Set)) as Boolean - - // Check that they are in the right order - def channel_priority_violation = false - def n = required_channels_in_order.size() - for (int i = 0; i < n - 1; i++) { - channel_priority_violation |= !(channels.indexOf(required_channels_in_order[i]) < channels.indexOf(required_channels_in_order[i+1])) - } - - if (channels_missing | channel_priority_violation) { - log.warn "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + - " There is a problem with your Conda configuration!\n\n" + - " You will need to set-up the conda-forge and bioconda channels correctly.\n" + - " Please refer to https://bioconda.github.io/\n" + - " The observed channel order is \n" + - " ${channels}\n" + - " but the following channel order is required:\n" + - " ${required_channels_in_order}\n" + - "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" - } - } -} diff --git a/lib/WorkflowEpitopeprediction.groovy b/lib/WorkflowEpitopeprediction.groovy deleted file mode 100755 index caa0c46..0000000 --- a/lib/WorkflowEpitopeprediction.groovy +++ /dev/null @@ -1,123 +0,0 @@ -// -// This file holds several functions specific to the workflow/epitopeprediction.nf in the nf-core/epitopeprediction pipeline -// - -import nextflow.Nextflow -import groovy.text.SimpleTemplateEngine - -class WorkflowEpitopeprediction { - - // - // Check and validate parameters - // - public static void initialise(params, log) { - - genomeExistsError(params, log) - - - //if (!params.fasta) { - // Nextflow.error "Genome fasta file not specified with e.g. '--fasta genome.fa' or via a detectable config file." - //} - } - - // - // Get workflow summary for MultiQC - // - public static String paramsSummaryMultiqc(workflow, summary) { - String summary_section = '' - for (group in summary.keySet()) { - def group_params = summary.get(group) // This gets the parameters of that particular group - if (group_params) { - summary_section += "

$group

\n" - summary_section += "
\n" - for (param in group_params.keySet()) { - summary_section += "
$param
${group_params.get(param) ?: 'N/A'}
\n" - } - summary_section += '
\n' - } - } - - String yaml_file_text = "id: '${workflow.manifest.name.replace('/', '-')}-summary'\n" - yaml_file_text += "description: ' - this information is collected when the pipeline is started.'\n" - yaml_file_text += "section_name: '${workflow.manifest.name} Workflow Summary'\n" - yaml_file_text += "section_href: 'https://github.com/${workflow.manifest.name}'\n" - yaml_file_text += "plot_type: 'html'\n" - yaml_file_text += 'data: |\n' - yaml_file_text += "${summary_section}" - return yaml_file_text - } - - // - // Generate methods description for MultiQC - // - - public static String toolCitationText(params) { - - // TODO Optionally add in-text citation tools to this list. - // Can use ternary operators to dynamically construct based conditions, e.g. params["run_xyz"] ? "Tool (Foo et al. 2023)" : "", - // Uncomment function in methodsDescriptionText to render in MultiQC report - def citation_text = [ - "Tools used in the workflow included:", - "FastQC (Andrews 2010),", - "MultiQC (Ewels et al. 2016)", - "." - ].join(' ').trim() - - return citation_text - } - - public static String toolBibliographyText(params) { - - // TODO Optionally add bibliographic entries to this list. - // Can use ternary operators to dynamically construct based conditions, e.g. params["run_xyz"] ? "
  • Author (2023) Pub name, Journal, DOI
  • " : "", - // Uncomment function in methodsDescriptionText to render in MultiQC report - def reference_text = [ - "
  • Andrews S, (2010) FastQC, URL: https://www.bioinformatics.babraham.ac.uk/projects/fastqc/).
  • ", - "
  • Ewels, P., Magnusson, M., Lundin, S., & Käller, M. (2016). MultiQC: summarize analysis results for multiple tools and samples in a single report. Bioinformatics , 32(19), 3047–3048. doi: /10.1093/bioinformatics/btw354
  • " - ].join(' ').trim() - - return reference_text - } - - public static String methodsDescriptionText(run_workflow, mqc_methods_yaml, params) { - // Convert to a named map so can be used as with familar NXF ${workflow} variable syntax in the MultiQC YML file - def meta = [:] - meta.workflow = run_workflow.toMap() - meta["manifest_map"] = run_workflow.manifest.toMap() - - // Pipeline DOI - meta["doi_text"] = meta.manifest_map.doi ? "(doi: ${meta.manifest_map.doi})" : "" - meta["nodoi_text"] = meta.manifest_map.doi ? "": "
  • If available, make sure to update the text to include the Zenodo DOI of version of the pipeline used.
  • " - - // Tool references - meta["tool_citations"] = "" - meta["tool_bibliography"] = "" - - // TODO Only uncomment below if logic in toolCitationText/toolBibliographyText has been filled! - //meta["tool_citations"] = toolCitationText(params).replaceAll(", \\.", ".").replaceAll("\\. \\.", ".").replaceAll(", \\.", ".") - //meta["tool_bibliography"] = toolBibliographyText(params) - - - def methods_text = mqc_methods_yaml.text - - def engine = new SimpleTemplateEngine() - def description_html = engine.createTemplate(methods_text).make(meta) - - return description_html - } - - // - // Exit pipeline if incorrect --genome key provided - // - private static void genomeExistsError(params, log) { - if (params.genomes && params.genome && !params.genomes.containsKey(params.genome)) { - def error_string = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + - " Genome '${params.genome}' not found in any config files provided to the pipeline.\n" + - " Currently, the available genome keys are:\n" + - " ${params.genomes.keySet().join(", ")}\n" + - "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" - Nextflow.error(error_string) - } - } - -} diff --git a/lib/WorkflowMain.groovy b/lib/WorkflowMain.groovy deleted file mode 100755 index e45309e..0000000 --- a/lib/WorkflowMain.groovy +++ /dev/null @@ -1,62 +0,0 @@ -// -// This file holds several functions specific to the main.nf workflow in the nf-core/epitopeprediction pipeline -// - -import nextflow.Nextflow - -class WorkflowMain { - - // - // Citation string for pipeline - // - public static String citation(workflow) { - return "If you use ${workflow.manifest.name} for your analysis please cite:\n\n" + - "* The pipeline\n" + - " https://doi.org/10.5281/zenodo.3564666\n\n" + - "* The nf-core framework\n" + - " https://doi.org/10.1038/s41587-020-0439-x\n\n" + - "* Software dependencies\n" + - " https://github.com/${workflow.manifest.name}/blob/master/CITATIONS.md" - } - - - // - // Validate parameters and print summary to screen - // - public static void initialise(workflow, params, log) { - - // Print workflow version and exit on --version - if (params.version) { - String workflow_version = NfcoreTemplate.version(workflow) - log.info "${workflow.manifest.name} ${workflow_version}" - System.exit(0) - } - - // Check that a -profile or Nextflow config has been provided to run the pipeline - NfcoreTemplate.checkConfigProvided(workflow, log) - - // Check that conda channels are set-up correctly - if (workflow.profile.tokenize(',').intersect(['conda', 'mamba']).size() >= 1) { - Utils.checkCondaChannels(log) - } - - // Check AWS batch settings - NfcoreTemplate.awsBatch(workflow, params) - - // Check input has been provided - if (!params.input) { - Nextflow.error("Please provide an input samplesheet to the pipeline e.g. '--input samplesheet.csv'") - } - } - // - // Get attribute from genome config file e.g. fasta - // - public static Object getGenomeAttribute(params, attribute) { - if (params.genomes && params.genome && params.genomes.containsKey(params.genome)) { - if (params.genomes[ params.genome ].containsKey(attribute)) { - return params.genomes[ params.genome ][ attribute ] - } - } - return null - } -} diff --git a/lib/nfcore_external_java_deps.jar b/lib/nfcore_external_java_deps.jar deleted file mode 100644 index 805c8bb..0000000 Binary files a/lib/nfcore_external_java_deps.jar and /dev/null differ diff --git a/main.nf b/main.nf index dfb0d7f..fe7b702 100644 --- a/main.nf +++ b/main.nf @@ -9,59 +9,88 @@ ---------------------------------------------------------------------------------------- */ -nextflow.enable.dsl = 2 - /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - VALIDATE & PRINT PARAMETER SUMMARY + IMPORT FUNCTIONS / MODULES / SUBWORKFLOWS / WORKFLOWS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ -include { validateParameters; paramsHelp } from 'plugin/nf-validation' - -// Print help message if needed -if (params.help) { - def logo = NfcoreTemplate.logo(workflow, params.monochrome_logs) - def citation = '\n' + WorkflowMain.citation(workflow) + '\n' - def String command = "nextflow run ${workflow.manifest.name} --input samplesheet.csv --genome GRCh37 -profile docker" - log.info logo + paramsHelp(command) + citation + NfcoreTemplate.dashedLine(params.monochrome_logs) - System.exit(0) -} +include { EPITOPEPREDICTION } from './workflows/epitopeprediction' +include { PIPELINE_INITIALISATION } from './subworkflows/local/utils_nfcore_epitopeprediction_pipeline' +include { PIPELINE_COMPLETION } from './subworkflows/local/utils_nfcore_epitopeprediction_pipeline' +include { getGenomeAttribute } from './subworkflows/local/utils_nfcore_epitopeprediction_pipeline' -// Validate input parameters -if (params.validate_params) { - validateParameters() -} +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + GENOME PARAMETER VALUES +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ -WorkflowMain.initialise(workflow, params, log) /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - NAMED WORKFLOW FOR PIPELINE + NAMED WORKFLOWS FOR PIPELINE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ -include { EPITOPEPREDICTION } from './workflows/epitopeprediction' - // -// WORKFLOW: Run main nf-core/epitopeprediction analysis pipeline +// WORKFLOW: Run main analysis pipeline depending on type of input // workflow NFCORE_EPITOPEPREDICTION { - EPITOPEPREDICTION () -} + take: + samplesheet // channel: samplesheet read in from --input + + main: + + // + // WORKFLOW: Run pipeline + // + EPITOPEPREDICTION ( + samplesheet + ) + emit: + multiqc_report = EPITOPEPREDICTION.out.multiqc_report // channel: /path/to/multiqc_report.html +} /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - RUN ALL WORKFLOWS + RUN MAIN WORKFLOW ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ -// -// WORKFLOW: Execute a single named workflow for the pipeline -// See: https://github.com/nf-core/rnaseq/issues/619 -// workflow { - NFCORE_EPITOPEPREDICTION () + + main: + // + // SUBWORKFLOW: Run initialisation tasks + // + PIPELINE_INITIALISATION ( + params.version, + params.validate_params, + params.monochrome_logs, + args, + params.outdir, + params.input + ) + + // + // WORKFLOW: Run main workflow + // + NFCORE_EPITOPEPREDICTION ( + PIPELINE_INITIALISATION.out.samplesheet + ) + // + // SUBWORKFLOW: Run completion tasks + // + PIPELINE_COMPLETION ( + params.email, + params.email_on_fail, + params.plaintext_email, + params.outdir, + params.monochrome_logs, + params.hook_url, + NFCORE_EPITOPEPREDICTION.out.multiqc_report + ) } /* diff --git a/modules.json b/modules.json index d3987e8..91ef878 100644 --- a/modules.json +++ b/modules.json @@ -5,22 +5,36 @@ "https://github.com/nf-core/modules.git": { "modules": { "nf-core": { - "custom/dumpsoftwareversions": { - "branch": "master", - "git_sha": "911696ea0b62df80e900ef244d7867d177971f73", - "installed_by": ["modules"] - }, "gunzip": { "branch": "master", - "git_sha": "e06548bfa36ee31869b81041879dd6b3a83b1d57", + "git_sha": "666652151335353eef2fcd58880bcef5bc2928e1", "installed_by": ["modules"] }, "multiqc": { "branch": "master", - "git_sha": "911696ea0b62df80e900ef244d7867d177971f73", + "git_sha": "cf17ca47590cc578dfb47db1c2a44ef86f89976d", "installed_by": ["modules"] } } + }, + "subworkflows": { + "nf-core": { + "utils_nextflow_pipeline": { + "branch": "master", + "git_sha": "56372688d8979092cafbe0c5c3895b491166ca1c", + "installed_by": ["subworkflows"] + }, + "utils_nfcore_pipeline": { + "branch": "master", + "git_sha": "1b6b9a3338d011367137808b49b923515080e3ba", + "installed_by": ["subworkflows"] + }, + "utils_nfschema_plugin": { + "branch": "master", + "git_sha": "2fd2cd6d0e7b273747f32e465fdc6bcc3ae0814e", + "installed_by": ["subworkflows"] + } + } } } } diff --git a/modules/local/cat_files.nf b/modules/local/cat_files.nf index 20ca1e2..1e9bce0 100644 --- a/modules/local/cat_files.nf +++ b/modules/local/cat_files.nf @@ -30,4 +30,19 @@ process CAT_FILES { cat: \$(echo \$(cat --version 2>&1) | sed 's/^.*BusyBox //; s/ .*\$//') END_VERSIONS """ + + stub: + def fileExt = input[0].name.tokenize("\\.")[-1] + def prefix = task.ext.suffix ? "${meta.sample}_${task.ext.suffix}" : "${meta.sample}" + def type = fileExt == "tsv" ? "prediction_result" : "prediction_proteins" + + """ + touch ${prefix}_${type}.${fileExt} + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + cat: \$(echo \$(cat --version 2>&1) | sed 's/^.*BusyBox //; s/ .*\$//') + END_VERSIONS + """ + } diff --git a/modules/local/csvtk_concat.nf b/modules/local/csvtk_concat.nf index 31a0005..f3d986c 100644 --- a/modules/local/csvtk_concat.nf +++ b/modules/local/csvtk_concat.nf @@ -26,4 +26,14 @@ process CSVTK_CONCAT { csvtk: \$(echo \$( csvtk version | sed -e "s/csvtk v//g" )) END_VERSIONS """ + + stub: + """ + touch ${meta.sample}_prediction_result.tsv + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + csvtk: \$(echo \$( csvtk version | sed -e "s/csvtk v//g" )) + END_VERSIONS + """ } diff --git a/modules/local/csvtk_split.nf b/modules/local/csvtk_split.nf deleted file mode 100644 index e32f338..0000000 --- a/modules/local/csvtk_split.nf +++ /dev/null @@ -1,30 +0,0 @@ -process CSVTK_SPLIT { - label 'process_low' - - conda "conda-forge::sed=4.7 bioconda::csvtk=0.23.0" - container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/csvtk:0.23.0--h9ee0642_0' : - 'biocontainers/csvtk:0.23.0--h9ee0642_0' }" - - input: - tuple val(meta), path(raw) - - output: - tuple val(meta), path("*.tsv"), emit: splitted - path "versions.yml", emit: versions - - when: - task.ext.when == null || task.ext.when - - script: - """ - sed -i.bak '/^##/d' ${raw} - csvtk split ${raw} -t -C '&' -f '#chr' - - cat <<-END_VERSIONS > versions.yml - "${task.process}": - csvtk: \$(echo \$( csvtk version | sed -e "s/csvtk v//g" )) - END_VERSIONS - """ - -} diff --git a/modules/local/epytope_check_requested_models.nf b/modules/local/epytope_check_requested_models.nf index fa75353..2c189a4 100644 --- a/modules/local/epytope_check_requested_models.nf +++ b/modules/local/epytope_check_requested_models.nf @@ -1,10 +1,10 @@ process EPYTOPE_CHECK_REQUESTED_MODELS { label 'process_low' - conda "bioconda::epytope=3.1.0" + conda "bioconda::epytope=3.3.1" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/epytope:3.1.0--pyh5e36f6f_0' : - 'biocontainers/epytope:3.1.0--pyh5e36f6f_0' }" + 'https://depot.galaxyproject.org/singularity/epytope:3.3.1--pyh7cba7a3_0' : + 'biocontainers/epytope:3.3.1--pyh7cba7a3_0' }" input: tuple val(meta), path(input_file) @@ -30,8 +30,8 @@ process EPYTOPE_CHECK_REQUESTED_MODELS { } def prefix = task.ext.suffix ? "${meta.sample}_${task.ext.suffix}" : "${meta.sample}_peptides" - def min_length = ("${meta.mhcclass}" == "I") ? params.min_peptide_length : params.min_peptide_length_class2 - def max_length = ("${meta.mhcclass}" == "I") ? params.max_peptide_length : params.max_peptide_length_class2 + def min_length = ("${meta.mhc_class}" == "I") ? params.min_peptide_length : params.min_peptide_length_class2 + def max_length = ("${meta.mhc_class}" == "I") ? params.max_peptide_length : params.max_peptide_length_class2 """ check_requested_models.py ${argument} \ @@ -47,4 +47,17 @@ process EPYTOPE_CHECK_REQUESTED_MODELS { epytope: \$(echo \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('epytope').version)")) END_VERSIONS """ + + stub: + """ + touch model_report.txt + touch model_warnings.log + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + mhcflurry: \$(echo \$(mhcflurry-predict --version 2>&1 | sed 's/^mhcflurry //; s/ .*\$//') ) + mhcnuggets: \$(echo \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('mhcnuggets').version)")) + epytope: \$(echo \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('epytope').version)")) + END_VERSIONS + """ } diff --git a/modules/local/epytope_generate_peptides.nf b/modules/local/epytope_generate_peptides.nf index c4f9ac7..20bba5e 100644 --- a/modules/local/epytope_generate_peptides.nf +++ b/modules/local/epytope_generate_peptides.nf @@ -2,10 +2,10 @@ process EPYTOPE_GENERATE_PEPTIDES { label 'process_low' tag "${meta.sample}" - conda "bioconda::epytope=3.1.0" + conda "bioconda::epytope=3.3.1" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/epytope:3.1.0--pyh5e36f6f_0' : - 'biocontainers/epytope:3.1.0--pyh5e36f6f_0' }" + 'https://depot.galaxyproject.org/singularity/epytope:3.3.1--pyh7cba7a3_0' : + 'biocontainers/epytope:3.3.1--pyh7cba7a3_0' }" input: tuple val(meta), path(raw) @@ -19,8 +19,8 @@ process EPYTOPE_GENERATE_PEPTIDES { script: def prefix = task.ext.suffix ? "${meta.sample}_${task.ext.suffix}" : "${meta.sample}_peptides" - def min_length = (meta.mhcclass == "I") ? params.min_peptide_length : params.min_peptide_length_class2 - def max_length = (meta.mhcclass == "I") ? params.max_peptide_length : params.max_peptide_length_class2 + def min_length = (meta.mhc_class == "I") ? params.min_peptide_length : params.min_peptide_length_class2 + def max_length = (meta.mhc_class == "I") ? params.max_peptide_length : params.max_peptide_length_class2 """ gen_peptides.py --input ${raw} \\ @@ -35,4 +35,16 @@ process EPYTOPE_GENERATE_PEPTIDES { python: \$(python --version 2>&1 | sed 's/Python //g') END_VERSIONS """ + + stub: + def prefix = task.ext.suffix ? "${meta.sample}_${task.ext.suffix}" : "${meta.sample}_peptides" + """ + touch ${prefix}.tsv + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + epytope: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('epytope').version)") + python: \$(python --version 2>&1 | sed 's/Python //g') + END_VERSIONS + """ } diff --git a/modules/local/epytope_peptide_prediction.nf b/modules/local/epytope_peptide_prediction.nf index 929a557..a001dd5 100644 --- a/modules/local/epytope_peptide_prediction.nf +++ b/modules/local/epytope_peptide_prediction.nf @@ -2,9 +2,7 @@ process EPYTOPE_PEPTIDE_PREDICTION { label 'process_low' conda "conda-forge::coreutils=9.1 conda-forge::tcsh=6.20.00 bioconda::epytope=3.1.0 conda-forge::gawk=5.1.0 conda-forge::perl=5.32.1" - container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/mulled-v2-11bbf0d242ea96f7b9c08d5b5bc26f2cd5ac5943:3419f320edefe6077631798f50d7bd4f8dc4763f-0' : - 'biocontainers/mulled-v2-11bbf0d242ea96f7b9c08d5b5bc26f2cd5ac5943:3419f320edefe6077631798f50d7bd4f8dc4763f-0' }" + container 'ghcr.io/jonasscheid/epitopeprediction-2:0.3.0' input: tuple val(meta), path(splitted), path(software_versions) @@ -46,17 +44,18 @@ process EPYTOPE_PEPTIDE_PREDICTION { def netmhc_paths_string = netmhc_paths.join(",") def tools_split = params.tools.split(',') + // TODO: Move to nf-validation def class1_tools = tools_split.findAll { ! it.matches('.*(?i)(class-2|ii).*') } def class2_tools = tools_split.findAll { it.matches('.*(?i)(syf|class-2|ii).*') } - - if (((meta.mhcclass == "I") & class1_tools.empty) | ((meta.mhcclass == "II") & class2_tools.empty)) { - exit 1, "No tools specified for mhc class ${meta.mhcclass}" + // TODO: Move to nf-validation + if (((meta.mhc_class == "I") & class1_tools.empty) | ((meta.mhc_class == "II") & class2_tools.empty)) { + exit 1, "No tools specified for mhc class ${meta.mhc_class}" } - def min_length = (meta.mhcclass == "I") ? params.min_peptide_length : params.min_peptide_length_class2 - def max_length = (meta.mhcclass == "I") ? params.max_peptide_length : params.max_peptide_length_class2 + def min_length = (meta.mhc_class == "I") ? params.min_peptide_length : params.min_peptide_length_class2 + def max_length = (meta.mhc_class == "I") ? params.max_peptide_length : params.max_peptide_length_class2 - def tools_to_use = ((meta.mhcclass == "I") | (meta.mhcclass == "H-2")) ? class1_tools.join(',') : class2_tools.join(',') + def tools_to_use = ((meta.mhc_class == "I") | (meta.mhc_class == "H-2")) ? class1_tools.join(',') : class2_tools.join(',') """ # create folder for MHCflurry downloads to avoid permission problems when running pipeline with docker profile and mhcflurry selected @@ -85,7 +84,24 @@ process EPYTOPE_PEPTIDE_PREDICTION { python: \$(python --version 2>&1 | sed 's/Python //g') epytope: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('epytope').version)") pandas: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('pandas').version)") - pyvcf: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('pyvcf').version)") + pyvcf: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('PyVCF3').version)") + mhcflurry: \$(mhcflurry-predict --version 2>&1 | sed 's/^mhcflurry //; s/ .*\$//') + mhcnuggets: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('mhcnuggets').version)") + END_VERSIONS + """ + + stub: + """ + touch ${splitted.baseName}.json + touch ${splitted.baseName}.tsv + touch ${splitted.baseName}.fasta + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + python: \$(python --version 2>&1 | sed 's/Python //g') + epytope: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('epytope').version)") + pandas: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('pandas').version)") + pyvcf: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('PyVCF3').version)") mhcflurry: \$(mhcflurry-predict --version 2>&1 | sed 's/^mhcflurry //; s/ .*\$//') mhcnuggets: \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('mhcnuggets').version)") END_VERSIONS diff --git a/modules/local/epytope_show_supported_models.nf b/modules/local/epytope_show_supported_models.nf index ee9f117..68a8e1b 100644 --- a/modules/local/epytope_show_supported_models.nf +++ b/modules/local/epytope_show_supported_models.nf @@ -1,10 +1,10 @@ process EPYTOPE_SHOW_SUPPORTED_MODELS { label 'process_low' - conda "bioconda::epytope=3.1.0" + conda "bioconda::epytope=3.3.1" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/epytope:3.1.0--pyh5e36f6f_0' : - 'biocontainers/epytope:3.1.0--pyh5e36f6f_0' }" + 'https://depot.galaxyproject.org/singularity/epytope:3.3.1--pyh7cba7a3_0' : + 'biocontainers/epytope:3.3.1--pyh7cba7a3_0' }" input: tuple val(meta), path(raw), path(software_versions) diff --git a/modules/local/external_tools_import.nf b/modules/local/external_tools_import.nf index 2895b48..1e64e52 100644 --- a/modules/local/external_tools_import.nf +++ b/modules/local/external_tools_import.nf @@ -7,7 +7,7 @@ process EXTERNAL_TOOLS_IMPORT { conda "conda-forge::coreutils=9.1" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? 'https://containers.biocontainers.pro/s3/SingImgsRepo/biocontainers/v1.2.0_cv1/biocontainers_v1.2.0_cv1.img' : - 'biocontainers/biocontainers:v1.2.0_cv1' }" + 'docker.io/biocontainers/biocontainers:v1.2.0_cv2' }" input: tuple val(toolname), val(toolversion), val(toolchecksum), path(tooltarball), file(datatarball), val(datachecksum), val(toolbinaryname) @@ -64,20 +64,31 @@ process EXTERNAL_TOOLS_IMPORT { # # VALIDATE THE CHECKSUM OF THE DOWNLOADED MODEL DATA # - checksum="\$(md5sum "$datatarball" | cut -f1 -d' ')" - if [ "\$checksum" != "${datachecksum}" ]; then - echo "A checksum mismatch occurred when checking the data file for ${toolname}." >&2 - exit 3 - fi + if [ "$toolname" == "netmhcpan" ]; then + checksum="\$(md5sum "$datatarball" | cut -f1 -d' ')" + if [ "\$checksum" != "${datachecksum}" ]; then + echo "A checksum mismatch occurred when checking the data file for ${toolname}." >&2 + exit 3 + fi - # - # UNPACK THE DOWNLOADED MODEL DATA - # - tar -C "${toolname}" -v -x -f "$datatarball" + # + # UNPACK THE DOWNLOADED MODEL DATA + # + tar -C "${toolname}" -v -x -f "$datatarball" + fi # # CREATE VERSION FILE # + cat <<-END_VERSIONS > versions.yml + "${task.process}": + ${toolname}: ${toolversion} + END_VERSIONS + """ + + stub: + """ + mkdir "${toolname}" cat <<-END_VERSIONS > versions.yml "${task.process}": diff --git a/modules/local/get_prediction_versions.nf b/modules/local/get_prediction_versions.nf index 5364ddb..70a31df 100644 --- a/modules/local/get_prediction_versions.nf +++ b/modules/local/get_prediction_versions.nf @@ -1,10 +1,10 @@ process GET_PREDICTION_VERSIONS { label 'process_low' - conda "bioconda::epytope=3.1.0" + conda "bioconda::epytope=3.3.1" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/epytope:3.1.0--pyh5e36f6f_0' : - 'biocontainers/epytope:3.1.0--pyh5e36f6f_0' }" + 'https://depot.galaxyproject.org/singularity/epytope:3.3.1--pyh7cba7a3_0' : + 'biocontainers/epytope:3.3.1--pyh7cba7a3_0' }" input: val external_tool_versions @@ -19,7 +19,27 @@ process GET_PREDICTION_VERSIONS { def external_tools = external_tool_versions.join(",") """ - cat <<-END_VERSIONS > versions.csv + cat <<-END_VERSIONS >> versions.csv + mhcflurry: \$(mhcflurry-predict --version 2>&1 | sed 's/^mhcflurry //; s/ .*\$//') + mhcnuggets: \$(python -c "import pkg_resources; print('mhcnuggets' + pkg_resources.get_distribution('mhcnuggets').version)" | sed 's/^mhcnuggets//; s/ .*\$//' ) + epytope: \$(python -c "import pkg_resources; print('epytope' + pkg_resources.get_distribution('epytope').version)" | sed 's/^epytope//; s/ .*\$//') + END_VERSIONS + + IFS=',' read -r -a external_tools <<< \"$external_tools\" + if ! [ -z "${external_tool_versions}" ]; then + for TOOL in "\${external_tools[@]}"; do + echo "\$TOOL" >> versions.csv + done + fi + """ + + stub: + def external_tools = external_tool_versions.join(",") + + """ + touch versions.csv + + cat <<-END_VERSIONS >> versions.csv mhcflurry: \$(mhcflurry-predict --version 2>&1 | sed 's/^mhcflurry //; s/ .*\$//') mhcnuggets: \$(python -c "import pkg_resources; print('mhcnuggets' + pkg_resources.get_distribution('mhcnuggets').version)" | sed 's/^mhcnuggets//; s/ .*\$//' ) epytope: \$(python -c "import pkg_resources; print('epytope' + pkg_resources.get_distribution('epytope').version)" | sed 's/^epytope//; s/ .*\$//') diff --git a/modules/local/merge_json.nf b/modules/local/merge_json.nf index 5d66f78..953f2d5 100644 --- a/modules/local/merge_json.nf +++ b/modules/local/merge_json.nf @@ -29,4 +29,14 @@ process MERGE_JSON { python: \$(python --version | sed 's/Python //g') END_VERSIONS """ + + stub: + """ + touch ${meta.sample}.json + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + python: \$(python --version | sed 's/Python //g') + END_VERSIONS + """ } diff --git a/modules/local/merge_predictions.nf b/modules/local/merge_predictions.nf index 4b9ea3d..c8701a8 100644 --- a/modules/local/merge_predictions.nf +++ b/modules/local/merge_predictions.nf @@ -8,27 +8,29 @@ process MERGE_PREDICTIONS { 'quay.io/biocontainers/mhcgnomes:1.8.4--pyh7cba7a3_0' }" input: - tuple val(meta), path(prediction_files), path(metadata_file) + tuple val(meta), path(prediction_files) output: tuple val(meta), path("*.tsv"), emit: merged path "versions.yml", emit: versions script: - def output = prediction_files.first().baseName.split("_").dropRight(2).join("_") + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ - cat <<-END_VERSIONS > versions.yml - "${task.process}": - python \$(python --version | sed 's/Python //g') - mhcgnomes \$(python -c "from mhcgnomes import version; print(version.__version__)" ) - END_VERSIONS """ stub: + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ touch merged_prediction.tsv - touch versions.yml + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + VERSION_PLACEHOLDER + END_VERSIONS """ } diff --git a/modules/local/mhcflurry.nf b/modules/local/mhcflurry.nf index 657b49c..61ed356 100644 --- a/modules/local/mhcflurry.nf +++ b/modules/local/mhcflurry.nf @@ -4,8 +4,8 @@ process MHCFLURRY { conda "bioconda::mhcflurry=2.0.6" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/mhcflurry:2.0.6--pyh7cba7a3_0' : - 'quay.io/biocontainers/mhcflurry:2.0.6--pyh7cba7a3_0' }" + 'https://depot.galaxyproject.org/singularity/mhcflurry:2.1.4--pyh7e72e81_0' : + 'quay.io/biocontainers/mhcflurry:2.1.4--pyh7e72e81_0' }" input: tuple val(meta), path(peptide_file) @@ -15,19 +15,24 @@ process MHCFLURRY { path "versions.yml", emit: versions script: - if (meta.mhc_class == "II") { error("MHCflurry prediction of ${meta.sample} is not possible with MHC class II!") } - - def prefix = "${meta.sample}_${peptide_file.baseName}" + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ """ stub: + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ - touch ${meta.sample}_predicted_mhcflurry.tsv - touch versions.yml + touch ${prefix}_predicted_mhcflurry.tsv + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + \$(mhcflurry-predict --version) + END_VERSIONS """ } diff --git a/modules/local/mhcnuggets.nf b/modules/local/mhcnuggets.nf index 3f76b6e..a196eb5 100644 --- a/modules/local/mhcnuggets.nf +++ b/modules/local/mhcnuggets.nf @@ -15,13 +15,20 @@ process MHCNUGGETS { path "versions.yml", emit: versions script: - def prefix = "${meta.sample}_${peptide_file.baseName}" + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ """ stub: + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ - touch ${meta.sample}_predicted_mhcnuggets.tsv - touch versions.yml + touch ${prefix}_predicted_mhcnuggets.tsv + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + mhcnuggets \$(python -c "import pkg_resources; print(pkg_resources.get_distribution('mhcnuggets').version)") + END_VERSIONS """ } diff --git a/modules/local/netmhciipan.nf b/modules/local/netmhciipan.nf index 1a41b7b..2b8fcde 100644 --- a/modules/local/netmhciipan.nf +++ b/modules/local/netmhciipan.nf @@ -2,11 +2,10 @@ process NETMHCIIPAN { label 'process_single' tag "${meta.sample}" - container 'ghcr.io/jonasscheid/epitopeprediction-2:netmhc' input: - tuple val(meta), path(peptide_file) + tuple val(meta), path(peptide_file), path(software) output: tuple val(meta), path("*.tsv"), emit: predicted @@ -14,15 +13,23 @@ process NETMHCIIPAN { script: if (meta.mhc_class != "II") { - error "NETMHCIIPAN only supports MHC class II. Use NETMHCPAN for MHC class I, or adjust the samplesheet accordingly." + error "NETMHCIIPAN only supports MHC class II. Use NETMHCPAN for MHC class I." } + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ """ stub: + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ - touch ${meta.sample}_predicted_netmhciipan.tsv - touch versions.yml + touch ${prefix}_predicted_netmhciipan.tsv + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + netmhciipan \$(cat data/version | sed -s 's/ version/:/g') + END_VERSIONS """ } diff --git a/modules/local/netmhcpan.nf b/modules/local/netmhcpan.nf index b400c79..2059027 100644 --- a/modules/local/netmhcpan.nf +++ b/modules/local/netmhcpan.nf @@ -5,7 +5,7 @@ process NETMHCPAN { container 'ghcr.io/jonasscheid/epitopeprediction-2:netmhc' input: - tuple val(meta), path(peptide_file), path(nonfree_tools) + tuple val(meta), path(peptide_file), path(software) output: tuple val(meta), path("*.tsv"), emit: predicted @@ -13,15 +13,23 @@ process NETMHCPAN { script: if (meta.mhc_class != "I") { - error "NETMHCPAN only supports MHC class I. Use NETMHCIIPAN for MHC class II, or adjust the samplesheet accordingly." + error "NETMHCPAN only supports MHC class I. Use NETMHCIIPAN for MHC class II." } - def prefix = peptide_file.baseName + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ """ + stub: + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ - touch ${meta.sample}_predicted_netmhcpan.tsv - touch versions.yml + touch ${prefix}_predicted_netmhcpan.tsv + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + netmhcpan \$(cat data/version | sed -s 's/ version/:/g') + END_VERSIONS """ } diff --git a/modules/local/prepare_prediction_input.nf b/modules/local/prepare_prediction_input.nf index 070ec7c..68644a4 100755 --- a/modules/local/prepare_prediction_input.nf +++ b/modules/local/prepare_prediction_input.nf @@ -17,17 +17,25 @@ process PREPARE_PREDICTION_INPUT { path "versions.yml", emit: versions script: + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample //TODO handle the thresholds (parse the --tools_thresholds and --use_affinity_thresholds) - def min_length = (meta.mhc_class == "I") ? params.min_peptide_length_mhc_I : params.min_peptide_length_mhc_II - def max_length = (meta.mhc_class == "I") ? params.max_peptide_length_mhc_I : params.max_peptide_length_mhc_II + def min_length = (meta.mhc_class == "I") ? params.min_peptide_length : params.min_peptide_length_class2 + def max_length = (meta.mhc_class == "I") ? params.max_peptide_length : params.max_peptide_length_class2 //tools über params.tools ziehen """ """ stub: + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ - touch syfpeithi_input.csv + touch ${prefix}_syfpeithi.csv + touch ${prefix}_mhcflurry.csv + touch ${prefix}_mhcnuggets.csv + touch ${prefix}_netmhcpan.csv + touch ${prefix}_netmhciipan.csv touch versions.yml """ } diff --git a/modules/local/samplesheet_check.nf b/modules/local/samplesheet_check.nf deleted file mode 100644 index ae63801..0000000 --- a/modules/local/samplesheet_check.nf +++ /dev/null @@ -1,31 +0,0 @@ -process SAMPLESHEET_CHECK { - tag "$samplesheet" - label 'process_single' - - conda "conda-forge::python=3.8.3" - container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/python:3.8.3' : - 'biocontainers/python:3.8.3' }" - - input: - path samplesheet - - output: - path '*.csv' , emit: csv - path "versions.yml", emit: versions - - when: - task.ext.when == null || task.ext.when - - script: // This script is bundled with the pipeline, in nf-core/epitopeprediction/bin/ - """ - check_samplesheet.py \\ - $samplesheet \\ - samplesheet.valid.csv - - cat <<-END_VERSIONS > versions.yml - "${task.process}": - python: \$(python --version | sed 's/Python //g') - END_VERSIONS - """ -} diff --git a/modules/local/snpsift_split.nf b/modules/local/snpsift_split.nf index 1e7f218..c4a8b25 100644 --- a/modules/local/snpsift_split.nf +++ b/modules/local/snpsift_split.nf @@ -25,4 +25,15 @@ process SNPSIFT_SPLIT { snpsift: \$( echo \$(SnpSift split -h 2>&1) | sed 's/^.*version //' | sed 's/(.*//' | sed 's/t//g' ) END_VERSIONS """ + + stub: + """ + touch ${input_file.baseName}.chr1.vcf + touch ${input_file.baseName}.chr2.vcf + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + snpsift: \$( echo \$(SnpSift split -h 2>&1) | sed 's/^.*version //' | sed 's/(.*//' | sed 's/t//g' ) + END_VERSIONS + """ } diff --git a/modules/local/split_peptides.nf b/modules/local/split_peptides.nf index 3ade5b8..998b18a 100644 --- a/modules/local/split_peptides.nf +++ b/modules/local/split_peptides.nf @@ -29,4 +29,16 @@ process SPLIT_PEPTIDES { python: \$(python --version | sed 's/Python //g') END_VERSIONS """ + + stub: + def prefix = task.ext.suffix ? "${peptide.baseName}_${task.ext.suffix}" : "${peptide.baseName}" + """ + touch ${prefix}_1.tsv + touch ${prefix}_2.tsv + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + python: \$(python --version | sed 's/Python //g') + END_VERSIONS + """ } diff --git a/modules/local/syfpeithi.nf b/modules/local/syfpeithi.nf index 488dd74..2d54726 100644 --- a/modules/local/syfpeithi.nf +++ b/modules/local/syfpeithi.nf @@ -15,14 +15,21 @@ process SYFPEITHI { path "versions.yml", emit: versions script: - def prefix = "${meta.sample}_${peptide_file.baseName}" + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: meta.sample """ """ stub: + def args = task.ext.args ?: '' + def prefix = task.ext.prefix ?: "${meta.id}" """ - touch ${meta.sample}_predicted_syfpeithi.tsv - touch versions.yml + touch ${prefix}_predicted_syfpeithi.tsv + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + syfpeithi: V1.0.0 + END_VERSIONS """ } diff --git a/modules/local/variant_split.nf b/modules/local/variant_split.nf index e0695c3..f66b4c5 100644 --- a/modules/local/variant_split.nf +++ b/modules/local/variant_split.nf @@ -29,4 +29,14 @@ process VARIANT_SPLIT { END_VERSIONS """ + stub: + """ + touch ${input_file.baseName}_1.vcf + touch ${input_file.baseName}_2.vcf + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + python: \$(python --version 2>&1 | sed 's/Python //g') + END_VERSIONS + """ } diff --git a/modules/nf-core/custom/dumpsoftwareversions/main.nf b/modules/nf-core/custom/dumpsoftwareversions/main.nf deleted file mode 100644 index ebc8727..0000000 --- a/modules/nf-core/custom/dumpsoftwareversions/main.nf +++ /dev/null @@ -1,24 +0,0 @@ -process CUSTOM_DUMPSOFTWAREVERSIONS { - label 'process_single' - - // Requires `pyyaml` which does not have a dedicated container but is in the MultiQC container - conda "bioconda::multiqc=1.14" - container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/multiqc:1.14--pyhdfd78af_0' : - 'biocontainers/multiqc:1.14--pyhdfd78af_0' }" - - input: - path versions - - output: - path "software_versions.yml" , emit: yml - path "software_versions_mqc.yml", emit: mqc_yml - path "versions.yml" , emit: versions - - when: - task.ext.when == null || task.ext.when - - script: - def args = task.ext.args ?: '' - template 'dumpsoftwareversions.py' -} diff --git a/modules/nf-core/custom/dumpsoftwareversions/meta.yml b/modules/nf-core/custom/dumpsoftwareversions/meta.yml deleted file mode 100644 index c32657d..0000000 --- a/modules/nf-core/custom/dumpsoftwareversions/meta.yml +++ /dev/null @@ -1,36 +0,0 @@ -# yaml-language-server: $schema=https://raw.githubusercontent.com/nf-core/modules/master/modules/yaml-schema.json -name: custom_dumpsoftwareversions -description: Custom module used to dump software versions within the nf-core pipeline template -keywords: - - custom - - dump - - version -tools: - - custom: - description: Custom module used to dump software versions within the nf-core pipeline template - homepage: https://github.com/nf-core/tools - documentation: https://github.com/nf-core/tools - licence: ["MIT"] -input: - - versions: - type: file - description: YML file containing software versions - pattern: "*.yml" - -output: - - yml: - type: file - description: Standard YML file containing software versions - pattern: "software_versions.yml" - - mqc_yml: - type: file - description: MultiQC custom content YML file containing software versions - pattern: "software_versions_mqc.yml" - - versions: - type: file - description: File containing software versions - pattern: "versions.yml" - -authors: - - "@drpatelh" - - "@grst" diff --git a/modules/nf-core/custom/dumpsoftwareversions/templates/dumpsoftwareversions.py b/modules/nf-core/custom/dumpsoftwareversions/templates/dumpsoftwareversions.py deleted file mode 100755 index da03340..0000000 --- a/modules/nf-core/custom/dumpsoftwareversions/templates/dumpsoftwareversions.py +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env python - - -"""Provide functions to merge multiple versions.yml files.""" - - -import yaml -import platform -from textwrap import dedent - - -def _make_versions_html(versions): - """Generate a tabular HTML output of all versions for MultiQC.""" - html = [ - dedent( - """\\ - - - - - - - - - - """ - ) - ] - for process, tmp_versions in sorted(versions.items()): - html.append("") - for i, (tool, version) in enumerate(sorted(tmp_versions.items())): - html.append( - dedent( - f"""\\ - - - - - - """ - ) - ) - html.append("") - html.append("
    Process Name Software Version
    {process if (i == 0) else ''}{tool}{version}
    ") - return "\\n".join(html) - - -def main(): - """Load all version files and generate merged output.""" - versions_this_module = {} - versions_this_module["${task.process}"] = { - "python": platform.python_version(), - "yaml": yaml.__version__, - } - - with open("$versions") as f: - versions_by_process = yaml.load(f, Loader=yaml.BaseLoader) | versions_this_module - - # aggregate versions by the module name (derived from fully-qualified process name) - versions_by_module = {} - for process, process_versions in versions_by_process.items(): - module = process.split(":")[-1] - try: - if versions_by_module[module] != process_versions: - raise AssertionError( - "We assume that software versions are the same between all modules. " - "If you see this error-message it means you discovered an edge-case " - "and should open an issue in nf-core/tools. " - ) - except KeyError: - versions_by_module[module] = process_versions - - versions_by_module["Workflow"] = { - "Nextflow": "$workflow.nextflow.version", - "$workflow.manifest.name": "$workflow.manifest.version", - } - - versions_mqc = { - "id": "software_versions", - "section_name": "${workflow.manifest.name} Software Versions", - "section_href": "https://github.com/${workflow.manifest.name}", - "plot_type": "html", - "description": "are collected at run time from the software output.", - "data": _make_versions_html(versions_by_module), - } - - with open("software_versions.yml", "w") as f: - yaml.dump(versions_by_module, f, default_flow_style=False) - with open("software_versions_mqc.yml", "w") as f: - yaml.dump(versions_mqc, f, default_flow_style=False) - - with open("versions.yml", "w") as f: - yaml.dump(versions_this_module, f, default_flow_style=False) - - -if __name__ == "__main__": - main() diff --git a/modules/nf-core/gunzip/environment.yml b/modules/nf-core/gunzip/environment.yml new file mode 100644 index 0000000..c779485 --- /dev/null +++ b/modules/nf-core/gunzip/environment.yml @@ -0,0 +1,7 @@ +channels: + - conda-forge + - bioconda +dependencies: + - conda-forge::grep=3.11 + - conda-forge::sed=4.8 + - conda-forge::tar=1.34 diff --git a/modules/nf-core/gunzip/main.nf b/modules/nf-core/gunzip/main.nf index 73bf08c..5e67e3b 100644 --- a/modules/nf-core/gunzip/main.nf +++ b/modules/nf-core/gunzip/main.nf @@ -2,10 +2,10 @@ process GUNZIP { tag "$archive" label 'process_single' - conda "conda-forge::sed=4.7" + conda "${moduleDir}/environment.yml" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/ubuntu:20.04' : - 'nf-core/ubuntu:20.04' }" + 'https://depot.galaxyproject.org/singularity/ubuntu:22.04' : + 'nf-core/ubuntu:22.04' }" input: tuple val(meta), path(archive) @@ -18,8 +18,11 @@ process GUNZIP { task.ext.when == null || task.ext.when script: - def args = task.ext.args ?: '' - gunzip = archive.toString() - '.gz' + def args = task.ext.args ?: '' + def extension = ( archive.toString() - '.gz' ).tokenize('.')[-1] + def name = archive.toString() - '.gz' - ".$extension" + def prefix = task.ext.prefix ?: name + gunzip = prefix + ".$extension" """ # Not calling gunzip itself because it creates files # with the original group ownership rather than the @@ -37,7 +40,11 @@ process GUNZIP { """ stub: - gunzip = archive.toString() - '.gz' + def args = task.ext.args ?: '' + def extension = ( archive.toString() - '.gz' ).tokenize('.')[-1] + def name = archive.toString() - '.gz' - ".$extension" + def prefix = task.ext.prefix ?: name + gunzip = prefix + ".$extension" """ touch $gunzip cat <<-END_VERSIONS > versions.yml diff --git a/modules/nf-core/gunzip/meta.yml b/modules/nf-core/gunzip/meta.yml index 4cdcdf4..9066c03 100644 --- a/modules/nf-core/gunzip/meta.yml +++ b/modules/nf-core/gunzip/meta.yml @@ -10,26 +10,38 @@ tools: gzip is a file format and a software application used for file compression and decompression. documentation: https://www.gnu.org/software/gzip/manual/gzip.html licence: ["GPL-3.0-or-later"] + identifier: "" input: - - meta: - type: map - description: | - Optional groovy Map containing meta information - e.g. [ id:'test', single_end:false ] - - archive: - type: file - description: File to be compressed/uncompressed - pattern: "*.*" + - - meta: + type: map + description: | + Optional groovy Map containing meta information + e.g. [ id:'test', single_end:false ] + - archive: + type: file + description: File to be compressed/uncompressed + pattern: "*.*" output: - gunzip: - type: file - description: Compressed/uncompressed file - pattern: "*.*" + - meta: + type: file + description: Compressed/uncompressed file + pattern: "*.*" + - $gunzip: + type: file + description: Compressed/uncompressed file + pattern: "*.*" - versions: - type: file - description: File containing software versions - pattern: "versions.yml" + - versions.yml: + type: file + description: File containing software versions + pattern: "versions.yml" authors: - "@joseespinosa" - "@drpatelh" - "@jfy133" +maintainers: + - "@joseespinosa" + - "@drpatelh" + - "@jfy133" + - "@gallvp" diff --git a/modules/nf-core/gunzip/tests/main.nf.test b/modules/nf-core/gunzip/tests/main.nf.test new file mode 100644 index 0000000..776211a --- /dev/null +++ b/modules/nf-core/gunzip/tests/main.nf.test @@ -0,0 +1,121 @@ +nextflow_process { + + name "Test Process GUNZIP" + script "../main.nf" + process "GUNZIP" + tag "gunzip" + tag "modules_nfcore" + tag "modules" + + test("Should run without failures") { + + when { + params { + outdir = "$outputDir" + } + process { + """ + input[0] = Channel.of([ + [], + file(params.modules_testdata_base_path + 'genomics/sarscov2/illumina/fastq/test_1.fastq.gz', checkIfExists: true) + ] + ) + """ + } + } + + then { + assertAll( + { assert process.success }, + { assert snapshot(process.out).match() } + ) + } + + } + + test("Should run without failures - prefix") { + + config './nextflow.config' + + when { + params { + outdir = "$outputDir" + } + process { + """ + input[0] = Channel.of([ + [ id: 'test' ], + file(params.modules_testdata_base_path + 'genomics/sarscov2/illumina/fastq/test_1.fastq.gz', checkIfExists: true) + ] + ) + """ + } + } + + then { + assertAll( + { assert process.success }, + { assert snapshot(process.out).match() } + ) + } + + } + + test("Should run without failures - stub") { + + options '-stub' + + when { + params { + outdir = "$outputDir" + } + process { + """ + input[0] = Channel.of([ + [], + file(params.modules_testdata_base_path + 'genomics/sarscov2/illumina/fastq/test_1.fastq.gz', checkIfExists: true) + ] + ) + """ + } + } + + then { + assertAll( + { assert process.success }, + { assert snapshot(process.out).match() } + ) + } + + } + + test("Should run without failures - prefix - stub") { + + options '-stub' + config './nextflow.config' + + when { + params { + outdir = "$outputDir" + } + process { + """ + input[0] = Channel.of([ + [ id: 'test' ], + file(params.modules_testdata_base_path + 'genomics/sarscov2/illumina/fastq/test_1.fastq.gz', checkIfExists: true) + ] + ) + """ + } + } + + then { + assertAll( + { assert process.success }, + { assert snapshot(process.out).match() } + ) + } + + } + +} diff --git a/modules/nf-core/gunzip/tests/main.nf.test.snap b/modules/nf-core/gunzip/tests/main.nf.test.snap new file mode 100644 index 0000000..069967e --- /dev/null +++ b/modules/nf-core/gunzip/tests/main.nf.test.snap @@ -0,0 +1,134 @@ +{ + "Should run without failures - prefix - stub": { + "content": [ + { + "0": [ + [ + { + "id": "test" + }, + "test.xyz.fastq:md5,d41d8cd98f00b204e9800998ecf8427e" + ] + ], + "1": [ + "versions.yml:md5,54376d32aca20e937a4ec26dac228e84" + ], + "gunzip": [ + [ + { + "id": "test" + }, + "test.xyz.fastq:md5,d41d8cd98f00b204e9800998ecf8427e" + ] + ], + "versions": [ + "versions.yml:md5,54376d32aca20e937a4ec26dac228e84" + ] + } + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "24.04.2" + }, + "timestamp": "2024-06-25T11:35:10.861293" + }, + "Should run without failures - stub": { + "content": [ + { + "0": [ + [ + [ + + ], + "test_1.fastq:md5,d41d8cd98f00b204e9800998ecf8427e" + ] + ], + "1": [ + "versions.yml:md5,54376d32aca20e937a4ec26dac228e84" + ], + "gunzip": [ + [ + [ + + ], + "test_1.fastq:md5,d41d8cd98f00b204e9800998ecf8427e" + ] + ], + "versions": [ + "versions.yml:md5,54376d32aca20e937a4ec26dac228e84" + ] + } + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "24.04.2" + }, + "timestamp": "2024-06-25T11:35:05.857145" + }, + "Should run without failures": { + "content": [ + { + "0": [ + [ + [ + + ], + "test_1.fastq:md5,4161df271f9bfcd25d5845a1e220dbec" + ] + ], + "1": [ + "versions.yml:md5,54376d32aca20e937a4ec26dac228e84" + ], + "gunzip": [ + [ + [ + + ], + "test_1.fastq:md5,4161df271f9bfcd25d5845a1e220dbec" + ] + ], + "versions": [ + "versions.yml:md5,54376d32aca20e937a4ec26dac228e84" + ] + } + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "24.04.2" + }, + "timestamp": "2023-10-17T15:35:37.690477896" + }, + "Should run without failures - prefix": { + "content": [ + { + "0": [ + [ + { + "id": "test" + }, + "test.xyz.fastq:md5,4161df271f9bfcd25d5845a1e220dbec" + ] + ], + "1": [ + "versions.yml:md5,54376d32aca20e937a4ec26dac228e84" + ], + "gunzip": [ + [ + { + "id": "test" + }, + "test.xyz.fastq:md5,4161df271f9bfcd25d5845a1e220dbec" + ] + ], + "versions": [ + "versions.yml:md5,54376d32aca20e937a4ec26dac228e84" + ] + } + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "24.04.2" + }, + "timestamp": "2024-06-25T11:33:32.921739" + } +} \ No newline at end of file diff --git a/modules/nf-core/gunzip/tests/nextflow.config b/modules/nf-core/gunzip/tests/nextflow.config new file mode 100644 index 0000000..dec7764 --- /dev/null +++ b/modules/nf-core/gunzip/tests/nextflow.config @@ -0,0 +1,5 @@ +process { + withName: GUNZIP { + ext.prefix = { "${meta.id}.xyz" } + } +} diff --git a/modules/nf-core/gunzip/tests/tags.yml b/modules/nf-core/gunzip/tests/tags.yml new file mode 100644 index 0000000..fd3f691 --- /dev/null +++ b/modules/nf-core/gunzip/tests/tags.yml @@ -0,0 +1,2 @@ +gunzip: + - modules/nf-core/gunzip/** diff --git a/modules/nf-core/multiqc/environment.yml b/modules/nf-core/multiqc/environment.yml new file mode 100644 index 0000000..6f5b867 --- /dev/null +++ b/modules/nf-core/multiqc/environment.yml @@ -0,0 +1,5 @@ +channels: + - conda-forge + - bioconda +dependencies: + - bioconda::multiqc=1.25.1 diff --git a/modules/nf-core/multiqc/main.nf b/modules/nf-core/multiqc/main.nf index 1fc387b..cc0643e 100644 --- a/modules/nf-core/multiqc/main.nf +++ b/modules/nf-core/multiqc/main.nf @@ -1,16 +1,18 @@ process MULTIQC { label 'process_single' - conda "bioconda::multiqc=1.14" + conda "${moduleDir}/environment.yml" container "${ workflow.containerEngine == 'singularity' && !task.ext.singularity_pull_docker_container ? - 'https://depot.galaxyproject.org/singularity/multiqc:1.14--pyhdfd78af_0' : - 'biocontainers/multiqc:1.14--pyhdfd78af_0' }" + 'https://depot.galaxyproject.org/singularity/multiqc:1.25.1--pyhdfd78af_0' : + 'biocontainers/multiqc:1.25.1--pyhdfd78af_0' }" input: path multiqc_files, stageAs: "?/*" path(multiqc_config) path(extra_multiqc_config) path(multiqc_logo) + path(replace_names) + path(sample_names) output: path "*multiqc_report.html", emit: report @@ -23,14 +25,22 @@ process MULTIQC { script: def args = task.ext.args ?: '' + def prefix = task.ext.prefix ? "--filename ${task.ext.prefix}.html" : '' def config = multiqc_config ? "--config $multiqc_config" : '' def extra_config = extra_multiqc_config ? "--config $extra_multiqc_config" : '' + def logo = multiqc_logo ? "--cl-config 'custom_logo: \"${multiqc_logo}\"'" : '' + def replace = replace_names ? "--replace-names ${replace_names}" : '' + def samples = sample_names ? "--sample-names ${sample_names}" : '' """ multiqc \\ --force \\ $args \\ $config \\ + $prefix \\ $extra_config \\ + $logo \\ + $replace \\ + $samples \\ . cat <<-END_VERSIONS > versions.yml @@ -41,8 +51,8 @@ process MULTIQC { stub: """ - touch multiqc_data - touch multiqc_plots + mkdir multiqc_data + mkdir multiqc_plots touch multiqc_report.html cat <<-END_VERSIONS > versions.yml diff --git a/modules/nf-core/multiqc/meta.yml b/modules/nf-core/multiqc/meta.yml index f93b5ee..b16c187 100644 --- a/modules/nf-core/multiqc/meta.yml +++ b/modules/nf-core/multiqc/meta.yml @@ -1,6 +1,6 @@ -# yaml-language-server: $schema=https://raw.githubusercontent.com/nf-core/modules/master/modules/yaml-schema.json -name: MultiQC -description: Aggregate results from bioinformatics analyses across many samples into a single report +name: multiqc +description: Aggregate results from bioinformatics analyses across many samples into + a single report keywords: - QC - bioinformatics tools @@ -13,44 +13,66 @@ tools: homepage: https://multiqc.info/ documentation: https://multiqc.info/docs/ licence: ["GPL-3.0-or-later"] - + identifier: biotools:multiqc input: - - multiqc_files: - type: file - description: | - List of reports / files recognised by MultiQC, for example the html and zip output of FastQC - - multiqc_config: - type: file - description: Optional config yml for MultiQC - pattern: "*.{yml,yaml}" - - extra_multiqc_config: - type: file - description: Second optional config yml for MultiQC. Will override common sections in multiqc_config. - pattern: "*.{yml,yaml}" - - multiqc_logo: - type: file - description: Optional logo file for MultiQC - pattern: "*.{png}" - + - - multiqc_files: + type: file + description: | + List of reports / files recognised by MultiQC, for example the html and zip output of FastQC + - - multiqc_config: + type: file + description: Optional config yml for MultiQC + pattern: "*.{yml,yaml}" + - - extra_multiqc_config: + type: file + description: Second optional config yml for MultiQC. Will override common sections + in multiqc_config. + pattern: "*.{yml,yaml}" + - - multiqc_logo: + type: file + description: Optional logo file for MultiQC + pattern: "*.{png}" + - - replace_names: + type: file + description: | + Optional two-column sample renaming file. First column a set of + patterns, second column a set of corresponding replacements. Passed via + MultiQC's `--replace-names` option. + pattern: "*.{tsv}" + - - sample_names: + type: file + description: | + Optional TSV file with headers, passed to the MultiQC --sample_names + argument. + pattern: "*.{tsv}" output: - report: - type: file - description: MultiQC report file - pattern: "multiqc_report.html" + - "*multiqc_report.html": + type: file + description: MultiQC report file + pattern: "multiqc_report.html" - data: - type: directory - description: MultiQC data dir - pattern: "multiqc_data" + - "*_data": + type: directory + description: MultiQC data dir + pattern: "multiqc_data" - plots: - type: file - description: Plots created by MultiQC - pattern: "*_data" + - "*_plots": + type: file + description: Plots created by MultiQC + pattern: "*_data" - versions: - type: file - description: File containing software versions - pattern: "versions.yml" + - versions.yml: + type: file + description: File containing software versions + pattern: "versions.yml" authors: - "@abhi18av" - "@bunop" - "@drpatelh" - "@jfy133" +maintainers: + - "@abhi18av" + - "@bunop" + - "@drpatelh" + - "@jfy133" diff --git a/modules/nf-core/multiqc/tests/main.nf.test b/modules/nf-core/multiqc/tests/main.nf.test new file mode 100644 index 0000000..33316a7 --- /dev/null +++ b/modules/nf-core/multiqc/tests/main.nf.test @@ -0,0 +1,92 @@ +nextflow_process { + + name "Test Process MULTIQC" + script "../main.nf" + process "MULTIQC" + + tag "modules" + tag "modules_nfcore" + tag "multiqc" + + config "./nextflow.config" + + test("sarscov2 single-end [fastqc]") { + + when { + process { + """ + input[0] = Channel.of(file(params.modules_testdata_base_path + 'genomics/sarscov2/illumina/fastqc/test_fastqc.zip', checkIfExists: true)) + input[1] = [] + input[2] = [] + input[3] = [] + input[4] = [] + input[5] = [] + """ + } + } + + then { + assertAll( + { assert process.success }, + { assert process.out.report[0] ==~ ".*/multiqc_report.html" }, + { assert process.out.data[0] ==~ ".*/multiqc_data" }, + { assert snapshot(process.out.versions).match("multiqc_versions_single") } + ) + } + + } + + test("sarscov2 single-end [fastqc] [config]") { + + when { + process { + """ + input[0] = Channel.of(file(params.modules_testdata_base_path + 'genomics/sarscov2/illumina/fastqc/test_fastqc.zip', checkIfExists: true)) + input[1] = Channel.of(file("https://github.com/nf-core/tools/raw/dev/nf_core/pipeline-template/assets/multiqc_config.yml", checkIfExists: true)) + input[2] = [] + input[3] = [] + input[4] = [] + input[5] = [] + """ + } + } + + then { + assertAll( + { assert process.success }, + { assert process.out.report[0] ==~ ".*/multiqc_report.html" }, + { assert process.out.data[0] ==~ ".*/multiqc_data" }, + { assert snapshot(process.out.versions).match("multiqc_versions_config") } + ) + } + } + + test("sarscov2 single-end [fastqc] - stub") { + + options "-stub" + + when { + process { + """ + input[0] = Channel.of(file(params.modules_testdata_base_path + 'genomics/sarscov2/illumina/fastqc/test_fastqc.zip', checkIfExists: true)) + input[1] = [] + input[2] = [] + input[3] = [] + input[4] = [] + input[5] = [] + """ + } + } + + then { + assertAll( + { assert process.success }, + { assert snapshot(process.out.report.collect { file(it).getName() } + + process.out.data.collect { file(it).getName() } + + process.out.plots.collect { file(it).getName() } + + process.out.versions ).match("multiqc_stub") } + ) + } + + } +} diff --git a/modules/nf-core/multiqc/tests/main.nf.test.snap b/modules/nf-core/multiqc/tests/main.nf.test.snap new file mode 100644 index 0000000..2fcbb5f --- /dev/null +++ b/modules/nf-core/multiqc/tests/main.nf.test.snap @@ -0,0 +1,41 @@ +{ + "multiqc_versions_single": { + "content": [ + [ + "versions.yml:md5,41f391dcedce7f93ca188f3a3ffa0916" + ] + ], + "meta": { + "nf-test": "0.9.0", + "nextflow": "24.04.4" + }, + "timestamp": "2024-10-02T17:51:46.317523" + }, + "multiqc_stub": { + "content": [ + [ + "multiqc_report.html", + "multiqc_data", + "multiqc_plots", + "versions.yml:md5,41f391dcedce7f93ca188f3a3ffa0916" + ] + ], + "meta": { + "nf-test": "0.9.0", + "nextflow": "24.04.4" + }, + "timestamp": "2024-10-02T17:52:20.680978" + }, + "multiqc_versions_config": { + "content": [ + [ + "versions.yml:md5,41f391dcedce7f93ca188f3a3ffa0916" + ] + ], + "meta": { + "nf-test": "0.9.0", + "nextflow": "24.04.4" + }, + "timestamp": "2024-10-02T17:52:09.185842" + } +} \ No newline at end of file diff --git a/modules/nf-core/multiqc/tests/nextflow.config b/modules/nf-core/multiqc/tests/nextflow.config new file mode 100644 index 0000000..c537a6a --- /dev/null +++ b/modules/nf-core/multiqc/tests/nextflow.config @@ -0,0 +1,5 @@ +process { + withName: 'MULTIQC' { + ext.prefix = null + } +} diff --git a/modules/nf-core/multiqc/tests/tags.yml b/modules/nf-core/multiqc/tests/tags.yml new file mode 100644 index 0000000..bea6c0d --- /dev/null +++ b/modules/nf-core/multiqc/tests/tags.yml @@ -0,0 +1,2 @@ +multiqc: + - modules/nf-core/multiqc/** diff --git a/nextflow.config b/nextflow.config index 0b6dcc9..8666527 100644 --- a/nextflow.config +++ b/nextflow.config @@ -9,203 +9,184 @@ // Global default params, used in configs params { // Input options - input = null - peptides_split_maxchunks = 100 - peptides_split_minchunksize = 5000 - split_by_variants = false - split_by_variants_size = 0 - split_by_variants_distance = 110000 + input = null + peptides_split_maxchunks = 100 + peptides_split_minchunksize = 5000 + split_by_variants = false + split_by_variants_size = 0 + split_by_variants_distance = 110000 // References - genome_version = 'GRCh37' + genome_reference = 'grch37' // Options: Predictions - tools = 'syfpeithi' - tool_thresholds = null + tools = 'syfpeithi' + tool_thresholds = null use_affinity_thresholds = false // Options: Filtering - filter_self = false + filter_self = false show_supported_models = false // External tools external_tools_meta = "${projectDir}/assets/external_tools_meta.json" - netmhc_system = 'linux' - netmhcpan_path = null - netmhc_path = null - netmhciipan_path = null - netmhcii_path = null + netmhc_system = 'linux' + netmhcpan_path = null + netmhc_path = null + netmhciipan_path = null + netmhcii_path = null // Options: Peptides - max_peptide_length = 11 - min_peptide_length = 8 + max_peptide_length = 11 + min_peptide_length = 8 max_peptide_length_class2 = 16 min_peptide_length_class2 = 15 // Options: Annotation - proteome = null + proteome = null wild_type = false // Options: Output fasta_output = false // MultiQC options - multiqc_config = null - multiqc_title = null - multiqc_logo = "$projectDir/assets/nf-core-epitopeprediction_logo_light.png" - max_multiqc_email_size = '25.MB' + multiqc_config = null + multiqc_title = null + multiqc_logo = "$projectDir/assets/nf-core-epitopeprediction_logo_light.png" + max_multiqc_email_size = '25.MB' multiqc_methods_description = null // Boilerplate options - outdir = null - publish_dir_mode = 'copy' - email = null - email_on_fail = null - plaintext_email = false - monochrome_logs = false - hook_url = null - help = false - version = false - validate_params = true - show_hidden_params = false - schema_ignore_params = 'genomes' - igenomes_ignore = true + outdir = null + publish_dir_mode = 'copy' + email = null + email_on_fail = null + plaintext_email = false + monochrome_logs = false + hook_url = null + help = false + help_full = false + show_hidden = false + version = false + pipelines_testdata_base_path = 'https://raw.githubusercontent.com/nf-core/test-datasets/' // Config options config_profile_name = null config_profile_description = null + custom_config_version = 'master' custom_config_base = "https://raw.githubusercontent.com/nf-core/configs/${params.custom_config_version}" config_profile_contact = null config_profile_url = null - config_profile_name = null - - // Max resource options - // Defaults only, expecting to be overwritten - max_memory = '128.GB' - max_cpus = 16 - max_time = '240.h' // Schema validation default options - validationFailUnrecognisedParams = false - validationLenientMode = false - validationSchemaIgnoreParams = 'genomes' - validationShowHiddenParams = false - validate_params = true - - conda.enabled = false - + validate_params = true } // Load base.config by default for all pipelines includeConfig 'conf/base.config' -// Load nf-core custom profiles from different Institutions -try { - includeConfig "${params.custom_config_base}/nfcore_custom.config" -} catch (Exception e) { - System.err.println("WARNING: Could not load nf-core/config profiles: ${params.custom_config_base}/nfcore_custom.config") -} - -// Load nf-core/epitopeprediction custom profiles from different institutions. -// Warning: Uncomment only if a pipeline-specific instititutional config already exists on nf-core/configs! -// try { -// includeConfig "${params.custom_config_base}/pipeline/epitopeprediction.config" -// } catch (Exception e) { -// System.err.println("WARNING: Could not load nf-core/config/epitopeprediction profiles: ${params.custom_config_base}/pipeline/epitopeprediction.config") -// } profiles { debug { - dumpHashes = true - process.beforeScript = 'echo $HOSTNAME' - cleanup = false + dumpHashes = true + process.beforeScript = 'echo $HOSTNAME' + cleanup = false + nextflow.enable.configProcessNamesValidation = true } conda { - conda.enabled = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - apptainer.enabled = false + conda.enabled = true + docker.enabled = false + singularity.enabled = false + podman.enabled = false + shifter.enabled = false + charliecloud.enabled = false + conda.channels = ['conda-forge', 'bioconda'] + apptainer.enabled = false } mamba { - conda.enabled = true - conda.useMamba = true - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - apptainer.enabled = false + conda.enabled = true + conda.useMamba = true + docker.enabled = false + singularity.enabled = false + podman.enabled = false + shifter.enabled = false + charliecloud.enabled = false + apptainer.enabled = false } docker { - docker.enabled = true - docker.userEmulation = true - conda.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - apptainer.enabled = false + docker.enabled = true + conda.enabled = false + singularity.enabled = false + podman.enabled = false + shifter.enabled = false + charliecloud.enabled = false + apptainer.enabled = false + docker.runOptions = '-u $(id -u):$(id -g)' } arm { - docker.runOptions = '-u $(id -u):$(id -g) --platform=linux/amd64' + docker.runOptions = '-u $(id -u):$(id -g) --platform=linux/amd64' } singularity { - singularity.enabled = true - singularity.autoMounts = true - conda.enabled = false - docker.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false - apptainer.enabled = false + singularity.enabled = true + singularity.autoMounts = true + conda.enabled = false + docker.enabled = false + podman.enabled = false + shifter.enabled = false + charliecloud.enabled = false + apptainer.enabled = false } podman { - podman.enabled = true - conda.enabled = false - docker.enabled = false - singularity.enabled = false - shifter.enabled = false - charliecloud.enabled = false - apptainer.enabled = false + podman.enabled = true + conda.enabled = false + docker.enabled = false + singularity.enabled = false + shifter.enabled = false + charliecloud.enabled = false + apptainer.enabled = false } shifter { - shifter.enabled = true - conda.enabled = false - docker.enabled = false - singularity.enabled = false - podman.enabled = false - charliecloud.enabled = false - apptainer.enabled = false + shifter.enabled = true + conda.enabled = false + docker.enabled = false + singularity.enabled = false + podman.enabled = false + charliecloud.enabled = false + apptainer.enabled = false } charliecloud { - charliecloud.enabled = true - conda.enabled = false - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - apptainer.enabled = false + charliecloud.enabled = true + conda.enabled = false + docker.enabled = false + singularity.enabled = false + podman.enabled = false + shifter.enabled = false + apptainer.enabled = false } apptainer { - apptainer.enabled = true - conda.enabled = false - docker.enabled = false - singularity.enabled = false - podman.enabled = false - shifter.enabled = false - charliecloud.enabled = false + apptainer.enabled = true + apptainer.autoMounts = true + conda.enabled = false + docker.enabled = false + singularity.enabled = false + podman.enabled = false + shifter.enabled = false + charliecloud.enabled = false + } + wave { + apptainer.ociAutoPull = true + singularity.ociAutoPull = true + wave.enabled = true + wave.freeze = true + wave.strategy = 'conda,container' } gitpod { - executor.name = 'local' - executor.cpus = 16 - executor.memory = 60.GB + executor.name = 'local' + executor.cpus = 4 + executor.memory = 8.GB } test { includeConfig 'conf/test.config' } - test_variant_tsv { includeConfig 'conf/test_variant_tsv.config' } - test_grch38_variant_tsv { includeConfig 'conf/test_grch38_variant_tsv.config' } + test_grch38 { includeConfig 'conf/test_grch38.config' } test_peptides { includeConfig 'conf/test_peptides.config' } test_peptides_h2 { includeConfig 'conf/test_peptides_h2.config' } test_proteins { includeConfig 'conf/test_proteins.config' } @@ -217,25 +198,18 @@ profiles { test_full { includeConfig 'conf/test_full.config' } } -// Set default registry for Apptainer, Docker, Podman and Singularity independent of -profile -// Will not be used unless Apptainer / Docker / Podman / Singularity are enabled -// Set to your registry if you have a mirror of containers -apptainer.registry = 'quay.io' -docker.registry = 'quay.io' -podman.registry = 'quay.io' -singularity.registry = 'quay.io' +// Load nf-core custom profiles from different Institutions +includeConfig !System.getenv('NXF_OFFLINE') && params.custom_config_base ? "${params.custom_config_base}/nfcore_custom.config" : "/dev/null" -// Nextflow plugins -plugins { - id 'nf-validation' // Validation of pipeline parameters and creation of an input channel from a sample sheet -} +// Set default registry for Apptainer, Docker, Podman, Charliecloud and Singularity independent of -profile +// Will not be used unless Apptainer / Docker / Podman / Charliecloud / Singularity are enabled +// Set to your registry if you have a mirror of containers +apptainer.registry = 'quay.io' +docker.registry = 'quay.io' +podman.registry = 'quay.io' +singularity.registry = 'quay.io' +charliecloud.registry = 'quay.io' -// Load igenomes.config if required -if (!params.igenomes_ignore) { - includeConfig 'conf/igenomes.config' -} else { - params.genomes = [:] -} // Export these variables to prevent local Python/R libraries from conflicting with those in the container // The JULIA depot path has been adjusted to a fixed path `/usr/local/share/julia` that needs to be used for packages in the container. // See https://apeltzer.github.io/post/03-julia-lang-nextflow/ for details on that. Once we have a common agreement on where to keep Julia packages, this is adjustable. @@ -247,8 +221,18 @@ env { JULIA_DEPOT_PATH = "/usr/local/share/julia" } -// Capture exit codes from upstream processes when piping -process.shell = ['/bin/bash', '-euo', 'pipefail'] +// Set bash options +process.shell = """\ +bash + +set -e # Exit if a tool returns a non-zero status/exit code +set -u # Treat unset variables and parameters as an error +set -o pipefail # Returns the status of the last command to exit with a non-zero status or zero if all successfully execute +set -C # No clobber - prevent output redirection from overwriting files. +""" + +// Disable process selector warnings by default. Use debug profile to enable warnings. +nextflow.enable.configProcessNamesValidation = false def trace_timestamp = new java.util.Date().format( 'yyyy-MM-dd_HH-mm-ss') timeline { @@ -277,40 +261,46 @@ manifest { homePage = 'https://github.com/nf-core/epitopeprediction' description = """A fully reproducible and state of the art epitope prediction pipeline.""" mainScript = 'main.nf' - nextflowVersion = '!>=23.04.0' - version = '2.2.2dev' + nextflowVersion = '!>=24.04.2' + version = '2.4.0dev' doi = '' } -// Function to ensure that resource requirements don't go beyond -// a maximum limit -def check_max(obj, type) { - if (type == 'memory') { - try { - if (obj.compareTo(params.max_memory as nextflow.util.MemoryUnit) == 1) - return params.max_memory as nextflow.util.MemoryUnit - else - return obj - } catch (all) { - println " ### ERROR ### Max memory '${params.max_memory}' is not valid! Using default value: $obj" - return obj - } - } else if (type == 'time') { - try { - if (obj.compareTo(params.max_time as nextflow.util.Duration) == 1) - return params.max_time as nextflow.util.Duration - else - return obj - } catch (all) { - println " ### ERROR ### Max time '${params.max_time}' is not valid! Using default value: $obj" - return obj - } - } else if (type == 'cpus') { - try { - return Math.min( obj, params.max_cpus as int ) - } catch (all) { - println " ### ERROR ### Max cpus '${params.max_cpus}' is not valid! Using default value: $obj" - return obj - } +// Nextflow plugins +plugins { + id 'nf-schema@2.1.1' // Validation of pipeline parameters and creation of an input channel from a sample sheet +} + +validation { + //defaultIgnoreParams = ["genomes"] + help { + enabled = true + command = "nextflow run $manifest.name -profile --input samplesheet.csv --outdir " + fullParameter = "help_full" + showHiddenParameter = "show_hidden" + beforeText = """ +-\033[2m----------------------------------------------------\033[0m- + \033[0;32m,--.\033[0;30m/\033[0;32m,-.\033[0m +\033[0;34m ___ __ __ __ ___ \033[0;32m/,-._.--~\'\033[0m +\033[0;34m |\\ | |__ __ / ` / \\ |__) |__ \033[0;33m} {\033[0m +\033[0;34m | \\| | \\__, \\__/ | \\ |___ \033[0;32m\\`-._,-`-,\033[0m + \033[0;32m`._,._,\'\033[0m +\033[0;35m ${manifest.name} ${manifest.version}\033[0m +-\033[2m----------------------------------------------------\033[0m- +""" + afterText = """${manifest.doi ? "* The pipeline\n" : ""}${manifest.doi.tokenize(",").collect { " https://doi.org/${it.trim().replace('https://doi.org/','')}"}.join("\n")}${manifest.doi ? "\n" : ""} +* The nf-core framework + https://doi.org/10.1038/s41587-020-0439-x + +* Software dependencies + https://github.com/${manifest.name}/blob/master/CITATIONS.md +""" + } + summary { + beforeText = validation.help.beforeText + afterText = validation.help.afterText } } + +// Load modules.config for DSL2 module specific options +includeConfig 'conf/modules.config' diff --git a/nextflow_schema.json b/nextflow_schema.json index aefc10b..4a5bf5d 100644 --- a/nextflow_schema.json +++ b/nextflow_schema.json @@ -1,10 +1,10 @@ { - "$schema": "http://json-schema.org/draft-07/schema", + "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://raw.githubusercontent.com/nf-core/epitopeprediction/master/nextflow_schema.json", "title": "nf-core/epitopeprediction pipeline parameters", "description": "A fully reproducible and state of the art epitope prediction pipeline.", "type": "object", - "definitions": { + "$defs": { "input_output_options": { "title": "Input/output options", "type": "object", @@ -16,8 +16,7 @@ "type": "string", "format": "file-path", "exists": true, - "mimetype": "text/csv", - "pattern": "^\\S+\\.csv$", + "schema": "assets/schema_input.json", "description": "Path to comma-separated file containing information about the samples in the experiment.", "help_text": "You will need to create a design file with information about the samples in your experiment before running the pipeline. Use this parameter to specify its location. It has to be a comma-separated file with 3 columns, and a header row. See [usage docs](https://nf-co.re/epitopeprediction/usage#samplesheet-input).", "fa_icon": "fas fa-file-csv" @@ -48,12 +47,11 @@ "description": "Options for the genome and proteome reference.", "fa_icon": "fas fa-stream", "properties": { - "genome_version": { + "genome_reference": { "type": "string", - "default": "GRCh37", - "help_text": "This defines against which human reference genome the pipeline performs the analysis including the incorporation of genetic variants e.g..", - "enum": ["GRCh37", "GRCh38"], - "description": "Specifies the human reference genome version." + "default": "grch37", + "help_text": "This defines against which human Ensembl genome reference the pipeline performs the analysis including the incorporation of genetic variants. If `grch37` or `grch38` are specified, the most recent Ensembl Biomart version for genome versions will be used. Alternatively, an Ensembl Biomart (archive) version can be specified, e.g. http://jan2020.archive.ensembl.org/.", + "description": "Specifies the Ensembl genome reference version that will be used." }, "proteome": { "type": "string", @@ -62,21 +60,6 @@ } } }, - "reference_genome_options": { - "title": "Reference genome options", - "type": "object", - "fa_icon": "fas fa-dna", - "description": "Reference genome related files and options required for the workflow.", - "properties": { - "igenomes_ignore": { - "type": "boolean", - "description": "Do not load the iGenomes reference config.", - "fa_icon": "fas fa-ban", - "hidden": true, - "help_text": "Do not load `igenomes.config` when running the pipeline. You may choose this option if you observe clashes between custom parameters and those supplied in `igenomes.config`." - } - } - }, "peptide_prediction_options": { "title": "Peptide prediction options", "type": "object", @@ -113,6 +96,7 @@ "tools": { "type": "string", "default": "syfpeithi", + "pattern": "^(syfpeithi|mhcnuggets-class-1|mhcnuggets-class-2|mhcflurry|netmhc-4.0|netmhcpan-4.0|netmhcpan-4.1|netmhciipan-4.1|netmhc_darwin-4.0|netmhcpan_darwin-4.0|netmhcpan_darwin-4.1|netmhciipan_darwin-4.1)(,(syfpeithi|mhcnuggets-class-1|mhcnuggets-class-2|mhcflurry|netmhc-4.0|netmhcpan-4.0|netmhcpan-4.1|netmhciipan-4.1|netmhc_darwin-4.0|netmhcpan_darwin-4.0|netmhcpan_darwin-4.1|netmhciipan_darwin-4.1))*$", "help_text": "Specifies the tool(s) to use. Multiple tools can be combined in a list separated by comma.\nAvailable are: `syfpeithi`, `mhcflurry`, `mhcnuggets-class-1`, `mhcnuggets-class-2`,`netmhcpan-4.0`,`netmhcpan-4.1`,`netmhc-4.0`,`netmhciipan-4.1`.", "description": "Specifies the prediction tool(s) to use." }, @@ -186,32 +170,40 @@ "properties": { "external_tools_meta": { "type": "string", - "default": "${projectDir}/assets/external_tools_meta.json", "description": "Specifies the path to the JSON file with meta information on external prediction tools." }, "netmhc_system": { "type": "string", "default": "linux", + "enum": ["linux", "darwin"], "description": "Specifies the operating system in use (Linux or Darwin). This is only necessary if conda is used." }, "netmhcpan_path": { "type": "string", - "default": "None", + "format": "file-path", + "exists": true, + "pattern": "^\\S+\\.tar\\.gz$", "description": "To use the 'netmhcpan' tool, specify the path to the original software tarball for NetMHCpan 4.0 here." }, "netmhc_path": { "type": "string", - "default": "None", + "format": "file-path", + "exists": true, + "pattern": "^\\S+\\.tar\\.gz$", "description": "To use the 'netmhc' tool, specify the path to the original software tarball for NetMHC 4.0 here." }, "netmhciipan_path": { "type": "string", - "default": "None", + "format": "file-path", + "exists": true, + "pattern": "^\\S+\\.tar\\.gz$", "description": "To use the 'netmhciipan' tool, specify the path to the original software tarball for NetMHCIIpan 3.1 here." }, "netmhcii_path": { "type": "string", - "default": "None", + "format": "file-path", + "exists": true, + "pattern": "^\\S+\\.tar\\.gz$", "description": "To use the 'netmhcii' tool, specify the path to the original software tarball for NetMHCII 2.2 here." } } @@ -265,41 +257,6 @@ } } }, - "max_job_request_options": { - "title": "Max job request options", - "type": "object", - "fa_icon": "fab fa-acquisitions-incorporated", - "description": "Set the top limit for requested resources for any single job.", - "help_text": "If you are running on a smaller system, a pipeline step requesting more resources than are available may cause the Nextflow to stop the run with an error. These options allow you to cap the maximum resources requested by any single job so that the pipeline will run on your system.\n\nNote that you can not _increase_ the resources requested by any job using these options. For that you will need your own configuration file. See [the nf-core website](https://nf-co.re/usage/configuration) for details.", - "properties": { - "max_cpus": { - "type": "integer", - "description": "Maximum number of CPUs that can be requested for any single job.", - "default": 16, - "fa_icon": "fas fa-microchip", - "hidden": true, - "help_text": "Use to set an upper-limit for the CPU requirement for each process. Should be an integer e.g. `--max_cpus 1`" - }, - "max_memory": { - "type": "string", - "description": "Maximum amount of memory that can be requested for any single job.", - "default": "128.GB", - "fa_icon": "fas fa-memory", - "pattern": "^\\d+(\\.\\d+)?\\.?\\s*(K|M|G|T)?B$", - "hidden": true, - "help_text": "Use to set an upper-limit for the memory requirement for each process. Should be a string in the format integer-unit e.g. `--max_memory '8.GB'`" - }, - "max_time": { - "type": "string", - "description": "Maximum amount of time that can be requested for any single job.", - "default": "240.h", - "fa_icon": "far fa-clock", - "pattern": "^(\\d+\\.?\\s*(s|m|h|d|day)\\s*)+$", - "hidden": true, - "help_text": "Use to set an upper-limit for the time requirement for each process. Should be a string in the format integer-unit e.g. `--max_time '2.h'`" - } - } - }, "generic_options": { "title": "Generic options", "type": "object", @@ -307,18 +264,10 @@ "description": "Less common options for the pipeline, typically set in a config file.", "help_text": "These options are common to all nf-core pipelines and allow you to customise some of the core preferences for how the pipeline runs.\n\nTypically these options would be set in a Nextflow config file loaded for all pipeline runs, such as `~/.nextflow/config`.", "properties": { - "help": { - "type": "boolean", - "description": "Display help text.", - "fa_icon": "fas fa-question-circle", - "default": false, - "hidden": true - }, "version": { "type": "boolean", "description": "Display version and exit.", "fa_icon": "fas fa-question-circle", - "default": false, "hidden": true }, "publish_dir_mode": { @@ -342,7 +291,6 @@ "type": "boolean", "description": "Send plain-text email instead of HTML.", "fa_icon": "fas fa-remove-format", - "default": false, "hidden": true }, "max_multiqc_email_size": { @@ -357,7 +305,6 @@ "type": "boolean", "description": "Do not use coloured log outputs.", "fa_icon": "fas fa-palette", - "default": false, "hidden": true }, "hook_url": { @@ -392,42 +339,11 @@ "fa_icon": "fas fa-check-square", "hidden": true }, - "validationShowHiddenParams": { - "type": "boolean", - "fa_icon": "far fa-eye-slash", - "description": "Show all params when using `--help`", - "default": false, - "hidden": true, - "help_text": "By default, parameters set as _hidden_ in the schema are not shown on the command line when a user runs with `--help`. Specifying this option will tell the pipeline to show all parameters." - }, - "validationFailUnrecognisedParams": { - "type": "boolean", - "fa_icon": "far fa-check-circle", - "description": "Validation of parameters fails when an unrecognised parameter is found.", - "default": false, - "hidden": true, - "help_text": "By default, when an unrecognised parameter is found, it returns a warinig." - }, - "validationLenientMode": { - "type": "boolean", - "fa_icon": "far fa-check-circle", - "description": "Validation of parameters in lenient more.", - "default": false, - "hidden": true, - "help_text": "Allows string values that are parseable as numbers or booleans. For further information see [JSONSchema docs](https://github.com/everit-org/json-schema#lenient-mode)." - }, - "show_hidden_params": { - "type": "boolean", - "fa_icon": "far fa-eye-slash", - "description": "Show all params when using `--help`", - "hidden": true, - "help_text": "By default, parameters set as _hidden_ in the schema are not shown on the command line when a user runs with `--help`. Specifying this option will tell the pipeline to show all parameters." - }, - "schema_ignore_params": { + "pipelines_testdata_base_path": { "type": "string", - "default": "genomes", - "description": "Ignore JSON schema validation of the following params", - "fa_icon": "fas fa-ban", + "fa_icon": "far fa-check-circle", + "description": "Base URL or local path to location of pipeline test dataset files", + "default": "https://raw.githubusercontent.com/nf-core/test-datasets/", "hidden": true } } @@ -435,31 +351,25 @@ }, "allOf": [ { - "$ref": "#/definitions/input_output_options" - }, - { - "$ref": "#/definitions/reference_options" - }, - { - "$ref": "#/definitions/reference_genome_options" + "$ref": "#/$defs/input_output_options" }, { - "$ref": "#/definitions/peptide_prediction_options" + "$ref": "#/$defs/reference_options" }, { - "$ref": "#/definitions/run_optimisation" + "$ref": "#/$defs/peptide_prediction_options" }, { - "$ref": "#/definitions/external_software" + "$ref": "#/$defs/run_optimisation" }, { - "$ref": "#/definitions/institutional_config_options" + "$ref": "#/$defs/external_software" }, { - "$ref": "#/definitions/max_job_request_options" + "$ref": "#/$defs/institutional_config_options" }, { - "$ref": "#/definitions/generic_options" + "$ref": "#/$defs/generic_options" } ] } diff --git a/pyproject.toml b/pyproject.toml deleted file mode 100644 index 0d62beb..0000000 --- a/pyproject.toml +++ /dev/null @@ -1,10 +0,0 @@ -# Config file for Python. Mostly used to configure linting of bin/check_samplesheet.py with Black. -# Should be kept the same as nf-core/tools to avoid fighting with template synchronisation. -[tool.black] -line-length = 120 -target_version = ["py37", "py38", "py39", "py310"] - -[tool.isort] -profile = "black" -known_first_party = ["nf_core"] -multi_line_output = 3 diff --git a/subworkflows/local/input_check.nf b/subworkflows/local/input_check.nf deleted file mode 100644 index af9f467..0000000 --- a/subworkflows/local/input_check.nf +++ /dev/null @@ -1,61 +0,0 @@ -// -// Check input samplesheet and get read channels -// - -include { SAMPLESHEET_CHECK } from '../../modules/local/samplesheet_check' - -workflow INPUT_CHECK { - take: - samplesheet // file: /path/to/samplesheet.csv - - main: - SAMPLESHEET_CHECK ( samplesheet ) - .csv - .splitCsv ( header:true ) - .map { get_samplesheet_paths(it) } - .set { meta } - - emit: meta // channel: [ val(meta), [ files ] ] - versions = SAMPLESHEET_CHECK.out.versions // channel: [ versions.yml ] -} - -// Function to get list of [ meta, filenames ] -def get_samplesheet_paths(LinkedHashMap row) { - //--------- - // Save sample, alleles, mhc_class and file_type in a dictionary (metadata) - // and return a list of meta and the filename. - //--------- - - def meta = [:] - meta.sample = row.sample - meta.alleles = row.alleles - meta.mhcclass = row.mhc_class - meta.inputtype = row.inputtype - - def array = [] - if (!file(row.filename).exists()) { - exit 1, "ERROR: Please check input samplesheet -> file does not exist!\n${row.Filename}" - } else { - array = [ meta, file(row.filename) ] - } - return array -} - -def generate_allele_string(String alleles, String mhcclass) { - // Collect the allele information from the file - def allele_string - valid_class1_loci = ['A*','B*','C*','E*','G*'] - valid_class2_loci = ['DR','DP','DQ'] - if ( alleles.endsWith(".txt") || alleles.endsWith(".alleles") ) { - allele_string = file(alleles).readLines().join(';') - if ((mhcclass == 'I' & valid_class2_loci.any { allele_string.contains(it)}) | - (mhcclass == 'II' & valid_class1_loci.any { allele_string.contains(it)})) { - exit 1, "ERROR: Please check input samplesheet -> invalid mhc class and allele combination found!\n${row.Filename}" - } - } - // or assign the information to a new variable - else { - allele_string = alleles - } - return allele_string -} diff --git a/subworkflows/local/mhc_binding_prediction.nf b/subworkflows/local/mhc_binding_prediction.nf index cac618b..31c5272 100755 --- a/subworkflows/local/mhc_binding_prediction.nf +++ b/subworkflows/local/mhc_binding_prediction.nf @@ -1,118 +1,85 @@ // // Check input samplesheet and get read channels // - +include { PREPARE_PREDICTION_INPUT } from '../../modules/local/prepare_prediction_input' include { SYFPEITHI } from '../../modules/local/syfpeithi' include { MHCFLURRY } from '../../modules/local/mhcflurry' include { MHCNUGGETS } from '../../modules/local/mhcnuggets' include { NETMHCPAN } from '../../modules/local/netmhcpan' include { NETMHCIIPAN } from '../../modules/local/netmhciipan' -include { EXTERNAL_TOOLS_IMPORT} from '../../modules/local/external_tools_import' +include { parse_netmhc_params } from '../../subworkflows/local/utils_nfcore_epitopeprediction_pipeline' +include { EXTERNAL_TOOLS_IMPORT as NETMHCPAN_IMPORT; + EXTERNAL_TOOLS_IMPORT as NETMHCIIPAN_IMPORT} from '../../modules/local/external_tools_import' include { MERGE_PREDICTIONS } from '../../modules/local/merge_predictions' -include { PREPARE_PREDICTION_INPUT } from '../../modules/local/prepare_prediction_input' workflow MHC_BINDING_PREDICTION { take: - metadata_and_file + ch_peptides main: ch_versions = Channel.empty() - ch_combined_predictions = Channel.empty() + ch_binding_predictors_out = Channel.empty() - if (params.tools.isEmpty()) { exit 1, "No valid tools specified." } - - tools = params.tools.split(',') + //TODO: Add //"pattern": "^(syfpeithi|mhcnuggets|mhcflurry|netmhcpan|netmhciipan)(,(syfpeithi|mhcnuggets|mhcflurry|netmhcpan|netmhciipan)){0,4}$", + // to nextflow_schema.json once this subworkflow is completed //prepare the input file - PREPARE_PREDICTION_INPUT( metadata_and_file ) + PREPARE_PREDICTION_INPUT( ch_peptides ) .prepared - .set { prepared_metadata_and_file } - - prepared_metadata_and_file + .transpose() .branch { - meta, peptide_file -> - syfpeithi : peptide_file.toString().contains("syfpeithi_input.csv") - return [meta, peptide_file] - mhcflurry : peptide_file.toString().contains("mhcflurry_input.csv") - return [meta, peptide_file] - mhcnuggets : peptide_file.toString().contains("mhcnuggets_input.csv") - return [meta, peptide_file] - netmhcpan: peptide_file.toString().contains("netmhcpan_input.csv") - return [meta, peptide_file] - netmhciipan: peptide_file.toString().contains("netmhciipan_input.csv") - return [meta, peptide_file] + meta, file -> + syfpeithi : file.name.contains('syfpeithi') + return [meta, file] + mhcflurry : file.name.contains('mhcflurry') + return [meta, file] + mhcnuggets : file.name.contains('mhcnuggets') + return [meta, file] + netmhcpan: file.name.contains('netmhcpan') + return [meta, file] + netmhciipan: file.name.contains('netmhciipan') + return [meta, file] } - .set{ prepared } + .set{ ch_prediction_input } - SYFPEITHI ( prepared.syfpeithi ) + SYFPEITHI ( ch_prediction_input.syfpeithi ) ch_versions = ch_versions.mix(SYFPEITHI.out.versions) - ch_combined_predictions = ch_combined_predictions.join(SYFPEITHI.out.predicted, remainder: true) + ch_binding_predictors_out = ch_binding_predictors_out.mix(SYFPEITHI.out.predicted) - MHCFLURRY ( prepared.mhcflurry ) + MHCFLURRY ( ch_prediction_input.mhcflurry ) ch_versions = ch_versions.mix(MHCFLURRY.out.versions) - ch_combined_predictions = ch_combined_predictions.join(MHCFLURRY.out.predicted, remainder: true) + ch_binding_predictors_out = ch_binding_predictors_out.mix(MHCFLURRY.out.predicted) - MHCNUGGETS ( prepared.mhcnuggets ) + MHCNUGGETS ( ch_prediction_input.mhcnuggets ) ch_versions = ch_versions.mix(MHCNUGGETS.out.versions) - ch_combined_predictions = ch_combined_predictions.join(MHCNUGGETS.out.predicted, remainder: true) + ch_binding_predictors_out = ch_binding_predictors_out.mix(MHCNUGGETS.out.predicted) - if ( "netmhcpan" in tools ) + if ( "netmhcpan" in params.tools.tokenize(",") ) { - EXTERNAL_TOOLS_IMPORT (parse_netmhc_params("netmhcpan", "4.1")) - NETMHCPAN (prepared.combine(EXTERNAL_TOOLS_IMPORT.out.nonfree_tools)) + //TODO: Refactor to support only one netmhc version + //TODO: Fix parsing version + NETMHCPAN_IMPORT( parse_netmhc_params("netmhcpan", "4.1") ) + //TODO: Update netmhc container + //TODO Fix parsing version + NETMHCPAN ( ch_prediction_input.netmhcpan.combine(NETMHCPAN_IMPORT.out.nonfree_tools) ) ch_versions = ch_versions.mix(NETMHCPAN.out.versions) - ch_combined_predictions = ch_combined_predictions.join(NETMHCPAN.out.predicted, remainder: true) + ch_binding_predictors_out = ch_binding_predictors_out.mix(NETMHCPAN.out.predicted) } - // TODO: External tools import for netmhciipan - if ( "netmhciipan" in tools ) + + if ( "netmhciipan" in params.tools.tokenize(",") ) { - NETMHCIIPAN ( prepared_metadata_and_file.netmhciipan ) + // TODO: External tools import for netmhciipan + NETMHCIIPAN_IMPORT( parse_netmhc_params("netmhciipan", "4.3") ) + //TODO: Update netmhc container + NETMHCIIPAN ( ch_prediction_input.netmhcpan.combine(NETMHCIIPAN_IMPORT.out.nonfree_tools) ) ch_versions = ch_versions.mix(NETMHCIIPAN.out.versions) - ch_combined_predictions = ch_combined_predictions.join(NETMHCIIPAN.out.predicted, remainder: true) + ch_binding_predictors_out = ch_binding_predictors_out.mix(NETMHCIIPAN.out.predicted) } - - //remove the null (it[1]) in the channel output and join metadata and input channel with metadata and output channel - ch_combined_predictions = ch_combined_predictions.map{ it -> [it[0], it[2..-1]]}.join(prepared_metadata_and_file, remainder: true) - - //merge the prediction output of all tools into one output merged_prediction.tsv - //MERGE_PREDICTIONS (ch_combined_predictions) - //ch_versions = ch_versions.mix(MERGE_PREDICTIONS.out.versions) + ch_binding_predictors_out.groupTuple().view() + MERGE_PREDICTIONS (ch_binding_predictors_out.groupTuple()) + ch_versions = ch_versions.mix(MERGE_PREDICTIONS.out.versions) emit: - //predicted = MERGE_PREDICTIONS.out.merged - predicted = Channel.empty() + predicted = MERGE_PREDICTIONS.out.merged versions = ch_versions } - -// Functions -def parse_netmhc_params(tool_name, tool_version) { - // Check if the _path parameter was set for this tool - if (!params["${tool_name}_path"]) - { - error("--${tool_name}_path not specified, but --tools contains ${tool_name}. Both have to be specified to enable ${tool_name}. Ignoring.") - } - else if (params["${tool_name}_path"]) - { - // Import mandatory netmhc metadata - def jsonSlurper = new groovy.json.JsonSlurper() - def external_tools_meta = jsonSlurper.parse(file(params.external_tools_meta, checkIfExists: true)) - def entry = external_tools_meta[tool_name][tool_version] - - if (params["netmhc_system"] == 'darwin') { - entry = external_tools_meta["${tool_name}_darwin"][tool_version] - } - // If so, add the tool name and user installation path to the external tools import channel - ch_nonfree_paths = Channel.empty() - ch_nonfree_paths.bind([ - tool_name, - entry.version, - entry.software_md5, - file(params["${tool_name}_path"], checkIfExists:true), - file(entry.data_url), - entry.data_md5, - entry.binary_name - ]) - - return ch_nonfree_paths - } -} diff --git a/subworkflows/local/utils_nfcore_epitopeprediction_pipeline/main.nf b/subworkflows/local/utils_nfcore_epitopeprediction_pipeline/main.nf new file mode 100644 index 0000000..e5f39cd --- /dev/null +++ b/subworkflows/local/utils_nfcore_epitopeprediction_pipeline/main.nf @@ -0,0 +1,284 @@ +// +// Subworkflow with functionality specific to the nf-core/epitopeprediction pipeline +// + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + IMPORT FUNCTIONS / MODULES / SUBWORKFLOWS +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ + +include { UTILS_NFSCHEMA_PLUGIN } from '../../nf-core/utils_nfschema_plugin' +include { paramsSummaryMap } from 'plugin/nf-schema' +include { samplesheetToList } from 'plugin/nf-schema' +include { completionEmail } from '../../nf-core/utils_nfcore_pipeline' +include { completionSummary } from '../../nf-core/utils_nfcore_pipeline' +include { imNotification } from '../../nf-core/utils_nfcore_pipeline' +include { UTILS_NFCORE_PIPELINE } from '../../nf-core/utils_nfcore_pipeline' +include { UTILS_NEXTFLOW_PIPELINE } from '../../nf-core/utils_nextflow_pipeline' + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + SUBWORKFLOW TO INITIALISE PIPELINE +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ + +workflow PIPELINE_INITIALISATION { + + take: + version // boolean: Display version and exit + validate_params // boolean: Boolean whether to validate parameters against the schema at runtime + monochrome_logs // boolean: Do not use coloured log outputs + nextflow_cli_args // array: List of positional nextflow CLI args + outdir // string: The output directory where the results will be saved + input // string: Path to input samplesheet + + main: + + ch_versions = Channel.empty() + + // + // Print version and exit if required and dump pipeline parameters to JSON file + // + UTILS_NEXTFLOW_PIPELINE ( + version, + true, + outdir, + workflow.profile.tokenize(',').intersect(['conda', 'mamba']).size() >= 1 + ) + + // + // Validate parameters and generate parameter summary to stdout + // + UTILS_NFSCHEMA_PLUGIN ( + workflow, + validate_params, + null + ) + + // + // Check config provided to the pipeline + // + UTILS_NFCORE_PIPELINE ( + nextflow_cli_args + ) + + // + // Custom validation for pipeline parameters + // + //validateInputParameters() + + // + // Create channel from input file provided through params.input + // + + Channel + .fromList(samplesheetToList(params.input, "${projectDir}/assets/schema_input.json")) + //.map { meta, file -> [ meta + [tools: params.tools.tokenize(',')], file ] } + .set { ch_samplesheet } + + emit: + samplesheet = ch_samplesheet + versions = ch_versions +} + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + SUBWORKFLOW FOR PIPELINE COMPLETION +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ + +workflow PIPELINE_COMPLETION { + + take: + email // string: email address + email_on_fail // string: email address sent on pipeline failure + plaintext_email // boolean: Send plain-text email instead of HTML + outdir // path: Path to output directory where results will be published + monochrome_logs // boolean: Disable ANSI colour codes in log output + hook_url // string: hook URL for notifications + multiqc_report // string: Path to MultiQC report + + main: + summary_params = paramsSummaryMap(workflow, parameters_schema: "nextflow_schema.json") + + // + // Completion email and summary + // + workflow.onComplete { + if (email || email_on_fail) { + completionEmail( + summary_params, + email, + email_on_fail, + plaintext_email, + outdir, + monochrome_logs, + multiqc_report.toList() + ) + } + + completionSummary(monochrome_logs) + if (hook_url) { + imNotification(summary_params, hook_url) + } + } + + workflow.onError { + log.error "Pipeline failed. Please refer to troubleshooting docs: https://nf-co.re/docs/usage/troubleshooting" + } +} + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + FUNCTIONS +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ +// +// Check and validate pipeline parameters +// +//def validateInputParameters() { +// genomeExistsError() +//} + +// +// Prepare import of NetMHC software +// +def parse_netmhc_params(tool_name, tool_version) { + // Check if the _path parameter was set for this tool + if (!params["${tool_name}_path"]) + { + error("--${tool_name}_path not specified, but --tools contains ${tool_name}. Both have to be specified to enable ${tool_name}. Ignoring.") + } + else if (params["${tool_name}_path"]) + { + // Import mandatory netmhc metadata + def jsonSlurper = new groovy.json.JsonSlurper() + def external_tools_meta = jsonSlurper.parse(file(params.external_tools_meta, checkIfExists: true)) + def entry = external_tools_meta[tool_name][tool_version] + + if (params["netmhc_system"] == 'darwin') { + entry = external_tools_meta["${tool_name}_darwin"][tool_version] + } + // If so, add the tool name and user installation path to the external tools import channel + ch_nonfree_paths = Channel.empty() + ch_nonfree_paths.bind([ + tool_name, + entry.version, + entry.software_md5, + file(params["${tool_name}_path"], checkIfExists:true), + entry.data ? file(params["${tool_name}_data"], checkIfExists:true) : [], + entry.data_md5 ? entry.data_md5 : "", + entry.binary_name + ]) + + return ch_nonfree_paths + } +} + +// +// Validate channels from input samplesheet +// +def validateInputSamplesheet(input) { + def (metas, fastqs) = input[1..2] + + // Check that multiple runs of the same sample are of the same datatype i.e. single-end / paired-end + def endedness_ok = metas.collect{ meta -> meta.single_end }.unique().size == 1 + if (!endedness_ok) { + error("Please check input samplesheet -> Multiple runs of a sample must be of the same datatype i.e. single-end or paired-end: ${metas[0].id}") + } + + return [ metas[0], fastqs ] +} +// +// Get attribute from genome config file e.g. fasta +// +def getGenomeAttribute(attribute) { + if (params.genomes && params.genome && params.genomes.containsKey(params.genome)) { + if (params.genomes[ params.genome ].containsKey(attribute)) { + return params.genomes[ params.genome ][ attribute ] + } + } + return null +} + +// +// Exit pipeline if incorrect --genome key provided +// +def genomeExistsError() { + if (params.genomes && params.genome && !params.genomes.containsKey(params.genome)) { + def error_string = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + + " Genome '${params.genome}' not found in any config files provided to the pipeline.\n" + + " Currently, the available genome keys are:\n" + + " ${params.genomes.keySet().join(", ")}\n" + + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + error(error_string) + } +} +// +// Generate methods description for MultiQC +// +def toolCitationText() { + def citation_text = [ + "Tools used in the workflow included:", + "Epytope (Schuber et al. 2016)", + "SYFPEITHI (Schuler et al. 2007)", + "NetMHC (Andreatta and Nielsen 2016)", + "NetMHCpan (Reynisson et al. 2020)", + "NetMHCIIpan (Nilsson et al. 2023)", + "MHCnuggets (Shao et al. 2020)", + "MHCflurry (O'Donnell et al. 2020)", + "MultiQC (Ewels et al. 2016)", + "." + ].join(' ').trim() + + return citation_text +} + +def toolBibliographyText() { + def reference_text = [ + "
  • Schubert et al. (2016). FRED 2: an immunoinformatics framework for Python. Bioinformatics , 32(13), 2044–2046. doi: /10.1093/bioinformatics/btw113
  • ", + "
  • Schuler et al. (2007). SYFPEITHI: database for searching and T-cell epitope prediction. Immunoinformatics, 75–93. doi: /10.1007/978-1-60327-118-9_5
  • ", + "
  • Andreatta and Nielsen (2016). Gapped sequence alignment using artificial neural networks: application to the MHC class I system. Bioinformatics, 32(4), 511–517. doi: /10.1093/bioinformatics/btv639
  • ", + "
  • Reynisson et al. (2020). NetMHCpan-4.1 and NetMHCIIpan-4.0: Improved predictions of MHC antigen presentation by concurrent motif deconvolution and integration of MS MHC eluted ligand data. Nucleic Acids Research, Volume 48, Issue W1, Pages W449–W454. doi: /10.1093/nar/gkaa379
  • ", + "
  • Nilsson et al. (2023). Accurate prediction of HLA class II antigen presentation across all loci using tailored data acquisition and refined machine learning. Science Advances, Vol 9, Issue 47. doi: /10.1126/sciadv.adj6367
  • ", + "
  • Shao et al. (2020). High-throughput prediction of MHC class I and II neoantigens with MHCnuggets. Cancer Immunology Research, 8(3), 396–408. doi: /10.1158/2326-6066.CIR-19-0464
  • ", + "
  • O'Donnell et al. (2020). MHCflurry 2.0: improved pan-allele prediction of MHC class I-presented peptides by incorporating antigen processing. Cell Systems, 11, 42–48. doi: /10.1016/j.cels.2020.06.010
  • ", + "
  • Ewels, P., Magnusson, M., Lundin, S., & Käller, M. (2016). MultiQC: summarize analysis results for multiple tools and samples in a single report. Science Advances , Vol 9, Issue 47. doi: /10.1126/sciadv.adj6367
  • " + ].join(' ').trim() + + return reference_text +} + +def methodsDescriptionText(mqc_methods_yaml) { + // Convert to a named map so can be used as with familar NXF ${workflow} variable syntax in the MultiQC YML file + def meta = [:] + meta.workflow = workflow.toMap() + meta["manifest_map"] = workflow.manifest.toMap() + + // Pipeline DOI + if (meta.manifest_map.doi) { + // Using a loop to handle multiple DOIs + // Removing `https://doi.org/` to handle pipelines using DOIs vs DOI resolvers + // Removing ` ` since the manifest.doi is a string and not a proper list + def temp_doi_ref = "" + def manifest_doi = meta.manifest_map.doi.tokenize(",") + manifest_doi.each { doi_ref -> + temp_doi_ref += "(doi: ${doi_ref.replace("https://doi.org/", "").replace(" ", "")}), " + } + meta["doi_text"] = temp_doi_ref.substring(0, temp_doi_ref.length() - 2) + } else meta["doi_text"] = "" + meta["nodoi_text"] = meta.manifest_map.doi ? "" : "
  • If available, make sure to update the text to include the Zenodo DOI of version of the pipeline used.
  • " + + meta["tool_citations"] = toolCitationText().replaceAll(", \\.", ".").replaceAll("\\. \\.", ".").replaceAll(", \\.", ".") + meta["tool_bibliography"] = toolBibliographyText() + + + def methods_text = mqc_methods_yaml.text + + def engine = new groovy.text.SimpleTemplateEngine() + def description_html = engine.createTemplate(methods_text).make(meta) + + return description_html.toString() +} + diff --git a/subworkflows/nf-core/utils_nextflow_pipeline/main.nf b/subworkflows/nf-core/utils_nextflow_pipeline/main.nf new file mode 100644 index 0000000..0fcbf7b --- /dev/null +++ b/subworkflows/nf-core/utils_nextflow_pipeline/main.nf @@ -0,0 +1,124 @@ +// +// Subworkflow with functionality that may be useful for any Nextflow pipeline +// + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + SUBWORKFLOW DEFINITION +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ + +workflow UTILS_NEXTFLOW_PIPELINE { + take: + print_version // boolean: print version + dump_parameters // boolean: dump parameters + outdir // path: base directory used to publish pipeline results + check_conda_channels // boolean: check conda channels + + main: + + // + // Print workflow version and exit on --version + // + if (print_version) { + log.info("${workflow.manifest.name} ${getWorkflowVersion()}") + System.exit(0) + } + + // + // Dump pipeline parameters to a JSON file + // + if (dump_parameters && outdir) { + dumpParametersToJSON(outdir) + } + + // + // When running with Conda, warn if channels have not been set-up appropriately + // + if (check_conda_channels) { + checkCondaChannels() + } + + emit: + dummy_emit = true +} + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + FUNCTIONS +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ + +// +// Generate version string +// +def getWorkflowVersion() { + def version_string = "" as String + if (workflow.manifest.version) { + def prefix_v = workflow.manifest.version[0] != 'v' ? 'v' : '' + version_string += "${prefix_v}${workflow.manifest.version}" + } + + if (workflow.commitId) { + def git_shortsha = workflow.commitId.substring(0, 7) + version_string += "-g${git_shortsha}" + } + + return version_string +} + +// +// Dump pipeline parameters to a JSON file +// +def dumpParametersToJSON(outdir) { + def timestamp = new java.util.Date().format('yyyy-MM-dd_HH-mm-ss') + def filename = "params_${timestamp}.json" + def temp_pf = new File(workflow.launchDir.toString(), ".${filename}") + def jsonStr = groovy.json.JsonOutput.toJson(params) + temp_pf.text = groovy.json.JsonOutput.prettyPrint(jsonStr) + + nextflow.extension.FilesEx.copyTo(temp_pf.toPath(), "${outdir}/pipeline_info/params_${timestamp}.json") + temp_pf.delete() +} + +// +// When running with -profile conda, warn if channels have not been set-up appropriately +// +def checkCondaChannels() { + def parser = new org.yaml.snakeyaml.Yaml() + def channels = [] + try { + def config = parser.load("conda config --show channels".execute().text) + channels = config.channels + } + catch (NullPointerException e) { + log.warn("Could not verify conda channel configuration.") + return null + } + catch (IOException e) { + log.warn("Could not verify conda channel configuration.") + return null + } + + // Check that all channels are present + // This channel list is ordered by required channel priority. + def required_channels_in_order = ['conda-forge', 'bioconda'] + def channels_missing = ((required_channels_in_order as Set) - (channels as Set)) as Boolean + + // Check that they are in the right order + def channel_priority_violation = required_channels_in_order != channels.findAll { ch -> ch in required_channels_in_order } + + if (channels_missing | channel_priority_violation) { + log.warn """\ + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + There is a problem with your Conda configuration! + You will need to set-up the conda-forge and bioconda channels correctly. + Please refer to https://bioconda.github.io/ + The observed channel order is + ${channels} + but the following channel order is required: + ${required_channels_in_order} + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" + """.stripIndent(true) + } +} diff --git a/subworkflows/nf-core/utils_nextflow_pipeline/meta.yml b/subworkflows/nf-core/utils_nextflow_pipeline/meta.yml new file mode 100644 index 0000000..e5c3a0a --- /dev/null +++ b/subworkflows/nf-core/utils_nextflow_pipeline/meta.yml @@ -0,0 +1,38 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/nf-core/modules/master/subworkflows/yaml-schema.json +name: "UTILS_NEXTFLOW_PIPELINE" +description: Subworkflow with functionality that may be useful for any Nextflow pipeline +keywords: + - utility + - pipeline + - initialise + - version +components: [] +input: + - print_version: + type: boolean + description: | + Print the version of the pipeline and exit + - dump_parameters: + type: boolean + description: | + Dump the parameters of the pipeline to a JSON file + - output_directory: + type: directory + description: Path to output dir to write JSON file to. + pattern: "results/" + - check_conda_channel: + type: boolean + description: | + Check if the conda channel priority is correct. +output: + - dummy_emit: + type: boolean + description: | + Dummy emit to make nf-core subworkflows lint happy +authors: + - "@adamrtalbot" + - "@drpatelh" +maintainers: + - "@adamrtalbot" + - "@drpatelh" + - "@maxulysse" diff --git a/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.function.nf.test b/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.function.nf.test new file mode 100644 index 0000000..68718e4 --- /dev/null +++ b/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.function.nf.test @@ -0,0 +1,54 @@ + +nextflow_function { + + name "Test Functions" + script "subworkflows/nf-core/utils_nextflow_pipeline/main.nf" + config "subworkflows/nf-core/utils_nextflow_pipeline/tests/nextflow.config" + tag 'subworkflows' + tag 'utils_nextflow_pipeline' + tag 'subworkflows/utils_nextflow_pipeline' + + test("Test Function getWorkflowVersion") { + + function "getWorkflowVersion" + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } + + test("Test Function dumpParametersToJSON") { + + function "dumpParametersToJSON" + + when { + function { + """ + // define inputs of the function here. Example: + input[0] = "$outputDir" + """.stripIndent() + } + } + + then { + assertAll( + { assert function.success } + ) + } + } + + test("Test Function checkCondaChannels") { + + function "checkCondaChannels" + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } +} diff --git a/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.function.nf.test.snap b/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.function.nf.test.snap new file mode 100644 index 0000000..e3f0baf --- /dev/null +++ b/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.function.nf.test.snap @@ -0,0 +1,20 @@ +{ + "Test Function getWorkflowVersion": { + "content": [ + "v9.9.9" + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:02:05.308243" + }, + "Test Function checkCondaChannels": { + "content": null, + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:02:12.425833" + } +} \ No newline at end of file diff --git a/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.workflow.nf.test b/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.workflow.nf.test new file mode 100644 index 0000000..02dbf09 --- /dev/null +++ b/subworkflows/nf-core/utils_nextflow_pipeline/tests/main.workflow.nf.test @@ -0,0 +1,113 @@ +nextflow_workflow { + + name "Test Workflow UTILS_NEXTFLOW_PIPELINE" + script "../main.nf" + config "subworkflows/nf-core/utils_nextflow_pipeline/tests/nextflow.config" + workflow "UTILS_NEXTFLOW_PIPELINE" + tag 'subworkflows' + tag 'utils_nextflow_pipeline' + tag 'subworkflows/utils_nextflow_pipeline' + + test("Should run no inputs") { + + when { + workflow { + """ + print_version = false + dump_parameters = false + outdir = null + check_conda_channels = false + + input[0] = print_version + input[1] = dump_parameters + input[2] = outdir + input[3] = check_conda_channels + """ + } + } + + then { + assertAll( + { assert workflow.success } + ) + } + } + + test("Should print version") { + + when { + workflow { + """ + print_version = true + dump_parameters = false + outdir = null + check_conda_channels = false + + input[0] = print_version + input[1] = dump_parameters + input[2] = outdir + input[3] = check_conda_channels + """ + } + } + + then { + expect { + with(workflow) { + assert success + assert "nextflow_workflow v9.9.9" in stdout + } + } + } + } + + test("Should dump params") { + + when { + workflow { + """ + print_version = false + dump_parameters = true + outdir = 'results' + check_conda_channels = false + + input[0] = false + input[1] = true + input[2] = outdir + input[3] = false + """ + } + } + + then { + assertAll( + { assert workflow.success } + ) + } + } + + test("Should not create params JSON if no output directory") { + + when { + workflow { + """ + print_version = false + dump_parameters = true + outdir = null + check_conda_channels = false + + input[0] = false + input[1] = true + input[2] = outdir + input[3] = false + """ + } + } + + then { + assertAll( + { assert workflow.success } + ) + } + } +} diff --git a/subworkflows/nf-core/utils_nextflow_pipeline/tests/nextflow.config b/subworkflows/nf-core/utils_nextflow_pipeline/tests/nextflow.config new file mode 100644 index 0000000..a09572e --- /dev/null +++ b/subworkflows/nf-core/utils_nextflow_pipeline/tests/nextflow.config @@ -0,0 +1,9 @@ +manifest { + name = 'nextflow_workflow' + author = """nf-core""" + homePage = 'https://127.0.0.1' + description = """Dummy pipeline""" + nextflowVersion = '!>=23.04.0' + version = '9.9.9' + doi = 'https://doi.org/10.5281/zenodo.5070524' +} diff --git a/subworkflows/nf-core/utils_nextflow_pipeline/tests/tags.yml b/subworkflows/nf-core/utils_nextflow_pipeline/tests/tags.yml new file mode 100644 index 0000000..f847611 --- /dev/null +++ b/subworkflows/nf-core/utils_nextflow_pipeline/tests/tags.yml @@ -0,0 +1,2 @@ +subworkflows/utils_nextflow_pipeline: + - subworkflows/nf-core/utils_nextflow_pipeline/** diff --git a/subworkflows/nf-core/utils_nfcore_pipeline/main.nf b/subworkflows/nf-core/utils_nfcore_pipeline/main.nf new file mode 100644 index 0000000..5cb7baf --- /dev/null +++ b/subworkflows/nf-core/utils_nfcore_pipeline/main.nf @@ -0,0 +1,462 @@ +// +// Subworkflow with utility functions specific to the nf-core pipeline template +// + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + SUBWORKFLOW DEFINITION +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ + +workflow UTILS_NFCORE_PIPELINE { + take: + nextflow_cli_args + + main: + valid_config = checkConfigProvided() + checkProfileProvided(nextflow_cli_args) + + emit: + valid_config +} + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + FUNCTIONS +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ + +// +// Warn if a -profile or Nextflow config has not been provided to run the pipeline +// +def checkConfigProvided() { + def valid_config = true as Boolean + if (workflow.profile == 'standard' && workflow.configFiles.size() <= 1) { + log.warn( + "[${workflow.manifest.name}] You are attempting to run the pipeline without any custom configuration!\n\n" + "This will be dependent on your local compute environment but can be achieved via one or more of the following:\n" + " (1) Using an existing pipeline profile e.g. `-profile docker` or `-profile singularity`\n" + " (2) Using an existing nf-core/configs for your Institution e.g. `-profile crick` or `-profile uppmax`\n" + " (3) Using your own local custom config e.g. `-c /path/to/your/custom.config`\n\n" + "Please refer to the quick start section and usage docs for the pipeline.\n " + ) + valid_config = false + } + return valid_config +} + +// +// Exit pipeline if --profile contains spaces +// +def checkProfileProvided(nextflow_cli_args) { + if (workflow.profile.endsWith(',')) { + error( + "The `-profile` option cannot end with a trailing comma, please remove it and re-run the pipeline!\n" + "HINT: A common mistake is to provide multiple values separated by spaces e.g. `-profile test, docker`.\n" + ) + } + if (nextflow_cli_args[0]) { + log.warn( + "nf-core pipelines do not accept positional arguments. The positional argument `${nextflow_cli_args[0]}` has been detected.\n" + "HINT: A common mistake is to provide multiple values separated by spaces e.g. `-profile test, docker`.\n" + ) + } +} + +// +// Citation string for pipeline +// +def workflowCitation() { + def temp_doi_ref = "" + def manifest_doi = workflow.manifest.doi.tokenize(",") + // Handling multiple DOIs + // Removing `https://doi.org/` to handle pipelines using DOIs vs DOI resolvers + // Removing ` ` since the manifest.doi is a string and not a proper list + manifest_doi.each { doi_ref -> + temp_doi_ref += " https://doi.org/${doi_ref.replace('https://doi.org/', '').replace(' ', '')}\n" + } + return "If you use ${workflow.manifest.name} for your analysis please cite:\n\n" + "* The pipeline\n" + temp_doi_ref + "\n" + "* The nf-core framework\n" + " https://doi.org/10.1038/s41587-020-0439-x\n\n" + "* Software dependencies\n" + " https://github.com/${workflow.manifest.name}/blob/master/CITATIONS.md" +} + +// +// Generate workflow version string +// +def getWorkflowVersion() { + def version_string = "" as String + if (workflow.manifest.version) { + def prefix_v = workflow.manifest.version[0] != 'v' ? 'v' : '' + version_string += "${prefix_v}${workflow.manifest.version}" + } + + if (workflow.commitId) { + def git_shortsha = workflow.commitId.substring(0, 7) + version_string += "-g${git_shortsha}" + } + + return version_string +} + +// +// Get software versions for pipeline +// +def processVersionsFromYAML(yaml_file) { + def yaml = new org.yaml.snakeyaml.Yaml() + def versions = yaml.load(yaml_file).collectEntries { k, v -> [k.tokenize(':')[-1], v] } + return yaml.dumpAsMap(versions).trim() +} + +// +// Get workflow version for pipeline +// +def workflowVersionToYAML() { + return """ + Workflow: + ${workflow.manifest.name}: ${getWorkflowVersion()} + Nextflow: ${workflow.nextflow.version} + """.stripIndent().trim() +} + +// +// Get channel of software versions used in pipeline in YAML format +// +def softwareVersionsToYAML(ch_versions) { + return ch_versions.unique().map { version -> processVersionsFromYAML(version) }.unique().mix(Channel.of(workflowVersionToYAML())) +} + +// +// Get workflow summary for MultiQC +// +def paramsSummaryMultiqc(summary_params) { + def summary_section = '' + summary_params + .keySet() + .each { group -> + def group_params = summary_params.get(group) + // This gets the parameters of that particular group + if (group_params) { + summary_section += "

    ${group}

    \n" + summary_section += "
    \n" + group_params + .keySet() + .sort() + .each { param -> + summary_section += "
    ${param}
    ${group_params.get(param) ?: 'N/A'}
    \n" + } + summary_section += "
    \n" + } + } + + def yaml_file_text = "id: '${workflow.manifest.name.replace('/', '-')}-summary'\n" as String + yaml_file_text += "description: ' - this information is collected when the pipeline is started.'\n" + yaml_file_text += "section_name: '${workflow.manifest.name} Workflow Summary'\n" + yaml_file_text += "section_href: 'https://github.com/${workflow.manifest.name}'\n" + yaml_file_text += "plot_type: 'html'\n" + yaml_file_text += "data: |\n" + yaml_file_text += "${summary_section}" + + return yaml_file_text +} + +// +// nf-core logo +// +def nfCoreLogo(monochrome_logs=true) { + def colors = logColours(monochrome_logs) as Map + String.format( + """\n + ${dashedLine(monochrome_logs)} + ${colors.green},--.${colors.black}/${colors.green},-.${colors.reset} + ${colors.blue} ___ __ __ __ ___ ${colors.green}/,-._.--~\'${colors.reset} + ${colors.blue} |\\ | |__ __ / ` / \\ |__) |__ ${colors.yellow}} {${colors.reset} + ${colors.blue} | \\| | \\__, \\__/ | \\ |___ ${colors.green}\\`-._,-`-,${colors.reset} + ${colors.green}`._,._,\'${colors.reset} + ${colors.purple} ${workflow.manifest.name} ${getWorkflowVersion()}${colors.reset} + ${dashedLine(monochrome_logs)} + """.stripIndent() + ) +} + +// +// Return dashed line +// +def dashedLine(monochrome_logs=true) { + def colors = logColours(monochrome_logs) as Map + return "-${colors.dim}----------------------------------------------------${colors.reset}-" +} + +// +// ANSII colours used for terminal logging +// +def logColours(monochrome_logs=true) { + def colorcodes = [:] as Map + + // Reset / Meta + colorcodes['reset'] = monochrome_logs ? '' : "\033[0m" + colorcodes['bold'] = monochrome_logs ? '' : "\033[1m" + colorcodes['dim'] = monochrome_logs ? '' : "\033[2m" + colorcodes['underlined'] = monochrome_logs ? '' : "\033[4m" + colorcodes['blink'] = monochrome_logs ? '' : "\033[5m" + colorcodes['reverse'] = monochrome_logs ? '' : "\033[7m" + colorcodes['hidden'] = monochrome_logs ? '' : "\033[8m" + + // Regular Colors + colorcodes['black'] = monochrome_logs ? '' : "\033[0;30m" + colorcodes['red'] = monochrome_logs ? '' : "\033[0;31m" + colorcodes['green'] = monochrome_logs ? '' : "\033[0;32m" + colorcodes['yellow'] = monochrome_logs ? '' : "\033[0;33m" + colorcodes['blue'] = monochrome_logs ? '' : "\033[0;34m" + colorcodes['purple'] = monochrome_logs ? '' : "\033[0;35m" + colorcodes['cyan'] = monochrome_logs ? '' : "\033[0;36m" + colorcodes['white'] = monochrome_logs ? '' : "\033[0;37m" + + // Bold + colorcodes['bblack'] = monochrome_logs ? '' : "\033[1;30m" + colorcodes['bred'] = monochrome_logs ? '' : "\033[1;31m" + colorcodes['bgreen'] = monochrome_logs ? '' : "\033[1;32m" + colorcodes['byellow'] = monochrome_logs ? '' : "\033[1;33m" + colorcodes['bblue'] = monochrome_logs ? '' : "\033[1;34m" + colorcodes['bpurple'] = monochrome_logs ? '' : "\033[1;35m" + colorcodes['bcyan'] = monochrome_logs ? '' : "\033[1;36m" + colorcodes['bwhite'] = monochrome_logs ? '' : "\033[1;37m" + + // Underline + colorcodes['ublack'] = monochrome_logs ? '' : "\033[4;30m" + colorcodes['ured'] = monochrome_logs ? '' : "\033[4;31m" + colorcodes['ugreen'] = monochrome_logs ? '' : "\033[4;32m" + colorcodes['uyellow'] = monochrome_logs ? '' : "\033[4;33m" + colorcodes['ublue'] = monochrome_logs ? '' : "\033[4;34m" + colorcodes['upurple'] = monochrome_logs ? '' : "\033[4;35m" + colorcodes['ucyan'] = monochrome_logs ? '' : "\033[4;36m" + colorcodes['uwhite'] = monochrome_logs ? '' : "\033[4;37m" + + // High Intensity + colorcodes['iblack'] = monochrome_logs ? '' : "\033[0;90m" + colorcodes['ired'] = monochrome_logs ? '' : "\033[0;91m" + colorcodes['igreen'] = monochrome_logs ? '' : "\033[0;92m" + colorcodes['iyellow'] = monochrome_logs ? '' : "\033[0;93m" + colorcodes['iblue'] = monochrome_logs ? '' : "\033[0;94m" + colorcodes['ipurple'] = monochrome_logs ? '' : "\033[0;95m" + colorcodes['icyan'] = monochrome_logs ? '' : "\033[0;96m" + colorcodes['iwhite'] = monochrome_logs ? '' : "\033[0;97m" + + // Bold High Intensity + colorcodes['biblack'] = monochrome_logs ? '' : "\033[1;90m" + colorcodes['bired'] = monochrome_logs ? '' : "\033[1;91m" + colorcodes['bigreen'] = monochrome_logs ? '' : "\033[1;92m" + colorcodes['biyellow'] = monochrome_logs ? '' : "\033[1;93m" + colorcodes['biblue'] = monochrome_logs ? '' : "\033[1;94m" + colorcodes['bipurple'] = monochrome_logs ? '' : "\033[1;95m" + colorcodes['bicyan'] = monochrome_logs ? '' : "\033[1;96m" + colorcodes['biwhite'] = monochrome_logs ? '' : "\033[1;97m" + + return colorcodes +} + +// +// Attach the multiqc report to email +// +def attachMultiqcReport(multiqc_report) { + def mqc_report = null + try { + if (workflow.success) { + mqc_report = multiqc_report.getVal() + if (mqc_report.getClass() == ArrayList && mqc_report.size() >= 1) { + if (mqc_report.size() > 1) { + log.warn("[${workflow.manifest.name}] Found multiple reports from process 'MULTIQC', will use only one") + } + mqc_report = mqc_report[0] + } + } + } + catch (Exception all) { + if (multiqc_report) { + log.warn("[${workflow.manifest.name}] Could not attach MultiQC report to summary email") + } + } + return mqc_report +} + +// +// Construct and send completion email +// +def completionEmail(summary_params, email, email_on_fail, plaintext_email, outdir, monochrome_logs=true, multiqc_report=null) { + + // Set up the e-mail variables + def subject = "[${workflow.manifest.name}] Successful: ${workflow.runName}" + if (!workflow.success) { + subject = "[${workflow.manifest.name}] FAILED: ${workflow.runName}" + } + + def summary = [:] + summary_params + .keySet() + .sort() + .each { group -> + summary << summary_params[group] + } + + def misc_fields = [:] + misc_fields['Date Started'] = workflow.start + misc_fields['Date Completed'] = workflow.complete + misc_fields['Pipeline script file path'] = workflow.scriptFile + misc_fields['Pipeline script hash ID'] = workflow.scriptId + if (workflow.repository) { + misc_fields['Pipeline repository Git URL'] = workflow.repository + } + if (workflow.commitId) { + misc_fields['Pipeline repository Git Commit'] = workflow.commitId + } + if (workflow.revision) { + misc_fields['Pipeline Git branch/tag'] = workflow.revision + } + misc_fields['Nextflow Version'] = workflow.nextflow.version + misc_fields['Nextflow Build'] = workflow.nextflow.build + misc_fields['Nextflow Compile Timestamp'] = workflow.nextflow.timestamp + + def email_fields = [:] + email_fields['version'] = getWorkflowVersion() + email_fields['runName'] = workflow.runName + email_fields['success'] = workflow.success + email_fields['dateComplete'] = workflow.complete + email_fields['duration'] = workflow.duration + email_fields['exitStatus'] = workflow.exitStatus + email_fields['errorMessage'] = (workflow.errorMessage ?: 'None') + email_fields['errorReport'] = (workflow.errorReport ?: 'None') + email_fields['commandLine'] = workflow.commandLine + email_fields['projectDir'] = workflow.projectDir + email_fields['summary'] = summary << misc_fields + + // On success try attach the multiqc report + def mqc_report = attachMultiqcReport(multiqc_report) + + // Check if we are only sending emails on failure + def email_address = email + if (!email && email_on_fail && !workflow.success) { + email_address = email_on_fail + } + + // Render the TXT template + def engine = new groovy.text.GStringTemplateEngine() + def tf = new File("${workflow.projectDir}/assets/email_template.txt") + def txt_template = engine.createTemplate(tf).make(email_fields) + def email_txt = txt_template.toString() + + // Render the HTML template + def hf = new File("${workflow.projectDir}/assets/email_template.html") + def html_template = engine.createTemplate(hf).make(email_fields) + def email_html = html_template.toString() + + // Render the sendmail template + def max_multiqc_email_size = (params.containsKey('max_multiqc_email_size') ? params.max_multiqc_email_size : 0) as nextflow.util.MemoryUnit + def smail_fields = [email: email_address, subject: subject, email_txt: email_txt, email_html: email_html, projectDir: "${workflow.projectDir}", mqcFile: mqc_report, mqcMaxSize: max_multiqc_email_size.toBytes()] + def sf = new File("${workflow.projectDir}/assets/sendmail_template.txt") + def sendmail_template = engine.createTemplate(sf).make(smail_fields) + def sendmail_html = sendmail_template.toString() + + // Send the HTML e-mail + def colors = logColours(monochrome_logs) as Map + if (email_address) { + try { + if (plaintext_email) { +new org.codehaus.groovy.GroovyException('Send plaintext e-mail, not HTML') } + // Try to send HTML e-mail using sendmail + def sendmail_tf = new File(workflow.launchDir.toString(), ".sendmail_tmp.html") + sendmail_tf.withWriter { w -> w << sendmail_html } + ['sendmail', '-t'].execute() << sendmail_html + log.info("-${colors.purple}[${workflow.manifest.name}]${colors.green} Sent summary e-mail to ${email_address} (sendmail)-") + } + catch (Exception all) { + // Catch failures and try with plaintext + def mail_cmd = ['mail', '-s', subject, '--content-type=text/html', email_address] + mail_cmd.execute() << email_html + log.info("-${colors.purple}[${workflow.manifest.name}]${colors.green} Sent summary e-mail to ${email_address} (mail)-") + } + } + + // Write summary e-mail HTML to a file + def output_hf = new File(workflow.launchDir.toString(), ".pipeline_report.html") + output_hf.withWriter { w -> w << email_html } + nextflow.extension.FilesEx.copyTo(output_hf.toPath(), "${outdir}/pipeline_info/pipeline_report.html") + output_hf.delete() + + // Write summary e-mail TXT to a file + def output_tf = new File(workflow.launchDir.toString(), ".pipeline_report.txt") + output_tf.withWriter { w -> w << email_txt } + nextflow.extension.FilesEx.copyTo(output_tf.toPath(), "${outdir}/pipeline_info/pipeline_report.txt") + output_tf.delete() +} + +// +// Print pipeline summary on completion +// +def completionSummary(monochrome_logs=true) { + def colors = logColours(monochrome_logs) as Map + if (workflow.success) { + if (workflow.stats.ignoredCount == 0) { + log.info("-${colors.purple}[${workflow.manifest.name}]${colors.green} Pipeline completed successfully${colors.reset}-") + } + else { + log.info("-${colors.purple}[${workflow.manifest.name}]${colors.yellow} Pipeline completed successfully, but with errored process(es) ${colors.reset}-") + } + } + else { + log.info("-${colors.purple}[${workflow.manifest.name}]${colors.red} Pipeline completed with errors${colors.reset}-") + } +} + +// +// Construct and send a notification to a web server as JSON e.g. Microsoft Teams and Slack +// +def imNotification(summary_params, hook_url) { + def summary = [:] + summary_params + .keySet() + .sort() + .each { group -> + summary << summary_params[group] + } + + def misc_fields = [:] + misc_fields['start'] = workflow.start + misc_fields['complete'] = workflow.complete + misc_fields['scriptfile'] = workflow.scriptFile + misc_fields['scriptid'] = workflow.scriptId + if (workflow.repository) { + misc_fields['repository'] = workflow.repository + } + if (workflow.commitId) { + misc_fields['commitid'] = workflow.commitId + } + if (workflow.revision) { + misc_fields['revision'] = workflow.revision + } + misc_fields['nxf_version'] = workflow.nextflow.version + misc_fields['nxf_build'] = workflow.nextflow.build + misc_fields['nxf_timestamp'] = workflow.nextflow.timestamp + + def msg_fields = [:] + msg_fields['version'] = getWorkflowVersion() + msg_fields['runName'] = workflow.runName + msg_fields['success'] = workflow.success + msg_fields['dateComplete'] = workflow.complete + msg_fields['duration'] = workflow.duration + msg_fields['exitStatus'] = workflow.exitStatus + msg_fields['errorMessage'] = (workflow.errorMessage ?: 'None') + msg_fields['errorReport'] = (workflow.errorReport ?: 'None') + msg_fields['commandLine'] = workflow.commandLine.replaceFirst(/ +--hook_url +[^ ]+/, "") + msg_fields['projectDir'] = workflow.projectDir + msg_fields['summary'] = summary << misc_fields + + // Render the JSON template + def engine = new groovy.text.GStringTemplateEngine() + // Different JSON depending on the service provider + // Defaults to "Adaptive Cards" (https://adaptivecards.io), except Slack which has its own format + def json_path = hook_url.contains("hooks.slack.com") ? "slackreport.json" : "adaptivecard.json" + def hf = new File("${workflow.projectDir}/assets/${json_path}") + def json_template = engine.createTemplate(hf).make(msg_fields) + def json_message = json_template.toString() + + // POST + def post = new URL(hook_url).openConnection() + post.setRequestMethod("POST") + post.setDoOutput(true) + post.setRequestProperty("Content-Type", "application/json") + post.getOutputStream().write(json_message.getBytes("UTF-8")) + def postRC = post.getResponseCode() + if (!postRC.equals(200)) { + log.warn(post.getErrorStream().getText()) + } +} diff --git a/subworkflows/nf-core/utils_nfcore_pipeline/meta.yml b/subworkflows/nf-core/utils_nfcore_pipeline/meta.yml new file mode 100644 index 0000000..d08d243 --- /dev/null +++ b/subworkflows/nf-core/utils_nfcore_pipeline/meta.yml @@ -0,0 +1,24 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/nf-core/modules/master/subworkflows/yaml-schema.json +name: "UTILS_NFCORE_PIPELINE" +description: Subworkflow with utility functions specific to the nf-core pipeline template +keywords: + - utility + - pipeline + - initialise + - version +components: [] +input: + - nextflow_cli_args: + type: list + description: | + Nextflow CLI positional arguments +output: + - success: + type: boolean + description: | + Dummy output to indicate success +authors: + - "@adamrtalbot" +maintainers: + - "@adamrtalbot" + - "@maxulysse" diff --git a/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.function.nf.test b/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.function.nf.test new file mode 100644 index 0000000..1dc317f --- /dev/null +++ b/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.function.nf.test @@ -0,0 +1,134 @@ + +nextflow_function { + + name "Test Functions" + script "../main.nf" + config "subworkflows/nf-core/utils_nfcore_pipeline/tests/nextflow.config" + tag "subworkflows" + tag "subworkflows_nfcore" + tag "utils_nfcore_pipeline" + tag "subworkflows/utils_nfcore_pipeline" + + test("Test Function checkConfigProvided") { + + function "checkConfigProvided" + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } + + test("Test Function checkProfileProvided") { + + function "checkProfileProvided" + + when { + function { + """ + input[0] = [] + """ + } + } + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } + + test("Test Function workflowCitation") { + + function "workflowCitation" + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } + + test("Test Function nfCoreLogo") { + + function "nfCoreLogo" + + when { + function { + """ + input[0] = false + """ + } + } + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } + + test("Test Function dashedLine") { + + function "dashedLine" + + when { + function { + """ + input[0] = false + """ + } + } + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } + + test("Test Function without logColours") { + + function "logColours" + + when { + function { + """ + input[0] = true + """ + } + } + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } + + test("Test Function with logColours") { + function "logColours" + + when { + function { + """ + input[0] = false + """ + } + } + + then { + assertAll( + { assert function.success }, + { assert snapshot(function.result).match() } + ) + } + } +} diff --git a/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.function.nf.test.snap b/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.function.nf.test.snap new file mode 100644 index 0000000..1037232 --- /dev/null +++ b/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.function.nf.test.snap @@ -0,0 +1,166 @@ +{ + "Test Function checkProfileProvided": { + "content": null, + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:03:03.360873" + }, + "Test Function checkConfigProvided": { + "content": [ + true + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:02:59.729647" + }, + "Test Function nfCoreLogo": { + "content": [ + "\n\n-\u001b[2m----------------------------------------------------\u001b[0m-\n \u001b[0;32m,--.\u001b[0;30m/\u001b[0;32m,-.\u001b[0m\n\u001b[0;34m ___ __ __ __ ___ \u001b[0;32m/,-._.--~'\u001b[0m\n\u001b[0;34m |\\ | |__ __ / ` / \\ |__) |__ \u001b[0;33m} {\u001b[0m\n\u001b[0;34m | \\| | \\__, \\__/ | \\ |___ \u001b[0;32m\\`-._,-`-,\u001b[0m\n \u001b[0;32m`._,._,'\u001b[0m\n\u001b[0;35m nextflow_workflow v9.9.9\u001b[0m\n-\u001b[2m----------------------------------------------------\u001b[0m-\n" + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:03:10.562934" + }, + "Test Function workflowCitation": { + "content": [ + "If you use nextflow_workflow for your analysis please cite:\n\n* The pipeline\n https://doi.org/10.5281/zenodo.5070524\n\n* The nf-core framework\n https://doi.org/10.1038/s41587-020-0439-x\n\n* Software dependencies\n https://github.com/nextflow_workflow/blob/master/CITATIONS.md" + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:03:07.019761" + }, + "Test Function without logColours": { + "content": [ + { + "reset": "", + "bold": "", + "dim": "", + "underlined": "", + "blink": "", + "reverse": "", + "hidden": "", + "black": "", + "red": "", + "green": "", + "yellow": "", + "blue": "", + "purple": "", + "cyan": "", + "white": "", + "bblack": "", + "bred": "", + "bgreen": "", + "byellow": "", + "bblue": "", + "bpurple": "", + "bcyan": "", + "bwhite": "", + "ublack": "", + "ured": "", + "ugreen": "", + "uyellow": "", + "ublue": "", + "upurple": "", + "ucyan": "", + "uwhite": "", + "iblack": "", + "ired": "", + "igreen": "", + "iyellow": "", + "iblue": "", + "ipurple": "", + "icyan": "", + "iwhite": "", + "biblack": "", + "bired": "", + "bigreen": "", + "biyellow": "", + "biblue": "", + "bipurple": "", + "bicyan": "", + "biwhite": "" + } + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:03:17.969323" + }, + "Test Function dashedLine": { + "content": [ + "-\u001b[2m----------------------------------------------------\u001b[0m-" + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:03:14.366181" + }, + "Test Function with logColours": { + "content": [ + { + "reset": "\u001b[0m", + "bold": "\u001b[1m", + "dim": "\u001b[2m", + "underlined": "\u001b[4m", + "blink": "\u001b[5m", + "reverse": "\u001b[7m", + "hidden": "\u001b[8m", + "black": "\u001b[0;30m", + "red": "\u001b[0;31m", + "green": "\u001b[0;32m", + "yellow": "\u001b[0;33m", + "blue": "\u001b[0;34m", + "purple": "\u001b[0;35m", + "cyan": "\u001b[0;36m", + "white": "\u001b[0;37m", + "bblack": "\u001b[1;30m", + "bred": "\u001b[1;31m", + "bgreen": "\u001b[1;32m", + "byellow": "\u001b[1;33m", + "bblue": "\u001b[1;34m", + "bpurple": "\u001b[1;35m", + "bcyan": "\u001b[1;36m", + "bwhite": "\u001b[1;37m", + "ublack": "\u001b[4;30m", + "ured": "\u001b[4;31m", + "ugreen": "\u001b[4;32m", + "uyellow": "\u001b[4;33m", + "ublue": "\u001b[4;34m", + "upurple": "\u001b[4;35m", + "ucyan": "\u001b[4;36m", + "uwhite": "\u001b[4;37m", + "iblack": "\u001b[0;90m", + "ired": "\u001b[0;91m", + "igreen": "\u001b[0;92m", + "iyellow": "\u001b[0;93m", + "iblue": "\u001b[0;94m", + "ipurple": "\u001b[0;95m", + "icyan": "\u001b[0;96m", + "iwhite": "\u001b[0;97m", + "biblack": "\u001b[1;90m", + "bired": "\u001b[1;91m", + "bigreen": "\u001b[1;92m", + "biyellow": "\u001b[1;93m", + "biblue": "\u001b[1;94m", + "bipurple": "\u001b[1;95m", + "bicyan": "\u001b[1;96m", + "biwhite": "\u001b[1;97m" + } + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:03:21.714424" + } +} \ No newline at end of file diff --git a/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.workflow.nf.test b/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.workflow.nf.test new file mode 100644 index 0000000..8940d32 --- /dev/null +++ b/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.workflow.nf.test @@ -0,0 +1,29 @@ +nextflow_workflow { + + name "Test Workflow UTILS_NFCORE_PIPELINE" + script "../main.nf" + config "subworkflows/nf-core/utils_nfcore_pipeline/tests/nextflow.config" + workflow "UTILS_NFCORE_PIPELINE" + tag "subworkflows" + tag "subworkflows_nfcore" + tag "utils_nfcore_pipeline" + tag "subworkflows/utils_nfcore_pipeline" + + test("Should run without failures") { + + when { + workflow { + """ + input[0] = [] + """ + } + } + + then { + assertAll( + { assert workflow.success }, + { assert snapshot(workflow.out).match() } + ) + } + } +} diff --git a/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.workflow.nf.test.snap b/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.workflow.nf.test.snap new file mode 100644 index 0000000..859d103 --- /dev/null +++ b/subworkflows/nf-core/utils_nfcore_pipeline/tests/main.workflow.nf.test.snap @@ -0,0 +1,19 @@ +{ + "Should run without failures": { + "content": [ + { + "0": [ + true + ], + "valid_config": [ + true + ] + } + ], + "meta": { + "nf-test": "0.8.4", + "nextflow": "23.10.1" + }, + "timestamp": "2024-02-28T12:03:25.726491" + } +} \ No newline at end of file diff --git a/subworkflows/nf-core/utils_nfcore_pipeline/tests/nextflow.config b/subworkflows/nf-core/utils_nfcore_pipeline/tests/nextflow.config new file mode 100644 index 0000000..d0a926b --- /dev/null +++ b/subworkflows/nf-core/utils_nfcore_pipeline/tests/nextflow.config @@ -0,0 +1,9 @@ +manifest { + name = 'nextflow_workflow' + author = """nf-core""" + homePage = 'https://127.0.0.1' + description = """Dummy pipeline""" + nextflowVersion = '!>=23.04.0' + version = '9.9.9' + doi = 'https://doi.org/10.5281/zenodo.5070524' +} diff --git a/subworkflows/nf-core/utils_nfcore_pipeline/tests/tags.yml b/subworkflows/nf-core/utils_nfcore_pipeline/tests/tags.yml new file mode 100644 index 0000000..ac8523c --- /dev/null +++ b/subworkflows/nf-core/utils_nfcore_pipeline/tests/tags.yml @@ -0,0 +1,2 @@ +subworkflows/utils_nfcore_pipeline: + - subworkflows/nf-core/utils_nfcore_pipeline/** diff --git a/subworkflows/nf-core/utils_nfschema_plugin/main.nf b/subworkflows/nf-core/utils_nfschema_plugin/main.nf new file mode 100644 index 0000000..4994303 --- /dev/null +++ b/subworkflows/nf-core/utils_nfschema_plugin/main.nf @@ -0,0 +1,46 @@ +// +// Subworkflow that uses the nf-schema plugin to validate parameters and render the parameter summary +// + +include { paramsSummaryLog } from 'plugin/nf-schema' +include { validateParameters } from 'plugin/nf-schema' + +workflow UTILS_NFSCHEMA_PLUGIN { + + take: + input_workflow // workflow: the workflow object used by nf-schema to get metadata from the workflow + validate_params // boolean: validate the parameters + parameters_schema // string: path to the parameters JSON schema. + // this has to be the same as the schema given to `validation.parametersSchema` + // when this input is empty it will automatically use the configured schema or + // "${projectDir}/nextflow_schema.json" as default. This input should not be empty + // for meta pipelines + + main: + + // + // Print parameter summary to stdout. This will display the parameters + // that differ from the default given in the JSON schema + // + if(parameters_schema) { + log.info paramsSummaryLog(input_workflow, parameters_schema:parameters_schema) + } else { + log.info paramsSummaryLog(input_workflow) + } + + // + // Validate the parameters using nextflow_schema.json or the schema + // given via the validation.parametersSchema configuration option + // + if(validate_params) { + if(parameters_schema) { + validateParameters(parameters_schema:parameters_schema) + } else { + validateParameters() + } + } + + emit: + dummy_emit = true +} + diff --git a/subworkflows/nf-core/utils_nfschema_plugin/meta.yml b/subworkflows/nf-core/utils_nfschema_plugin/meta.yml new file mode 100644 index 0000000..f7d9f02 --- /dev/null +++ b/subworkflows/nf-core/utils_nfschema_plugin/meta.yml @@ -0,0 +1,35 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/nf-core/modules/master/subworkflows/yaml-schema.json +name: "utils_nfschema_plugin" +description: Run nf-schema to validate parameters and create a summary of changed parameters +keywords: + - validation + - JSON schema + - plugin + - parameters + - summary +components: [] +input: + - input_workflow: + type: object + description: | + The workflow object of the used pipeline. + This object contains meta data used to create the params summary log + - validate_params: + type: boolean + description: Validate the parameters and error if invalid. + - parameters_schema: + type: string + description: | + Path to the parameters JSON schema. + This has to be the same as the schema given to the `validation.parametersSchema` config + option. When this input is empty it will automatically use the configured schema or + "${projectDir}/nextflow_schema.json" as default. The schema should not be given in this way + for meta pipelines. +output: + - dummy_emit: + type: boolean + description: Dummy emit to make nf-core subworkflows lint happy +authors: + - "@nvnieuwk" +maintainers: + - "@nvnieuwk" diff --git a/subworkflows/nf-core/utils_nfschema_plugin/tests/main.nf.test b/subworkflows/nf-core/utils_nfschema_plugin/tests/main.nf.test new file mode 100644 index 0000000..8fb3016 --- /dev/null +++ b/subworkflows/nf-core/utils_nfschema_plugin/tests/main.nf.test @@ -0,0 +1,117 @@ +nextflow_workflow { + + name "Test Subworkflow UTILS_NFSCHEMA_PLUGIN" + script "../main.nf" + workflow "UTILS_NFSCHEMA_PLUGIN" + + tag "subworkflows" + tag "subworkflows_nfcore" + tag "subworkflows/utils_nfschema_plugin" + tag "plugin/nf-schema" + + config "./nextflow.config" + + test("Should run nothing") { + + when { + + params { + test_data = '' + } + + workflow { + """ + validate_params = false + input[0] = workflow + input[1] = validate_params + input[2] = "" + """ + } + } + + then { + assertAll( + { assert workflow.success } + ) + } + } + + test("Should validate params") { + + when { + + params { + test_data = '' + outdir = null + } + + workflow { + """ + validate_params = true + input[0] = workflow + input[1] = validate_params + input[2] = "" + """ + } + } + + then { + assertAll( + { assert workflow.failed }, + { assert workflow.stdout.any { it.contains('ERROR ~ Validation of pipeline parameters failed!') } } + ) + } + } + + test("Should run nothing - custom schema") { + + when { + + params { + test_data = '' + } + + workflow { + """ + validate_params = false + input[0] = workflow + input[1] = validate_params + input[2] = "${projectDir}/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow_schema.json" + """ + } + } + + then { + assertAll( + { assert workflow.success } + ) + } + } + + test("Should validate params - custom schema") { + + when { + + params { + test_data = '' + outdir = null + } + + workflow { + """ + validate_params = true + input[0] = workflow + input[1] = validate_params + input[2] = "${projectDir}/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow_schema.json" + """ + } + } + + then { + assertAll( + { assert workflow.failed }, + { assert workflow.stdout.any { it.contains('ERROR ~ Validation of pipeline parameters failed!') } } + ) + } + } +} diff --git a/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow.config b/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow.config new file mode 100644 index 0000000..0907ac5 --- /dev/null +++ b/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow.config @@ -0,0 +1,8 @@ +plugins { + id "nf-schema@2.1.0" +} + +validation { + parametersSchema = "${projectDir}/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow_schema.json" + monochromeLogs = true +} \ No newline at end of file diff --git a/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow_schema.json b/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow_schema.json new file mode 100644 index 0000000..331e0d2 --- /dev/null +++ b/subworkflows/nf-core/utils_nfschema_plugin/tests/nextflow_schema.json @@ -0,0 +1,96 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/./master/nextflow_schema.json", + "title": ". pipeline parameters", + "description": "", + "type": "object", + "$defs": { + "input_output_options": { + "title": "Input/output options", + "type": "object", + "fa_icon": "fas fa-terminal", + "description": "Define where the pipeline should find input data and save output data.", + "required": ["outdir"], + "properties": { + "validate_params": { + "type": "boolean", + "description": "Validate parameters?", + "default": true, + "hidden": true + }, + "outdir": { + "type": "string", + "format": "directory-path", + "description": "The output directory where the results will be saved. You have to use absolute paths to storage on Cloud infrastructure.", + "fa_icon": "fas fa-folder-open" + }, + "test_data_base": { + "type": "string", + "default": "https://raw.githubusercontent.com/nf-core/test-datasets/modules", + "description": "Base for test data directory", + "hidden": true + }, + "test_data": { + "type": "string", + "description": "Fake test data param", + "hidden": true + } + } + }, + "generic_options": { + "title": "Generic options", + "type": "object", + "fa_icon": "fas fa-file-import", + "description": "Less common options for the pipeline, typically set in a config file.", + "help_text": "These options are common to all nf-core pipelines and allow you to customise some of the core preferences for how the pipeline runs.\n\nTypically these options would be set in a Nextflow config file loaded for all pipeline runs, such as `~/.nextflow/config`.", + "properties": { + "help": { + "type": "boolean", + "description": "Display help text.", + "fa_icon": "fas fa-question-circle", + "hidden": true + }, + "version": { + "type": "boolean", + "description": "Display version and exit.", + "fa_icon": "fas fa-question-circle", + "hidden": true + }, + "logo": { + "type": "boolean", + "default": true, + "description": "Display nf-core logo in console output.", + "fa_icon": "fas fa-image", + "hidden": true + }, + "singularity_pull_docker_container": { + "type": "boolean", + "description": "Pull Singularity container from Docker?", + "hidden": true + }, + "publish_dir_mode": { + "type": "string", + "default": "copy", + "description": "Method used to save pipeline results to output directory.", + "help_text": "The Nextflow `publishDir` option specifies which intermediate files should be saved to the output directory. This option tells the pipeline what method should be used to move these files. See [Nextflow docs](https://www.nextflow.io/docs/latest/process.html#publishdir) for details.", + "fa_icon": "fas fa-copy", + "enum": ["symlink", "rellink", "link", "copy", "copyNoFollow", "move"], + "hidden": true + }, + "monochrome_logs": { + "type": "boolean", + "description": "Use monochrome_logs", + "hidden": true + } + } + } + }, + "allOf": [ + { + "$ref": "#/$defs/input_output_options" + }, + { + "$ref": "#/$defs/generic_options" + } + ] +} diff --git a/workflows/epitopeprediction.nf b/workflows/epitopeprediction.nf index f912dee..1284da3 100644 --- a/workflows/epitopeprediction.nf +++ b/workflows/epitopeprediction.nf @@ -1,72 +1,39 @@ -/* -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - PRINT PARAMS SUMMARY -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -*/ - -include { paramsSummaryLog; paramsSummaryMap } from 'plugin/nf-validation' - -def logo = NfcoreTemplate.logo(workflow, params.monochrome_logs) -def citation = '\n' + WorkflowMain.citation(workflow) + '\n' -def summary_params = paramsSummaryMap(workflow) - -// Print parameter summary log to screen -log.info logo + paramsSummaryLog(workflow) + citation - -WorkflowEpitopeprediction.initialise(params, log) - -/* -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - CONFIG FILES -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -*/ - -ch_multiqc_config = Channel.fromPath("$projectDir/assets/multiqc_config.yml", checkIfExists: true) -ch_multiqc_custom_config = params.multiqc_config ? Channel.fromPath( params.multiqc_config, checkIfExists: true ) : Channel.empty() -ch_multiqc_logo = params.multiqc_logo ? Channel.fromPath( params.multiqc_logo, checkIfExists: true ) : Channel.empty() -ch_multiqc_custom_methods_description = params.multiqc_methods_description ? file(params.multiqc_methods_description, checkIfExists: true) : file("$projectDir/assets/methods_description_template.yml", checkIfExists: true) - /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ IMPORT LOCAL MODULES/SUBWORKFLOWS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ - // // MODULE: Local to the pipeline // -include { GET_PREDICTION_VERSIONS } from '../modules/local/get_prediction_versions' - -include { EXTERNAL_TOOLS_IMPORT } from '../modules/local/external_tools_import' - +include { GET_PREDICTION_VERSIONS } from '../modules/local/get_prediction_versions' +include { EXTERNAL_TOOLS_IMPORT } from '../modules/local/external_tools_import' include { EPYTOPE_CHECK_REQUESTED_MODELS as EPYTOPE_CHECK_REQUESTED_MODELS_PROTEIN } from '../modules/local/epytope_check_requested_models' -include { EPYTOPE_CHECK_REQUESTED_MODELS as EPYTOPE_CHECK_REQUESTED_MODELS_PEP } from '../modules/local/epytope_check_requested_models' -include { EPYTOPE_CHECK_REQUESTED_MODELS } from '../modules/local/epytope_check_requested_models' -include { EPYTOPE_SHOW_SUPPORTED_MODELS } from '../modules/local/epytope_show_supported_models' +include { EPYTOPE_CHECK_REQUESTED_MODELS as EPYTOPE_CHECK_REQUESTED_MODELS_PEP } from '../modules/local/epytope_check_requested_models' +include { EPYTOPE_CHECK_REQUESTED_MODELS } from '../modules/local/epytope_check_requested_models' +include { EPYTOPE_SHOW_SUPPORTED_MODELS } from '../modules/local/epytope_show_supported_models' -include { VARIANT_SPLIT} from '../modules/local/variant_split' -include { SNPSIFT_SPLIT} from '../modules/local/snpsift_split' -include { CSVTK_SPLIT} from '../modules/local/csvtk_split' +include { VARIANT_SPLIT } from '../modules/local/variant_split' +include { SNPSIFT_SPLIT } from '../modules/local/snpsift_split' -include { EPYTOPE_GENERATE_PEPTIDES } from '../modules/local/epytope_generate_peptides' -include { SPLIT_PEPTIDES as SPLIT_PEPTIDES_PEPTIDES } from '../modules/local/split_peptides' -include { SPLIT_PEPTIDES as SPLIT_PEPTIDES_PROTEIN } from '../modules/local/split_peptides' +include { EPYTOPE_GENERATE_PEPTIDES } from '../modules/local/epytope_generate_peptides' +include { SPLIT_PEPTIDES as SPLIT_PEPTIDES_PEPTIDES } from '../modules/local/split_peptides' +include { SPLIT_PEPTIDES as SPLIT_PEPTIDES_PROTEIN } from '../modules/local/split_peptides' -include { EPYTOPE_PEPTIDE_PREDICTION as EPYTOPE_PEPTIDE_PREDICTION_PROTEIN } from '../modules/local/epytope_peptide_prediction' -//include { EPYTOPE_PEPTIDE_PREDICTION as EPYTOPE_PEPTIDE_PREDICTION_PEP } from '../modules/local/epytope_peptide_prediction' -include { EPYTOPE_PEPTIDE_PREDICTION as EPYTOPE_PEPTIDE_PREDICTION_VAR } from '../modules/local/epytope_peptide_prediction' +include { EPYTOPE_PEPTIDE_PREDICTION as EPYTOPE_PEPTIDE_PREDICTION_PROTEIN } from '../modules/local/epytope_peptide_prediction' +include { EPYTOPE_PEPTIDE_PREDICTION as EPYTOPE_PEPTIDE_PREDICTION_PEP } from '../modules/local/epytope_peptide_prediction' +include { EPYTOPE_PEPTIDE_PREDICTION as EPYTOPE_PEPTIDE_PREDICTION_VAR } from '../modules/local/epytope_peptide_prediction' -include { CAT_FILES as CAT_TSV } from '../modules/local/cat_files' -include { CAT_FILES as CAT_FASTA } from '../modules/local/cat_files' -include { CSVTK_CONCAT } from '../modules/local/csvtk_concat' +include { CAT_FILES as CAT_TSV } from '../modules/local/cat_files' +include { CAT_FILES as CAT_FASTA } from '../modules/local/cat_files' +include { CSVTK_CONCAT } from '../modules/local/csvtk_concat' -include { MERGE_JSON as MERGE_JSON_SINGLE } from '../modules/local/merge_json' -include { MERGE_JSON as MERGE_JSON_MULTI } from '../modules/local/merge_json' +include { MERGE_JSON as MERGE_JSON_SINGLE } from '../modules/local/merge_json' +include { MERGE_JSON as MERGE_JSON_MULTI } from '../modules/local/merge_json' // // SUBWORKFLOW: Consisting of a mix of local and nf-core/modules -include { INPUT_CHECK } from '../subworkflows/local/input_check' include { MHC_BINDING_PREDICTION } from '../subworkflows/local/mhc_binding_prediction' /* @@ -79,86 +46,100 @@ include { MHC_BINDING_PREDICTION } from '../subworkflows/local/mhc_binding_predi // MODULE: Installed directly from nf-core/modules // include { MULTIQC } from '../modules/nf-core/multiqc/main' -include { CUSTOM_DUMPSOFTWAREVERSIONS } from '../modules/nf-core/custom/dumpsoftwareversions/main' include { GUNZIP as GUNZIP_VCF } from '../modules/nf-core/gunzip/main' +include { paramsSummaryMap } from 'plugin/nf-schema' +include { paramsSummaryMultiqc } from '../subworkflows/nf-core/utils_nfcore_pipeline' +include { softwareVersionsToYAML } from '../subworkflows/nf-core/utils_nfcore_pipeline' +include { methodsDescriptionText } from '../subworkflows/local/utils_nfcore_epitopeprediction_pipeline' + /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - RUN MAIN WORKFLOW + FUNCTIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ - -// Info required for completion email and summary -def multiqc_report = [] - -// load meta data of external tools import groovy.json.JsonSlurper + +// Load meta data of external tools def jsonSlurper = new JsonSlurper() def external_tools_meta = jsonSlurper.parse(file(params.external_tools_meta, checkIfExists: true)) +// Function to check if the alleles are valid for the given mhc class +def validate_alleles(String alleles, String mhc_class) { + valid_class1_loci = ['A*','B*','C*','E*','G*'] + valid_class2_loci = ['DR','DP','DQ'] + allele_list = alleles.split(';') + if (( mhc_class == 'I' & allele_list.every { allele -> valid_class2_loci.any { allele.startsWith(it) }}) | + ( mhc_class == 'II' & allele_list.every { allele -> valid_class1_loci.any { allele.startsWith(it) }})) { + exit 1, "Please check input samplesheet -> Invalid mhc class ${mhc_class} and allele combination ${allele_list} found!" + } +} + +/* +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + RUN MAIN WORKFLOW +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +*/ + + workflow EPITOPEPREDICTION { + take: + samplesheet + + main: + // Function to read the alleles from a file or use given string + def readAlleles = { input -> + if (input.endsWith(".txt")) { + def file = file(input) + // Alleles are listed in the first line of the file + return file.readLines().get(0) + } else { + // Not a file path, return the original string + return input + } + } + + // Initialise needed channels ch_versions = Channel.empty() - ch_software_versions = Channel.empty() - // Non-free prediction tools + ch_multiqc_files = Channel.empty() ch_nonfree_paths = Channel.empty() - // - // SUBWORKFLOW: Read in samplesheet, validate and stage input files - // - INPUT_CHECK ( - file(params.input) - ) - ch_versions = ch_versions.mix(INPUT_CHECK.out.versions) - // TODO: OPTIONAL, you can use nf-validation plugin to create an input channel from the samplesheet with Channel.fromSamplesheet("input") - // See the documentation https://nextflow-io.github.io/nf-validation/samplesheets/fromSamplesheet/ - // ! There is currently no tooling to help you write a sample sheet schema - - INPUT_CHECK.out.meta - .branch { - meta_data, input_file -> - variant_compressed : meta_data.inputtype == 'variant_compressed' - return [ meta_data, input_file ] - variant_uncompressed : meta_data.inputtype == 'variant' - return [ meta_data, input_file ] - peptide : meta_data.inputtype == 'peptide' - return [ meta_data, input_file ] - protein : meta_data.inputtype == 'protein' - return [ meta_data, input_file ] - } - .set { ch_samples_from_sheet } + // Load samplesheet and branch channels based on input type + samplesheet + .branch { meta, filename -> + def allele_list = readAlleles(meta.alleles) + validate_alleles(allele_list, meta.mhc_class) + // TODO: Replace sample with id + variant_compressed : filename.endsWith('.vcf.gz') + return [meta + [input_type:'variant_compressed'], filename ] + variant_uncompressed : filename.endsWith('.vcf') + return [meta + [input_type:'variant'], filename ] + peptide : filename.endsWith('.tsv') + return [meta + [input_type:'peptide'], filename ] + protein : filename.endsWith('.fasta') || filename.endsWith('.fa') + return [meta + [input_type:'protein'], filename ] + } + .set { ch_samplesheet } // gunzip variant files - GUNZIP_VCF ( - ch_samples_from_sheet.variant_compressed - ) - ch_versions = ch_versions.mix(GUNZIP_VCF.out.versions.ifEmpty(null)) + GUNZIP_VCF ( ch_samplesheet.variant_compressed ) + ch_versions = ch_versions.mix(GUNZIP_VCF.out.versions) - ch_variants_uncompressed = GUNZIP_VCF.out.gunzip - .mix(ch_samples_from_sheet.variant_uncompressed) + ch_variants_uncompressed = GUNZIP_VCF.out.gunzip.mix( ch_samplesheet.variant_uncompressed ) // (re)combine different input file types - ch_samples_uncompressed = ch_samples_from_sheet.protein - .mix(ch_samples_from_sheet.peptide) + ch_samples_uncompressed = ch_samplesheet.protein + .mix(ch_samplesheet.peptide) .mix(ch_variants_uncompressed) .branch { - meta_data, input_file -> - variant : meta_data.inputtype == 'variant' | meta_data.inputtype == 'variant_compressed' - peptide : meta_data.inputtype == 'peptide' - protein : meta_data.inputtype == 'protein' - } - - tools = params.tools?.tokenize(',') - - if (tools.isEmpty()) { exit 1, "No valid tools specified." } - - if (params.conda.enabled && params.tools.contains("netmhc")) { - log.warn("Please note: if you want to use external prediction tools with conda it might be necessary to set --netmhc_system to darwin depending on your system.") - } - - c_purple = params.monochrome_logs ? '' : "\033[0;35m"; - c_reset = params.monochrome_logs ? '' : "\033[0m"; + meta_data, input_file -> + variant : meta_data.input_type == 'variant' | meta_data.input_type == 'variant_compressed' + peptide : meta_data.input_type == 'peptide' + protein : meta_data.input_type == 'protein' + } + tools = params.tools.tokenize(",") // get versions of specified external tools ch_external_versions = Channel .from(tools) @@ -168,18 +149,18 @@ workflow EPITOPEPREDICTION { // get versions of all prediction tools GET_PREDICTION_VERSIONS(ch_external_versions.ifEmpty("")) - ch_prediction_tool_versions = GET_PREDICTION_VERSIONS.out.versions.ifEmpty(null) + ch_prediction_tool_versions = GET_PREDICTION_VERSIONS.out.versions // TODO I guess it would be better to have two subworkflows for the if else parts (CM) if (params.show_supported_models) { - SHOW_SUPPORTED_MODELS( + EPYTOPE_SHOW_SUPPORTED_MODELS( ch_samples_uncompressed .protein .mix(ch_samples_uncompressed.variant, ch_samples_uncompressed.peptide) .combine(ch_prediction_tool_versions) .first() ) - ch_versions = ch_versions.mix(SHOW_SUPPORTED_MODELS.out.versions.ifEmpty(null)) + ch_versions = ch_versions.mix(EPYTOPE_SHOW_SUPPORTED_MODELS.out.versions) } else { @@ -190,24 +171,19 @@ workflow EPITOPEPREDICTION { ======================================================================================== */ - /* - #We will be changing the implementation of check requested models so it doesn't depend on epytope - (this is necessary to work with newer versions of tools that aren't updated in epytope) - # The new check requested models will be implemented in the input_check.nf script - // perform the check requested models on the variant files EPYTOPE_CHECK_REQUESTED_MODELS( ch_samples_uncompressed.variant, ch_prediction_tool_versions ) - ch_versions = ch_versions.mix(EPYTOPE_CHECK_REQUESTED_MODELS.out.versions.ifEmpty(null)) + ch_versions = ch_versions.mix(EPYTOPE_CHECK_REQUESTED_MODELS.out.versions) // perform the check requested models on the protein files EPYTOPE_CHECK_REQUESTED_MODELS_PROTEIN( ch_samples_uncompressed.protein, ch_prediction_tool_versions ) - ch_versions = ch_versions.mix(EPYTOPE_CHECK_REQUESTED_MODELS_PROTEIN.out.versions.ifEmpty(null)) + ch_versions = ch_versions.mix(EPYTOPE_CHECK_REQUESTED_MODELS_PROTEIN.out.versions) // perform the check requested models on the peptide file where we need the input itself to determine the given peptide lengths EPYTOPE_CHECK_REQUESTED_MODELS_PEP( ch_samples_uncompressed @@ -215,7 +191,7 @@ workflow EPITOPEPREDICTION { .map { meta_data, input_file -> tuple( meta_data, input_file ) }, ch_prediction_tool_versions ) - ch_versions = ch_versions.mix(EPYTOPE_CHECK_REQUESTED_MODELS_PEP.out.versions.ifEmpty(null)) + ch_versions = ch_versions.mix(EPYTOPE_CHECK_REQUESTED_MODELS_PEP.out.versions) // Return a warning if this is raised EPYTOPE_CHECK_REQUESTED_MODELS @@ -233,7 +209,6 @@ workflow EPITOPEPREDICTION { } } } - */ // Retrieve meta data for external tools tools.each { @@ -279,7 +254,7 @@ workflow EPITOPEPREDICTION { EXTERNAL_TOOLS_IMPORT( ch_nonfree_paths ) - ch_versions = ch_versions.mix(EXTERNAL_TOOLS_IMPORT.out.versions.ifEmpty(null)) + ch_versions = ch_versions.mix(EXTERNAL_TOOLS_IMPORT.out.versions) /* ======================================================================================== @@ -287,58 +262,30 @@ workflow EPITOPEPREDICTION { ======================================================================================== */ - // Make a division for the variant files and process them further accordingly - ch_samples_uncompressed - .variant - .branch { - meta_data, input_file -> - vcf : input_file.extension == 'vcf' || input_file.extension == 'vcf.gz' - return [ meta_data, input_file ] - tab : input_file.extension == 'tsv' || input_file.extension == 'GSvar' - return [ meta_data, input_file ] - } - .set { ch_variants } - - // decide between the split_by_variants and snpsift_split (by chromosome) function (only vcf and vcf.gz variant files) + // decide between the split_by_variants and snpsift_split (by chromosome) function if (params.split_by_variants) { - VARIANT_SPLIT( - ch_variants.vcf - ) - .set { ch_split_variants } - ch_versions = ch_versions.mix( VARIANT_SPLIT.out.versions.ifEmpty(null) ) + VARIANT_SPLIT( ch_samples_uncompressed.variant ) + .set { ch_split_variants } + ch_versions = ch_versions.mix( VARIANT_SPLIT.out.versions ) } else { - SNPSIFT_SPLIT( - ch_variants.vcf - ) - .set { ch_split_variants } - ch_versions = ch_versions.mix( SNPSIFT_SPLIT.out.versions.ifEmpty(null) ) + SNPSIFT_SPLIT( ch_samples_uncompressed.variant ) + .set { ch_split_variants } + ch_versions = ch_versions.mix( SNPSIFT_SPLIT.out.versions ) } - // include the csvtk_split function (only variant files with an tsv and GSvar executable) - CSVTK_SPLIT( - ch_variants.tab - ) - - ch_versions = ch_versions.mix( CSVTK_SPLIT.out.versions.ifEmpty(null) ) // process FASTA file and generated peptides - EPYTOPE_GENERATE_PEPTIDES( - ch_samples_uncompressed.protein - ) - ch_versions = ch_versions.mix(EPYTOPE_GENERATE_PEPTIDES.out.versions.ifEmpty(null)) + EPYTOPE_GENERATE_PEPTIDES( ch_samples_uncompressed.protein ) + ch_versions = ch_versions.mix(EPYTOPE_GENERATE_PEPTIDES.out.versions) - SPLIT_PEPTIDES_PROTEIN( - EPYTOPE_GENERATE_PEPTIDES.out.splitted - ) - ch_versions = ch_versions.mix(SPLIT_PEPTIDES_PROTEIN.out.versions.ifEmpty(null)) + SPLIT_PEPTIDES_PROTEIN( EPYTOPE_GENERATE_PEPTIDES.out.splitted ) + ch_versions = ch_versions.mix(SPLIT_PEPTIDES_PROTEIN.out.versions) // split peptide data - SPLIT_PEPTIDES_PEPTIDES( - ch_samples_uncompressed.peptide - ) - ch_versions = ch_versions.mix( SPLIT_PEPTIDES_PEPTIDES.out.versions.ifEmpty(null) ) + SPLIT_PEPTIDES_PEPTIDES( ch_samples_uncompressed.peptide ) + ch_versions = ch_versions.mix( SPLIT_PEPTIDES_PEPTIDES.out.versions ) /* ======================================================================================== @@ -346,7 +293,6 @@ workflow EPITOPEPREDICTION { ======================================================================================== */ - // not sure if this is the best solution to also have a extra process for protein, but I think we need it for cases when we have both in one sheet? (CM) // run epitope prediction for proteins EPYTOPE_PEPTIDE_PREDICTION_PROTEIN( @@ -357,11 +303,9 @@ workflow EPITOPEPREDICTION { .transpose(), EXTERNAL_TOOLS_IMPORT.out.nonfree_tools.collect().ifEmpty([]) ) - ch_versions = ch_versions.mix( EPYTOPE_PEPTIDE_PREDICTION_PROTEIN.out.versions.ifEmpty(null) ) - + ch_versions = ch_versions.mix( EPYTOPE_PEPTIDE_PREDICTION_PROTEIN.out.versions ) // Run epitope prediction for peptides - /* EPYTOPE_PEPTIDE_PREDICTION_PEP( SPLIT_PEPTIDES_PEPTIDES .out @@ -370,38 +314,27 @@ workflow EPITOPEPREDICTION { .transpose(), EXTERNAL_TOOLS_IMPORT.out.nonfree_tools.collect().ifEmpty([]) ) - ch_versions = ch_versions.mix( EPYTOPE_PEPTIDE_PREDICTION_PEP.out.versions.ifEmpty(null) ) - */ - - ch_prediction_input = SPLIT_PEPTIDES_PEPTIDES - .out - .splitted - //.combine( ch_prediction_tool_versions ) - .transpose() + ch_versions = ch_versions.mix( EPYTOPE_PEPTIDE_PREDICTION_PEP.out.versions ) - MHC_BINDING_PREDICTION( - ch_prediction_input) + ch_prediction_input = SPLIT_PEPTIDES_PEPTIDES.out.splitted.transpose() - ch_predicted_peptides = MHC_BINDING_PREDICTION - .out - .predicted + MHC_BINDING_PREDICTION( ch_samples_uncompressed.peptide ) + ch_versions = ch_versions.mix(MHC_BINDING_PREDICTION.out.versions) - ch_versions = ch_versions.mix(MHC_BINDING_PREDICTION.out.versions.ifEmpty(null)) + ch_predicted_peptides = MHC_BINDING_PREDICTION.out.predicted // Run epitope prediction for variants EPYTOPE_PEPTIDE_PREDICTION_VAR( - CSVTK_SPLIT - .out + ch_split_variants .splitted - .mix( ch_split_variants.splitted ) .combine( ch_prediction_tool_versions ) .transpose(), EXTERNAL_TOOLS_IMPORT.out.nonfree_tools.collect().ifEmpty([]) ) - ch_versions = ch_versions.mix( EPYTOPE_PEPTIDE_PREDICTION_VAR.out.versions.ifEmpty(null) ) + ch_versions = ch_versions.mix( EPYTOPE_PEPTIDE_PREDICTION_VAR.out.versions ) // Combine the predicted files and save them in a branch to make a distinction between samples with single and multi files - /*EPYTOPE_PEPTIDE_PREDICTION_PEP + EPYTOPE_PEPTIDE_PREDICTION_PEP .out .predicted .mix( EPYTOPE_PEPTIDE_PREDICTION_VAR.out.predicted, EPYTOPE_PEPTIDE_PREDICTION_PROTEIN.out.predicted ) @@ -415,19 +348,13 @@ workflow EPITOPEPREDICTION { return [ meta_data, predicted ] } .set { ch_predicted_peptides } -*/ // Combine epitope prediction results - CAT_TSV( - ch_predicted_peptides - ) - ch_versions = ch_versions.mix( CAT_TSV.out.versions.ifEmpty(null) ) + CAT_TSV( ch_predicted_peptides.multi ) + ch_versions = ch_versions.mix( CAT_TSV.out.versions ) -/* - CSVTK_CONCAT( - ch_predicted_peptides.multi - ) - ch_versions = ch_versions.mix( CSVTK_CONCAT.out.versions.ifEmpty(null) ) + CSVTK_CONCAT( ch_predicted_peptides.multi ) + ch_versions = ch_versions.mix( CSVTK_CONCAT.out.versions ) // Combine protein sequences CAT_FASTA( @@ -437,7 +364,7 @@ workflow EPITOPEPREDICTION { .mix( EPYTOPE_PEPTIDE_PREDICTION_VAR.out.fasta, EPYTOPE_PEPTIDE_PREDICTION_PROTEIN.out.fasta ) .groupTuple() ) - ch_versions = ch_versions.mix( CAT_FASTA.out.versions.ifEmpty(null) ) + ch_versions = ch_versions.mix( CAT_FASTA.out.versions ) EPYTOPE_PEPTIDE_PREDICTION_PEP .out @@ -456,62 +383,67 @@ workflow EPITOPEPREDICTION { .set { ch_json_reports } // Combine epitope prediction reports - MERGE_JSON_SINGLE( - ch_json_reports.single - ) - ch_versions = ch_versions.mix( MERGE_JSON_SINGLE.out.versions.ifEmpty(null) ) + MERGE_JSON_SINGLE( ch_json_reports.single ) + ch_versions = ch_versions.mix( MERGE_JSON_SINGLE.out.versions ) - MERGE_JSON_MULTI( - ch_json_reports.multi - ) - ch_versions = ch_versions.mix( MERGE_JSON_MULTI.out.versions.ifEmpty(null) ) - */ + MERGE_JSON_MULTI( ch_json_reports.multi ) + ch_versions = ch_versions.mix( MERGE_JSON_MULTI.out.versions ) + } // - // MODULE: Pipeline reporting + // Collate and save software versions // - CUSTOM_DUMPSOFTWAREVERSIONS ( - ch_versions.unique().collectFile(name: 'collated_versions.yml') - ) + softwareVersionsToYAML(ch_versions) + .collectFile( + storeDir: "${params.outdir}/pipeline_info", + name: 'nf_core_' + 'pipeline_software_' + 'mqc_' + 'versions.yml', + sort: true, + newLine: true + ).set { ch_collated_versions } // // MODULE: MultiQC // - workflow_summary = WorkflowEpitopeprediction.paramsSummaryMultiqc( workflow, summary_params ) - ch_workflow_summary = Channel.value( workflow_summary ) - - methods_description = WorkflowEpitopeprediction.methodsDescriptionText(workflow, ch_multiqc_custom_methods_description, params) - ch_methods_description = Channel.value(methods_description) - - ch_multiqc_files = Channel.empty() - ch_multiqc_files = ch_multiqc_files.mix(ch_workflow_summary.collectFile(name: 'workflow_summary_mqc.yaml')) - ch_multiqc_files = ch_multiqc_files.mix(ch_methods_description.collectFile(name: 'methods_description_mqc.yaml')) - ch_multiqc_files = ch_multiqc_files.mix(CUSTOM_DUMPSOFTWAREVERSIONS.out.mqc_yml.collect()) + ch_multiqc_config = Channel.fromPath( + "$projectDir/assets/multiqc_config.yml", checkIfExists: true) + ch_multiqc_custom_config = params.multiqc_config ? + Channel.fromPath(params.multiqc_config, checkIfExists: true) : + Channel.empty() + ch_multiqc_logo = params.multiqc_logo ? + Channel.fromPath(params.multiqc_logo, checkIfExists: true) : + Channel.empty() + + summary_params = paramsSummaryMap( + workflow, parameters_schema: "nextflow_schema.json") + ch_workflow_summary = Channel.value(paramsSummaryMultiqc(summary_params)) + ch_multiqc_files = ch_multiqc_files.mix( + ch_workflow_summary.collectFile(name: 'workflow_summary_mqc.yaml')) + ch_multiqc_custom_methods_description = params.multiqc_methods_description ? + file(params.multiqc_methods_description, checkIfExists: true) : + file("$projectDir/assets/methods_description_template.yml", checkIfExists: true) + ch_methods_description = Channel.value( + methodsDescriptionText(ch_multiqc_custom_methods_description)) + + ch_multiqc_files = ch_multiqc_files.mix(ch_collated_versions) + ch_multiqc_files = ch_multiqc_files.mix( + ch_methods_description.collectFile( + name: 'methods_description_mqc.yaml', + sort: true + ) + ) MULTIQC ( ch_multiqc_files.collect(), ch_multiqc_config.toList(), ch_multiqc_custom_config.toList(), - ch_multiqc_logo.toList() + ch_multiqc_logo.toList(), + [], + [] ) - multiqc_report = MULTIQC.out.report.toList() - } -} -/* -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - COMPLETION EMAIL AND SUMMARY -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -*/ + emit:multiqc_report = MULTIQC.out.report.toList() // channel: /path/to/multiqc_report.html + versions = ch_versions // channel: [ path(versions.yml) ] -workflow.onComplete { - if (params.email || params.email_on_fail) { - NfcoreTemplate.email(workflow, params, summary_params, projectDir, log, multiqc_report) - } - NfcoreTemplate.summary(workflow, params, log) - if (params.hook_url) { - NfcoreTemplate.IM_notification(workflow, params, summary_params, projectDir, log) - } } /*