diff --git a/.circleci/config.yml b/.circleci/config.yml index c8058c48b7..7e826eb547 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,5 +1,5 @@ _machine_kwds: &machine_kwds - image: circleci/classic:201808-01 + image: ubuntu-2004:202107-02 _store_artifacts_kwds: &store_artifacts_kwds path: /home/circleci/work/tests @@ -43,15 +43,16 @@ _get_base_image: &get_base_image exit 1 fi -_build_main_image_py36: &build_main_image_py36 - name: Build main image (py36) +_build_main_image_py38: &build_main_image_py38 + name: Build main image (py38) no_output_timeout: 60m command: | tools/retry_cmd.sh -n 5 -s 15 \ docker build \ --rm=false \ --tag nipype/nipype:latest \ - --tag nipype/nipype:py36 \ + --tag nipype/nipype:py38 \ + $(test -z "${CIRCLE_TAG}" || echo --tag nipype/nipype:"${CIRCLE_TAG}") \ --build-arg BUILD_DATE="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" \ --build-arg VCS_REF="$(git rev-parse --short HEAD)" \ --build-arg VERSION="${CIRCLE_TAG}" /home/circleci/nipype @@ -63,14 +64,21 @@ _download_test_data: &_download_test_data environment: OSF_NIPYPE_URL: "https://files.osf.io/v1/resources/nefdp/providers/osfstorage" command: | + set -x export DATA_NIPYPE_TUTORIAL_URL="${OSF_NIPYPE_URL}/57f4739cb83f6901ed94bf21" - curl -sSL --retry 5 --connect-timeout 15 "$DATA_NIPYPE_TUTORIAL_URL" | tar xj + if [[ ! -d nipype-tutorial ]]; then + curl -sSL --retry 5 --connect-timeout 15 "$DATA_NIPYPE_TUTORIAL_URL" | tar xjv + fi export DATA_NIPYPE_FSL_COURSE="${OSF_NIPYPE_URL}/57f472cf9ad5a101f977ecfe" - curl -sSL --retry 5 --connect-timeout 15 "$DATA_NIPYPE_FSL_COURSE" | tar xz + if [[ ! -d nipype-fsl_course_data ]]; then + curl -sSL --retry 5 --connect-timeout 15 "$DATA_NIPYPE_FSL_COURSE" | tar xzv + fi export DATA_NIPYPE_FSL_FEEDS="${OSF_NIPYPE_URL}/57f473066c613b01f113e7af" - curl -sSL --retry 5 --connect-timeout 15 "$DATA_NIPYPE_FSL_FEEDS" | tar xz + if [[ ! -d feeds ]]; then + curl -sSL --retry 5 --connect-timeout 15 "$DATA_NIPYPE_FSL_FEEDS" | tar xzv + fi _prepare_working_directory: &prepare_working_directory name: Prepare working directory @@ -101,7 +109,7 @@ version: 2 jobs: compare_base_dockerfiles: docker: - - image: docker:17.10.0-ce-git + - image: cimg/base:2022.04 steps: - checkout: path: /home/circleci/nipype @@ -111,10 +119,10 @@ jobs: working_directory: /home/circleci/nipype/docker command: | mkdir -p /tmp/docker - ash ./generate_dockerfiles.sh -b + bash ./generate_dockerfiles.sh -b # Use the sha256 sum of the pruned Dockerfile as the cache key. - ash prune_dockerfile.sh Dockerfile.base > /tmp/docker/Dockerfile.base-pruned + bash prune_dockerfile.sh Dockerfile.base > /tmp/docker/Dockerfile.base-pruned - restore_cache: key: dockerfile-cache-v1-master-{{ checksum "/tmp/docker/Dockerfile.base-pruned" }} - run: @@ -133,6 +141,23 @@ jobs: - docker/Dockerfile.base-pruned - docker/get_base_image.sh + get_test_data: + machine: *machine_kwds + working_directory: /home/circleci/nipype + steps: + - restore_cache: + keys: + - data-v0-{{ .Branch }}-{{ .Revision }} + - data-v0--{{ .Revision }} + - data-v0-{{ .Branch }}- + - data-v0-master- + - data-v0- + - run: *_download_test_data + - save_cache: + key: data-v0-{{ .Branch }}-{{ .Revision }} + paths: + - /home/circleci/examples + test_pytest: machine: *machine_kwds working_directory: /home/circleci/nipype @@ -141,13 +166,15 @@ jobs: path: /home/circleci/nipype - attach_workspace: at: /tmp + - restore_cache: + keys: + - data-v0-{{ .Branch }}-{{ .Revision }} - run: *set_pr_number - run: *generate_dockerfiles - run: *modify_nipype_version - run: *get_base_image - - run: *build_main_image_py36 + - run: *build_main_image_py38 - run: *_get_codecov - - run: *_download_test_data - run: *prepare_working_directory - run: name: Run pytests @@ -164,111 +191,14 @@ jobs: if [ "$CIRCLE_BRANCH" = "master" -a -z "$CIRCLE_PULL_REQUEST" ]; then docker save nipype/nipype:base \ nipype/nipype:latest \ - nipype/nipype:py36 | gzip -1 > /tmp/docker/nipype-base-latest-py36.tar.gz \ - && du -h /tmp/docker/nipype-base-latest-py36.tar.gz + nipype/nipype:py38 | gzip -1 > /tmp/docker/nipype-base-latest-py38.tar.gz \ + && du -h /tmp/docker/nipype-base-latest-py38.tar.gz fi - persist_to_workspace: root: /tmp paths: - docker - test_fmri_fsl_spm: - machine: *machine_kwds - working_directory: /home/circleci/nipype - steps: - - checkout: - path: /home/circleci/nipype - - attach_workspace: - at: /tmp - - run: *set_pr_number - - run: *generate_dockerfiles - - run: *modify_nipype_version - - run: *get_base_image - - run: *build_main_image_py36 - - run: *_get_codecov - - run: *_download_test_data - - run: *prepare_working_directory - - run: - name: Run FSL reuse pipeline - no_output_timeout: 40m - environment: *test_environment - command: bash -ux /home/circleci/nipype/.circleci/test_fmri_fsl_reuse_linear_l1.sh - - run: - name: Run SPM test workflow - 3D inputs - no_output_timeout: 40m - environment: *test_environment - command: bash -ux /home/circleci/nipype/.circleci/test_fmri_spm_linear_3d.sh - - run: - name: Run SPM test workflow - 4D inputs - no_output_timeout: 40m - environment: *test_environment - command: bash -ux /home/circleci/nipype/.circleci/test_fmri_spm_linear_4d.sh - - run: *_run_codecov_smoke - - store_artifacts: *store_artifacts_kwds - - test_fmri_spm_dartel_multiproc: - machine: *machine_kwds - working_directory: /home/circleci/nipype - steps: - - checkout: - path: /home/circleci/nipype - - attach_workspace: - at: /tmp - - run: *set_pr_number - - run: *generate_dockerfiles - - run: *modify_nipype_version - - run: *get_base_image - - run: *build_main_image_py36 - - run: *_get_codecov - - run: *_download_test_data - - run: *prepare_working_directory - - run: - name: Run SPM DARTEL Level 1 pipeline - no_output_timeout: 1h - environment: *test_environment - command: bash -ux /home/circleci/nipype/.circleci/test_fmri_spm_dartel_multiproc_l1.sh - - run: - name: Run SPM DARTEL Level 2 pipeline - no_output_timeout: 30m - environment: *test_environment - command: bash -ux /home/circleci/nipype/.circleci/test_fmri_spm_dartel_multiproc_l2.sh - - run: *_run_codecov_smoke - - store_artifacts: *store_artifacts_kwds - - test_fmri_spm_nested_fsl_feeds: - machine: *machine_kwds - working_directory: /home/circleci/nipype - steps: - - checkout: - path: /home/circleci/nipype - - attach_workspace: - at: /tmp - - run: *set_pr_number - - run: *generate_dockerfiles - - run: *modify_nipype_version - - run: *get_base_image - - run: *build_main_image_py36 - - run: *_get_codecov - - run: *_download_test_data - - run: *prepare_working_directory - - run: - name: Run SPM Nested Level 1 pipeline - no_output_timeout: 1h - environment: *test_environment - command: bash -ux /home/circleci/nipype/.circleci/test_fmri_spm_nested_multiproc_l1.sh - - run: - name: Run SPM Nested Level 2 pipeline - no_output_timeout: 30m - environment: *test_environment - command: bash -ux /home/circleci/nipype/.circleci/test_fmri_spm_nested_multiproc_l2.sh - - run: - name: Run FSL FEEDS pipeline - no_output_timeout: 40m - environment: *test_environment - command: bash -ux /home/circleci/nipype/.circleci/test_fmri_fsl_feeds_linear_l1.sh - - run: *_run_codecov_smoke - - store_artifacts: *store_artifacts_kwds - deploy_dockerhub: docker: - image: docker:17.10.0-ce-git @@ -280,7 +210,7 @@ jobs: name: Load saved Docker images. no_output_timeout: 60m command: | - docker load < /tmp/docker/nipype-base-latest-py36.tar.gz + docker load < /tmp/docker/nipype-base-latest-py38.tar.gz - run: name: Push to DockerHub no_output_timeout: 120m @@ -288,7 +218,8 @@ jobs: echo "$DOCKER_PASS" | docker login -u "$DOCKER_USER" --password-stdin docker push nipype/nipype:base docker push nipype/nipype:latest - docker push nipype/nipype:py36 + docker push nipype/nipype:py38 + test -z "${CIRCLE_TAG}" || docker push nipype/nipype:"${CIRCLE_TAG}" - run: name: Move pruned Dockerfile to /tmp/docker/cache directory command: | @@ -299,61 +230,6 @@ jobs: - /tmp/docker/cache/Dockerfile.base-pruned key: dockerfile-cache-v1-{{ .Branch }}-{{ checksum "/tmp/docker/cache/Dockerfile.base-pruned" }} - pypi_precheck: - machine: *machine_kwds - working_directory: /home/circleci/nipype - steps: - - checkout: - path: /home/circleci/nipype - - run: - name: Check pypi preconditions - command: | - pyenv local 3.6.5 - pip install --upgrade pip twine future wheel readme_renderer setuptools - python setup.py sdist bdist_wheel - twine check dist/* - - run: - name: Validate Python 3 installation - command: | - pyenv local 3.6.5 - pip install --upgrade pip - pip install dist/nipype-*-py3-none-any.whl - - run: - name: Validate Python 3.7 installation - command: | - pyenv local 3.7.0 - pip install --upgrade pip - # Pre-install a version of numpy that will not pass - pip install numpy==1.15.0 - pip install dist/nipype-*-py3-none-any.whl - # Numpy should be upgraded to >= 1.15.3 - test "$(pip show numpy | grep Version)" \> "Version: 1.15.2" - - run: - name: Check python_requires prevents installation on Python 3.3 - command: | - pyenv install 3.3.7 - pyenv local 3.3.7 - FAIL=false - pip install dist/nipype-*-py2.py3-none-any.whl || FAIL=true - $FAIL - - store_artifacts: - path: /home/circleci/nipype/dist - - deploy_pypi: - machine: *machine_kwds - working_directory: /home/circleci/nipype - steps: - - checkout: - path: /home/circleci/nipype - - run: - name: Deploy to PyPI - command: | - pyenv local 3.6.5 - pip install --upgrade twine wheel readme_renderer setuptools - python setup.py check -r -s - python setup.py sdist bdist_wheel - twine upload dist/* - update_feedstock: machine: *machine_kwds working_directory: /home/circleci/nipype @@ -363,9 +239,9 @@ jobs: - run: name: Install hub command: | - curl -sSL https://github.com/github/hub/releases/download/v2.2.9/hub-linux-amd64-2.2.9.tgz | \ + curl -sSL https://github.com/github/hub/releases/download/v2.14.2/hub-linux-amd64-2.14.2.tgz | \ tar zxv -C /tmp - sudo /tmp/hub-linux-amd64-2.2.9/install + sudo /tmp/hub-linux-amd64-2.14.2/install - run: name: Expand SSH Key command: | @@ -375,10 +251,11 @@ jobs: chmod go-rwx ~/.ssh/id_ed25519 ssh-keygen -y -f ~/.ssh/id_ed25519 > ~/.ssh/id_ed25519.pub - run: - name: Set git identity + name: Set git/hub configuration command: | git config --global user.name "nipybot" git config --global user.email "nipybot@gmail.com" + git config --global hub.protocol ssh - run: name: Update feedstock command: | @@ -386,109 +263,7 @@ jobs: ssh-add ~/.ssh/id_ed25519 /home/circleci/nipype/tools/feedstock.sh - build_docs: - docker: - - image: python:3.7.4 - working_directory: /tmp/src/nipype - environment: - - FSLOUTPUTTYPE: 'NIFTI' - steps: - - checkout - - run: - name: Check Python version and upgrade pip - command: | - python --version - python -m pip install -U pip - - run: - name: Install graphviz - command: | - apt-get update - apt-get install -y graphviz - - run: - name: Install Requirements (may contain pinned versions) - command: python -m pip install -r doc/requirements.txt - - run: - name: Install NiPype - command: python -m pip install ".[doc]" - - run: - name: Build documentation - command: make -C doc html - - store_artifacts: - path: /tmp/src/nipype/doc/_build/html - workflows: version: 2 build_test_deploy: - jobs: - - build_docs: - filters: - tags: - only: /.*/ - - pypi_precheck: - filters: - branches: - only: /(rel|dev)\/.*/ - tags: - only: /.*/ - - compare_base_dockerfiles: - filters: - branches: - ignore: - - /docs?\/.*/ - tags: - only: /.*/ - - test_pytest: - filters: - branches: - ignore: - - /docs?\/.*/ - tags: - only: /.*/ - requires: - - compare_base_dockerfiles - - test_fmri_fsl_spm: - filters: - branches: - ignore: - - /docs?\/.*/ - requires: - - compare_base_dockerfiles - - test_fmri_spm_dartel_multiproc: - filters: - branches: - ignore: - - /docs?\/.*/ - requires: - - compare_base_dockerfiles - - test_fmri_spm_nested_fsl_feeds: - filters: - branches: - ignore: - - /docs?\/.*/ - requires: - - compare_base_dockerfiles - - deploy_dockerhub: - filters: - branches: - only: master - requires: - - test_pytest - - test_fmri_spm_nested_fsl_feeds - - test_fmri_fsl_spm - - test_fmri_spm_dartel_multiproc - - deploy_pypi: - filters: - branches: - ignore: /.*/ - tags: - only: /.*/ - requires: - - pypi_precheck - - test_pytest - - update_feedstock: - context: nipybot - filters: - branches: - only: /rel\/.*/ - tags: - only: /.*/ + jobs: [] diff --git a/.circleci/test_fmri_fsl_feeds_linear_l1.sh b/.circleci/test_fmri_fsl_feeds_linear_l1.sh deleted file mode 100644 index 9666829b74..0000000000 --- a/.circleci/test_fmri_fsl_feeds_linear_l1.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work "${DOCKER_IMAGE}:py36" /usr/bin/run_examples.sh fmri_fsl_feeds Linear /data/examples/ l1pipeline diff --git a/.circleci/test_fmri_fsl_reuse_linear_l1.sh b/.circleci/test_fmri_fsl_reuse_linear_l1.sh deleted file mode 100644 index 48be49d80d..0000000000 --- a/.circleci/test_fmri_fsl_reuse_linear_l1.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work "${DOCKER_IMAGE}:py36" /usr/bin/run_examples.sh fmri_fsl_reuse Linear /data/examples/ level1_workflow diff --git a/.circleci/test_fmri_spm_dartel_multiproc_l1.sh b/.circleci/test_fmri_spm_dartel_multiproc_l1.sh deleted file mode 100644 index 4208eed506..0000000000 --- a/.circleci/test_fmri_spm_dartel_multiproc_l1.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work "${DOCKER_IMAGE}:py36" /usr/bin/run_examples.sh fmri_spm_dartel MultiProc /data/examples/ level1 diff --git a/.circleci/test_fmri_spm_dartel_multiproc_l2.sh b/.circleci/test_fmri_spm_dartel_multiproc_l2.sh deleted file mode 100644 index 86119e7654..0000000000 --- a/.circleci/test_fmri_spm_dartel_multiproc_l2.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work "${DOCKER_IMAGE}:py36" /usr/bin/run_examples.sh fmri_spm_dartel MultiProc /data/examples/ l2pipeline diff --git a/.circleci/test_fmri_spm_linear_3d.sh b/.circleci/test_fmri_spm_linear_3d.sh deleted file mode 100644 index 27c2c92a1a..0000000000 --- a/.circleci/test_fmri_spm_linear_3d.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work "${DOCKER_IMAGE}:py36" /usr/bin/run_examples.sh test_spm Linear /data/examples/ workflow3d diff --git a/.circleci/test_fmri_spm_linear_4d.sh b/.circleci/test_fmri_spm_linear_4d.sh deleted file mode 100644 index cd255d60ca..0000000000 --- a/.circleci/test_fmri_spm_linear_4d.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work "${DOCKER_IMAGE}:py36" /usr/bin/run_examples.sh test_spm Linear /data/examples/ workflow4d diff --git a/.circleci/test_fmri_spm_nested_multiproc_l1.sh b/.circleci/test_fmri_spm_nested_multiproc_l1.sh deleted file mode 100644 index a6d2133a42..0000000000 --- a/.circleci/test_fmri_spm_nested_multiproc_l1.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work -e NIPYPE_NUMBER_OF_CPUS=4 "${DOCKER_IMAGE}:py36" /usr/bin/run_examples.sh fmri_spm_nested MultiProc /data/examples/ level1 diff --git a/.circleci/test_fmri_spm_nested_multiproc_l2.sh b/.circleci/test_fmri_spm_nested_multiproc_l2.sh deleted file mode 100644 index c0926be148..0000000000 --- a/.circleci/test_fmri_spm_nested_multiproc_l2.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work -e NIPYPE_NUMBER_OF_CPUS=4 -e NIPYPE_RESOURCE_MONITOR=1 "${DOCKER_IMAGE}:py36" /usr/bin/run_examples.sh fmri_spm_nested MultiProc /data/examples/ l2pipeline diff --git a/.circleci/test_pytest.sh b/.circleci/test_pytest.sh index b93208f395..832a52a02b 100644 --- a/.circleci/test_pytest.sh +++ b/.circleci/test_pytest.sh @@ -1,3 +1,3 @@ #!/bin/bash -docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work -e CI_SKIP_TEST=1 -e NIPYPE_RESOURCE_MONITOR=1 "${DOCKER_IMAGE}:py36" /usr/bin/run_pytests.sh +docker run --rm=false -t -v $WORKDIR:/work -v $HOME/examples:/data/examples:ro -w /work -e CI_SKIP_TEST=1 -e NIPYPE_RESOURCE_MONITOR=1 "${DOCKER_IMAGE}:py38" /usr/bin/run_pytests.sh diff --git a/.codespellrc b/.codespellrc new file mode 100644 index 0000000000..6b83f1227e --- /dev/null +++ b/.codespellrc @@ -0,0 +1,13 @@ +[codespell] +skip = .git,*.pdf,*.svg,external +# nd,nam - import module short +# fith - oddness coming from AFNI +# whos - smth used in matlab things +# SMAL - Stanford CNI MRS Library +# Suh - name +# noo,crasher,afile - field/var name used +# Reson - short journal name +# ALS, FWE - neuroimaging specific abbrevs +# Comision - foreign word used +# expad - AFNI flag +ignore-words-list = te,inport,objekt,jist,nd,hel,inout,fith,whos,fot,ue,shs,smal,nam,filetest,suh,noo,reson,als,fwe,crasher,comision,afile,expad,burnin diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000..6f762e919b --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,102 @@ +# Fri Feb 21 14:06:53 2025 -0500 - markiewicz@stanford.edu - sty: black [ignore-rev] +8ed2b2306aeb7d89de4958b5293223ffe27a4f34 +# Tue Apr 13 10:16:17 2021 -0400 - markiewicz@stanford.edu - STY: black +b1690d5beb391e08c1e5463f1e3c641cf1e9f58e +# Thu Oct 31 10:01:38 2024 -0400 - effigies@gmail.com - STY: black [ignore-rev] +bd0d5856d183ba3918eda31f80db3b1d4387c55c +# Thu Mar 21 13:34:09 2024 -0400 - effigies@gmail.com - STY: black [ignore-rev] +c52fece0cf154c1a93a55b202d088f08924a023e +# Sun Mar 17 10:58:12 2024 -0400 - effigies@gmail.com - STY: black [ignore-rev] +e447b92bcb3b9ed9e35394d6edef1d91b7c424e6 +# Sun Mar 17 10:44:57 2024 -0400 - effigies@gmail.com - STY: black +f1a8909d233ed2a707b6ee8937504eea9ee7f154 +# Tue Feb 27 14:28:18 2024 -0500 - effigies@gmail.com - STY: black 2024.2 [ignore-rev] +f1cbc1c941f8d02659f8ef245aac0862efb80ccf +# Mon Sep 11 13:36:40 2023 +0200 - 37933899+servoz@users.noreply.github.com - run black for nipype/interfaces/spm/preprocess.py +b9cac5e993143febb01ade42e56b41009427a4b6 +# Wed Jul 5 16:31:45 2023 -0400 - effigies@gmail.com - STY: Run black and fix typo +34a4ac6eeff8d4924b40875c45df5d84a97da90b +# Wed Jul 5 11:30:42 2023 -0400 - effigies@gmail.com - STY: black +3b89ca85faf2428ecf7844de9c0db4aa7c329c93 +# Wed Jul 5 09:49:31 2023 -0400 - effigies@gmail.com - STY: black +4a6a7d9d25d5d1e1f0eb55828dede58f8b9c9f80 +# Wed Apr 5 14:01:05 2023 -0400 - effigies@gmail.com - STY: black [ignore-rev] +a9ce9b78a402ebacf7726ad6454bb75b1447f52f +# Wed Sep 14 14:12:07 2022 -0400 - mathiasg@stanford.edu - STY: Black +f4a779223c6b0dffa47138d24ec9ef378c7164a9 +# Tue Apr 19 14:09:31 2022 -0400 - markiewicz@stanford.edu - STY: black [ignore-rev] +b9716ebd46541f7fb1b96a94cc35b5e2ea6c3bba +# Fri Apr 15 06:59:48 2022 -0700 - markiewicz@stanford.edu - STY: black [ignore-rev] +d223fbccda6dee0ef39e00084296a3292f2ccf87 +# Fri Apr 8 21:34:43 2022 -0400 - markiewicz@stanford.edu - STY: black [ignore-rev] +e3f56da124fd58041018c2e70d16a130ef189a66 +# Sun Apr 3 10:27:07 2022 -0400 - markiewicz@stanford.edu - STY: black [ignore-rev] +988c382ebfc7df964874b6287b9d9e27e274a4a4 +# Sat Apr 2 21:32:56 2022 -0400 - markiewicz@stanford.edu - STY: black [ignore-rev] +230fac6149d4dfbd5da669a983332a1fe318ef57 +# Sat Apr 2 12:49:15 2022 -0400 - markiewicz@stanford.edu - STY/TEST: Make specs and run black [ignore-rev] +2ba8dacb8cc1f6f9c5b15b1cfb7b0395d45dcfb3 +# Sun Mar 20 21:19:39 2022 -0400 - markiewicz@stanford.edu - STY: black [ignore-rev] +87cc1b54981113024ec3fd594881f72cf67513fb +# Wed Dec 8 17:02:09 2021 -0500 - markiewicz@stanford.edu - STY: black [ignore-rev] +5ac2f18ac116832d81a13f0c83e0a6aeda1457cf +# Thu Dec 2 09:30:42 2021 -0500 - markiewicz@stanford.edu - STY: black +ee50279ebf061a70ff502e7d2e51385b285cfda4 +# Tue Oct 26 11:18:02 2021 +0200 - code@oscaresteban.es - sty: run black +5d9adbbb77b7047b9b47cd2fa079dee0094cfc91 +# Wed Oct 20 12:07:15 2021 +0200 - fabio.bernardoni@uniklinikum-dresden.de - run black on the preprocess.py file to improve formatting +674e9b0eeca082efb5322b61fea57ee89a3e4a24 +# Wed Oct 13 16:08:23 2021 -0400 - markiewicz@stanford.edu - ENH: Add expected steps for FreeSurfer 7 recon-all (#3389) +8f7c0bf2ec9c819844a2736a9ae2f6eef19a8e7f +# Wed Oct 13 14:26:48 2021 -0400 - markiewicz@stanford.edu - STY: black +d8dbc6f7b6a5385535e2fa53b7c6af7aa1370f46 +# Wed Sep 29 16:53:54 2021 +0200 - code@oscaresteban.es - sty: run black on affected files +5f280da629bb7b5dce908633d2deea85b55dd67b +# Thu Jun 24 17:43:22 2021 +0200 - code@oscaresteban.es - sty: run black +135ce497a18adbe0811441c2b720910ec549aa6f +# Thu Sep 23 08:56:28 2021 -0400 - markiewicz@stanford.edu - STY: black +f69b3fb09560616822737764bb07272cd587e4a0 +# Fri Apr 30 17:19:55 2021 -0400 - markiewicz@stanford.edu - STY: black +04718ac71436b6f283af7575dda0f6998b64f893 +# Fri Apr 30 16:50:00 2021 -0400 - markiewicz@stanford.edu - STY: black +12deb959cccc431fb8222cc5854f1c92a0080021 +# Thu Apr 1 12:26:08 2021 -0400 - markiewicz@stanford.edu - STY: black +f64bf338f630a9ee5cbe7a3ec98c68292897e720 +# Thu Dec 3 09:24:05 2020 +1100 - tom.g.close@gmail.com - run black over touched files +c81259bc3b28baa1f18f95f6b056c228c6bfd115 +# Fri Aug 14 17:15:15 2020 -0400 - markiewicz@stanford.edu - STY: Black +83358d7f17aac07cb90d0330f11ea2322e2974d8 +# Sat Mar 14 12:44:20 2020 -0400 - markiewicz@stanford.edu - STY: black +faef7d0f93013a700c882f709e98fb3cd36ebb03 +# Sun Mar 8 15:05:28 2020 +0100 - 3453485+daniel-ge@users.noreply.github.com - FIX: get length of generator + STY: Black +02991da67458b879d7c6360aa6457eb3c1bd5a07 +# Wed Mar 4 16:30:39 2020 -0500 - markiewicz@stanford.edu - STY: black +d50c1858564c0b3073fb23c54886a0454cb66afa +# Thu Feb 27 15:08:42 2020 -0800 - code@oscaresteban.es - sty: black +417b8897a116fcded5000e21e2b6ccbe29452a52 +# Thu Jan 2 11:29:05 2020 -0800 - code@oscaresteban.es - sty: black +aaf677a87f64c485f3e305799e4a5dc73b69e5fb +# Sun Dec 29 17:47:51 2019 -0800 - code@oscaresteban.es - sty: black +f763008442d88d8ce00ec266698268389415f8d6 +# Thu Jan 2 11:29:05 2020 -0800 - code@oscaresteban.es - sty: black +b1eccafd4edc8503b02d715f5b5f6f783520fdf9 +# Sun Dec 29 17:47:51 2019 -0800 - code@oscaresteban.es - sty: black +70db90349598cc7f26a4a513779529fba7d0a797 +# Thu Dec 19 09:22:22 2019 -0500 - markiewicz@stanford.edu - STY: Black +6c1d91d71f6f0db0e985bd2adc34206442b0653d +# Thu Dec 19 15:51:11 2019 -0500 - markiewicz@stanford.edu - STY: Black +97bdbd5f48ab242de5288ba4715192a27619a803 +# Fri Nov 15 14:38:10 2019 -0500 - steve@steventilley.com - run black +78fa360f5b785224349b8b85b07e510d2233bb63 +# Fri Nov 15 14:34:03 2019 -0500 - steve@steventilley.com - run black +7f85f43a34de8bff8e634232c939b17cee8e8fc5 +# Thu Nov 14 11:14:51 2019 -0500 - markiewicz@stanford.edu - Merge pull request #3096 from effigies/sty/black +1a869991adc024577536689d557fc748c764f15d +# Thu Nov 14 09:15:20 2019 -0500 - markiewicz@stanford.edu - STY: Black setup.py +9c50b5daa797def5672dd057155b0e2c658853e2 +# Thu Nov 14 09:14:38 2019 -0500 - markiewicz@stanford.edu - STY: Black for tools/ +47194993ae14aceeec436cfb3769def667196668 +# Wed Nov 13 23:41:15 2019 -0500 - markiewicz@stanford.edu - STY: Black +75653feadc6667d5313d83e9c62a5d5819771a9c +# Tue Nov 12 09:43:34 2019 -0500 - markiewicz@stanford.edu - STY: Black files pre-merge +497b44d680eee0892fa59c6aaaae22a17d70a536 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index cfc5007b49..a765cabb95 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -17,7 +17,3 @@ Fixes # . ## List of changes proposed in this PR (pull-request) - -## Acknowledgment - -- [ ] \(Mandatory\) I acknowledge that this contribution will be available under the Apache 2 license. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..61d6e0c09e --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# Dependabot configuration file +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + groups: + actions-infrastructure: + patterns: + - "actions/*" diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml new file mode 100644 index 0000000000..6f32efeaf1 --- /dev/null +++ b/.github/workflows/codespell.yml @@ -0,0 +1,19 @@ +--- +name: Codespell + +on: + push: + branches: [master] + pull_request: + branches: [master] + +jobs: + codespell: + name: Check for spelling errors + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Codespell + uses: codespell-project/actions-codespell@v2 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000000..7934de87a7 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,161 @@ +name: Tox + +on: + push: + branches: [ master, main, 'maint/*' ] + tags: [ '*' ] + pull_request: + branches: [ master, main, 'maint/*' ] + schedule: + # 8am EST / 9am EDT Mondays + - cron: "0 13 * * 1" + +defaults: + run: + shell: bash + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + # Force tox and pytest to use color + FORCE_COLOR: true + + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Install the latest version of uv + uses: astral-sh/setup-uv@v6 + - run: uv build + - run: uvx twine check dist/* + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist/ + + test-package: + runs-on: ubuntu-latest + needs: [build] + strategy: + matrix: + package: ["wheel", "sdist"] + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + - uses: actions/setup-python@v5 + with: + python-version: 3 + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: Update pip + run: pip install --upgrade pip + - name: Install wheel + run: pip install dist/nipype-*.whl + if: matrix.package == 'wheel' + - name: Install sdist + run: pip install dist/nipype-*.tar.gz + if: matrix.package == 'sdist' + - run: python -c 'import nipype; print(nipype.__version__)' + - name: Install test extras + run: pip install nipype[tests] + - name: Run tests + run: pytest --doctest-modules -v --pyargs nipype + + test: + # Check each OS, all supported Python, minimum versions and latest releases + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: ["ubuntu-latest"] + python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] + dependencies: [none, full, pre] + include: + - os: ubuntu-latest + python-version: "3.9" + dependencies: min + exclude: + # Skip some intermediate versions for full tests + - python-version: "3.10" + dependencies: full + - python-version: "3.11" + dependencies: full + # Do not test pre-releases for versions out of SPEC0 + - python-version: "3.9" + dependencies: pre + - python-version: "3.10" + dependencies: pre + + env: + DEPENDS: ${{ matrix.dependencies }} + + steps: + - uses: actions/checkout@v4 + - name: Install the latest version of uv + uses: astral-sh/setup-uv@v6 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Display Python version + run: python -c "import sys; print(sys.version)" + - name: Install tox + run: | + uv tool install tox --with=tox-uv --with=tox-gh-actions + - name: Show tox config + run: tox c + - name: Run tox + run: tox -v --exit-and-dump-after 1200 + - uses: codecov/codecov-action@v5 + with: + token: ${{ secrets.CODECOV_TOKEN }} + if: ${{ always() }} + - name: Upload pytest test results + uses: actions/upload-artifact@v4 + with: + name: pytest-results-${{ matrix.os }}-${{ matrix.python-version }}-${{ matrix.deb-depends }} + path: test-results.xml + if: ${{ always() && matrix.check == 'test' }} + + publish: + runs-on: ubuntu-latest + environment: "Package deployment" + needs: [test, test-package] + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.PYPI_API_TOKEN }} + + checks: + runs-on: 'ubuntu-latest' + continue-on-error: true + strategy: + matrix: + check: ['specs', 'style'] + + steps: + - uses: actions/checkout@v4 + - name: Install the latest version of uv + uses: astral-sh/setup-uv@v6 + - name: Show tox config + run: uvx tox c + - name: Show tox config (this call) + run: uvx tox c -e ${{ matrix.check }} + - name: Run check + run: uvx tox -e ${{ matrix.check }} diff --git a/.github/workflows/tutorials.yml b/.github/workflows/tutorials.yml new file mode 100644 index 0000000000..d920ed435d --- /dev/null +++ b/.github/workflows/tutorials.yml @@ -0,0 +1,76 @@ +name: Test tutorials + +on: + push: + branches: + - "rel/*" + +concurrency: + group: tutorials-${{ github.ref }} + cancel-in-progress: true + +permissions: {} +jobs: + tutorial: + runs-on: ubuntu-latest + env: + BRANCH_NAME: ${{ github.ref_name }} + steps: + - name: Start time + id: start + run: echo start_time=$(date +'%Y-%m-%dT%H:%M:%S%z') >> $GITHUB_OUTPUT + - name: Trigger Nipype tutorial Github Action + run: | + set -x + curl -X POST \ + -H "Authorization: Bearer ${{ secrets.TUTORIAL_ACCESS_TOKEN }}" \ + -H "Accept: application/vnd.github+json" \ + https://api.github.com/repos/miykael/nipype_tutorial/actions/workflows/testing.yml/dispatches \ + -d '{"ref": "master", "inputs": {"nipype_branch": "'${BRANCH_NAME}'"}}' + sleep 10 + - name: Check Action was successfully dispatched + id: dispatched + run: | + START=${{ steps.start.outputs.start_time }} + RUN_ID=$(curl -s -H "Accept: application/vnd.github+json" \ + 'https://api.github.com/repos/miykael/nipype_tutorial/actions/runs?created=%3E'${START}'&per_page=1' \ + | jq -r '.workflow_runs[0].id') + + # fail if not extracted + [[ -n $RUN_ID ]] || exit 1 + echo run_id=$RUN_ID >> $GITHUB_OUTPUT + - name: Check if action completed + timeout-minutes: 120 + run: | + RUN_ID=${{ steps.dispatched.outputs.run_id }} + while : + do + TIMESTAMP=$(date +'%Y-%m-%dT%H:%M:%S%z') + # check status every 5 minutes + STATUS=$(curl -s -H "Accept: application/vnd.github+json" \ + https://api.github.com/repos/miykael/nipype_tutorial/actions/runs/${RUN_ID} \ + | jq -r '.conclusion') + case $STATUS in + success) + echo "[$TIMESTAMP] Tutorial run $RUN_ID completed successfully." + exit 0 + ;; + failure) + echo "[$TIMESTAMP] Tutorial run $RUN_ID failed." + exit 1 + ;; + *) + echo "[$TIMESTAMP] Conclusion ($STATUS) is not yet complete" + sleep 300 + esac + done + - name: Cancel ongoing run if cancelled or failed + if: ${{ failure() || cancelled() }} + run: | + set -x + RUN_ID=${{ steps.dispatched.outputs.run_id }} + echo "Something went wrong, cancelling dispatched run" + curl -s -X POST \ + -H "Accept: application/vnd.github+json" \ + -H "Authorization: Bearer ${{ secrets.TUTORIAL_ACCESS_TOKEN }}" \ + https://api.github.com/repos/miykael/nipype_tutorial/actions/runs/${RUN_ID}/cancel diff --git a/.gitignore b/.gitignore index 4213d07a68..b2556cb084 100644 --- a/.gitignore +++ b/.gitignore @@ -29,3 +29,5 @@ __pycache__/ .ipynb_checkpoints/ .ruby-version .pytest_cache +.vscode/ +venv/ diff --git a/.mailmap b/.mailmap index 4df0aff6e5..35ccbf89d2 100644 --- a/.mailmap +++ b/.mailmap @@ -1,15 +1,17 @@ Abel A. González Orozco Aimi Watanabe Aimi Watanabe stymy -Alejandro Tabas -Alejandro Tabas Alejandro de la Vega Alejandro de la Vega +Alejandro Tabas +Alejandro Tabas Alexander Schaefer -Alexander Schaefer Alexander Schaefer +Alexander Schaefer Alexandre M. Savio Alexandre M. Savio +Andrea Dell'Orco +Andrea Dell'Orco Andrew Floren Andrey Chetverikov Andrey Chetverikov @@ -21,6 +23,8 @@ Ariel Rokem Ariel Rokem Arman Eshaghi Ashely Gillman +Avneet Kaur +Avneet Kaur Basille Pinsard Basille Pinsard Ben Cipollini @@ -35,8 +39,8 @@ Blake Dewey Brendan Moloney Caroline Froehlich Christopher J. Markiewicz -Christopher J. Markiewicz Christopher J. Markiewicz +Christopher J. Markiewicz Christopher John Steele Cindee Madison Colin Buchanan @@ -45,6 +49,8 @@ Colin Buchanan Daniel Brenner Daniel Clark Daniel Geisler +Daniel Geisler <3453485+daniel-ge@users.noreply.github.com> +Daniel Geisler Daniel Ginsburg Daniel McNamee David Ellis @@ -52,82 +58,103 @@ David Ellis David Mordom David Welch Dimitri Papadopoulos Orfanos +Dimitri Papadopoulos Orfanos <3234522+DimitriPapadopoulos@users.noreply.github.com> Dmytro Belevtsoff +Dorian Vogel Dylan M. Nielson Dylan M. Nielson Eduard Ort Elizabeth DuPre +Emmanuelle Gourieux <47973414+manuegrx@users.noreply.github.com> +Eric Condamine +Eric Condamine <37933899+servoz@users.noreply.github.com> Erik Ziegler -Erik Ziegler Erik Ziegler +Erik Ziegler +Fabio Bernardoni +Fabio Bernardoni Feilong Ma Fernando Pérez-García Franz Liem Franz Liem Fred Loney Gael Varoquaux +Gal Kepler +Gal Kepler Gavin Cooper +Ghislain Vaillant +Ghislain Vaillant Gilles de Hollander Gio Piantoni Guillaume Flandin Hans Johnson +Henry Jones Horea Christian Hrvoje Stojic Isaac Schwabacher Jakub Kaczmarzyk James Kent -James Kent Fred Mertz +James Kent +James Kent Janosch Linkersdörfer Jason Wong Jason Wong Jens Kleesiek -Jessica Forbes Jérémy Guillon +Jessica Forbes Joerg Stadler Joerg Stadler Joerg Stadler John A. Lee John A. Lee +Jon Cluce Joke Durnez +Jordi Huguet Josh Warner Junhao WEN Kai Schlamp Katherine Bottenhorn Kesshi Jordan -Kesshi Jordan Kesshi Jordan Kesshi Jordan +Kesshi Jordan Kesshi Jordan Kesshi Jordan Kevin Sitek Kevin Sitek -Sin Kim -Sin Kim +Koen Helwegen Kornelius Podranski +Kristofer Montazeri Krzysztof J. Gorgolewski Krzysztof J. Gorgolewski -Krzysztof J. Gorgolewski -Krzysztof J. Gorgolewski -Krzysztof J. Gorgolewski Krzysztof J. Gorgolewski Krzysztof J. Gorgolewski +Krzysztof J. Gorgolewski +Krzysztof J. Gorgolewski +Krzysztof J. Gorgolewski Kshitij Chawla Leonie Lampe Lukas Snoek Marcel Falkiewicz +Maria de Fatima Dias +Maria de Fatima Dias +Martin Norgaard Martin Perez-Guevara Mathias Goncalves -Mathieu Dubois +Mathias Goncalves Mathieu Dubois +Mathieu Dubois Matteo Mancini Matteo Visconti di Oleggio Castello Matteo Visconti di Oleggio Castello Matthew Cieslak +Maurilio Genovese +Maurilio Genovese <125388969+mauriliogenovese@users.noreply.github.com> Michael Clark Michael Dayan Michael Dayan -Michael Dayan mick-d Michael Dayan +Michael Dayan mick-d Michael Joseph Michael Joseph Michael Philipp Notter @@ -138,17 +165,22 @@ Michael Waskom Miguel Molina-Romero Murat Bilgel Nat Lee +Ole Numssen Oliver Contier Olivia Stanley Oscar Esteban Oscar Esteban -Pablo Polosecki Pablo Polosecki +Pablo Polosecki +Paul Kuntke +Paul Kuntke Paul Sharp Ranjit Khanuja Rastko Ćirić -Rastko Ćirić Rastko Ćirić +Rastko Ćirić +Raunak Jalan +Raunak Jalan <41023976+RaunakJalan@users.noreply.github.com> Ross Markello Russell Poldrack Russell Poldrack @@ -165,11 +197,18 @@ Shoshana Berleant Shoshana Berleant Ubuntu Simon Rothmei Simon Rothmei +Sin Kim +Sin Kim Siqi Liu Steven Giavasis -Steven Giavasis Steven Giavasis +Steven Giavasis Steven Tilley +Sulantha Mathotaarachchi +Sunjae Shim <85246533+sjshim@users.noreply.github.com> +Tim Robert-Fitzgerald +Tom Close +Tom Close Tristan Glatard Victor Férat Victor Férat @@ -178,5 +217,7 @@ Victor Saase Weijie Huang William Triplett Wolfgang Pauli +Wu Jianxiao +Wu Jianxiao Xiangzhen Kong Yaroslav Halchenko diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c429bfa6d9..c1bda308da 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,14 +1,18 @@ # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.0.0 + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml - - id: check-added-large-files -- repo: https://github.com/psf/black - rev: 19.3b0 + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-added-large-files + - repo: https://github.com/psf/black + rev: 24.2.0 hooks: - - id: black + - id: black + - repo: https://github.com/codespell-project/codespell + rev: v2.2.6 + hooks: + - id: codespell diff --git a/.readthedocs.yml b/.readthedocs.yml new file mode 100644 index 0000000000..33b5e91a58 --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,30 @@ +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +# Set the OS, Python version and other tools you might need +build: + os: ubuntu-22.04 + tools: + python: "3.10" + +# Build documentation in the docs/ directory with Sphinx +sphinx: + configuration: doc/conf.py + +# Optionally build your docs in additional formats such as PDF and ePub +formats: + - htmlzip + +# Optional but recommended, declare the Python requirements required +# to build your documentation +# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html +python: + install: + - requirements: doc/requirements.txt + - method: pip + path: . + extra_requirements: + - doc diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 3e4326c5a4..0000000000 --- a/.travis.yml +++ /dev/null @@ -1,86 +0,0 @@ -dist: xenial -sudo: true - -language: python -# our build matrix -python: -- 3.5 -- 3.6 -- 3.7 - -# NOTE: Any changes to the matrix section should be duplicated below for -# Python 3.4 -env: - global: - - EXTRA_WHEELS="https://5cf40426d9f06eb7461d-6fe47d9331aba7cd62fc36c7196769e4.ssl.cf2.rackcdn.com/" - - PRE_WHEELS="https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf2.rackcdn.com/" - - EXTRA_PIP_FLAGS="--find-links=$EXTRA_WHEELS" - - CHECK_TYPE=test - matrix: - - INSTALL_DEB_DEPENDECIES=true - NIPYPE_EXTRAS="doc,tests,nipy,profiler" - CI_SKIP_TEST=1 - - INSTALL_DEB_DEPENDECIES=false - NIPYPE_EXTRAS="doc,tests,profiler" - CI_SKIP_TEST=1 - - INSTALL_DEB_DEPENDECIES=true - NIPYPE_EXTRAS="doc,tests,nipy,profiler,duecredit,ssh" - CI_SKIP_TEST=1 - - INSTALL_DEB_DEPENDECIES=true - NIPYPE_EXTRAS="doc,tests,nipy,profiler" - EXTRA_PIP_FLAGS="--pre $EXTRA_PIP_FLAGS --find-links $PRE_WHEELS --upgrade" - CI_SKIP_TEST=1 - -matrix: - include: - - python: 3.7 - env: - - NIPYPE_EXTRAS=dev - CHECK_TYPE=specs - -addons: - apt: - packages: - - xvfb - - fusefat - - graphviz - -cache: - directories: - - ${HOME}/.cache - -before_install: -- if $INSTALL_DEB_DEPENDECIES; then sudo rm -rf /dev/shm; sudo ln -s /run/shm /dev/shm; fi -- travis_retry bash <(wget -q -O- http://neuro.debian.net/_files/neurodebian-travis.sh); -- if $INSTALL_DEB_DEPENDECIES; then - travis_retry sudo apt-get -y update && - travis_retry sudo apt-get install -y -qq fsl afni elastix fsl-atlases; - fi; -- if $INSTALL_DEB_DEPENDECIES; then - source /etc/fsl/fsl.sh; - source /etc/afni/afni.sh; - export FSLOUTPUTTYPE=NIFTI_GZ; - fi; - -- travis_retry pip install $EXTRA_PIP_FLAGS -r requirements.txt -- travis_retry pip install grabbit==0.2.6 -- travis_retry pip install -e git+https://github.com/bids-standard/pybids.git@0.7.0#egg=pybids - -install: -- travis_retry pip install $EXTRA_PIP_FLAGS -e .[$NIPYPE_EXTRAS] -- travis_retry pip install pytest-xdist - -script: -- | - if [ "$CHECK_TYPE" = "test" ]; then - py.test -v --cov nipype --cov-config .coveragerc --cov-report xml:cov.xml -c nipype/pytest.ini --doctest-modules nipype -n auto - fi -- | - if [ "$CHECK_TYPE" = "specs" ]; then - make specs - git add nipype - test "$( git diff --cached | wc -l )" -eq 0 || ( git diff --cached && false ) - fi - -after_script: -- codecov --file cov.xml --flags unittests -e TRAVIS_JOB_NUMBER diff --git a/.wci.yml b/.wci.yml new file mode 100644 index 0000000000..2adbae9fcc --- /dev/null +++ b/.wci.yml @@ -0,0 +1,30 @@ +# Project available at https://github.com/nipy/nipype + +name: nipype + +headline: "Neuroimaging in Python: Pipelines and Interfaces" + +description: | + Nipype, an open-source, community-developed initiative under the umbrella of NiPy, is a Python project that + provides a uniform interface to existing neuroimaging software and facilitates interaction between these + packages within a single workflow. Nipype provides an environment that encourages interactive exploration of + algorithms from different packages (e.g., SPM, FSL, FreeSurfer, AFNI, Slicer, ANTS), eases the design of + workflows within and between packages, and reduces the learning curve necessary to use different packages. + +language: Python3 + +documentation: + general: https://nipype.readthedocs.io/en/latest/ + installation: https://nipype.readthedocs.io/en/latest/users/install.html + tutorial: https://miykael.github.io/nipype_tutorial/ + +execution_environment: + resource_managers: + - SLURM + - Condor + - DAGMan + - LSF + - OAR + - PBS + - SGE + - Soma-workflow diff --git a/.zenodo.json b/.zenodo.json index 8532823a5f..3e2c2be6f6 100644 --- a/.zenodo.json +++ b/.zenodo.json @@ -11,19 +11,12 @@ "orcid": "0000-0002-6533-164X" }, { - "affiliation": "University of Iowa", - "name": "Johnson, Hans", - "orcid": "0000-0001-9513-2660" - }, - { - "affiliation": "Independent", - "name": "Ziegler, Erik", - "orcid": "0000-0003-1857-8129" + "name": "Burns, Christopher" }, { - "affiliation": "Klinikum rechts der Isar, TUM. ACPySS", - "name": "Manh\u00e3es-Savio, Alexandre", - "orcid": "0000-0002-6608-6885" + "affiliation": "MIT", + "name": "Goncalves, Mathias", + "orcid": "0000-0002-7252-7771" }, { "affiliation": "MIT", @@ -31,7 +24,12 @@ "orcid": "0000-0001-8282-2988" }, { - "name": "Burns, Christopher" + "affiliation": "Independent", + "name": "Ziegler, Erik", + "orcid": "0000-0003-1857-8129" + }, + { + "name": "Berleant, Shoshana" }, { "affiliation": "The University of Iowa", @@ -39,8 +37,14 @@ "orcid": "0000-0002-3718-6836" }, { - "name": "Hamalainen, Carlo", - "orcid": "0000-0001-7655-3830" + "name": "Pinsard, Basile" + }, + { + "name": "Madison, Cindee" + }, + { + "affiliation": "Department of Psychology, Stanford University", + "name": "Waskom, Michael" }, { "affiliation": "The Laboratory for Investigative Neurophysiology (The LINE), Department of Radiology and Department of Clinical Neurosciences, Lausanne, Switzerland; Center for Biomedical Imaging (CIBM), Lausanne, Switzerland", @@ -48,21 +52,24 @@ "orcid": "0000-0002-5866-047X" }, { - "name": "Yvernault, Benjamin" + "affiliation": "Developer", + "name": "Clark, Daniel", + "orcid": "0000-0002-8121-8954" }, { - "affiliation": "Florida International University", - "name": "Salo, Taylor", - "orcid": "0000-0001-9813-3167" + "affiliation": "Klinikum rechts der Isar, TUM. ACPySS", + "name": "Manhães-Savio, Alexandre", + "orcid": "0000-0002-6608-6885" }, { - "affiliation": "Department of Psychology, Stanford University", - "name": "Waskom, Michael" + "affiliation": "Dartmouth College: Hanover, NH, United States", + "name": "Halchenko, Yaroslav O.", + "orcid": "0000-0003-3456-2493" }, { - "affiliation": "MIT", - "name": "Goncalves, Mathias", - "orcid": "0000-0002-7252-7771" + "affiliation": "UC Berkeley", + "name": "Clark, Dav", + "orcid": "0000-0002-3982-4416" }, { "affiliation": "University of California, San Francisco", @@ -70,33 +77,41 @@ "orcid": "0000-0001-6313-0580" }, { - "affiliation": "Shattuck Lab, UCLA Brain Mapping Center", - "name": "Wong, Jason" + "affiliation": "Mayo Clinic, Neurology, Rochester, MN, USA", + "name": "Dayan, Michael", + "orcid": "0000-0002-2666-0969" }, { - "affiliation": "Department of Electrical and Computer Engineering, Johns Hopkins University", - "name": "Dewey, Blake E", - "orcid": "0000-0003-4554-5058" + "affiliation": "Department of Psychology, Stanford University", + "name": "Norgaard, Martin", + "orcid": "0000-0003-2131-5688" }, { - "name": "Madison, Cindee" + "name": "Loney, Fred" }, { - "affiliation": "Concordia University", - "name": "Benderoff, Erin" + "affiliation": "CEA", + "name": "Papadopoulos Orfanos, Dimitri", + "orcid": "0000-0002-1242-8990" }, { - "affiliation": "Developer", - "name": "Clark, Daniel", - "orcid": "0000-0002-8121-8954" + "affiliation": "Florida International University", + "name": "Salo, Taylor", + "orcid": "0000-0001-9813-3167" }, { - "name": "Loney, Fred" + "affiliation": "University of Iowa", + "name": "Johnson, Hans", + "orcid": "0000-0001-9513-2660" }, { - "affiliation": "UC Berkeley", - "name": "Clark, Dav", - "orcid": "0000-0002-3982-4416" + "affiliation": "Department of Electrical and Computer Engineering, Johns Hopkins University", + "name": "Dewey, Blake E", + "orcid": "0000-0003-4554-5058" + }, + { + "affiliation": "Molecular Imaging Research Center, CEA, France", + "name": "Bougacha, Salma" }, { "affiliation": "UC Berkeley - UCSF Graduate Program in Bioengineering", @@ -104,47 +119,39 @@ "orcid": "0000-0003-3554-043X" }, { - "affiliation": "The Centre for Addiction and Mental Health", - "name": "Joseph, Michael", - "orcid": "0000-0002-0068-230X" - }, - { - "affiliation": "National Institute of Mental Health", - "name": "Nielson, Dylan M.", - "orcid": "0000-0003-4613-6643" - }, - { - "affiliation": "Mayo Clinic, Neurology, Rochester, MN, USA", - "name": "Dayan, Michael", - "orcid": "0000-0002-2666-0969" + "name": "Yvernault, Benjamin" }, { - "name": "Modat, Marc" + "affiliation": "Institute for Biomedical Engineering, ETH and University of Zurich", + "name": "Christian, Horea", + "orcid": "0000-0001-7037-2449" }, { - "affiliation": "CNRS LTCI, Telecom ParisTech, Universit\u00e9 Paris-Saclay", - "name": "Gramfort, Alexandre", - "orcid": "0000-0001-9791-4404" + "name": "Hamalainen, Carlo", + "orcid": "0000-0001-7655-3830" }, { - "affiliation": "Molecular Imaging Research Center, CEA, France", - "name": "Bougacha, Salma" + "affiliation": "Stanford University", + "name": "Ćirić , Rastko", + "orcid": "0000-0001-6347-7939" }, { - "name": "Pinsard, Basile" + "name": "Dubois, Mathieu" }, { - "name": "Berleant, Shoshana" + "affiliation": "The Centre for Addiction and Mental Health", + "name": "Joseph, Michael", + "orcid": "0000-0002-0068-230X" }, { - "affiliation": "Institute for Biomedical Engineering, ETH and University of Zurich", - "name": "Christian, Horea", - "orcid": "0000-0001-7037-2449" + "affiliation": "UC San Diego", + "name": "Cipollini, Ben", + "orcid": "0000-0002-7782-0790" }, { - "affiliation": "The University of Washington eScience Institute", - "name": "Rokem, Ariel", - "orcid": "0000-0003-0679-1985" + "affiliation": "Holland Bloorview Kids Rehabilitation Hospital", + "name": "Tilley II, Steven", + "orcid": "0000-0003-4853-5082" }, { "affiliation": "Dartmouth College", @@ -152,9 +159,13 @@ "orcid": "0000-0001-7931-5272" }, { - "affiliation": "Dartmouth College: Hanover, NH, United States", - "name": "Halchenko, Yaroslav O.", - "orcid": "0000-0003-3456-2493" + "affiliation": "University of Texas at Austin", + "name": "De La Vega, Alejandro", + "orcid": "0000-0001-9062-3778" + }, + { + "affiliation": "Shattuck Lab, UCLA Brain Mapping Center", + "name": "Wong, Jason" }, { "affiliation": "MIT", @@ -162,50 +173,33 @@ "orcid": "0000-0002-5544-7577" }, { - "affiliation": "INRIA", - "name": "Varoquaux, Gael", - "orcid": "0000-0003-1076-5122" - }, - { - "affiliation": "Stanford University", - "name": "\u0106iri\u0107 , Rastko", - "orcid": "0000-0001-6347-7939" - }, - { - "name": "Moloney, Brendan" - }, - { - "affiliation": "Montreal Neurological Institute and Hospital", - "name": "DuPre, Elizabeth", - "orcid": "0000-0003-1358-196X" - }, - { - "affiliation": "Indiana University, IN, USA", - "name": "Koudoro, Serge" + "affiliation": "Research Group Neuroanatomy and Connectivity, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig, Germany", + "name": "Huntenburg, Julia M.", + "orcid": "0000-0003-0579-9811" }, { "affiliation": "National Institutes of Health", "name": "Clark, Michael G. " }, { - "affiliation": "UC San Diego", - "name": "Cipollini, Ben", - "orcid": "0000-0002-7782-0790" + "affiliation": "Neuroscience Program, University of Iowa", + "name": "Kent, James D.", + "orcid": "0000-0002-4892-2659" }, { - "affiliation": "Athena EPI, Inria Sophia-Antipolis", - "name": "Wassermann, Demian", - "orcid": "0000-0001-5194-6056" + "affiliation": "Concordia University", + "name": "Benderoff, Erin" }, { - "affiliation": "ARAMIS LAB, Brain and Spine Institute (ICM), Paris, France.", - "name": "Guillon, Je\u0301re\u0301my", - "orcid": "0000-0002-2672-7510" + "name": "Erickson, Drew" }, { - "affiliation": "Montreal Neurological Institute and Hospital", - "name": "Markello, Ross", - "orcid": "0000-0003-1057-1336" + "affiliation": "CIBIT, UC", + "name": "Dias, Maria de Fatima", + "orcid": "0000-0001-8878-1750" + }, + { + "name": "Moloney, Brendan" }, { "affiliation": "Otto-von-Guericke-University Magdeburg, Germany", @@ -213,20 +207,30 @@ "orcid": "0000-0001-6398-6370" }, { - "name": "Buchanan, Colin" + "affiliation": "Child Mind Institute", + "name": "Giavasis, Steven" + }, + { + "affiliation": "SRI International", + "name": "Nichols, B. Nolan", + "orcid": "0000-0003-1099-3328" }, { "name": "Tungaraza, Rosalia" }, { - "affiliation": "Australian eHealth Research Centre, Commonwealth Scientific and Industrial Research Organisation; University of Queensland", - "name": "Gillman, Ashley", - "orcid": "0000-0001-9130-1092" + "affiliation": "Charitè Universitätsmedizin Berlin, Germany", + "name": "Dell'Orco, Andrea", + "orcid": "0000-0002-3964-8360" }, { - "affiliation": "California Institute of Technology", - "name": "Pauli, Wolfgang M.", - "orcid": "0000-0002-0966-0254" + "affiliation": "Child Mind Institute", + "name": "Frohlich, Caroline" + }, + { + "affiliation": "Athena EPI, Inria Sophia-Antipolis", + "name": "Wassermann, Demian", + "orcid": "0000-0001-5194-6056" }, { "affiliation": "Vrije Universiteit, Amsterdam", @@ -234,19 +238,21 @@ "orcid": "0000-0003-1988-5091" }, { - "affiliation": "Nathan s Kline institute for psychiatric research", - "name": "Sikka, Sharad" + "affiliation": "Sagol School of Neuroscience, Tel Aviv University", + "name": "Kepler, Gal", + "orcid": "0000-0002-5655-9423" }, { - "name": "Forbes, Jessica" + "affiliation": "Indiana University, IN, USA", + "name": "Koudoro, Serge" }, { - "name": "Mordom, David" + "affiliation": "University College London", + "name": "Eshaghi, Arman", + "orcid": "0000-0002-6652-3512" }, { - "affiliation": "Duke University", - "name": "Iqbal, Shariq", - "orcid": "0000-0003-2766-8425" + "name": "Millman, Jarrod" }, { "affiliation": "University College London", @@ -254,441 +260,585 @@ "orcid": "0000-0001-7194-4568" }, { - "affiliation": "University College London", - "name": "Malone, Ian B.", - "orcid": "0000-0001-7512-7856" + "affiliation": "University of Sydney", + "name": "Close, Thomas", + "orcid": "0000-0002-4160-2134" }, { - "name": "Dubois, Mathieu" + "affiliation": "National Institute of Mental Health", + "name": "Nielson, Dylan M.", + "orcid": "0000-0003-4613-6643" }, { - "name": "Schwartz, Yannick" + "affiliation": "INRIA", + "name": "Varoquaux, Gael", + "orcid": "0000-0003-1076-5122" + }, + { + "affiliation": "Charite Universitatsmedizin Berlin, Germany", + "name": "Waller, Lea", + "orcid": "0000-0002-3239-6957" + }, + { + "name": "Watanabe, Aimi" + }, + { + "name": "Mordom, David" }, { "affiliation": "Child Mind Institute", - "name": "Frohlich, Caroline" + "name": "Cluce, Jon", + "orcid": "0000-0001-7590-5806" }, { - "affiliation": "Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig, Germany.", - "name": "Tabas, Alejandro", - "orcid": "0000-0002-8643-1543" + "affiliation": "ARAMIS LAB, Brain and Spine Institute (ICM), Paris, France.", + "name": "Guillon, Jérémy", + "orcid": "0000-0002-2672-7510" }, { - "affiliation": "University of Iowa", - "name": "Welch, David" + "affiliation": "Penn Statistics in Imaging and Visualization Endeavor, University of Pennsylvania", + "name": "Robert-Fitzgerald, Timothy", + "orcid": "0000-0001-8303-8001" }, { - "affiliation": "University of Washington", - "name": "Richie-Halford, Adam", - "orcid": "0000-0001-9276-9084" + "affiliation": "Donders Institute for Brain, Cognition and Behavior, Center for Cognitive Neuroimaging", + "name": "Chetverikov, Andrey", + "orcid": "0000-0003-2767-6310" }, { - "affiliation": "Holland Bloorview Kids Rehabilitation Hospital", - "name": "Tilley II, Steven", - "orcid": "0000-0003-4853-5082" + "affiliation": "The University of Washington eScience Institute", + "name": "Rokem, Ariel", + "orcid": "0000-0003-0679-1985" }, { - "name": "Watanabe, Aimi" + "affiliation": "Washington University in St Louis", + "name": "Acland, Benjamin", + "orcid": "0000-0001-6392-6634" }, { - "affiliation": "SRI International", - "name": "Nichols, B. Nolan", - "orcid": "0000-0003-1099-3328" + "affiliation": "Division of Psychological and Social Medicine and Developmental Neuroscience, Faculty of Medicine, Technische Universität Dresden, Dresden, Germany", + "name": "Bernardoni, Fabio", + "orcid": "0000-0002-5112-405X" }, { - "affiliation": "Research Group Neuroanatomy and Connectivity, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig, Germany", - "name": "Huntenburg, Julia M.", - "orcid": "0000-0003-0579-9811" + "name": "Forbes, Jessica" }, { - "affiliation": "University College London", - "name": "Eshaghi, Arman", - "orcid": "0000-0002-6652-3512" + "affiliation": "Montreal Neurological Institute and Hospital", + "name": "Markello, Ross", + "orcid": "0000-0003-1057-1336" }, { - "name": "Ginsburg, Daniel" + "affiliation": "Australian eHealth Research Centre, Commonwealth Scientific and Industrial Research Organisation; University of Queensland", + "name": "Gillman, Ashley", + "orcid": "0000-0001-9130-1092" }, { - "affiliation": "National University Singapore", - "name": "Schaefer, Alexander", - "orcid": "0000-0001-6488-4739" + "affiliation": "State Key Laboratory of Cognitive Neuroscience and Learning & IDG/McGovern Institute for Brain Research, Beijing Normal University, Beijing, China; Max Planck Institute for Psycholinguistics, Nijmegen, the Netherlands", + "name": "Kong, Xiang-Zhen", + "orcid": "0000-0002-0805-1350" }, { - "affiliation": "Florida International University", - "name": "Bottenhorn, Katherine", - "orcid": "0000-0002-7796-8795" + "affiliation": "Division of Psychological and Social Medicine and Developmental Neuroscience, Faculty of Medicine, Technische Universität Dresden, Dresden, Germany", + "name": "Geisler, Daniel", + "orcid": "0000-0003-2076-5329" }, { - "name": "Cumba, Chad" + "name": "Salvatore, John" }, { - "affiliation": "Washington University in St Louis", - "name": "Acland, Benjamin", - "orcid": "0000-0001-6392-6634" + "affiliation": "Medical College of Wisconsin", + "name": "Espana, Lezlie", + "orcid": "0000-0002-6466-4653" }, { - "name": "Heinsfeld, Anibal S\u00f3lon", - "orcid": "0000-0002-2050-0614" + "affiliation": "CNRS LTCI, Telecom ParisTech, Université Paris-Saclay", + "name": "Gramfort, Alexandre", + "orcid": "0000-0001-9791-4404" }, { - "affiliation": "Harvard University - Psychology", - "name": "Kastman, Erik", - "orcid": "0000-0001-7221-9042" + "affiliation": "Department of Psychology, University of Bielefeld, Bielefeld, Germany.", + "name": "Doll, Anna", + "orcid": "0000-0002-0799-0831" }, { - "affiliation": "Neuroscience Program, University of Iowa", - "name": "Kent, James D.", - "orcid": "0000-0002-4892-2659" + "name": "Buchanan, Colin" + }, + { + "affiliation": "Montreal Neurological Institute and Hospital", + "name": "DuPre, Elizabeth", + "orcid": "0000-0003-1358-196X" + }, + { + "affiliation": "The University of Sydney", + "name": "Liu, Siqi" + }, + { + "affiliation": "National University Singapore", + "name": "Schaefer, Alexander", + "orcid": "0000-0001-6488-4739" }, { "affiliation": "UniversityHospital Heidelberg, Germany", "name": "Kleesiek, Jens" }, + { + "affiliation": "Department of Neurology, BG-University Hospital Bergmannsheil Bochum, Germany", + "name": "Butry, Lionel" + }, + { + "affiliation": "Nathan s Kline institute for psychiatric research", + "name": "Sikka, Sharad" + }, + { + "name": "Schwartz, Yannick" + }, { "affiliation": "The University of Iowa", "name": "Ghayoor, Ali", "orcid": "0000-0002-8858-1254" }, { - "name": "Erickson, Drew" + "affiliation": "ARAMIS Lab, Paris Brain Institute", + "name": "Vaillant, Ghislain", + "orcid": "0000-0003-0267-3033" }, { - "affiliation": "Child Mind Institute", - "name": "Giavasis, Steven" + "affiliation": "NIMH IRP", + "name": "Lee, John A.", + "orcid": "0000-0001-5884-4247" }, { - "affiliation": "University of Texas at Austin", - "name": "De La Vega, Alejandro", - "orcid": "0000-0001-9062-3778" + "name": "Mattfeld, Aaron" + }, + { + "affiliation": "University of Washington", + "name": "Richie-Halford, Adam", + "orcid": "0000-0001-9276-9084" }, { "affiliation": "University of Zurich", "name": "Liem, Franz", "orcid": "0000-0003-0646-4810" }, - { - "name": "K\u00fcttner, Ren\u00e9" - }, { "affiliation": "Neurospin/Unicog/Inserm/CEA", "name": "Perez-Guevara, Martin Felipe", "orcid": "0000-0003-4497-861X" }, { - "affiliation": "NIMH IRP", - "name": "Lee, John A.", - "orcid": "0000-0001-5884-4247" + "name": "Heinsfeld, Anibal Sólon", + "orcid": "0000-0002-2050-0614" }, { - "name": "Millman, Jarrod" + "name": "Haselgrove, Christian" }, { - "name": "Lai, Jeff" + "affiliation": "Department of Psychology, Stanford University; Parietal, INRIA", + "name": "Durnez, Joke", + "orcid": "0000-0001-9030-2202" }, { - "name": "Zhou, Dale" + "affiliation": "MPI CBS Leipzig, Germany", + "name": "Lampe, Leonie" }, { - "name": "Haselgrove, Christian" + "name": "Poldrack, Russell" }, { - "affiliation": "NIMH, Scientific and Statistical Computing Core", - "name": "Glen, Daniel", - "orcid": "0000-0001-8456-5647" + "affiliation": "1 McGill Centre for Integrative Neuroscience (MCIN), Ludmer Centre for Neuroinformatics and Mental Health, Montreal Neurological Institute (MNI), McGill University, Montréal, 3801 University Street, WB-208, H3A 2B4, Québec, Canada. 2 University of Lyon, CNRS, INSERM, CREATIS., Villeurbanne, 7, avenue Jean Capelle, 69621, France.", + "name": "Glatard, Tristan", + "orcid": "0000-0003-2620-5883" }, { - "affiliation": "Department of Psychology, University of Bielefeld, Bielefeld, Germany.", - "name": "Doll, Anna", - "orcid": "0000-0002-0799-0831" + "affiliation": "Sagol School of Neuroscience, Tel Aviv University", + "name": "Baratz, Zvi", + "orcid": "0000-0001-7159-1387" }, { - "name": "Renfro, Mandy" + "affiliation": "Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig, Germany.", + "name": "Tabas, Alejandro", + "orcid": "0000-0002-8643-1543" + }, + { + "name": "Cumba, Chad" + }, + { + "affiliation": "University College London", + "name": "Pérez-García, Fernando", + "orcid": "0000-0001-9090-3024" + }, + { + "affiliation": "Azienda Ospedaliero-Universitaria di Modena", + "name": "Genovese, Maurilio", + "orcid": "0000-0002-8154-8224" + }, + { + "name": "Blair, Ross" + }, + { + "affiliation": "Duke University", + "name": "Iqbal, Shariq", + "orcid": "0000-0003-2766-8425" + }, + { + "affiliation": "University of Iowa", + "name": "Welch, David" + }, + { + "affiliation": "CNRS, UMS3552 IRMaGe", + "name": "Condamine, Eric", + "orcid": "0000-0002-9533-3769" + }, + { + "affiliation": "Max Planck Institute for Human Cognitive and Brain Sciences", + "name": "Contier, Oliver", + "orcid": "0000-0002-2983-4709" + }, + { + "affiliation": "Department of Psychology, Stanford University", + "name": "Triplett, William", + "orcid": "0000-0002-9546-1306" + }, + { + "affiliation": "Child Mind Institute", + "name": "Craddock, R. Cameron", + "orcid": "0000-0002-4950-1303" }, { "name": "Correa, Carlos" }, { - "affiliation": "The University of Sydney", - "name": "Liu, Siqi" + "affiliation": "Leibniz Institute for Neurobiology", + "name": "Stadler, Jörg", + "orcid": "0000-0003-4313-129X" }, { - "affiliation": "MPI CBS Leipzig, Germany", - "name": "Lampe, Leonie" + "affiliation": "Mayo Clinic", + "name": "Warner, Joshua", + "orcid": "0000-0003-3579-4835" }, { - "affiliation": "State Key Laboratory of Cognitive Neuroscience and Learning & IDG/McGovern Institute for Brain Research, Beijing Normal University, Beijing, China; Max Planck Institute for Psycholinguistics, Nijmegen, the Netherlands", - "name": "Kong, Xiang-Zhen", - "orcid": "0000-0002-0805-1350" + "affiliation": "Yale University; New Haven, CT, United States", + "name": "Sisk, Lucinda M.", + "orcid": "0000-0003-4900-9770" }, { - "name": "Hallquist, Michael" + "name": "Falkiewicz, Marcel" + }, + { + "affiliation": "University of Illinois Urbana Champaign", + "name": "Sharp, Paul" + }, + { + "name": "Rothmei, Simon" }, { "affiliation": "Korea Advanced Institute of Science and Technology", "name": "Kim, Sin", "orcid": "0000-0003-4652-3758" }, + { + "name": "Weinstein, Alejandro" + }, { "affiliation": "University of Pennsylvania", "name": "Kahn, Ari E.", "orcid": "0000-0002-2127-0507" }, { - "affiliation": "1 McGill Centre for Integrative Neuroscience (MCIN), Ludmer Centre for Neuroinformatics and Mental Health, Montreal Neurological Institute (MNI), McGill University, Montr\u00e9al, 3801 University Street, WB-208, H3A 2B4, Qu\u00e9bec, Canada. 2 University of Lyon, CNRS, INSERM, CREATIS., Villeurbanne, 7, avenue Jean Capelle, 69621, France.", - "name": "Glatard, Tristan", - "orcid": "0000-0003-2620-5883" + "affiliation": "Harvard University - Psychology", + "name": "Kastman, Erik", + "orcid": "0000-0001-7221-9042" }, { - "affiliation": "Department of Psychology, Stanford University", - "name": "Triplett, William", - "orcid": "0000-0002-9546-1306" + "affiliation": "Florida International University", + "name": "Bottenhorn, Katherine", + "orcid": "0000-0002-7796-8795" }, { - "affiliation": "INRIA-Saclay, Team Parietal", - "name": "Chawla, Kshitij", - "orcid": "0000-0002-7517-6321" + "affiliation": "GIGA Institute", + "name": "Grignard, Martin", + "orcid": "0000-0001-5549-1861" }, { - "name": "Salvatore, John" + "affiliation": "Boston University", + "name": "Perkins, L. Nathan" }, { - "affiliation": "University College London", - "name": "P\u00e9rez-Garc\u00eda, Fernando", - "orcid": "0000-0001-9090-3024" + "affiliation": "Lund University", + "name": "Anijärv, Toomas Erik", + "orcid": "0000-0002-3650-4230" }, { - "affiliation": "Dartmouth College", - "name": "Ma, Feilong", - "orcid": "0000-0002-6838-3971" + "name": "Zhou, Dale" + }, + { + "name": "Bielievtsov, Dmytro", + "orcid": "0000-0003-3846-7696" + }, + { + "affiliation": "University of Newcastle, Australia", + "name": "Cooper, Gavin", + "orcid": "0000-0002-7186-5293" + }, + { + "affiliation": "Max Planck UCL Centre for Computational Psychiatry and Ageing Research, University College London", + "name": "Stojic, Hrvoje", + "orcid": "0000-0002-9699-9052" + }, + { + "name": "Hui Qian, Tan" + }, + { + "affiliation": "German Institute for International Educational Research", + "name": "Linkersdörfer, Janosch", + "orcid": "0000-0002-1577-1233" + }, + { + "name": "Renfro, Mandy" }, { - "name": "Park, Anne" + "name": "Hinds, Oliver" }, { - "affiliation": "Child Mind Institute", - "name": "Craddock, R. Cameron", - "orcid": "0000-0002-4950-1303" + "affiliation": "Dept of Medical Biophysics, Univeristy of Western Ontario", + "name": "Stanley, Olivia" }, { - "name": "Hinds, Oliver" + "affiliation": "Flywheel.io, Minneapolis, MN, USA.", + "name": "Velasco, Pablo", + "orcid": "0000-0002-5749-6049" }, { - "name": "Poldrack, Russell" + "name": "Küttner, René" }, { - "affiliation": "Boston University", - "name": "Perkins, L. Nathan" + "affiliation": "California Institute of Technology", + "name": "Pauli, Wolfgang M.", + "orcid": "0000-0002-0966-0254" }, { - "affiliation": "Max Planck UCL Centre for Computational Psychiatry and Ageing Research, University College London", - "name": "Stojic, Hrvoje", - "orcid": "0000-0002-9699-9052" + "affiliation": "Research Centre Juelich", + "name": "Wu, Jianxiao", + "orcid": "0000-0002-4866-272X" }, { - "affiliation": "Donders Institute for Brain, Cognition and Behavior, Center for Cognitive Neuroimaging", - "name": "Chetverikov, Andrey", - "orcid": "0000-0003-2767-6310" + "affiliation": "Weill Cornell Medicine", + "name": "Xie, Xihe", + "orcid": "0000-0001-6595-2473" }, { - "name": "Inati, Souheil" + "affiliation": "NIMH, Scientific and Statistical Computing Core", + "name": "Glen, Daniel", + "orcid": "0000-0001-8456-5647" }, { - "affiliation": "GIGA Institute", - "name": "Grignard, Martin", - "orcid": "0000-0001-5549-1861" + "affiliation": "Florida International University", + "name": "Kimbler, Adam", + "orcid": "0000-0001-5885-9596" }, { - "affiliation": "University of Amsterdam", - "name": "Snoek, Lukas", - "orcid": "0000-0001-8972-204X" + "affiliation": "University of Pittsburgh", + "name": "Meyers, Benjamin", + "orcid": "0000-0001-9137-4363" }, { - "affiliation": "Yale University; New Haven, CT, United States", - "name": "Sisk, Lucinda M.", - "orcid": "0000-0003-4900-9770" + "name": "Tarbert, Claire" }, { - "affiliation": "TIB \u2013 Leibniz Information Centre for Science and Technology and University Library, Hannover, Germany", - "name": "Leinweber, Katrin", - "orcid": "0000-0001-5135-5758" + "name": "Ginsburg, Daniel" }, { - "affiliation": "University of Pennsylvania", - "name": "Junhao WEN", - "orcid": "0000-0003-2077-3070" + "name": "Haehn, Daniel" }, { - "name": "Urchs, Sebastian" + "affiliation": "Max Planck Research Group for Neuroanatomy & Connectivity, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig, Germany", + "name": "Margulies, Daniel S.", + "orcid": "0000-0002-8880-9204" }, { - "name": "Blair, Ross" + "affiliation": "Dartmouth College", + "name": "Ma, Feilong", + "orcid": "0000-0002-6838-3971" }, { - "name": "Matsubara, K" + "affiliation": "University College London", + "name": "Malone, Ian B.", + "orcid": "0000-0001-7512-7856" }, { - "affiliation": "The University of Texas at Austin", - "name": "Floren, Andrew", - "orcid": "0000-0003-3618-2056" + "affiliation": "University of Amsterdam", + "name": "Snoek, Lukas", + "orcid": "0000-0001-8972-204X" }, { - "name": "Mattfeld, Aaron" + "name": "Brett, Matthew" }, { - "affiliation": "Institute of Neuroinformatics, ETH/University of Zurich", - "name": "Gerhard, Stephan", - "orcid": "0000-0003-4454-6171" + "affiliation": "Department of Neuropsychiatry, University of Pennsylvania", + "name": "Cieslak, Matthew", + "orcid": "0000-0002-1931-4734" }, { - "affiliation": "Leibniz Institute for Neurobiology", - "name": "Stadler, J\u00f6rg", - "orcid": "0000-0003-4313-129X" + "name": "Hallquist, Michael" }, { - "affiliation": "University of Newcastle, Australia", - "name": "Cooper, Gavin", - "orcid": "0000-0002-7186-5293" + "affiliation": "Technical University Munich", + "name": "Molina-Romero, Miguel", + "orcid": "0000-0001-8054-0426" }, { - "name": "Haehn, Daniel" + "affiliation": "National Institute on Aging, Baltimore, MD, USA", + "name": "Bilgel, Murat", + "orcid": "0000-0001-5042-7422" }, { - "affiliation": "Duke University", - "name": "Broderick, William", - "orcid": "0000-0002-8999-9003" + "name": "Lee, Nat", + "orcid": "0000-0001-9308-9988" }, { - "affiliation": "University of Helsinki", - "name": "Andberg, Sami Kristian", - "orcid": "0000-0002-5650-3964" + "affiliation": "Insitiute and Polyclinc for Diagnostic and Interventional Neuroradiology, University Hospital Carl Gustav Carus, Dresden, Germany", + "name": "Kuntke, Paul", + "orcid": "0000-0003-1838-2230" }, { - "name": "Noel, Maxime" + "name": "Jalan, Raunak" }, { - "affiliation": "Department of Neuropsychiatry, University of Pennsylvania", - "name": "Cieslak, Matthew", - "orcid": "0000-0002-1931-4734" + "name": "Inati, Souheil" }, { - "affiliation": "Department of Psychology, Stanford University; Parietal, INRIA", - "name": "Durnez, Joke", - "orcid": "0000-0001-9030-2202" + "affiliation": "Institute of Neuroinformatics, ETH/University of Zurich", + "name": "Gerhard, Stephan", + "orcid": "0000-0003-4454-6171" }, { - "affiliation": "CNRS, UMS3552 IRMaGe", - "name": "Condamine, Eric", - "orcid": "0000-0002-9533-3769" + "affiliation": "Enigma Biomedical Group", + "name": "Mathotaarachchi, Sulantha" }, { - "affiliation": "CEA", - "name": "Papadopoulos Orfanos, Dimitri", - "orcid": "0000-0002-1242-8990" + "name": "Saase, Victor" }, { - "affiliation": "Technische Universit\u00e4t Dresden, Faculty of Medicine, Department of Child and Adolescent Psychiatry", - "name": "Geisler, Daniel", - "orcid": "0000-0003-2076-5329" + "affiliation": "Washington University in St Louis", + "name": "Van, Andrew", + "orcid": "0000-0002-8787-0943" }, { - "affiliation": "University of Pittsburgh", - "name": "Meyers, Benjamin", - "orcid": "0000-0001-9137-4363" + "affiliation": "Department of Psychological and Brain Sciences, Dartmouth College", + "name": "Petre, Bogdan", + "orcid": "0000-0002-8437-168X" }, { - "name": "Tambini, Arielle" + "affiliation": "MPI-CBS; McGill University", + "name": "Steele, Christopher John", + "orcid": "0000-0003-1656-7928" }, { - "name": "Weinstein, Alejandro" + "affiliation": "Vrije Universiteit Amsterdam", + "name": "Ort, Eduard" }, { - "affiliation": "Universidad de Guadalajara", - "name": "Gonz\u00e1lez Orozco, Abel A." + "affiliation": "Stanford University", + "name": "Lerma-Usabiaga, Garikoitz", + "orcid": "0000-0001-9800-4816" }, { - "name": "Harms, Robbert" + "name": "Schwabacher, Isaac" }, { - "name": "Khanuja, Ranjeet" + "name": "Arias, Jaime" }, { - "affiliation": "University of Illinois Urbana Champaign", - "name": "Sharp, Paul" + "name": "Lai, Jeff" }, { - "affiliation": "Dept of Medical Biophysics, Univeristy of Western Ontario", - "name": "Stanley, Olivia" + "affiliation": "Child Mind Institute / Nathan Kline Institute", + "name": "Pellman, John", + "orcid": "0000-0001-6810-4461" }, { - "name": "Lee, Nat", - "orcid": "0000-0001-9308-9988" + "affiliation": "BarcelonaBeta Brain Research Center", + "name": "Huguet, Jordi", + "orcid": "0000-0001-8420-4833" }, { - "name": "Crusoe, Michael R.", - "orcid": "0000-0002-2961-9670" + "affiliation": "University of Pennsylvania", + "name": "Junhao WEN", + "orcid": "0000-0003-2077-3070" }, { - "name": "Brett, Matthew" + "affiliation": "TIB – Leibniz Information Centre for Science and Technology and University Library, Hannover, Germany", + "name": "Leinweber, Katrin", + "orcid": "0000-0001-5135-5758" }, { - "name": "Falkiewicz, Marcel" + "affiliation": "INRIA-Saclay, Team Parietal", + "name": "Chawla, Kshitij", + "orcid": "0000-0002-7517-6321" }, { "affiliation": "Institute of Imaging & Computer Vision, RWTH Aachen University, Germany", "name": "Weninger, Leon" }, { - "name": "Podranski, Kornelius" + "name": "Modat, Marc" }, { - "affiliation": "German Institute for International Educational Research", - "name": "Linkersd\u00f6rfer, Janosch", - "orcid": "0000-0002-1577-1233" + "affiliation": "University of Tübingen and MPI for Biological Cybernertics", + "name": "Bannert, Michael M.", + "orcid": "0000-0003-1010-7517" }, { - "name": "Flandin, Guillaume" + "affiliation": "University of Waterloo", + "name": "Mukhometzianov, Rinat", + "orcid": "0000-0003-1274-4827" }, { - "affiliation": "Stanford University", - "name": "Lerma-Usabiaga, Garikoitz", - "orcid": "0000-0001-9800-4816" + "name": "Harms, Robbert" }, { - "name": "Tarbert, Claire" + "affiliation": "University of Helsinki", + "name": "Andberg, Sami Kristian", + "orcid": "0000-0002-5650-3964" }, { - "name": "Cheung, Brian" + "name": "Matsubara, K" }, { - "affiliation": "Washington University in St Louis", - "name": "Van, Andrew", - "orcid": "0000-0002-8787-0943" + "affiliation": "Universidad de Guadalajara", + "name": "González Orozco, Abel A." }, { - "name": "Davison, Andrew" + "affiliation": "ARAMIS Lab", + "name": "Routier, Alexandre", + "orcid": "0000-0003-1603-8049" }, { - "name": "Shachnev, Dmitry" + "name": "Marina, Ana" }, { - "affiliation": "Technical University Munich", - "name": "Molina-Romero, Miguel", - "orcid": "0000-0001-8054-0426" + "name": "Davison, Andrew" }, { - "name": "Rothmei, Simon" + "affiliation": "The University of Texas at Austin", + "name": "Floren, Andrew", + "orcid": "0000-0003-3618-2056" }, { - "affiliation": "National Institute on Aging, Baltimore, MD, USA", - "name": "Bilgel, Murat", - "orcid": "0000-0001-5042-7422" + "name": "Park, Anne" }, { - "name": "Schlamp, Kai" + "affiliation": "Consolidated Department of Psychiatry, Harvard Medical School", + "name": "Frederick, Blaise", + "orcid": "0000-0001-5832-5279" }, { - "affiliation": "Vrije Universiteit Amsterdam", - "name": "Ort, Eduard" + "name": "Cheung, Brian" + }, + { + "name": "McDermottroe, Conor" }, { "affiliation": "University of Cambridge", @@ -696,21 +846,20 @@ "orcid": "0000-0001-9928-4960" }, { - "name": "Arias, Jaime" + "name": "Shachnev, Dmitry" }, { - "name": "Bielievtsov, Dmytro", - "orcid": "0000-0003-3846-7696" + "affiliation": "University of Applied Sciences and Arts Northwestern Switzerland", + "name": "Vogel, Dorian", + "orcid": "0000-0003-3445-576X" }, { - "affiliation": "MPI-CBS; McGill University", - "name": "Steele, Christopher John", - "orcid": "0000-0003-1656-7928" + "name": "Flandin, Guillaume" }, { - "affiliation": "State Key Laboratory of Cognitive Neuroscience and Learning & IDG/McGovern Institute for Brain Research, Beijing Normal University, Beijing, China", - "name": "Huang, Lijie", - "orcid": "0000-0002-9910-5069" + "affiliation": "Stanford University and the University of Chicago", + "name": "Jones, Henry", + "orcid": "0000-0001-7719-3646" }, { "affiliation": "Athinoula A. Martinos Center for Biomedical Imaging, Department of Radiology, Massachusetts General Hospital, Charlestown, MA, USA", @@ -718,59 +867,64 @@ "orcid": "0000-0002-6451-6909" }, { - "affiliation": "Mayo Clinic", - "name": "Warner, Joshua", - "orcid": "0000-0003-3579-4835" + "name": "Varada, Jan" }, { - "affiliation": "Max Planck Research Group for Neuroanatomy & Connectivity, Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig, Germany", - "name": "Margulies, Daniel S.", - "orcid": "0000-0002-8880-9204" + "name": "Schlamp, Kai" }, { - "affiliation": "Otto-von-Guericke-University Magdeburg, Germany", - "name": "Contier, Oliver", - "orcid": "0000-0002-2983-4709" + "name": "Podranski, Kornelius" }, { - "name": "Marina, Ana" + "affiliation": "State Key Laboratory of Cognitive Neuroscience and Learning & IDG/McGovern Institute for Brain Research, Beijing Normal University, Beijing, China", + "name": "Huang, Lijie", + "orcid": "0000-0002-9910-5069" }, { - "name": "Saase, Victor" + "name": "Noel, Maxime" }, { - "name": "Nickson, Thomas" + "affiliation": "Medical Imaging & Biomarkers, Bioclinica, Newark, CA, USA.", + "name": "Pannetier, Nicolas", + "orcid": "0000-0002-0744-5155" }, { - "name": "Varada, Jan" + "affiliation": "Max Planck Institute for Human Cognitive and Brain Sciences", + "name": "Numssen, Ole", + "orcid": "0000-0001-7164-2682" }, { - "name": "Schwabacher, Isaac" + "name": "Khanuja, Ranjeet" }, { - "affiliation": "Child Mind Institute / Nathan Kline Institute", - "name": "Pellman, John", - "orcid": "0000-0001-6810-4461" + "name": "Urchs, Sebastian" }, { - "name": "Khanuja, Ranjeet" + "affiliation": "Department of Psychology, Stanford University", + "name": "Shim, Sunjae", + "orcid": "0000-0003-2773-0807" }, { - "affiliation": "Medical Imaging & Biomarkers, Bioclinica, Newark, CA, USA.", - "name": "Pannetier, Nicolas", - "orcid": "0000-0002-0744-5155" + "name": "Nickson, Thomas" }, { - "name": "McDermottroe, Conor" + "affiliation": "State Key Laboratory of Cognitive Neuroscience and Learning & IDG/McGovern Institute for Brain Research, Beijing Normal University, Beijing, China", + "name": "Huang, Lijie", + "orcid": "0000-0002-9910-5069" + }, + { + "affiliation": "Duke University", + "name": "Broderick, William", + "orcid": "0000-0002-8999-9003" + }, + { + "name": "Tambini, Arielle" }, { "affiliation": "Max Planck Institute for Human Cognitive and Brain Sciences, Leipzig, Germany.", "name": "Mihai, Paul Glad", "orcid": "0000-0001-5715-6442" }, - { - "name": "Lai, Jeff" - }, { "affiliation": "Department of Psychology, Stanford University", "name": "Gorgolewski, Krzysztof J.", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2f87417f08..302a32d626 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,8 +6,8 @@ These guidelines are designed to make it as easy as possible to get involved. If Before you start you'll need to set up a free [GitHub][link_github] account and sign in. Here are some [instructions][link_signupinstructions]. If you are not familiar with version control systems such as git, - [introductions and tutorials](http://www.reproducibleimaging.org/module-reproducible-basics/02-vcs/) - may be found on [ReproducibleImaging.org](https://www.reproducibleimaging.org/). +we recommend the [VCS module](http://www.reproducibleimaging.org/module-reproducible-basics/02-vcs/) +available from [ReproNim](http://www.reproducibleimaging.org/). Already know what you're looking for in this guide? Jump to the following sections: * [Understanding issue labels](#issue-labels) @@ -22,7 +22,7 @@ The current list of issue labels are [here][link_labels] and include: * [![Bugs](https://img.shields.io/badge/-bugs-fc2929.svg)][link_bugs] *These issues point to problems in the project.* - If you find new a bug, please provide as much information as possible to recreate the error. + If you find a new bug, please provide as much information as possible to recreate the error. The [issue template][link_issue_template] will automatically populate any new issue you open, and contains information we've found to be helpful in addressing bug reports. Please fill it out to the best of your ability! @@ -41,7 +41,7 @@ The current list of issue labels are [here][link_labels] and include: * [![Orphaned](https://img.shields.io/badge/-orphaned-9baddd.svg)][link_orphaned] *These pull requests have been closed for inactivity.* Before proposing a new pull request, browse through the "orphaned" pull requests. - You may find that someone has already made significant progress toward your goal, and you can re-use their + You may find that someone has already made significant progress toward your goal, and you can reuse their unfinished work. An adopted PR should be updated to merge or rebase the current master, and a new PR should be created (see below) that references the original PR. diff --git a/Makefile b/Makefile index 48f2c112c2..568d53379c 100644 --- a/Makefile +++ b/Makefile @@ -9,20 +9,24 @@ PYTHON ?= python zipdoc: html zip documentation.zip doc/_build/html +.git-blame-ignore-revs: .git/HEAD + git log --grep "\[ignore-rev\]\|STY: black\|run black" -i --pretty=format:"# %ad - %ae - %s%n%H" > .git-blame-ignore-revs + echo >> .git-blame-ignore-revs + sdist: zipdoc @echo "Building source distribution..." - python setup.py sdist + $(PYTHON) setup.py sdist @echo "Done building source distribution." # XXX copy documentation.zip to dist directory. egg: zipdoc @echo "Building egg..." - python setup.py bdist_egg + $(PYTHON) setup.py bdist_egg @echo "Done building egg." upload_to_pypi: zipdoc @echo "Uploading to PyPi..." - python setup.py sdist --formats=zip,gztar upload + $(PYTHON) setup.py sdist --formats=zip,gztar upload trailing-spaces: find . -name "*[.py|.rst]" -type f | xargs perl -pi -e 's/[ \t]*$$//' @@ -56,10 +60,10 @@ inplace: $(PYTHON) setup.py build_ext -i test-code: in - py.test --doctest-modules nipype + $(PYTHON) -m pytest --doctest-modules nipype test-coverage: clean-tests in - py.test --doctest-modules --cov-config .coveragerc --cov=nipype nipype + $(PYTHON) -m pytest --doctest-modules --cov-config .coveragerc --cov=nipype nipype test: tests # just another name tests: clean test-code @@ -70,7 +74,7 @@ html: specs: @echo "Checking specs and autogenerating spec tests" - env PYTHONPATH=".:$(PYTHONPATH)" python tools/checkspecs.py + env PYTHONPATH=".:$(PYTHONPATH)" $(PYTHON) tools/checkspecs.py check: check-before-commit # just a shortcut check-before-commit: specs trailing-spaces html test diff --git a/README.rst b/README.rst index 70e64061bd..b51c2bf401 100644 --- a/README.rst +++ b/README.rst @@ -82,7 +82,7 @@ Python 2 Statement Python 2.7 reaches its end-of-life in January 2020, which means it will *no longer be maintained* by Python developers. `Many projects -`__ are removing support in advance of this deadline, which will make it increasingly untenable to try to support Python 2, even if we wanted to. diff --git a/THANKS.rst b/THANKS.rst index 4d8cdd47e7..71c4d9eeac 100644 --- a/THANKS.rst +++ b/THANKS.rst @@ -19,4 +19,3 @@ and `UL1 TR000442 University of Iowa Clinical and Translational Science Program We would also like to thank `JetBrains `__ for providing `Pycharm `__ licenses. - diff --git a/doc/.gitignore b/doc/.gitignore index 1f812bd420..d396f26e2d 100644 --- a/doc/.gitignore +++ b/doc/.gitignore @@ -1 +1,2 @@ /documentation.zip +_static/python diff --git a/doc/Makefile b/doc/Makefile index bcb7ac2e8f..9b3e3783ef 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -24,7 +24,7 @@ help: @echo " doctest run all doctests embedded in the documentation" clean: - -rm -rf _build/* *~ api/generated interfaces/generated users/examples documentation.zip + -rm -rf _build/* *~ api/generated interfaces/generated users/examples documentation.zip _static/python htmlonly: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html diff --git a/doc/_static/nipype.css b/doc/_static/nipype.css index cec080b3d6..5aceb4c42a 100644 --- a/doc/_static/nipype.css +++ b/doc/_static/nipype.css @@ -5,6 +5,10 @@ body { min-width: 70em; } +div.sphinxsidebar { + position: relative; +} + div.sphinxsidebar h4, div.sphinxsidebar h3 { background-color: #2F83C8; } diff --git a/doc/_static/snakebrain-nipype.svg b/doc/_static/snakebrain-nipype.svg new file mode 100644 index 0000000000..04bfc05362 --- /dev/null +++ b/doc/_static/snakebrain-nipype.svg @@ -0,0 +1,108 @@ + + + + + + + + image/svg+xml + + + + + + Michael Hanke <michael.hanke@gmail.com> + + + Artwork by Arno Klein + The image has been converted from a pixel-based artwork. + + + Original artwork created by Arno Klein <arno@binarybottle.com>. +Converted to SVG by Michael Hanke <michael.hanke@gmail.com>. + + + + + + + + + + + + + + + + + + + + + + diff --git a/doc/_templates/indexsidebar.html b/doc/_templates/indexsidebar.html index ce03fb63f9..f771858968 100644 --- a/doc/_templates/indexsidebar.html +++ b/doc/_templates/indexsidebar.html @@ -11,4 +11,4 @@

{{ _('Links') }}

Python Versions -{% endblock %} +{% endblock %} diff --git a/doc/_templates/layout.html b/doc/_templates/layout.html index a8de8d176b..2228087cec 100644 --- a/doc/_templates/layout.html +++ b/doc/_templates/layout.html @@ -2,6 +2,9 @@ {% set title = 'Neuroimaging in Python - Pipelines and Interfaces' %} {% set short_title = 'Nipype' %} +{% block sidebar1 %}{{ sidebar() }}{% endblock %} +{% block sidebar2 %}{% endblock %} + {% block extrahead %} {{ super() }} @@ -42,8 +45,6 @@ {% block relbar1 %}{% endblock %} {% block relbar2 %}{% endblock %} -{% block sidebar1 %}{{ sidebar() }}{% endblock %} -{% block sidebar2 %}{% endblock %} {% block footer %} {{ super() }} diff --git a/doc/_templates/navbar.html b/doc/_templates/navbar.html index fd0216b53f..6b2d457a1f 100644 --- a/doc/_templates/navbar.html +++ b/doc/_templates/navbar.html @@ -1,7 +1,6 @@ \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "
\n", - "\n", - "\n", - "\n", - "
\n", - "\n", - "Most used/contributed policy!\n", - "\n", - "Not all components of these packages are available." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "skip" - } - }, - "source": [ - "# Workflows\n", - "\n", - "- Properties:\n", - "\n", - " - processing pipeline is a directed acyclic graph (DAG)\n", - " - nodes are processes\n", - " - edges represent data flow\n", - " - compact represenation for any process\n", - " - code and data separation" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "#Execution Plugins\n", - "\n", - "Allows seamless execution across many architectures\n", - "\n", - " - Local\n", - "\n", - " - Serial\n", - " - Multicore\n", - "\n", - " - Clusters\n", - "\n", - " - HTCondor\n", - " - PBS/Torque/SGE/LSF (native and via IPython)\n", - " - SSH (via IPython)\n", - " - Soma Workflow" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Learn Nipype concepts in 10 easy steps\n", - "\n", - "\n", - "1. Installing and testing the installation \n", - "2. Working with interfaces\n", - "3. Using Nipype caching\n", - "4. Creating Nodes, MapNodes and Workflows\n", - "5. Getting and saving data\n", - "6. Using Iterables\n", - "7. Function nodes\n", - "8. Distributed computation\n", - "9. Connecting to databases\n", - "10. Execution configuration options" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Step 1. Installing Nipype\n", - "\n", - "## Scientific Python:\n", - "\n", - "* Debian/Ubuntu/Scientific Fedora\n", - "* [Canopy from Enthought](https://www.enthought.com/products/canopy/)\n", - "* [Anaconda from Contnuum Analytics](https://store.continuum.io/cshop/anaconda/)\n", - "\n", - "## Installing Nipype:\n", - "\n", - "* Available from [@NeuroDebian](http://neuro.debian.net/pkgs/python-nipype.html),\n", - " [@PyPI](http://pypi.python.org/pypi/nipype/), and\n", - " [@GitHub](http://github.com/nipy/nipype)\n", - " \n", - " - pip install nipype\n", - " - easy_install nipype\n", - " - sudo apt-get install python-nipype\n", - "\n", - "* Dependencies: networkx, nibabel, numpy, scipy, traits\n", - "\n", - "## Running Nipype ([Quickstart](http://nipy.org/nipype/quickstart.html)):\n", - "\n", - "* Ensure underlying tools are installed and accessible\n", - "* Nipype **is a wrapper, not a substitute** for AFNI, ANTS, FreeSurfer, FSL, SPM,\n", - " NiPy, etc.,." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "# Step 1. Testing nipype" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "```\n", - "$ ipython notebook\n", - "```" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "import nipype\n", - "\n", - "# Comment the following section to increase verbosity of output\n", - "nipype.config.set('logging', 'workflow_level', 'CRITICAL')\n", - "nipype.config.set('logging', 'interface_level', 'CRITICAL')\n", - "nipype.logging.update_logging(nipype.config)\n", - "\n", - "nipype.test(verbose=0) # Increase verbosity parameter for more info" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "If all goes well you will see an OK:\n", - "\n", - " ----------------------------------------------------------------------\n", - " Ran 2497 tests in 68.486s\n", - "\n", - " OK (SKIP=13)\n", - "\n", - "The number of tests and time will vary depending on which interfaces you have installed on your system." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "nipype.get_info()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "# Environment and data setup\n", - "\n", - "Setting up your Ipython notebook environment and download some data to play with" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "%pylab inline" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "# Some preliminaries\n", - "import os\n", - "cwd = os.getcwd()\n", - "tutorial_dir = '/software/temp/nipype-tutorial/ohbm/'\n", - "if not os.path.exists(tutorial_dir):\n", - " os.mkdir(tutorial_dir)\n", - "os.chdir(tutorial_dir)" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "-" - } - }, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "import urllib\n", - "required_files = ['ds107/sub001/BOLD/task001_run001/bold.nii.gz',\n", - " 'ds107/sub001/BOLD/task001_run002/bold.nii.gz',\n", - " 'ds107/sub001/anatomy/highres001.nii.gz',\n", - " 'ds107/sub044/BOLD/task001_run001/bold.nii.gz',\n", - " 'ds107/sub044/BOLD/task001_run002/bold.nii.gz',\n", - " 'ds107/sub044/anatomy/highres001.nii.gz'\n", - " ]\n", - "base_url = 'http://openfmri.aws.amazon.com.s3.amazonaws.com/'\n", - "for filepath in required_files:\n", - " file_location = os.path.join(tutorial_dir, filepath)\n", - " if not os.path.exists(file_location):\n", - " print('Retrieving: ' + file_location)\n", - " os.makedirs(os.path.dirname(file_location))\n", - " urllib.urlretrieve(base_url + filepath, file_location)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Step 2. Working with interfaces" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "import nipype.algorithms" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.fsl import DTIFit\n", - "from nipype.interfaces.spm import Realign" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### Finding interface inputs and outputs and examples" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "DTIFit.help()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "Realign.help()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### Creating a directory for running interfaces" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "import os\n", - "from shutil import copyfile\n", - "library_dir = os.path.join(tutorial_dir, 'as_a_library')\n", - "if not os.path.exists(library_dir):\n", - " os.mkdir(library_dir)\n", - "os.chdir(library_dir)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Executing interfaces" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.freesurfer import MRIConvert\n", - "convert = MRIConvert(in_file='../ds107/sub001/BOLD/task001_run001/bold.nii.gz',\n", - " out_file='ds107.nii')\n", - "print(convert.cmdline)\n", - "results = convert.run(terminal_output='none') # allatonce, stream (default), file" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "results.outputs" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Other ways" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "convert = MRIConvert()\n", - "convert.inputs.in_file='../ds107/sub001/BOLD/task001_run001/bold.nii.gz'\n", - "convert.inputs.out_file='ds107.nii'\n", - "convert.run()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "convert = MRIConvert()\n", - "convert.run(in_file='../ds107/sub001/BOLD/task001_run001/bold.nii.gz',\n", - " out_file='ds107.nii')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": true, - "input": [ - "convert.inputs" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "#### Look at only the defined inputs" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "results.inputs" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "-" - } - }, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### Experiment with other interfaces\n", - "\n", - "For example, run realignment with SPM" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.spm import Realign\n", - "results1 = Realign(in_files='ds107.nii',\n", - " register_to_mean=False).run()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "And now use FSL" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.fsl import MCFLIRT\n", - "results2 = MCFLIRT(in_file='ds107.nii', ref_vol=0,\n", - " save_plots=True).run()" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "-" - } - }, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### Now we can look at some results" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "print results1.runtime.duration, results2.runtime.duration\n", - "subplot(211);plot(genfromtxt('ds107_mcf.nii.gz.par')[:, 3:]);title('FSL')\n", - "subplot(212);plot(genfromtxt('rp_ds107.txt')[:,:3]);title('SPM')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "#### if i execute the MCFLIRT line again, well, it runs again!" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Step 3. Nipype caching" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.caching import Memory\n", - "mem = Memory('.')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Create `cacheable` objects" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "spm_realign = mem.cache(Realign)\n", - "fsl_realign = mem.cache(MCFLIRT)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### Execute interfaces" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "spm_results = spm_realign(in_files='ds107.nii', register_to_mean=False)\n", - "fsl_results = fsl_realign(in_file='ds107.nii', ref_vol=0, save_plots=True)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "subplot(211);plot(genfromtxt(fsl_results.outputs.par_file)[:, 3:])\n", - "subplot(212);plot(genfromtxt(spm_results.outputs.realignment_parameters)[:,:3])" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "spm_results = spm_realign(in_files='ds107.nii', register_to_mean=False)\n", - "fsl_results = fsl_realign(in_file='ds107.nii', ref_vol=0, save_plots=True)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "# More caching" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from os.path import abspath as opap\n", - "files = [opap('../ds107/sub001/BOLD/task001_run001/bold.nii.gz'),\n", - " opap('../ds107/sub001/BOLD/task001_run002/bold.nii.gz')]\n", - "converter = mem.cache(MRIConvert)\n", - "newfiles = []\n", - "for idx, fname in enumerate(files):\n", - " newfiles.append(converter(in_file=fname,\n", - " out_type='nii').outputs.out_file)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "os.chdir(tutorial_dir)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Step 4: Nodes, Mapnodes and workflows\n", - "\n", - "**Where:**" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.pipeline.engine import Node, MapNode, Workflow" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Node**:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "realign_spm = Node(Realign(), name='motion_correct')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "**Mapnode**:\n", - "\n", - "" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "convert2nii = MapNode(MRIConvert(out_type='nii'),\n", - " iterfield=['in_file'],\n", - " name='convert2nii')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "# \"Hello World\" of Nipype workflows" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### Connect them up:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "realignflow = Workflow(name='realign_with_spm')\n", - "realignflow.connect(convert2nii, 'out_file',\n", - " realign_spm, 'in_files')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "convert2nii.inputs.in_file = files\n", - "realign_spm.inputs.register_to_mean = False\n", - "\n", - "realignflow.base_dir = opap('.')\n", - "realignflow.run()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "#Visualize the workflow" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "realignflow.write_graph()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from IPython.core.display import Image\n", - "Image('realign_with_spm/graph.png')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "realignflow.write_graph(graph2use='orig')\n", - "Image('realign_with_spm/graph_detailed.png')" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Step 5. Getting and saving data\n", - "\n", - "### Instead of assigning data ourselves, let's *glob* it" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "os.chdir(tutorial_dir)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.io import DataGrabber, DataFinder\n", - "ds = Node(DataGrabber(infields=['subject_id'], outfields=['func']),\n", - " name='datasource')\n", - "ds.inputs.base_directory = opap('ds107')\n", - "ds.inputs.template = '%s/BOLD/task001*/bold.nii.gz'\n", - "ds.inputs.sort_filelist = True\n", - "\n", - "ds.inputs.subject_id = 'sub001'\n", - "print ds.run().outputs" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "ds.inputs.subject_id = 'sub044'\n", - "print ds.run().outputs" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "#Multiple files\n", - "\n", - "### A little more practical usage" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "ds = Node(DataGrabber(infields=['subject_id', 'task_id'],\n", - " outfields=['func', 'anat']),\n", - " name='datasource')\n", - "ds.inputs.base_directory = opap('ds107')\n", - "ds.inputs.template = '*'\n", - "ds.inputs.template_args = {'func': [['subject_id', 'task_id']],\n", - " 'anat': [['subject_id']]}\n", - "ds.inputs.field_template = {'func': '%s/BOLD/task%03d*/bold.nii.gz',\n", - " 'anat': '%s/anatomy/highres001.nii.gz'}\n", - "ds.inputs.sort_filelist = True\n", - "ds.inputs.subject_id = 'sub001'\n", - "ds.inputs.task_id = 1\n", - "print ds.run().outputs" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "# Connecting to computation" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "convert2nii = MapNode(MRIConvert(out_type='nii'),\n", - " iterfield=['in_file'],\n", - " name='convert2nii')\n", - "\n", - "realign_spm = Node(Realign(), name='motion_correct')\n", - "realign_spm.inputs.register_to_mean = False\n", - "\n", - "connectedworkflow = Workflow(name='connectedtogether')\n", - "connectedworkflow.base_dir = opap('working_dir')\n", - "connectedworkflow.connect(ds, 'func', convert2nii, 'in_file')\n", - "connectedworkflow.connect(convert2nii, 'out_file', realign_spm, 'in_files')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "#Data sinking\n", - "\n", - "###Take output computed in a workflow out of it." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.io import DataSink\n", - "sinker = Node(DataSink(), name='sinker')\n", - "sinker.inputs.base_directory = opap('output')\n", - "connectedworkflow.connect(realign_spm, 'realigned_files',\n", - " sinker, 'realigned')\n", - "connectedworkflow.connect(realign_spm, 'realignment_parameters',\n", - " sinker, 'realigned.@parameters')\n", - "connectedworkflow.run()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### How to determine output location\n", - "\n", - " 'base_directory/container/parameterization/destloc/filename'\n", - " \n", - " destloc = [@]string[[.[@]]string[[.[@]]string]...] and\n", - " destloc = realigned.@parameters --> 'realigned'\n", - " destloc = realigned.parameters.@1 --> 'realigned/parameters'\n", - " destloc = realigned.parameters.@2 --> 'realigned/parameters'\n", - " filename comes from the input to the connect statement." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "#Step 6: *iterables* - parametric execution\n", - "\n", - "**Workflow + iterables**: runs subgraph several times, attribute not input" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "ds.iterables = ('subject_id', ['sub001', 'sub044'])\n", - "connectedworkflow.run()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "#Putting it all together\n", - "\n", - "### iterables + MapNode + Node + Workflow + DataGrabber + DataSink" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "connectedworkflow.write_graph()\n", - "Image('working_dir/connectedtogether/graph.png')" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "-" - } - }, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Step 7: The Function interface\n", - "\n", - "### The do anything you want card" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.utility import Function\n", - "\n", - "def myfunc(input1, input2):\n", - " \"\"\"Add and subtract two inputs\n", - " \"\"\"\n", - " return input1 + input2, input1 - input2\n", - "\n", - "calcfunc = Node(Function(input_names=['input1', 'input2'],\n", - " output_names = ['sum', 'difference'],\n", - " function=myfunc),\n", - " name='mycalc')\n", - "calcfunc.inputs.input1 = 1\n", - "calcfunc.inputs.input2 = 2\n", - "res = calcfunc.run()\n", - "print res.outputs" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "#Step 8: Distributed computing\n", - "\n", - "### Normally calling run executes the workflow in series" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "connectedworkflow.run()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### but you can scale very easily\n", - "\n", - "For example, to use multiple cores on your local machine" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "connectedworkflow.run('MultiProc', plugin_args={'n_procs': 4})" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### Or to other job managers\n", - "\n", - "- connectedworkflow.run('PBS', plugin_args={'qsub_args': '-q many'})\n", - "- connectedworkflow.run('SGE', plugin_args={'qsub_args': '-q many'})\n", - "- connectedworkflow.run('LSF', plugin_args={'qsub_args': '-q many'})\n", - "- connectedworkflow.run('Condor')\n", - "- connectedworkflow.run('IPython')\n", - "\n", - "### or submit graphs as a whole\n", - "\n", - "\n", - "- connectedworkflow.run('PBSGraph', plugin_args={'qsub_args': '-q many'})\n", - "- connectedworkflow.run('SGEGraph', plugin_args={'qsub_args': '-q many'})\n", - "- connectedworkflow.run('CondorDAGMan')\n", - "\n", - "### Current Requirement: **SHARED FILESYSTEM**" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### You can also set node specific plugin arguments" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "\n", - "- node.plugin_args = {'qsub_args': '-l nodes=1:ppn=3', 'overwrite': True}\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "#Step 9: Connecting to Databases" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from os.path import abspath as opap\n", - "\n", - "from nipype.interfaces.io import XNATSource\n", - "from nipype.pipeline.engine import Node, Workflow\n", - "from nipype.interfaces.fsl import BET\n", - "\n", - "subject_id = 'xnat_S00001'\n", - "\n", - "dg = Node(XNATSource(infields=['subject_id'],\n", - " outfields=['struct'],\n", - " config='/Users/satra/xnat_configs/nitrc_ir_config'),\n", - " name='xnatsource')\n", - "dg.inputs.query_template = ('/projects/fcon_1000/subjects/%s/experiments/xnat_E00001'\n", - " '/scans/%s/resources/NIfTI/files')\n", - "dg.inputs.query_template_args['struct'] = [['subject_id', 'anat_mprage_anonymized']]\n", - "dg.inputs.subject_id = subject_id\n", - "\n", - "bet = Node(BET(), name='skull_stripper')\n", - "\n", - "wf = Workflow(name='testxnat')\n", - "wf.base_dir = opap('xnattest')\n", - "wf.connect(dg, 'struct', bet, 'in_file')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.io import XNATSink\n", - "\n", - "ds = Node(XNATSink(config='/Users/satra/xnat_configs/central_config'),\n", - " name='xnatsink')\n", - "ds.inputs.project_id = 'NPTEST'\n", - "ds.inputs.subject_id = 'NPTEST_xnat_S00001'\n", - "ds.inputs.experiment_id = 'test_xnat'\n", - "ds.inputs.reconstruction_id = 'bet'\n", - "ds.inputs.share = True\n", - "wf.connect(bet, 'out_file', ds, 'brain')" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "skip" - } - }, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "wf.run()" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "#Step 10: Configuration options\n", - "\n", - "[Configurable options](http://nipy.org/nipype/users/config_file.html) control workflow and node execution options\n", - "\n", - "At the global level:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype import config, logging\n", - "\n", - "config.enable_debug_mode()\n", - "logging.update_logging(config)\n", - "\n", - "config.set('execution', 'stop_on_first_crash', 'true')" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "At the workflow level:" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "wf.config['execution']['hash_method'] = 'content'" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "Configurations can also be set at the node level." - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "bet.config = {'execution': {'keep_unnecessary_outputs': 'true'}}" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "wf.run()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Reusable workflows" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "config.set_default_config()\n", - "logging.update_logging(config)" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from niflow.nipype1.workflows.fmri.fsl.preprocess import create_susan_smooth\n", - "\n", - "smooth = create_susan_smooth()\n", - "smooth.inputs.inputnode.in_files = opap('output/realigned/_subject_id_sub044/rbold_out.nii')\n", - "smooth.inputs.inputnode.fwhm = 5\n", - "smooth.inputs.inputnode.mask_file = 'mask.nii'\n", - "\n", - "smooth.run() # Will error because mask.nii does not exist" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "from nipype.interfaces.fsl import BET, MeanImage, ImageMaths\n", - "from nipype.pipeline.engine import Node\n", - "\n", - "\n", - "remove_nan = Node(ImageMaths(op_string= '-nan'), name='nanremove')\n", - "remove_nan.inputs.in_file = opap('output/realigned/_subject_id_sub044/rbold_out.nii')\n", - "\n", - "mi = Node(MeanImage(), name='mean')\n", - "\n", - "mask = Node(BET(mask=True), name='mask')\n", - "\n", - "wf = Workflow('reuse')\n", - "wf.base_dir = opap('.')\n", - "wf.connect(remove_nan, 'out_file', mi, 'in_file')\n", - "wf.connect(mi, 'out_file', mask, 'in_file')\n", - "wf.connect(mask, 'out_file', smooth, 'inputnode.mask_file')\n", - "wf.connect(remove_nan, 'out_file', smooth, 'inputnode.in_files')\n", - "\n", - "wf.run()" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Setting internal parameters of workflows" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "print(smooth.list_node_names())\n", - "\n", - "median = smooth.get_node('median')\n", - "median.inputs.op_string = '-k %s -p 60'" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "-" - } - }, - "outputs": [] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "wf.run()" - ], - "language": "python", - "metadata": {}, - "outputs": [] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Summary\n", - "\n", - "\n", - "- This tutorial covers the concepts of Nipype\n", - "\n", - " 1. Installing and testing the installation \n", - " 2. Working with interfaces\n", - " 3. Using Nipype caching\n", - " 4. Creating Nodes, MapNodes and Workflows\n", - " 5. Getting and saving data\n", - " 6. Using Iterables\n", - " 7. Function nodes\n", - " 8. Distributed computation\n", - " 9. Connecting to databases\n", - " 10. Execution configuration options\n", - "\n", - "- It will allow you to reuse and debug the various workflows available in Nipype, BIPS and CPAC\n", - "- Please contribute new interfaces and workflows!" - ] - }, - { - "cell_type": "code", - "collapsed": false, - "input": [ - "import os\n", - "basedir = '/Users/satra/Dropbox/WORK/notebooks/'\n", - "if os.path.exists(basedir):\n", - " os.chdir(basedir)" - ], - "language": "python", - "metadata": { - "slideshow": { - "slide_type": "skip" - } - }, - "outputs": [] - } - ], - "metadata": {} - } - ] -} diff --git a/examples/rsfmri_vol_surface_preprocessing.py b/examples/rsfmri_vol_surface_preprocessing.py deleted file mode 100644 index 20b150b149..0000000000 --- a/examples/rsfmri_vol_surface_preprocessing.py +++ /dev/null @@ -1,1087 +0,0 @@ -#!/usr/bin/env python -# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- -# vi: set ft=python sts=4 ts=4 sw=4 et: -""" -==================================== -rsfMRI: ANTS, FS, FSL, SPM, aCompCor -==================================== - - -A preprocessing workflow for Siemens resting state data. - -This workflow makes use of: - -- ANTS -- FreeSurfer -- FSL -- SPM -- CompCor - -For example:: - - python rsfmri_preprocessing.py -d /data/12345-34-1.dcm -f /data/Resting.nii - -s subj001 -o output -p PBS --plugin_args "dict(qsub_args='-q many')" - - or - - python rsfmri_vol_surface_preprocessing.py -f SUB_1024011/E?/func/rest.nii - -t OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz --TR 2 -s SUB_1024011 - --subjects_dir fsdata --slice_times 0 17 1 18 2 19 3 20 4 21 5 22 6 23 - 7 24 8 25 9 26 10 27 11 28 12 29 13 30 14 31 15 32 16 -o . - -This workflow takes resting timeseries and a Siemens dicom file corresponding -to it and preprocesses it to produce timeseries coordinates or grayordinates. - -This workflow also requires 2mm subcortical atlas and templates that are -available from: - -http://mindboggle.info/data.html - -specifically the 2mm versions of: - -- `Joint Fusion Atlas `_ -- `MNI template `_ -""" - -from __future__ import division, unicode_literals -from builtins import open, range, str - -import os - -from nipype.interfaces.base import CommandLine -CommandLine.set_default_terminal_output('allatonce') - -from dicom import read_file - -from nipype.interfaces import (spm, fsl, Function, ants, freesurfer) -from nipype.interfaces.c3 import C3dAffineTool - -fsl.FSLCommand.set_default_output_type('NIFTI') - -from nipype import Workflow, Node, MapNode -from nipype.interfaces import matlab as mlab - -mlab.MatlabCommand.set_default_matlab_cmd("matlab -nodisplay") -# If SPM is not in your MATLAB path you should add it here -# mlab.MatlabCommand.set_default_paths('/software/matlab/spm12') - -from nipype.algorithms.rapidart import ArtifactDetect -from nipype.algorithms.misc import TSNR, CalculateMedian -from nipype.interfaces.utility import Rename, Merge, IdentityInterface -from nipype.utils.filemanip import filename_to_list -from nipype.interfaces.io import DataSink, FreeSurferSource - -import numpy as np -import scipy as sp -import nibabel as nb - -imports = [ - 'import os', 'import nibabel as nb', 'import numpy as np', - 'import scipy as sp', - 'from nipype.utils.filemanip import filename_to_list, list_to_filename, split_filename', - 'from scipy.special import legendre' -] - - -def get_info(dicom_files): - from dcmstack.extract import default_extractor - """Given a Siemens dicom file return metadata - - Returns - ------- - RepetitionTime - Slice Acquisition Times - Spacing between slices - """ - meta = default_extractor( - read_file( - filename_to_list(dicom_files)[0], - stop_before_pixels=True, - force=True)) - return (meta['RepetitionTime'] / 1000., meta['CsaImage.MosaicRefAcqTimes'], - meta['SpacingBetweenSlices']) - - -def median(in_files): - """Computes an average of the median of each realigned timeseries - - Parameters - ---------- - - in_files: one or more realigned Nifti 4D time series - - Returns - ------- - - out_file: a 3D Nifti file - """ - import numpy as np - import nibabel as nb - from nipype.utils import NUMPY_MMAP - average = None - for idx, filename in enumerate(filename_to_list(in_files)): - img = nb.load(filename, mmap=NUMPY_MMAP) - data = np.median(img.get_data(), axis=3) - if average is None: - average = data - else: - average = average + data - median_img = nb.Nifti1Image(average / float(idx + 1), img.affine, - img.header) - filename = os.path.join(os.getcwd(), 'median.nii.gz') - median_img.to_filename(filename) - return filename - - -def bandpass_filter(files, lowpass_freq, highpass_freq, fs): - """Bandpass filter the input files - - Parameters - ---------- - files: list of 4d nifti files - lowpass_freq: cutoff frequency for the low pass filter (in Hz) - highpass_freq: cutoff frequency for the high pass filter (in Hz) - fs: sampling rate (in Hz) - """ - from nipype.utils.filemanip import split_filename, list_to_filename - import numpy as np - import nibabel as nb - from nipype.utils import NUMPY_MMAP - out_files = [] - for filename in filename_to_list(files): - path, name, ext = split_filename(filename) - out_file = os.path.join(os.getcwd(), name + '_bp' + ext) - img = nb.load(filename, mmap=NUMPY_MMAP) - timepoints = img.shape[-1] - F = np.zeros((timepoints)) - lowidx = int(timepoints / 2) + 1 - if lowpass_freq > 0: - lowidx = np.round(lowpass_freq / fs * timepoints) - highidx = 0 - if highpass_freq > 0: - highidx = np.round(highpass_freq / fs * timepoints) - F[highidx:lowidx] = 1 - F = ((F + F[::-1]) > 0).astype(int) - data = img.get_data() - if np.all(F == 1): - filtered_data = data - else: - filtered_data = np.real(np.fft.ifftn(np.fft.fftn(data) * F)) - img_out = nb.Nifti1Image(filtered_data, img.affine, img.header) - img_out.to_filename(out_file) - out_files.append(out_file) - return list_to_filename(out_files) - - -def motion_regressors(motion_params, order=0, derivatives=1): - """Compute motion regressors upto given order and derivative - - motion + d(motion)/dt + d2(motion)/dt2 (linear + quadratic) - """ - import numpy as np - out_files = [] - for idx, filename in enumerate(filename_to_list(motion_params)): - params = np.genfromtxt(filename) - out_params = params - for d in range(1, derivatives + 1): - cparams = np.vstack((np.repeat(params[0, :][None, :], d, axis=0), - params)) - out_params = np.hstack((out_params, np.diff(cparams, d, axis=0))) - out_params2 = out_params - for i in range(2, order + 1): - out_params2 = np.hstack((out_params2, np.power(out_params, i))) - filename = os.path.join(os.getcwd(), "motion_regressor%02d.txt" % idx) - np.savetxt(filename, out_params2, fmt=b"%.10f") - out_files.append(filename) - return out_files - - -def build_filter1(motion_params, comp_norm, outliers, detrend_poly=None): - """Builds a regressor set comprisong motion parameters, composite norm and - outliers - - The outliers are added as a single time point column for each outlier - - - Parameters - ---------- - - motion_params: a text file containing motion parameters and its derivatives - comp_norm: a text file containing the composite norm - outliers: a text file containing 0-based outlier indices - detrend_poly: number of polynomials to add to detrend - - Returns - ------- - components_file: a text file containing all the regressors - """ - import numpy as np - import nibabel as nb - from scipy.special import legendre - out_files = [] - for idx, filename in enumerate(filename_to_list(motion_params)): - params = np.genfromtxt(filename) - norm_val = np.genfromtxt(filename_to_list(comp_norm)[idx]) - out_params = np.hstack((params, norm_val[:, None])) - try: - outlier_val = np.genfromtxt(filename_to_list(outliers)[idx]) - except IOError: - outlier_val = np.empty((0)) - for index in np.atleast_1d(outlier_val): - outlier_vector = np.zeros((out_params.shape[0], 1)) - outlier_vector[index] = 1 - out_params = np.hstack((out_params, outlier_vector)) - if detrend_poly: - timepoints = out_params.shape[0] - X = np.empty((timepoints, 0)) - for i in range(detrend_poly): - X = np.hstack((X, legendre(i + 1)(np.linspace( - -1, 1, timepoints))[:, None])) - out_params = np.hstack((out_params, X)) - filename = os.path.join(os.getcwd(), "filter_regressor%02d.txt" % idx) - np.savetxt(filename, out_params, fmt=b"%.10f") - out_files.append(filename) - return out_files - - -def extract_noise_components(realigned_file, - mask_file, - num_components=5, - extra_regressors=None): - """Derive components most reflective of physiological noise - - Parameters - ---------- - realigned_file: a 4D Nifti file containing realigned volumes - mask_file: a 3D Nifti file containing white matter + ventricular masks - num_components: number of components to use for noise decomposition - extra_regressors: additional regressors to add - - Returns - ------- - components_file: a text file containing the noise components - """ - from scipy.linalg.decomp_svd import svd - import numpy as np - import nibabel as nb - from nipype.utils import NUMPY_MMAP - import os - imgseries = nb.load(realigned_file, mmap=NUMPY_MMAP) - components = None - for filename in filename_to_list(mask_file): - mask = nb.load(filename, mmap=NUMPY_MMAP).get_data() - if len(np.nonzero(mask > 0)[0]) == 0: - continue - voxel_timecourses = imgseries.get_data()[mask > 0] - voxel_timecourses[np.isnan(np.sum(voxel_timecourses, axis=1)), :] = 0 - # remove mean and normalize by variance - # voxel_timecourses.shape == [nvoxels, time] - X = voxel_timecourses.T - stdX = np.std(X, axis=0) - stdX[stdX == 0] = 1. - stdX[np.isnan(stdX)] = 1. - stdX[np.isinf(stdX)] = 1. - X = (X - np.mean(X, axis=0)) / stdX - u, _, _ = svd(X, full_matrices=False) - if components is None: - components = u[:, :num_components] - else: - components = np.hstack((components, u[:, :num_components])) - if extra_regressors: - regressors = np.genfromtxt(extra_regressors) - components = np.hstack((components, regressors)) - components_file = os.path.join(os.getcwd(), 'noise_components.txt') - np.savetxt(components_file, components, fmt=b"%.10f") - return components_file - - -def rename(in_files, suffix=None): - from nipype.utils.filemanip import (filename_to_list, split_filename, - list_to_filename) - out_files = [] - for idx, filename in enumerate(filename_to_list(in_files)): - _, name, ext = split_filename(filename) - if suffix is None: - out_files.append(name + ('_%03d' % idx) + ext) - else: - out_files.append(name + suffix + ext) - return list_to_filename(out_files) - - -def get_aparc_aseg(files): - """Return the aparc+aseg.mgz file""" - for name in files: - if 'aparc+aseg.mgz' in name: - return name - raise ValueError('aparc+aseg.mgz not found') - - -def extract_subrois(timeseries_file, label_file, indices): - """Extract voxel time courses for each subcortical roi index - - Parameters - ---------- - - timeseries_file: a 4D Nifti file - label_file: a 3D file containing rois in the same space/size of the 4D file - indices: a list of indices for ROIs to extract. - - Returns - ------- - out_file: a text file containing time courses for each voxel of each roi - The first four columns are: freesurfer index, i, j, k positions in the - label file - """ - from nipype.utils.filemanip import split_filename - import nibabel as nb - from nipype.utils import NUMPY_MMAP - import os - img = nb.load(timeseries_file, mmap=NUMPY_MMAP) - data = img.get_data() - roiimg = nb.load(label_file, mmap=NUMPY_MMAP) - rois = roiimg.get_data() - prefix = split_filename(timeseries_file)[1] - out_ts_file = os.path.join(os.getcwd(), '%s_subcortical_ts.txt' % prefix) - with open(out_ts_file, 'wt') as fp: - for fsindex in indices: - ijk = np.nonzero(rois == fsindex) - ts = data[ijk] - for i0, row in enumerate(ts): - fp.write('%d,%d,%d,%d,' % ( - fsindex, ijk[0][i0], ijk[1][i0], - ijk[2][i0]) + ','.join(['%.10f' % val - for val in row]) + '\n') - return out_ts_file - - -def combine_hemi(left, right): - """Combine left and right hemisphere time series into a single text file - """ - import os - import numpy as np - from nipype.utils import NUMPY_MMAP - lh_data = nb.load(left, mmap=NUMPY_MMAP).get_data() - rh_data = nb.load(right, mmap=NUMPY_MMAP).get_data() - - indices = np.vstack((1000000 + np.arange(0, lh_data.shape[0])[:, None], - 2000000 + np.arange(0, rh_data.shape[0])[:, None])) - all_data = np.hstack((indices, - np.vstack((lh_data.squeeze(), rh_data.squeeze())))) - filename = left.split('.')[1] + '_combined.txt' - np.savetxt( - filename, - all_data, - fmt=','.join(['%d'] + ['%.10f'] * (all_data.shape[1] - 1))) - return os.path.abspath(filename) - - -def create_reg_workflow(name='registration'): - """Create a FEAT preprocessing workflow together with freesurfer - - Parameters - ---------- - - name : name of workflow (default: 'registration') - - Inputs:: - - inputspec.source_files : files (filename or list of filenames to register) - inputspec.mean_image : reference image to use - inputspec.anatomical_image : anatomical image to coregister to - inputspec.target_image : registration target - - Outputs:: - - outputspec.func2anat_transform : FLIRT transform - outputspec.anat2target_transform : FLIRT+FNIRT transform - outputspec.transformed_files : transformed files in target space - outputspec.transformed_mean : mean image in target space - """ - - register = Workflow(name=name) - - inputnode = Node( - interface=IdentityInterface(fields=[ - 'source_files', 'mean_image', 'subject_id', 'subjects_dir', - 'target_image' - ]), - name='inputspec') - - outputnode = Node( - interface=IdentityInterface(fields=[ - 'func2anat_transform', 'out_reg_file', 'anat2target_transform', - 'transforms', 'transformed_mean', 'segmentation_files', - 'anat2target', 'aparc' - ]), - name='outputspec') - - # Get the subject's freesurfer source directory - fssource = Node(FreeSurferSource(), name='fssource') - fssource.run_without_submitting = True - register.connect(inputnode, 'subject_id', fssource, 'subject_id') - register.connect(inputnode, 'subjects_dir', fssource, 'subjects_dir') - - convert = Node(freesurfer.MRIConvert(out_type='nii'), name="convert") - register.connect(fssource, 'T1', convert, 'in_file') - - # Coregister the median to the surface - bbregister = Node(freesurfer.BBRegister(), name='bbregister') - bbregister.inputs.init = 'fsl' - bbregister.inputs.contrast_type = 't2' - bbregister.inputs.out_fsl_file = True - bbregister.inputs.epi_mask = True - register.connect(inputnode, 'subject_id', bbregister, 'subject_id') - register.connect(inputnode, 'mean_image', bbregister, 'source_file') - register.connect(inputnode, 'subjects_dir', bbregister, 'subjects_dir') - """ - Estimate the tissue classes from the anatomical image. But use spm's segment - as FSL appears to be breaking. - """ - - stripper = Node(fsl.BET(), name='stripper') - register.connect(convert, 'out_file', stripper, 'in_file') - fast = Node(fsl.FAST(), name='fast') - register.connect(stripper, 'out_file', fast, 'in_files') - """ - Binarize the segmentation - """ - - binarize = MapNode( - fsl.ImageMaths(op_string='-nan -thr 0.9 -ero -bin'), - iterfield=['in_file'], - name='binarize') - register.connect(fast, 'partial_volume_files', binarize, 'in_file') - """ - Apply inverse transform to take segmentations to functional space - """ - - applyxfm = MapNode( - freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), - iterfield=['target_file'], - name='inverse_transform') - register.connect(inputnode, 'subjects_dir', applyxfm, 'subjects_dir') - register.connect(bbregister, 'out_reg_file', applyxfm, 'reg_file') - register.connect(binarize, 'out_file', applyxfm, 'target_file') - register.connect(inputnode, 'mean_image', applyxfm, 'source_file') - """ - Apply inverse transform to aparc file - """ - - aparcxfm = Node( - freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), - name='aparc_inverse_transform') - register.connect(inputnode, 'subjects_dir', aparcxfm, 'subjects_dir') - register.connect(bbregister, 'out_reg_file', aparcxfm, 'reg_file') - register.connect(fssource, ('aparc_aseg', get_aparc_aseg), aparcxfm, - 'target_file') - register.connect(inputnode, 'mean_image', aparcxfm, 'source_file') - """ - Convert the BBRegister transformation to ANTS ITK format - """ - - convert2itk = Node(C3dAffineTool(), name='convert2itk') - convert2itk.inputs.fsl2ras = True - convert2itk.inputs.itk_transform = True - register.connect(bbregister, 'out_fsl_file', convert2itk, 'transform_file') - register.connect(inputnode, 'mean_image', convert2itk, 'source_file') - register.connect(stripper, 'out_file', convert2itk, 'reference_file') - """ - Compute registration between the subject's structural and MNI template - This is currently set to perform a very quick registration. However, the - registration can be made significantly more accurate for cortical - structures by increasing the number of iterations - All parameters are set using the example from: - #https://github.com/stnava/ANTs/blob/master/Scripts/newAntsExample.sh - """ - - reg = Node(ants.Registration(), name='antsRegister') - reg.inputs.output_transform_prefix = "output_" - reg.inputs.transforms = ['Rigid', 'Affine', 'SyN'] - reg.inputs.transform_parameters = [(0.1, ), (0.1, ), (0.2, 3.0, 0.0)] - reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[ - 100, 30, 20 - ]] - reg.inputs.dimension = 3 - reg.inputs.write_composite_transform = True - reg.inputs.collapse_output_transforms = True - reg.inputs.initial_moving_transform_com = True - reg.inputs.metric = ['Mattes'] * 2 + [['Mattes', 'CC']] - reg.inputs.metric_weight = [1] * 2 + [[0.5, 0.5]] - reg.inputs.radius_or_number_of_bins = [32] * 2 + [[32, 4]] - reg.inputs.sampling_strategy = ['Regular'] * 2 + [[None, None]] - reg.inputs.sampling_percentage = [0.3] * 2 + [[None, None]] - reg.inputs.convergence_threshold = [1.e-8] * 2 + [-0.01] - reg.inputs.convergence_window_size = [20] * 2 + [5] - reg.inputs.smoothing_sigmas = [[4, 2, 1]] * 2 + [[1, 0.5, 0]] - reg.inputs.sigma_units = ['vox'] * 3 - reg.inputs.shrink_factors = [[3, 2, 1]] * 2 + [[4, 2, 1]] - reg.inputs.use_estimate_learning_rate_once = [True] * 3 - reg.inputs.use_histogram_matching = [False] * 2 + [True] - reg.inputs.winsorize_lower_quantile = 0.005 - reg.inputs.winsorize_upper_quantile = 0.995 - reg.inputs.float = True - reg.inputs.output_warped_image = 'output_warped_image.nii.gz' - reg.inputs.num_threads = 4 - reg.plugin_args = {'qsub_args': '-l nodes=1:ppn=4'} - register.connect(stripper, 'out_file', reg, 'moving_image') - register.connect(inputnode, 'target_image', reg, 'fixed_image') - """ - Concatenate the affine and ants transforms into a list - """ - - merge = Node(Merge(2), iterfield=['in2'], name='mergexfm') - register.connect(convert2itk, 'itk_transform', merge, 'in2') - register.connect(reg, 'composite_transform', merge, 'in1') - """ - Transform the mean image. First to anatomical and then to target - """ - - warpmean = Node(ants.ApplyTransforms(), name='warpmean') - warpmean.inputs.input_image_type = 3 - warpmean.inputs.interpolation = 'Linear' - warpmean.inputs.invert_transform_flags = [False, False] - warpmean.terminal_output = 'file' - warpmean.inputs.args = '--float' - warpmean.inputs.num_threads = 4 - - register.connect(inputnode, 'target_image', warpmean, 'reference_image') - register.connect(inputnode, 'mean_image', warpmean, 'input_image') - register.connect(merge, 'out', warpmean, 'transforms') - """ - Assign all the output files - """ - - register.connect(reg, 'warped_image', outputnode, 'anat2target') - register.connect(warpmean, 'output_image', outputnode, 'transformed_mean') - register.connect(applyxfm, 'transformed_file', outputnode, - 'segmentation_files') - register.connect(aparcxfm, 'transformed_file', outputnode, 'aparc') - register.connect(bbregister, 'out_fsl_file', outputnode, - 'func2anat_transform') - register.connect(bbregister, 'out_reg_file', outputnode, 'out_reg_file') - register.connect(reg, 'composite_transform', outputnode, - 'anat2target_transform') - register.connect(merge, 'out', outputnode, 'transforms') - - return register - - -""" -Creates the main preprocessing workflow -""" - - -def create_workflow(files, - target_file, - subject_id, - TR, - slice_times, - norm_threshold=1, - num_components=5, - vol_fwhm=None, - surf_fwhm=None, - lowpass_freq=-1, - highpass_freq=-1, - subjects_dir=None, - sink_directory=os.getcwd(), - target_subject=['fsaverage3', 'fsaverage4'], - name='resting'): - - wf = Workflow(name=name) - - # Rename files in case they are named identically - name_unique = MapNode( - Rename(format_string='rest_%(run)02d'), - iterfield=['in_file', 'run'], - name='rename') - name_unique.inputs.keep_ext = True - name_unique.inputs.run = list(range(1, len(files) + 1)) - name_unique.inputs.in_file = files - - realign = Node(interface=spm.Realign(), name="realign") - realign.inputs.jobtype = 'estwrite' - - num_slices = len(slice_times) - slice_timing = Node(interface=spm.SliceTiming(), name="slice_timing") - slice_timing.inputs.num_slices = num_slices - slice_timing.inputs.time_repetition = TR - slice_timing.inputs.time_acquisition = TR - TR / float(num_slices) - slice_timing.inputs.slice_order = (np.argsort(slice_times) + 1).tolist() - slice_timing.inputs.ref_slice = int(num_slices / 2) - - # Comute TSNR on realigned data regressing polynomials upto order 2 - tsnr = MapNode(TSNR(regress_poly=2), iterfield=['in_file'], name='tsnr') - wf.connect(slice_timing, 'timecorrected_files', tsnr, 'in_file') - - # Compute the median image across runs - calc_median = Node(CalculateMedian(), name='median') - wf.connect(tsnr, 'detrended_file', calc_median, 'in_files') - """Segment and Register - """ - - registration = create_reg_workflow(name='registration') - wf.connect(calc_median, 'median_file', registration, - 'inputspec.mean_image') - registration.inputs.inputspec.subject_id = subject_id - registration.inputs.inputspec.subjects_dir = subjects_dir - registration.inputs.inputspec.target_image = target_file - """Use :class:`nipype.algorithms.rapidart` to determine which of the - images in the functional series are outliers based on deviations in - intensity or movement. - """ - - art = Node(interface=ArtifactDetect(), name="art") - art.inputs.use_differences = [True, True] - art.inputs.use_norm = True - art.inputs.norm_threshold = norm_threshold - art.inputs.zintensity_threshold = 9 - art.inputs.mask_type = 'spm_global' - art.inputs.parameter_source = 'SPM' - """Here we are connecting all the nodes together. Notice that we add the merge node only if you choose - to use 4D. Also `get_vox_dims` function is passed along the input volume of normalise to set the optimal - voxel sizes. - """ - - wf.connect([ - (name_unique, realign, [('out_file', 'in_files')]), - (realign, slice_timing, [('realigned_files', 'in_files')]), - (slice_timing, art, [('timecorrected_files', 'realigned_files')]), - (realign, art, [('realignment_parameters', 'realignment_parameters')]), - ]) - - def selectindex(files, idx): - import numpy as np - from nipype.utils.filemanip import filename_to_list, list_to_filename - return list_to_filename( - np.array(filename_to_list(files))[idx].tolist()) - - mask = Node(fsl.BET(), name='getmask') - mask.inputs.mask = True - wf.connect(calc_median, 'median_file', mask, 'in_file') - - # get segmentation in normalized functional space - - def merge_files(in1, in2): - out_files = filename_to_list(in1) - out_files.extend(filename_to_list(in2)) - return out_files - - # filter some noise - - # Compute motion regressors - motreg = Node( - Function( - input_names=['motion_params', 'order', 'derivatives'], - output_names=['out_files'], - function=motion_regressors, - imports=imports), - name='getmotionregress') - wf.connect(realign, 'realignment_parameters', motreg, 'motion_params') - - # Create a filter to remove motion and art confounds - createfilter1 = Node( - Function( - input_names=[ - 'motion_params', 'comp_norm', 'outliers', 'detrend_poly' - ], - output_names=['out_files'], - function=build_filter1, - imports=imports), - name='makemotionbasedfilter') - createfilter1.inputs.detrend_poly = 2 - wf.connect(motreg, 'out_files', createfilter1, 'motion_params') - wf.connect(art, 'norm_files', createfilter1, 'comp_norm') - wf.connect(art, 'outlier_files', createfilter1, 'outliers') - - filter1 = MapNode( - fsl.GLM( - out_f_name='F_mcart.nii', out_pf_name='pF_mcart.nii', demean=True), - iterfield=['in_file', 'design', 'out_res_name'], - name='filtermotion') - - wf.connect(slice_timing, 'timecorrected_files', filter1, 'in_file') - wf.connect(slice_timing, ('timecorrected_files', rename, '_filtermotart'), - filter1, 'out_res_name') - wf.connect(createfilter1, 'out_files', filter1, 'design') - - createfilter2 = MapNode( - Function( - input_names=[ - 'realigned_file', 'mask_file', 'num_components', - 'extra_regressors' - ], - output_names=['out_files'], - function=extract_noise_components, - imports=imports), - iterfield=['realigned_file', 'extra_regressors'], - name='makecompcorrfilter') - createfilter2.inputs.num_components = num_components - - wf.connect(createfilter1, 'out_files', createfilter2, 'extra_regressors') - wf.connect(filter1, 'out_res', createfilter2, 'realigned_file') - wf.connect(registration, - ('outputspec.segmentation_files', selectindex, [0, 2]), - createfilter2, 'mask_file') - - filter2 = MapNode( - fsl.GLM(out_f_name='F.nii', out_pf_name='pF.nii', demean=True), - iterfield=['in_file', 'design', 'out_res_name'], - name='filter_noise_nosmooth') - wf.connect(filter1, 'out_res', filter2, 'in_file') - wf.connect(filter1, ('out_res', rename, '_cleaned'), filter2, - 'out_res_name') - wf.connect(createfilter2, 'out_files', filter2, 'design') - wf.connect(mask, 'mask_file', filter2, 'mask') - - bandpass = Node( - Function( - input_names=['files', 'lowpass_freq', 'highpass_freq', 'fs'], - output_names=['out_files'], - function=bandpass_filter, - imports=imports), - name='bandpass_unsmooth') - bandpass.inputs.fs = 1. / TR - bandpass.inputs.highpass_freq = highpass_freq - bandpass.inputs.lowpass_freq = lowpass_freq - wf.connect(filter2, 'out_res', bandpass, 'files') - """Smooth the functional data using - :class:`nipype.interfaces.spm.Smooth`. - """ - - smooth = Node(interface=spm.Smooth(), name="smooth") - smooth.inputs.fwhm = vol_fwhm - - wf.connect(bandpass, 'out_files', smooth, 'in_files') - - collector = Node(Merge(2), name='collect_streams') - wf.connect(smooth, 'smoothed_files', collector, 'in1') - wf.connect(bandpass, 'out_files', collector, 'in2') - """ - Transform the remaining images. First to anatomical and then to target - """ - - warpall = MapNode( - ants.ApplyTransforms(), iterfield=['input_image'], name='warpall') - warpall.inputs.input_image_type = 3 - warpall.inputs.interpolation = 'Linear' - warpall.inputs.invert_transform_flags = [False, False] - warpall.terminal_output = 'file' - warpall.inputs.reference_image = target_file - warpall.inputs.args = '--float' - warpall.inputs.num_threads = 1 - - # transform to target - wf.connect(collector, 'out', warpall, 'input_image') - wf.connect(registration, 'outputspec.transforms', warpall, 'transforms') - - mask_target = Node(fsl.ImageMaths(op_string='-bin'), name='target_mask') - - wf.connect(registration, 'outputspec.anat2target', mask_target, 'in_file') - - maskts = MapNode(fsl.ApplyMask(), iterfield=['in_file'], name='ts_masker') - wf.connect(warpall, 'output_image', maskts, 'in_file') - wf.connect(mask_target, 'out_file', maskts, 'mask_file') - - # map to surface - # extract aparc+aseg ROIs - # extract subcortical ROIs - # extract target space ROIs - # combine subcortical and cortical rois into a single cifti file - - ####### - # Convert aparc to subject functional space - - # Sample the average time series in aparc ROIs - sampleaparc = MapNode( - freesurfer.SegStats(default_color_table=True), - iterfield=['in_file', 'summary_file', 'avgwf_txt_file'], - name='aparc_ts') - sampleaparc.inputs.segment_id = ( - [8] + list(range(10, 14)) + [17, 18, 26, 47] + list(range(49, 55)) + - [58] + list(range(1001, 1036)) + list(range(2001, 2036))) - - wf.connect(registration, 'outputspec.aparc', sampleaparc, - 'segmentation_file') - wf.connect(collector, 'out', sampleaparc, 'in_file') - - def get_names(files, suffix): - """Generate appropriate names for output files - """ - from nipype.utils.filemanip import (split_filename, filename_to_list, - list_to_filename) - out_names = [] - for filename in files: - _, name, _ = split_filename(filename) - out_names.append(name + suffix) - return list_to_filename(out_names) - - wf.connect(collector, ('out', get_names, '_avgwf.txt'), sampleaparc, - 'avgwf_txt_file') - wf.connect(collector, ('out', get_names, '_summary.stats'), sampleaparc, - 'summary_file') - - # Sample the time series onto the surface of the target surface. Performs - # sampling into left and right hemisphere - target = Node(IdentityInterface(fields=['target_subject']), name='target') - target.iterables = ('target_subject', filename_to_list(target_subject)) - - samplerlh = MapNode( - freesurfer.SampleToSurface(), - iterfield=['source_file'], - name='sampler_lh') - samplerlh.inputs.sampling_method = "average" - samplerlh.inputs.sampling_range = (0.1, 0.9, 0.1) - samplerlh.inputs.sampling_units = "frac" - samplerlh.inputs.interp_method = "trilinear" - samplerlh.inputs.smooth_surf = surf_fwhm - # samplerlh.inputs.cortex_mask = True - samplerlh.inputs.out_type = 'niigz' - samplerlh.inputs.subjects_dir = subjects_dir - - samplerrh = samplerlh.clone('sampler_rh') - - samplerlh.inputs.hemi = 'lh' - wf.connect(collector, 'out', samplerlh, 'source_file') - wf.connect(registration, 'outputspec.out_reg_file', samplerlh, 'reg_file') - wf.connect(target, 'target_subject', samplerlh, 'target_subject') - - samplerrh.set_input('hemi', 'rh') - wf.connect(collector, 'out', samplerrh, 'source_file') - wf.connect(registration, 'outputspec.out_reg_file', samplerrh, 'reg_file') - wf.connect(target, 'target_subject', samplerrh, 'target_subject') - - # Combine left and right hemisphere to text file - combiner = MapNode( - Function( - input_names=['left', 'right'], - output_names=['out_file'], - function=combine_hemi, - imports=imports), - iterfield=['left', 'right'], - name="combiner") - wf.connect(samplerlh, 'out_file', combiner, 'left') - wf.connect(samplerrh, 'out_file', combiner, 'right') - - # Sample the time series file for each subcortical roi - ts2txt = MapNode( - Function( - input_names=['timeseries_file', 'label_file', 'indices'], - output_names=['out_file'], - function=extract_subrois, - imports=imports), - iterfield=['timeseries_file'], - name='getsubcortts') - ts2txt.inputs.indices = [8] + list(range(10, 14)) + [17, 18, 26, 47] +\ - list(range(49, 55)) + [58] - ts2txt.inputs.label_file = \ - os.path.abspath(('OASIS-TRT-20_jointfusion_DKT31_CMA_labels_in_MNI152_' - '2mm_v2.nii.gz')) - wf.connect(maskts, 'out_file', ts2txt, 'timeseries_file') - - ###### - - substitutions = [('_target_subject_', - ''), ('_filtermotart_cleaned_bp_trans_masked', ''), - ('_filtermotart_cleaned_bp', '')] - regex_subs = [ - ('_ts_masker.*/sar', '/smooth/'), - ('_ts_masker.*/ar', '/unsmooth/'), - ('_combiner.*/sar', '/smooth/'), - ('_combiner.*/ar', '/unsmooth/'), - ('_aparc_ts.*/sar', '/smooth/'), - ('_aparc_ts.*/ar', '/unsmooth/'), - ('_getsubcortts.*/sar', '/smooth/'), - ('_getsubcortts.*/ar', '/unsmooth/'), - ('series/sar', 'series/smooth/'), - ('series/ar', 'series/unsmooth/'), - ('_inverse_transform./', ''), - ] - # Save the relevant data into an output directory - datasink = Node(interface=DataSink(), name="datasink") - datasink.inputs.base_directory = sink_directory - datasink.inputs.container = subject_id - datasink.inputs.substitutions = substitutions - datasink.inputs.regexp_substitutions = regex_subs # (r'(/_.*(\d+/))', r'/run\2') - wf.connect(realign, 'realignment_parameters', datasink, - 'resting.qa.motion') - wf.connect(art, 'norm_files', datasink, 'resting.qa.art.@norm') - wf.connect(art, 'intensity_files', datasink, 'resting.qa.art.@intensity') - wf.connect(art, 'outlier_files', datasink, 'resting.qa.art.@outlier_files') - wf.connect(registration, 'outputspec.segmentation_files', datasink, - 'resting.mask_files') - wf.connect(registration, 'outputspec.anat2target', datasink, - 'resting.qa.ants') - wf.connect(mask, 'mask_file', datasink, 'resting.mask_files.@brainmask') - wf.connect(mask_target, 'out_file', datasink, 'resting.mask_files.target') - wf.connect(filter1, 'out_f', datasink, 'resting.qa.compmaps.@mc_F') - wf.connect(filter1, 'out_pf', datasink, 'resting.qa.compmaps.@mc_pF') - wf.connect(filter2, 'out_f', datasink, 'resting.qa.compmaps') - wf.connect(filter2, 'out_pf', datasink, 'resting.qa.compmaps.@p') - wf.connect(bandpass, 'out_files', datasink, - 'resting.timeseries.@bandpassed') - wf.connect(smooth, 'smoothed_files', datasink, - 'resting.timeseries.@smoothed') - wf.connect(createfilter1, 'out_files', datasink, - 'resting.regress.@regressors') - wf.connect(createfilter2, 'out_files', datasink, - 'resting.regress.@compcorr') - wf.connect(maskts, 'out_file', datasink, 'resting.timeseries.target') - wf.connect(sampleaparc, 'summary_file', datasink, - 'resting.parcellations.aparc') - wf.connect(sampleaparc, 'avgwf_txt_file', datasink, - 'resting.parcellations.aparc.@avgwf') - wf.connect(ts2txt, 'out_file', datasink, - 'resting.parcellations.grayo.@subcortical') - - datasink2 = Node(interface=DataSink(), name="datasink2") - datasink2.inputs.base_directory = sink_directory - datasink2.inputs.container = subject_id - datasink2.inputs.substitutions = substitutions - datasink2.inputs.regexp_substitutions = regex_subs # (r'(/_.*(\d+/))', r'/run\2') - wf.connect(combiner, 'out_file', datasink2, - 'resting.parcellations.grayo.@surface') - return wf - - -""" -Creates the full workflow including getting information from dicom files -""" - - -def create_resting_workflow(args, name=None): - TR = args.TR - slice_times = args.slice_times - if args.dicom_file: - TR, slice_times, slice_thickness = get_info(args.dicom_file) - slice_times = (np.array(slice_times) / 1000.).tolist() - if name is None: - name = 'resting_' + args.subject_id - kwargs = dict( - files=[os.path.abspath(filename) for filename in args.files], - target_file=os.path.abspath(args.target_file), - subject_id=args.subject_id, - TR=TR, - slice_times=slice_times, - vol_fwhm=args.vol_fwhm, - surf_fwhm=args.surf_fwhm, - norm_threshold=2., - subjects_dir=os.path.abspath(args.fsdir), - target_subject=args.target_surfs, - lowpass_freq=args.lowpass_freq, - highpass_freq=args.highpass_freq, - sink_directory=os.path.abspath(args.sink), - name=name) - wf = create_workflow(**kwargs) - return wf - - -if __name__ == "__main__": - from argparse import ArgumentParser, RawTextHelpFormatter - defstr = ' (default %(default)s)' - parser = ArgumentParser( - description=__doc__, formatter_class=RawTextHelpFormatter) - parser.add_argument( - "-d", - "--dicom_file", - dest="dicom_file", - help="an example dicom file from the resting series") - parser.add_argument( - "-f", - "--files", - dest="files", - nargs="+", - help="4d nifti files for resting state", - required=True) - parser.add_argument( - "-t", - "--target", - dest="target_file", - help=("Target in MNI space. Best to use the MindBoggle " - "template - " - "OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz"), - required=True) - parser.add_argument( - "-s", - "--subject_id", - dest="subject_id", - help="FreeSurfer subject id", - required=True) - parser.add_argument( - "--subjects_dir", - dest="fsdir", - help="FreeSurfer subject directory", - required=True) - parser.add_argument( - "--target_surfaces", - dest="target_surfs", - nargs="+", - default=['fsaverage5'], - help="FreeSurfer target surfaces" + defstr) - parser.add_argument( - "--TR", - dest="TR", - default=None, - type=float, - help="TR if dicom not provided in seconds") - parser.add_argument( - "--slice_times", - dest="slice_times", - nargs="+", - type=float, - help="Slice onset times in seconds") - parser.add_argument( - '--vol_fwhm', - default=6., - dest='vol_fwhm', - type=float, - help="Spatial FWHM" + defstr) - parser.add_argument( - '--surf_fwhm', - default=15., - dest='surf_fwhm', - type=float, - help="Spatial FWHM" + defstr) - parser.add_argument( - "-l", - "--lowpass_freq", - dest="lowpass_freq", - default=0.1, - type=float, - help="Low pass frequency (Hz)" + defstr) - parser.add_argument( - "-u", - "--highpass_freq", - dest="highpass_freq", - default=0.01, - type=float, - help="High pass frequency (Hz)" + defstr) - parser.add_argument( - "-o", - "--output_dir", - dest="sink", - help="Output directory base", - required=True) - parser.add_argument( - "-w", "--work_dir", dest="work_dir", help="Output directory base") - parser.add_argument( - "-p", - "--plugin", - dest="plugin", - default='Linear', - help="Plugin to use") - parser.add_argument( - "--plugin_args", dest="plugin_args", help="Plugin arguments") - args = parser.parse_args() - - wf = create_resting_workflow(args) - - if args.work_dir: - work_dir = os.path.abspath(args.work_dir) - else: - work_dir = os.getcwd() - - wf.base_dir = work_dir - if args.plugin_args: - wf.run(args.plugin, plugin_args=eval(args.plugin_args)) - else: - wf.run(args.plugin) diff --git a/examples/rsfmri_vol_surface_preprocessing_nipy.py b/examples/rsfmri_vol_surface_preprocessing_nipy.py deleted file mode 100644 index d3d9887cc6..0000000000 --- a/examples/rsfmri_vol_surface_preprocessing_nipy.py +++ /dev/null @@ -1,1084 +0,0 @@ -#!/usr/bin/env python -""" -===================================== -rsfMRI: ANTS, FS, FSL, NiPy, aCompCor -===================================== - - -A preprocessing workflow for Siemens resting state data. - -This workflow makes use of: - -- ANTS -- FreeSurfer -- FSL -- NiPy -- CompCor - -For example:: - - python rsfmri_preprocessing.py -d /data/12345-34-1.dcm -f /data/Resting.nii - -s subj001 -o output -p PBS --plugin_args "dict(qsub_args='-q many')" - -or:: - - python rsfmri_vol_surface_preprocessing.py -f SUB_1024011/E?/func/rest.nii - -t OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz --TR 2 -s SUB_1024011 - --subjects_dir fsdata --slice_times 0 17 1 18 2 19 3 20 4 21 5 22 6 23 - 7 24 8 25 9 26 10 27 11 28 12 29 13 30 14 31 15 32 16 -o . - -This workflow takes resting timeseries and a Siemens dicom file corresponding -to it and preprocesses it to produce timeseries coordinates or grayordinates. - -For non-Siemens dicoms, provide slice times instead, since the dicom extractor is not guaranteed to work. - -This workflow also requires 2mm subcortical atlas and templates that are -available from: - -http://mindboggle.info/data.html - -specifically the 2mm versions of: - - * `Joint Fusion Atlas `_ - * `MNI template `_ - -Import necessary modules from nipype. -""" - -from __future__ import division, unicode_literals -from builtins import open, range, str - -import os - -from nipype.interfaces.base import CommandLine -CommandLine.set_default_terminal_output('allatonce') - -# https://github.com/moloney/dcmstack -from dcmstack.extract import default_extractor -# pip install pydicom -from dicom import read_file - -from nipype.interfaces import (fsl, Function, ants, freesurfer, nipy) -from nipype.interfaces.c3 import C3dAffineTool - -fsl.FSLCommand.set_default_output_type('NIFTI_GZ') - -from nipype import Workflow, Node, MapNode - -from nipype.algorithms.rapidart import ArtifactDetect -from nipype.algorithms.misc import TSNR, CalculateMedian -from nipype.algorithms.confounds import ACompCor -from nipype.interfaces.utility import Rename, Merge, IdentityInterface -from nipype.utils.filemanip import filename_to_list -from nipype.interfaces.io import DataSink, FreeSurferSource -import nipype.interfaces.freesurfer as fs - -import numpy as np -import scipy as sp -import nibabel as nb -from nipype.utils.config import NUMPY_MMAP - -""" -A list of modules and functions to import inside of nodes -""" - -imports = [ - 'import os', - 'import nibabel as nb', - 'import numpy as np', - 'import scipy as sp', - 'from nipype.utils.filemanip import filename_to_list, list_to_filename, split_filename', - 'from scipy.special import legendre' - ] - -""" -Define utility functions for use in workflow nodes -""" - - -def get_info(dicom_files): - """Given a Siemens dicom file return metadata - - Returns - ------- - RepetitionTime - Slice Acquisition Times - Spacing between slices - """ - meta = default_extractor( - read_file( - filename_to_list(dicom_files)[0], - stop_before_pixels=True, - force=True)) - return (meta['RepetitionTime'] / 1000., meta['CsaImage.MosaicRefAcqTimes'], - meta['SpacingBetweenSlices']) - - -def median(in_files): - """Computes an average of the median of each realigned timeseries - - Parameters - ---------- - - in_files: one or more realigned Nifti 4D time series - - Returns - ------- - - out_file: a 3D Nifti file - """ - average = None - for idx, filename in enumerate(filename_to_list(in_files)): - img = nb.load(filename, mmap=NUMPY_MMAP) - data = np.median(img.get_data(), axis=3) - if average is None: - average = data - else: - average = average + data - median_img = nb.Nifti1Image(average / float(idx + 1), img.affine, - img.header) - filename = os.path.join(os.getcwd(), 'median.nii.gz') - median_img.to_filename(filename) - return filename - - -def bandpass_filter(files, lowpass_freq, highpass_freq, fs): - """Bandpass filter the input files - - Parameters - ---------- - files: list of 4d nifti files - lowpass_freq: cutoff frequency for the low pass filter (in Hz) - highpass_freq: cutoff frequency for the high pass filter (in Hz) - fs: sampling rate (in Hz) - """ - out_files = [] - for filename in filename_to_list(files): - path, name, ext = split_filename(filename) - out_file = os.path.join(os.getcwd(), name + '_bp' + ext) - img = nb.load(filename, mmap=NUMPY_MMAP) - timepoints = img.shape[-1] - F = np.zeros((timepoints)) - lowidx = int(timepoints / 2) + 1 - if lowpass_freq > 0: - lowidx = np.round(float(lowpass_freq) / fs * timepoints) - highidx = 0 - if highpass_freq > 0: - highidx = np.round(float(highpass_freq) / fs * timepoints) - F[highidx:lowidx] = 1 - F = ((F + F[::-1]) > 0).astype(int) - data = img.get_data() - if np.all(F == 1): - filtered_data = data - else: - filtered_data = np.real(np.fft.ifftn(np.fft.fftn(data) * F)) - img_out = nb.Nifti1Image(filtered_data, img.affine, img.header) - img_out.to_filename(out_file) - out_files.append(out_file) - return list_to_filename(out_files) - - -def motion_regressors(motion_params, order=0, derivatives=1): - """Compute motion regressors upto given order and derivative - - motion + d(motion)/dt + d2(motion)/dt2 (linear + quadratic) - """ - out_files = [] - for idx, filename in enumerate(filename_to_list(motion_params)): - params = np.genfromtxt(filename) - out_params = params - for d in range(1, derivatives + 1): - cparams = np.vstack((np.repeat(params[0, :][None, :], d, axis=0), - params)) - out_params = np.hstack((out_params, np.diff(cparams, d, axis=0))) - out_params2 = out_params - for i in range(2, order + 1): - out_params2 = np.hstack((out_params2, np.power(out_params, i))) - filename = os.path.join(os.getcwd(), "motion_regressor%02d.txt" % idx) - np.savetxt(filename, out_params2, fmt=b"%.10f") - out_files.append(filename) - return out_files - - -def build_filter1(motion_params, comp_norm, outliers, detrend_poly=None): - """Builds a regressor set comprisong motion parameters, composite norm and - outliers - - The outliers are added as a single time point column for each outlier - - - Parameters - ---------- - - motion_params: a text file containing motion parameters and its derivatives - comp_norm: a text file containing the composite norm - outliers: a text file containing 0-based outlier indices - detrend_poly: number of polynomials to add to detrend - - Returns - ------- - components_file: a text file containing all the regressors - """ - out_files = [] - for idx, filename in enumerate(filename_to_list(motion_params)): - params = np.genfromtxt(filename) - norm_val = np.genfromtxt(filename_to_list(comp_norm)[idx]) - out_params = np.hstack((params, norm_val[:, None])) - try: - outlier_val = np.genfromtxt(filename_to_list(outliers)[idx]) - except IOError: - outlier_val = np.empty((0)) - for index in np.atleast_1d(outlier_val): - outlier_vector = np.zeros((out_params.shape[0], 1)) - outlier_vector[index] = 1 - out_params = np.hstack((out_params, outlier_vector)) - if detrend_poly: - timepoints = out_params.shape[0] - X = np.empty((timepoints, 0)) - for i in range(detrend_poly): - X = np.hstack((X, legendre(i + 1)(np.linspace( - -1, 1, timepoints))[:, None])) - out_params = np.hstack((out_params, X)) - filename = os.path.join(os.getcwd(), "filter_regressor%02d.txt" % idx) - np.savetxt(filename, out_params, fmt=b"%.10f") - out_files.append(filename) - return out_files - - -def rename(in_files, suffix=None): - from nipype.utils.filemanip import (filename_to_list, split_filename, - list_to_filename) - out_files = [] - for idx, filename in enumerate(filename_to_list(in_files)): - _, name, ext = split_filename(filename) - if suffix is None: - out_files.append(name + ('_%03d' % idx) + ext) - else: - out_files.append(name + suffix + ext) - return list_to_filename(out_files) - - -def get_aparc_aseg(files): - """Return the aparc+aseg.mgz file""" - for name in files: - if 'aparc+aseg.mgz' in name: - return name - raise ValueError('aparc+aseg.mgz not found') - - -def extract_subrois(timeseries_file, label_file, indices): - """Extract voxel time courses for each subcortical roi index - - Parameters - ---------- - - timeseries_file: a 4D Nifti file - label_file: a 3D file containing rois in the same space/size of the 4D file - indices: a list of indices for ROIs to extract. - - Returns - ------- - out_file: a text file containing time courses for each voxel of each roi - The first four columns are: freesurfer index, i, j, k positions in the - label file - """ - img = nb.load(timeseries_file, mmap=NUMPY_MMAP) - data = img.get_data() - roiimg = nb.load(label_file, mmap=NUMPY_MMAP) - rois = roiimg.get_data() - prefix = split_filename(timeseries_file)[1] - out_ts_file = os.path.join(os.getcwd(), '%s_subcortical_ts.txt' % prefix) - with open(out_ts_file, 'wt') as fp: - for fsindex in indices: - ijk = np.nonzero(rois == fsindex) - ts = data[ijk] - for i0, row in enumerate(ts): - fp.write('%d,%d,%d,%d,' % ( - fsindex, ijk[0][i0], ijk[1][i0], - ijk[2][i0]) + ','.join(['%.10f' % val - for val in row]) + '\n') - return out_ts_file - - -def combine_hemi(left, right): - """Combine left and right hemisphere time series into a single text file - """ - lh_data = nb.load(left, mmap=NUMPY_MMAP).get_data() - rh_data = nb.load(right, mmap=NUMPY_MMAP).get_data() - - indices = np.vstack((1000000 + np.arange(0, lh_data.shape[0])[:, None], - 2000000 + np.arange(0, rh_data.shape[0])[:, None])) - all_data = np.hstack((indices, - np.vstack((lh_data.squeeze(), rh_data.squeeze())))) - filename = left.split('.')[1] + '_combined.txt' - np.savetxt( - filename, - all_data, - fmt=','.join(['%d'] + ['%.10f'] * (all_data.shape[1] - 1))) - return os.path.abspath(filename) - -""" -Create a Registration Workflow -""" - - -def create_reg_workflow(name='registration'): - """Create a FEAT preprocessing workflow together with freesurfer - - Parameters - ---------- - name : name of workflow (default: 'registration') - - Inputs: - - inputspec.source_files : files (filename or list of filenames to register) - inputspec.mean_image : reference image to use - inputspec.anatomical_image : anatomical image to coregister to - inputspec.target_image : registration target - - Outputs: - - outputspec.func2anat_transform : FLIRT transform - outputspec.anat2target_transform : FLIRT+FNIRT transform - outputspec.transformed_files : transformed files in target space - outputspec.transformed_mean : mean image in target space - - Example - ------- - See code below - """ - - register = Workflow(name=name) - - inputnode = Node( - interface=IdentityInterface(fields=[ - 'source_files', 'mean_image', 'subject_id', 'subjects_dir', - 'target_image' - ]), - name='inputspec') - - outputnode = Node( - interface=IdentityInterface(fields=[ - 'func2anat_transform', 'out_reg_file', 'anat2target_transform', - 'transforms', 'transformed_mean', 'segmentation_files', - 'anat2target', 'aparc', 'min_cost_file' - ]), - name='outputspec') - - # Get the subject's freesurfer source directory - fssource = Node(FreeSurferSource(), name='fssource') - fssource.run_without_submitting = True - register.connect(inputnode, 'subject_id', fssource, 'subject_id') - register.connect(inputnode, 'subjects_dir', fssource, 'subjects_dir') - - convert = Node(freesurfer.MRIConvert(out_type='nii'), name="convert") - register.connect(fssource, 'T1', convert, 'in_file') - - # Coregister the median to the surface - bbregister = Node(freesurfer.BBRegister(), name='bbregister') - bbregister.inputs.init = 'fsl' - bbregister.inputs.contrast_type = 't2' - bbregister.inputs.out_fsl_file = True - bbregister.inputs.epi_mask = True - register.connect(inputnode, 'subject_id', bbregister, 'subject_id') - register.connect(inputnode, 'mean_image', bbregister, 'source_file') - register.connect(inputnode, 'subjects_dir', bbregister, 'subjects_dir') - """ - Estimate the tissue classes from the anatomical image. But use aparc+aseg's brain mask - """ - - binarize = Node( - fs.Binarize(min=0.5, out_type="nii.gz", dilate=1), - name="binarize_aparc") - register.connect(fssource, ("aparc_aseg", get_aparc_aseg), binarize, - "in_file") - stripper = Node(fsl.ApplyMask(), name='stripper') - register.connect(binarize, "binary_file", stripper, "mask_file") - register.connect(convert, 'out_file', stripper, 'in_file') - - fast = Node(fsl.FAST(), name='fast') - register.connect(stripper, 'out_file', fast, 'in_files') - """ - Binarize the segmentation - """ - - binarize = MapNode( - fsl.ImageMaths(op_string='-nan -thr 0.9 -ero -bin'), - iterfield=['in_file'], - name='binarize') - register.connect(fast, 'partial_volume_files', binarize, 'in_file') - """ - Apply inverse transform to take segmentations to functional space - """ - - applyxfm = MapNode( - freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), - iterfield=['target_file'], - name='inverse_transform') - register.connect(inputnode, 'subjects_dir', applyxfm, 'subjects_dir') - register.connect(bbregister, 'out_reg_file', applyxfm, 'reg_file') - register.connect(binarize, 'out_file', applyxfm, 'target_file') - register.connect(inputnode, 'mean_image', applyxfm, 'source_file') - """ - Apply inverse transform to aparc file - """ - - aparcxfm = Node( - freesurfer.ApplyVolTransform(inverse=True, interp='nearest'), - name='aparc_inverse_transform') - register.connect(inputnode, 'subjects_dir', aparcxfm, 'subjects_dir') - register.connect(bbregister, 'out_reg_file', aparcxfm, 'reg_file') - register.connect(fssource, ('aparc_aseg', get_aparc_aseg), aparcxfm, - 'target_file') - register.connect(inputnode, 'mean_image', aparcxfm, 'source_file') - """ - Convert the BBRegister transformation to ANTS ITK format - """ - - convert2itk = Node(C3dAffineTool(), name='convert2itk') - convert2itk.inputs.fsl2ras = True - convert2itk.inputs.itk_transform = True - register.connect(bbregister, 'out_fsl_file', convert2itk, 'transform_file') - register.connect(inputnode, 'mean_image', convert2itk, 'source_file') - register.connect(stripper, 'out_file', convert2itk, 'reference_file') - """ - Compute registration between the subject's structural and MNI template - - * All parameters are set using the example from: - #https://github.com/stnava/ANTs/blob/master/Scripts/newAntsExample.sh - * This is currently set to perform a very quick registration. However, - the registration can be made significantly more accurate for cortical - structures by increasing the number of iterations. - """ - - reg = Node(ants.Registration(), name='antsRegister') - reg.inputs.output_transform_prefix = "output_" - reg.inputs.transforms = ['Rigid', 'Affine', 'SyN'] - reg.inputs.transform_parameters = [(0.1, ), (0.1, ), (0.2, 3.0, 0.0)] - reg.inputs.number_of_iterations = [[10000, 11110, 11110]] * 2 + [[ - 100, 30, 20 - ]] - reg.inputs.dimension = 3 - reg.inputs.write_composite_transform = True - reg.inputs.collapse_output_transforms = True - reg.inputs.initial_moving_transform_com = True - reg.inputs.metric = ['Mattes'] * 2 + [['Mattes', 'CC']] - reg.inputs.metric_weight = [1] * 2 + [[0.5, 0.5]] - reg.inputs.radius_or_number_of_bins = [32] * 2 + [[32, 4]] - reg.inputs.sampling_strategy = ['Regular'] * 2 + [[None, None]] - reg.inputs.sampling_percentage = [0.3] * 2 + [[None, None]] - reg.inputs.convergence_threshold = [1.e-8] * 2 + [-0.01] - reg.inputs.convergence_window_size = [20] * 2 + [5] - reg.inputs.smoothing_sigmas = [[4, 2, 1]] * 2 + [[1, 0.5, 0]] - reg.inputs.sigma_units = ['vox'] * 3 - reg.inputs.shrink_factors = [[3, 2, 1]] * 2 + [[4, 2, 1]] - reg.inputs.use_estimate_learning_rate_once = [True] * 3 - reg.inputs.use_histogram_matching = [False] * 2 + [True] - reg.inputs.winsorize_lower_quantile = 0.005 - reg.inputs.winsorize_upper_quantile = 0.995 - reg.inputs.float = True - reg.inputs.output_warped_image = 'output_warped_image.nii.gz' - reg.inputs.num_threads = 4 - reg.plugin_args = {'sbatch_args': '-c%d' % 4} - register.connect(stripper, 'out_file', reg, 'moving_image') - register.connect(inputnode, 'target_image', reg, 'fixed_image') - - """ - Concatenate the affine and ants transforms into a list - """ - - merge = Node(Merge(2), iterfield=['in2'], name='mergexfm') - register.connect(convert2itk, 'itk_transform', merge, 'in2') - register.connect(reg, ('composite_transform', pickfirst), merge, 'in1') - - """ - Transform the mean image. First to anatomical and then to target - """ - - warpmean = Node(ants.ApplyTransforms(), name='warpmean') - warpmean.inputs.input_image_type = 3 - warpmean.inputs.interpolation = 'Linear' - warpmean.inputs.invert_transform_flags = [False, False] - warpmean.terminal_output = 'file' - warpmean.inputs.args = '--float' - warpmean.inputs.num_threads = 4 - warpmean.plugin_args = {'sbatch_args': '-c%d' % 4} - - register.connect(inputnode, 'target_image', warpmean, 'reference_image') - register.connect(inputnode, 'mean_image', warpmean, 'input_image') - register.connect(merge, 'out', warpmean, 'transforms') - - """ - Assign all the output files - """ - - register.connect(reg, 'warped_image', outputnode, 'anat2target') - register.connect(warpmean, 'output_image', outputnode, 'transformed_mean') - register.connect(applyxfm, 'transformed_file', outputnode, - 'segmentation_files') - register.connect(aparcxfm, 'transformed_file', outputnode, 'aparc') - register.connect(bbregister, 'out_fsl_file', outputnode, - 'func2anat_transform') - register.connect(bbregister, 'out_reg_file', outputnode, 'out_reg_file') - register.connect(reg, 'composite_transform', outputnode, - 'anat2target_transform') - register.connect(merge, 'out', outputnode, 'transforms') - register.connect(bbregister, 'min_cost_file', outputnode, 'min_cost_file') - - return register - -""" -Creates the main preprocessing workflow -""" - - -def create_workflow(files, - target_file, - subject_id, - TR, - slice_times, - norm_threshold=1, - num_components=5, - vol_fwhm=None, - surf_fwhm=None, - lowpass_freq=-1, - highpass_freq=-1, - subjects_dir=None, - sink_directory=os.getcwd(), - target_subject=['fsaverage3', 'fsaverage4'], - name='resting'): - - wf = Workflow(name=name) - - # Rename files in case they are named identically - name_unique = MapNode( - Rename(format_string='rest_%(run)02d'), - iterfield=['in_file', 'run'], - name='rename') - name_unique.inputs.keep_ext = True - name_unique.inputs.run = list(range(1, len(files) + 1)) - name_unique.inputs.in_file = files - - realign = Node(nipy.SpaceTimeRealigner(), name="spacetime_realign") - realign.inputs.slice_times = slice_times - realign.inputs.tr = TR - realign.inputs.slice_info = 2 - realign.plugin_args = {'sbatch_args': '-c%d' % 4} - - # Compute TSNR on realigned data regressing polynomials up to order 2 - tsnr = MapNode(TSNR(regress_poly=2), iterfield=['in_file'], name='tsnr') - wf.connect(realign, "out_file", tsnr, "in_file") - - # Compute the median image across runs - calc_median = Node(CalculateMedian(), name='median') - wf.connect(tsnr, 'detrended_file', calc_median, 'in_files') - - """ - Segment and Register - """ - - registration = create_reg_workflow(name='registration') - wf.connect(calc_median, 'median_file', registration, - 'inputspec.mean_image') - registration.inputs.inputspec.subject_id = subject_id - registration.inputs.inputspec.subjects_dir = subjects_dir - registration.inputs.inputspec.target_image = target_file - - """Quantify TSNR in each freesurfer ROI - """ - - get_roi_tsnr = MapNode( - fs.SegStats(default_color_table=True), - iterfield=['in_file'], - name='get_aparc_tsnr') - get_roi_tsnr.inputs.avgwf_txt_file = True - wf.connect(tsnr, 'tsnr_file', get_roi_tsnr, 'in_file') - wf.connect(registration, 'outputspec.aparc', get_roi_tsnr, - 'segmentation_file') - - """Use :class:`nipype.algorithms.rapidart` to determine which of the - images in the functional series are outliers based on deviations in - intensity or movement. - """ - - art = Node(interface=ArtifactDetect(), name="art") - art.inputs.use_differences = [True, True] - art.inputs.use_norm = True - art.inputs.norm_threshold = norm_threshold - art.inputs.zintensity_threshold = 9 - art.inputs.mask_type = 'spm_global' - art.inputs.parameter_source = 'NiPy' - - """Here we are connecting all the nodes together. Notice that we add the merge node only if you choose - to use 4D. Also `get_vox_dims` function is passed along the input volume of normalise to set the optimal - voxel sizes. - """ - - wf.connect([ - (name_unique, realign, [('out_file', 'in_file')]), - (realign, art, [('out_file', 'realigned_files')]), - (realign, art, [('par_file', 'realignment_parameters')]), - ]) - - def selectindex(files, idx): - import numpy as np - from nipype.utils.filemanip import filename_to_list, list_to_filename - return list_to_filename( - np.array(filename_to_list(files))[idx].tolist()) - - mask = Node(fsl.BET(), name='getmask') - mask.inputs.mask = True - wf.connect(calc_median, 'median_file', mask, 'in_file') - - # get segmentation in normalized functional space - - def merge_files(in1, in2): - out_files = filename_to_list(in1) - out_files.extend(filename_to_list(in2)) - return out_files - - # filter some noise - - # Compute motion regressors - motreg = Node( - Function( - input_names=['motion_params', 'order', 'derivatives'], - output_names=['out_files'], - function=motion_regressors, - imports=imports), - name='getmotionregress') - wf.connect(realign, 'par_file', motreg, 'motion_params') - - # Create a filter to remove motion and art confounds - createfilter1 = Node( - Function( - input_names=[ - 'motion_params', 'comp_norm', 'outliers', 'detrend_poly' - ], - output_names=['out_files'], - function=build_filter1, - imports=imports), - name='makemotionbasedfilter') - createfilter1.inputs.detrend_poly = 2 - wf.connect(motreg, 'out_files', createfilter1, 'motion_params') - wf.connect(art, 'norm_files', createfilter1, 'comp_norm') - wf.connect(art, 'outlier_files', createfilter1, 'outliers') - - filter1 = MapNode( - fsl.GLM( - out_f_name='F_mcart.nii.gz', - out_pf_name='pF_mcart.nii.gz', - demean=True), - iterfield=['in_file', 'design', 'out_res_name'], - name='filtermotion') - - wf.connect(realign, 'out_file', filter1, 'in_file') - wf.connect(realign, ('out_file', rename, '_filtermotart'), filter1, - 'out_res_name') - wf.connect(createfilter1, 'out_files', filter1, 'design') - - createfilter2 = MapNode( - ACompCor(), - iterfield=['realigned_file', 'extra_regressors'], - name='makecompcorrfilter') - createfilter2.inputs.components_file = 'noise_components.txt' - createfilter2.inputs.num_components = num_components - - wf.connect(createfilter1, 'out_files', createfilter2, 'extra_regressors') - wf.connect(filter1, 'out_res', createfilter2, 'realigned_file') - wf.connect(registration, - ('outputspec.segmentation_files', selectindex, [0, 2]), - createfilter2, 'mask_file') - - filter2 = MapNode( - fsl.GLM(out_f_name='F.nii.gz', out_pf_name='pF.nii.gz', demean=True), - iterfield=['in_file', 'design', 'out_res_name'], - name='filter_noise_nosmooth') - wf.connect(filter1, 'out_res', filter2, 'in_file') - wf.connect(filter1, ('out_res', rename, '_cleaned'), filter2, - 'out_res_name') - wf.connect(createfilter2, 'components_file', filter2, 'design') - wf.connect(mask, 'mask_file', filter2, 'mask') - - bandpass = Node( - Function( - input_names=['files', 'lowpass_freq', 'highpass_freq', 'fs'], - output_names=['out_files'], - function=bandpass_filter, - imports=imports), - name='bandpass_unsmooth') - bandpass.inputs.fs = 1. / TR - bandpass.inputs.highpass_freq = highpass_freq - bandpass.inputs.lowpass_freq = lowpass_freq - wf.connect(filter2, 'out_res', bandpass, 'files') - """Smooth the functional data using - :class:`nipype.interfaces.fsl.IsotropicSmooth`. - """ - - smooth = MapNode( - interface=fsl.IsotropicSmooth(), name="smooth", iterfield=["in_file"]) - smooth.inputs.fwhm = vol_fwhm - - wf.connect(bandpass, 'out_files', smooth, 'in_file') - - collector = Node(Merge(2), name='collect_streams') - wf.connect(smooth, 'out_file', collector, 'in1') - wf.connect(bandpass, 'out_files', collector, 'in2') - """ - Transform the remaining images. First to anatomical and then to target - """ - - warpall = MapNode( - ants.ApplyTransforms(), iterfield=['input_image'], name='warpall') - warpall.inputs.input_image_type = 3 - warpall.inputs.interpolation = 'Linear' - warpall.inputs.invert_transform_flags = [False, False] - warpall.terminal_output = 'file' - warpall.inputs.reference_image = target_file - warpall.inputs.args = '--float' - warpall.inputs.num_threads = 2 - warpall.plugin_args = {'sbatch_args': '-c%d' % 2} - - # transform to target - wf.connect(collector, 'out', warpall, 'input_image') - wf.connect(registration, 'outputspec.transforms', warpall, 'transforms') - - mask_target = Node(fsl.ImageMaths(op_string='-bin'), name='target_mask') - - wf.connect(registration, 'outputspec.anat2target', mask_target, 'in_file') - - maskts = MapNode(fsl.ApplyMask(), iterfield=['in_file'], name='ts_masker') - wf.connect(warpall, 'output_image', maskts, 'in_file') - wf.connect(mask_target, 'out_file', maskts, 'mask_file') - - # map to surface - # extract aparc+aseg ROIs - # extract subcortical ROIs - # extract target space ROIs - # combine subcortical and cortical rois into a single cifti file - - ####### - # Convert aparc to subject functional space - - # Sample the average time series in aparc ROIs - sampleaparc = MapNode( - freesurfer.SegStats(default_color_table=True), - iterfield=['in_file', 'summary_file', 'avgwf_txt_file'], - name='aparc_ts') - sampleaparc.inputs.segment_id = ( - [8] + list(range(10, 14)) + [17, 18, 26, 47] + list(range(49, 55)) + - [58] + list(range(1001, 1036)) + list(range(2001, 2036))) - - wf.connect(registration, 'outputspec.aparc', sampleaparc, - 'segmentation_file') - wf.connect(collector, 'out', sampleaparc, 'in_file') - - def get_names(files, suffix): - """Generate appropriate names for output files - """ - from nipype.utils.filemanip import (split_filename, filename_to_list, - list_to_filename) - import os - out_names = [] - for filename in files: - path, name, _ = split_filename(filename) - out_names.append(os.path.join(path, name + suffix)) - return list_to_filename(out_names) - - wf.connect(collector, ('out', get_names, '_avgwf.txt'), sampleaparc, - 'avgwf_txt_file') - wf.connect(collector, ('out', get_names, '_summary.stats'), sampleaparc, - 'summary_file') - - # Sample the time series onto the surface of the target surface. Performs - # sampling into left and right hemisphere - target = Node(IdentityInterface(fields=['target_subject']), name='target') - target.iterables = ('target_subject', filename_to_list(target_subject)) - - samplerlh = MapNode( - freesurfer.SampleToSurface(), - iterfield=['source_file'], - name='sampler_lh') - samplerlh.inputs.sampling_method = "average" - samplerlh.inputs.sampling_range = (0.1, 0.9, 0.1) - samplerlh.inputs.sampling_units = "frac" - samplerlh.inputs.interp_method = "trilinear" - samplerlh.inputs.smooth_surf = surf_fwhm - # samplerlh.inputs.cortex_mask = True - samplerlh.inputs.out_type = 'niigz' - samplerlh.inputs.subjects_dir = subjects_dir - - samplerrh = samplerlh.clone('sampler_rh') - - samplerlh.inputs.hemi = 'lh' - wf.connect(collector, 'out', samplerlh, 'source_file') - wf.connect(registration, 'outputspec.out_reg_file', samplerlh, 'reg_file') - wf.connect(target, 'target_subject', samplerlh, 'target_subject') - - samplerrh.set_input('hemi', 'rh') - wf.connect(collector, 'out', samplerrh, 'source_file') - wf.connect(registration, 'outputspec.out_reg_file', samplerrh, 'reg_file') - wf.connect(target, 'target_subject', samplerrh, 'target_subject') - - # Combine left and right hemisphere to text file - combiner = MapNode( - Function( - input_names=['left', 'right'], - output_names=['out_file'], - function=combine_hemi, - imports=imports), - iterfield=['left', 'right'], - name="combiner") - wf.connect(samplerlh, 'out_file', combiner, 'left') - wf.connect(samplerrh, 'out_file', combiner, 'right') - - # Sample the time series file for each subcortical roi - ts2txt = MapNode( - Function( - input_names=['timeseries_file', 'label_file', 'indices'], - output_names=['out_file'], - function=extract_subrois, - imports=imports), - iterfield=['timeseries_file'], - name='getsubcortts') - ts2txt.inputs.indices = [8] + list(range(10, 14)) + [17, 18, 26, 47] +\ - list(range(49, 55)) + [58] - ts2txt.inputs.label_file = \ - os.path.abspath(('OASIS-TRT-20_jointfusion_DKT31_CMA_labels_in_MNI152_' - '2mm_v2.nii.gz')) - wf.connect(maskts, 'out_file', ts2txt, 'timeseries_file') - - ###### - - substitutions = [ - ('_target_subject_', ''), - ('_filtermotart_cleaned_bp_trans_masked', ''), - ('_filtermotart_cleaned_bp', ''), - ] - substitutions += [("_smooth%d" % i, "") for i in range(11)[::-1]] - substitutions += [("_ts_masker%d" % i, "") for i in range(11)[::-1]] - substitutions += [("_getsubcortts%d" % i, "") for i in range(11)[::-1]] - substitutions += [("_combiner%d" % i, "") for i in range(11)[::-1]] - substitutions += [("_filtermotion%d" % i, "") for i in range(11)[::-1]] - substitutions += [("_filter_noise_nosmooth%d" % i, "") - for i in range(11)[::-1]] - substitutions += [("_makecompcorfilter%d" % i, "") - for i in range(11)[::-1]] - substitutions += [("_get_aparc_tsnr%d/" % i, "run%d_" % (i + 1)) - for i in range(11)[::-1]] - - substitutions += [("T1_out_brain_pve_0_maths_warped", "compcor_csf"), - ("T1_out_brain_pve_1_maths_warped", - "compcor_gm"), ("T1_out_brain_pve_2_maths_warped", - "compcor_wm"), - ("output_warped_image_maths", - "target_brain_mask"), ("median_brain_mask", - "native_brain_mask"), ("corr_", - "")] - - regex_subs = [ - ('_combiner.*/sar', '/smooth/'), - ('_combiner.*/ar', '/unsmooth/'), - ('_aparc_ts.*/sar', '/smooth/'), - ('_aparc_ts.*/ar', '/unsmooth/'), - ('_getsubcortts.*/sar', '/smooth/'), - ('_getsubcortts.*/ar', '/unsmooth/'), - ('series/sar', 'series/smooth/'), - ('series/ar', 'series/unsmooth/'), - ('_inverse_transform./', ''), - ] - # Save the relevant data into an output directory - datasink = Node(interface=DataSink(), name="datasink") - datasink.inputs.base_directory = sink_directory - datasink.inputs.container = subject_id - datasink.inputs.substitutions = substitutions - datasink.inputs.regexp_substitutions = regex_subs # (r'(/_.*(\d+/))', r'/run\2') - wf.connect(realign, 'par_file', datasink, 'resting.qa.motion') - wf.connect(art, 'norm_files', datasink, 'resting.qa.art.@norm') - wf.connect(art, 'intensity_files', datasink, 'resting.qa.art.@intensity') - wf.connect(art, 'outlier_files', datasink, 'resting.qa.art.@outlier_files') - wf.connect(registration, 'outputspec.segmentation_files', datasink, - 'resting.mask_files') - wf.connect(registration, 'outputspec.anat2target', datasink, - 'resting.qa.ants') - wf.connect(mask, 'mask_file', datasink, 'resting.mask_files.@brainmask') - wf.connect(mask_target, 'out_file', datasink, 'resting.mask_files.target') - wf.connect(filter1, 'out_f', datasink, 'resting.qa.compmaps.@mc_F') - wf.connect(filter1, 'out_pf', datasink, 'resting.qa.compmaps.@mc_pF') - wf.connect(filter2, 'out_f', datasink, 'resting.qa.compmaps') - wf.connect(filter2, 'out_pf', datasink, 'resting.qa.compmaps.@p') - wf.connect(registration, 'outputspec.min_cost_file', datasink, - 'resting.qa.mincost') - wf.connect(tsnr, 'tsnr_file', datasink, 'resting.qa.tsnr.@map') - wf.connect([(get_roi_tsnr, datasink, - [('avgwf_txt_file', 'resting.qa.tsnr'), - ('summary_file', 'resting.qa.tsnr.@summary')])]) - - wf.connect(bandpass, 'out_files', datasink, - 'resting.timeseries.@bandpassed') - wf.connect(smooth, 'out_file', datasink, 'resting.timeseries.@smoothed') - wf.connect(createfilter1, 'out_files', datasink, - 'resting.regress.@regressors') - wf.connect(createfilter2, 'components_file', datasink, - 'resting.regress.@compcorr') - wf.connect(maskts, 'out_file', datasink, 'resting.timeseries.target') - wf.connect(sampleaparc, 'summary_file', datasink, - 'resting.parcellations.aparc') - wf.connect(sampleaparc, 'avgwf_txt_file', datasink, - 'resting.parcellations.aparc.@avgwf') - wf.connect(ts2txt, 'out_file', datasink, - 'resting.parcellations.grayo.@subcortical') - - datasink2 = Node(interface=DataSink(), name="datasink2") - datasink2.inputs.base_directory = sink_directory - datasink2.inputs.container = subject_id - datasink2.inputs.substitutions = substitutions - datasink2.inputs.regexp_substitutions = regex_subs # (r'(/_.*(\d+/))', r'/run\2') - wf.connect(combiner, 'out_file', datasink2, - 'resting.parcellations.grayo.@surface') - return wf - - -""" -Creates the full workflow including getting information from dicom files -""" - - -def create_resting_workflow(args, name=None): - TR = args.TR - slice_times = args.slice_times - if args.dicom_file: - TR, slice_times, slice_thickness = get_info(args.dicom_file) - slice_times = (np.array(slice_times) / 1000.).tolist() - - if name is None: - name = 'resting_' + args.subject_id - kwargs = dict( - files=[os.path.abspath(filename) for filename in args.files], - target_file=os.path.abspath(args.target_file), - subject_id=args.subject_id, - TR=TR, - slice_times=slice_times, - vol_fwhm=args.vol_fwhm, - surf_fwhm=args.surf_fwhm, - norm_threshold=2., - subjects_dir=os.path.abspath(args.fsdir), - target_subject=args.target_surfs, - lowpass_freq=args.lowpass_freq, - highpass_freq=args.highpass_freq, - sink_directory=os.path.abspath(args.sink), - name=name) - wf = create_workflow(**kwargs) - return wf - - -if __name__ == "__main__": - from argparse import ArgumentParser, RawTextHelpFormatter - defstr = ' (default %(default)s)' - parser = ArgumentParser( - description=__doc__, formatter_class=RawTextHelpFormatter) - parser.add_argument( - "-d", - "--dicom_file", - dest="dicom_file", - help="a SIEMENS example dicom file from the resting series") - parser.add_argument( - "-f", - "--files", - dest="files", - nargs="+", - help="4d nifti files for resting state", - required=True) - parser.add_argument( - "-t", - "--target", - dest="target_file", - help=("Target in MNI space. Best to use the MindBoggle " - "template - " - "OASIS-30_Atropos_template_in_MNI152_2mm.nii.gz"), - required=True) - parser.add_argument( - "-s", - "--subject_id", - dest="subject_id", - help="FreeSurfer subject id", - required=True) - parser.add_argument( - "--subjects_dir", - dest="fsdir", - help="FreeSurfer subject directory", - required=True) - parser.add_argument( - "--target_surfaces", - dest="target_surfs", - nargs="+", - default=['fsaverage5'], - help="FreeSurfer target surfaces" + defstr) - parser.add_argument( - "--TR", - dest="TR", - default=None, - type=float, - help="TR if dicom not provided in seconds") - parser.add_argument( - "--slice_times", - dest="slice_times", - nargs="+", - type=float, - help="Slice onset times in seconds") - parser.add_argument( - '--vol_fwhm', - default=6., - dest='vol_fwhm', - type=float, - help="Spatial FWHM" + defstr) - parser.add_argument( - '--surf_fwhm', - default=15., - dest='surf_fwhm', - type=float, - help="Spatial FWHM" + defstr) - parser.add_argument( - "-l", - "--lowpass_freq", - dest="lowpass_freq", - default=0.1, - type=float, - help="Low pass frequency (Hz)" + defstr) - parser.add_argument( - "-u", - "--highpass_freq", - dest="highpass_freq", - default=0.01, - type=float, - help="High pass frequency (Hz)" + defstr) - parser.add_argument( - "-o", - "--output_dir", - dest="sink", - help="Output directory base", - required=True) - parser.add_argument( - "-w", "--work_dir", dest="work_dir", help="Output directory base") - parser.add_argument( - "-p", - "--plugin", - dest="plugin", - default='Linear', - help="Plugin to use") - parser.add_argument( - "--plugin_args", dest="plugin_args", help="Plugin arguments") - args = parser.parse_args() - - wf = create_resting_workflow(args) - - if args.work_dir: - work_dir = os.path.abspath(args.work_dir) - else: - work_dir = os.getcwd() - - wf.base_dir = work_dir - if args.plugin_args: - wf.run(args.plugin, plugin_args=eval(args.plugin_args)) - else: - wf.run(args.plugin) diff --git a/examples/smri_ants_build_template.py b/examples/smri_ants_build_template.py deleted file mode 100644 index 53f3981428..0000000000 --- a/examples/smri_ants_build_template.py +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python -# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- -# vi: set ft=python sts=4 ts=4 sw=4 et: -""" -=============================================== -sMRI: Using new ANTS for creating a T1 template -=============================================== - -In this tutorial we will use ANTS (old version aka "ANTS") based workflow to -create a template out of multiple T1 volumes. - -1. Tell python where to find the appropriate functions. -""" - -from __future__ import print_function, unicode_literals -from builtins import open -from future import standard_library -standard_library.install_aliases() - -import os -import nipype.interfaces.utility as util -import nipype.interfaces.ants as ants -import nipype.interfaces.io as io -import nipype.pipeline.engine as pe # pypeline engine - -from niflow.nipype1.workflows.smri.ants import ANTSTemplateBuildSingleIterationWF -""" -2. Download T1 volumes into home directory -""" - -import urllib.request -import urllib.error -import urllib.parse -homeDir = os.getenv("HOME") -requestedPath = os.path.join(homeDir, 'nipypeTestPath') -mydatadir = os.path.realpath(requestedPath) -if not os.path.exists(mydatadir): - os.makedirs(mydatadir) -print(mydatadir) - -MyFileURLs = [ - ('http://slicer.kitware.com/midas3/download?bitstream=13121', - '01_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13122', - '02_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13124', - '03_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13128', - '01_T1_inv_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13123', - '02_T1_inv_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13125', - '03_T1_inv_half.nii.gz'), -] -for tt in MyFileURLs: - myURL = tt[0] - localFilename = os.path.join(mydatadir, tt[1]) - if not os.path.exists(localFilename): - remotefile = urllib.request.urlopen(myURL) - - localFile = open(localFilename, 'wb') - localFile.write(remotefile.read()) - localFile.close() - print("Downloaded file: {0}".format(localFilename)) - else: - print("File previously downloaded {0}".format(localFilename)) - -input_images = [ - os.path.join(mydatadir, '01_T1_half.nii.gz'), - os.path.join(mydatadir, '02_T1_half.nii.gz'), - os.path.join(mydatadir, '03_T1_half.nii.gz') -] -input_passive_images = [{ - 'INV_T1': - os.path.join(mydatadir, '01_T1_inv_half.nii.gz') -}, { - 'INV_T1': - os.path.join(mydatadir, '02_T1_inv_half.nii.gz') -}, { - 'INV_T1': - os.path.join(mydatadir, '03_T1_inv_half.nii.gz') -}] -""" -3. Define the workflow and its working directory -""" - -tbuilder = pe.Workflow(name="ANTSTemplateBuilder") -tbuilder.base_dir = requestedPath -""" -4. Define data sources. In real life these would be replace by DataGrabbers -""" - -datasource = pe.Node( - interface=util.IdentityInterface( - fields=['imageList', 'passiveImagesDictionariesList']), - run_without_submitting=True, - name='InputImages') -datasource.inputs.imageList = input_images -datasource.inputs.passiveImagesDictionariesList = input_passive_images -datasource.inputs.sort_filelist = True -""" -5. Template is initialized by a simple average -""" - -initAvg = pe.Node(interface=ants.AverageImages(), name='initAvg') -initAvg.inputs.dimension = 3 -initAvg.inputs.normalize = True - -tbuilder.connect(datasource, "imageList", initAvg, "images") -""" -6. Define the first iteration of template building -""" - -buildTemplateIteration1 = ANTSTemplateBuildSingleIterationWF('iteration01') -tbuilder.connect(initAvg, 'output_average_image', buildTemplateIteration1, - 'inputspec.fixed_image') -tbuilder.connect(datasource, 'imageList', buildTemplateIteration1, - 'inputspec.images') -tbuilder.connect(datasource, 'passiveImagesDictionariesList', - buildTemplateIteration1, - 'inputspec.ListOfPassiveImagesDictionaries') -""" -7. Define the second iteration of template building -""" - -buildTemplateIteration2 = ANTSTemplateBuildSingleIterationWF('iteration02') -tbuilder.connect(buildTemplateIteration1, 'outputspec.template', - buildTemplateIteration2, 'inputspec.fixed_image') -tbuilder.connect(datasource, 'imageList', buildTemplateIteration2, - 'inputspec.images') -tbuilder.connect(datasource, 'passiveImagesDictionariesList', - buildTemplateIteration2, - 'inputspec.ListOfPassiveImagesDictionaries') -""" -8. Move selected files to a designated results folder -""" - -datasink = pe.Node(io.DataSink(), name="datasink") -datasink.inputs.base_directory = os.path.join(requestedPath, "results") - -tbuilder.connect(buildTemplateIteration2, 'outputspec.template', datasink, - 'PrimaryTemplate') -tbuilder.connect(buildTemplateIteration2, - 'outputspec.passive_deformed_templates', datasink, - 'PassiveTemplate') -tbuilder.connect(initAvg, 'output_average_image', datasink, - 'PreRegisterAverage') -""" -8. Run the workflow -""" - -tbuilder.run() diff --git a/examples/smri_ants_registration.py b/examples/smri_ants_registration.py deleted file mode 100644 index e7050b05b7..0000000000 --- a/examples/smri_ants_registration.py +++ /dev/null @@ -1,109 +0,0 @@ -#!/usr/bin/env python -# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- -# vi: set ft=python sts=4 ts=4 sw=4 et: -""" -================================== -sMRI: Using ANTS for registration -================================== - -In this simple tutorial we will use the Registration interface from ANTS to -coregister two T1 volumes. - -1. Tell python where to find the appropriate functions. - -""" - -from __future__ import print_function, unicode_literals -from builtins import open - -from future import standard_library -standard_library.install_aliases() - -import os -import urllib.request -import urllib.error -import urllib.parse -from nipype.interfaces.ants import Registration -from nipype.testing import example_data -""" -2. Download T1 volumes into home directory - -""" - -homeDir = os.getenv("HOME") -requestedPath = os.path.join(homeDir, 'nipypeTestPath') -mydatadir = os.path.realpath(requestedPath) -if not os.path.exists(mydatadir): - os.makedirs(mydatadir) -print(mydatadir) - -MyFileURLs = [ - ('http://slicer.kitware.com/midas3/download?bitstream=13121', - '01_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13122', - '02_T1_half.nii.gz'), -] -for tt in MyFileURLs: - myURL = tt[0] - localFilename = os.path.join(mydatadir, tt[1]) - if not os.path.exists(localFilename): - remotefile = urllib.request.urlopen(myURL) - - localFile = open(localFilename, 'wb') - localFile.write(remotefile.read()) - localFile.close() - print("Downloaded file: {0}".format(localFilename)) - else: - print("File previously downloaded {0}".format(localFilename)) - -input_images = [ - os.path.join(mydatadir, '01_T1_half.nii.gz'), - os.path.join(mydatadir, '02_T1_half.nii.gz'), -] -""" -3. Define the parameters of the registration. Settings are -found in the file ``smri_ants_registration_settings.json`` -distributed with the ``example_data`` of `nipype`. - -""" - -reg = Registration( - from_file=example_data('smri_ants_registration_settings.json')) -reg.inputs.fixed_image = input_images[0] -reg.inputs.moving_image = input_images[1] -""" -Alternatively to the use of the ``from_file`` feature to load ANTs settings, -the user can manually set all those inputs instead:: - - reg.inputs.output_transform_prefix = 'thisTransform' - reg.inputs.output_warped_image = 'INTERNAL_WARPED.nii.gz' - reg.inputs.output_transform_prefix = "output_" - reg.inputs.transforms = ['Translation', 'Rigid', 'Affine', 'SyN'] - reg.inputs.transform_parameters = [(0.1,), (0.1,), (0.1,), (0.2, 3.0, 0.0)] - reg.inputs.number_of_iterations = ([[10000, 111110, 11110]] * 3 + - [[100, 50, 30]]) - reg.inputs.dimension = 3 - reg.inputs.write_composite_transform = True - reg.inputs.collapse_output_transforms = False - reg.inputs.metric = ['Mattes'] * 3 + [['Mattes', 'CC']] - reg.inputs.metric_weight = [1] * 3 + [[0.5, 0.5]] - reg.inputs.radius_or_number_of_bins = [32] * 3 + [[32, 4]] - reg.inputs.sampling_strategy = ['Regular'] * 3 + [[None, None]] - reg.inputs.sampling_percentage = [0.3] * 3 + [[None, None]] - reg.inputs.convergence_threshold = [1.e-8] * 3 + [-0.01] - reg.inputs.convergence_window_size = [20] * 3 + [5] - reg.inputs.smoothing_sigmas = [[4, 2, 1]] * 3 + [[1, 0.5, 0]] - reg.inputs.sigma_units = ['vox'] * 4 - reg.inputs.shrink_factors = [[6, 4, 2]] + [[3, 2, 1]] * 2 + [[4, 2, 1]] - reg.inputs.use_estimate_learning_rate_once = [True] * 4 - reg.inputs.use_histogram_matching = [False] * 3 + [True] - reg.inputs.initial_moving_transform_com = True - -""" - -print(reg.cmdline) -""" -3. Run the registration -""" - -reg.run() diff --git a/examples/smri_antsregistration_build_template.py b/examples/smri_antsregistration_build_template.py deleted file mode 100644 index e84fc5b509..0000000000 --- a/examples/smri_antsregistration_build_template.py +++ /dev/null @@ -1,222 +0,0 @@ -#!/usr/bin/env python -# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- -# vi: set ft=python sts=4 ts=4 sw=4 et: -""" -====================================================== -sMRI: Using new ANTS for creating a T1 template (ITK4) -====================================================== - -In this tutorial we will use ANTS (new ITK4 version aka "antsRegistration") based workflow to -create a template out of multiple T1 volumes. We will also showcase how to fine tune SGE jobs requirements. - -1. Tell python where to find the appropriate functions. -""" - -from __future__ import print_function -from future import standard_library -standard_library.install_aliases() - -import os -import nipype.interfaces.utility as util -import nipype.interfaces.ants as ants -import nipype.interfaces.io as io -import nipype.pipeline.engine as pe # pypeline engine - -from niflow.nipype1.workflows.smri.ants import antsRegistrationTemplateBuildSingleIterationWF -""" -2. Download T1 volumes into home directory -""" - -import urllib.request -import urllib.error -import urllib.parse -homeDir = os.getenv("HOME") -requestedPath = os.path.join(homeDir, 'nipypeTestPath') -mydatadir = os.path.realpath(requestedPath) -if not os.path.exists(mydatadir): - os.makedirs(mydatadir) -print(mydatadir) - -MyFileURLs = [ - ('http://slicer.kitware.com/midas3/download?bitstream=13121', - '01_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13122', - '02_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13124', - '03_T1_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13128', - '01_T1_inv_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13123', - '02_T1_inv_half.nii.gz'), - ('http://slicer.kitware.com/midas3/download?bitstream=13125', - '03_T1_inv_half.nii.gz'), -] -for tt in MyFileURLs: - myURL = tt[0] - localFilename = os.path.join(mydatadir, tt[1]) - if not os.path.exists(localFilename): - remotefile = urllib.request.urlopen(myURL) - - localFile = open(localFilename, 'wb') - localFile.write(remotefile.read()) - localFile.close() - print("Downloaded file: {0}".format(localFilename)) - else: - print("File previously downloaded {0}".format(localFilename)) -""" -ListOfImagesDictionaries - a list of dictionaries where each dictionary is -for one scan session, and the mappings in the dictionary are for all the -co-aligned images for that one scan session -""" - -ListOfImagesDictionaries = [{ - 'T1': - os.path.join(mydatadir, '01_T1_half.nii.gz'), - 'INV_T1': - os.path.join(mydatadir, '01_T1_inv_half.nii.gz'), - 'LABEL_MAP': - os.path.join(mydatadir, '01_T1_inv_half.nii.gz') -}, { - 'T1': - os.path.join(mydatadir, '02_T1_half.nii.gz'), - 'INV_T1': - os.path.join(mydatadir, '02_T1_inv_half.nii.gz'), - 'LABEL_MAP': - os.path.join(mydatadir, '02_T1_inv_half.nii.gz') -}, { - 'T1': - os.path.join(mydatadir, '03_T1_half.nii.gz'), - 'INV_T1': - os.path.join(mydatadir, '03_T1_inv_half.nii.gz'), - 'LABEL_MAP': - os.path.join(mydatadir, '03_T1_inv_half.nii.gz') -}] -input_passive_images = [{ - 'INV_T1': - os.path.join(mydatadir, '01_T1_inv_half.nii.gz') -}, { - 'INV_T1': - os.path.join(mydatadir, '02_T1_inv_half.nii.gz') -}, { - 'INV_T1': - os.path.join(mydatadir, '03_T1_inv_half.nii.gz') -}] -""" -registrationImageTypes - A list of the image types to be used actively during -the estimation process of registration, any image type not in this list -will be passively resampled with the estimated transforms. -['T1','T2'] -""" - -registrationImageTypes = ['T1'] -""" -interpolationMap - A map of image types to interpolation modes. If an -image type is not listed, it will be linearly interpolated. -{ 'labelmap':'NearestNeighbor', 'FLAIR':'WindowedSinc' } -""" - -interpolationMapping = { - 'INV_T1': 'LanczosWindowedSinc', - 'LABEL_MAP': 'NearestNeighbor', - 'T1': 'Linear' -} -""" -3. Define the workflow and its working directory -""" - -tbuilder = pe.Workflow(name="antsRegistrationTemplateBuilder") -tbuilder.base_dir = requestedPath -""" -4. Define data sources. In real life these would be replace by DataGrabbers -""" - -InitialTemplateInputs = [mdict['T1'] for mdict in ListOfImagesDictionaries] - -datasource = pe.Node( - interface=util.IdentityInterface(fields=[ - 'InitialTemplateInputs', 'ListOfImagesDictionaries', - 'registrationImageTypes', 'interpolationMapping' - ]), - run_without_submitting=True, - name='InputImages') -datasource.inputs.InitialTemplateInputs = InitialTemplateInputs -datasource.inputs.ListOfImagesDictionaries = ListOfImagesDictionaries -datasource.inputs.registrationImageTypes = registrationImageTypes -datasource.inputs.interpolationMapping = interpolationMapping -datasource.inputs.sort_filelist = True -""" -5. Template is initialized by a simple average in this simple example, - any reference image could be used (i.e. a previously created template) -""" - -initAvg = pe.Node(interface=ants.AverageImages(), name='initAvg') -initAvg.inputs.dimension = 3 -initAvg.inputs.normalize = True - -tbuilder.connect(datasource, "InitialTemplateInputs", initAvg, "images") -""" -6. Define the first iteration of template building -""" - -buildTemplateIteration1 = antsRegistrationTemplateBuildSingleIterationWF( - 'iteration01') -""" -Here we are fine tuning parameters of the SGE job (memory limit, numebr of cores etc.) -""" - -BeginANTS = buildTemplateIteration1.get_node("BeginANTS") -BeginANTS.plugin_args = { - 'qsub_args': - '-S /bin/bash -pe smp1 8-12 -l mem_free=6000M -o /dev/null -e /dev/null queue_name', - 'overwrite': - True -} - -tbuilder.connect(initAvg, 'output_average_image', buildTemplateIteration1, - 'inputspec.fixed_image') -tbuilder.connect(datasource, 'ListOfImagesDictionaries', - buildTemplateIteration1, 'inputspec.ListOfImagesDictionaries') -tbuilder.connect(datasource, 'registrationImageTypes', buildTemplateIteration1, - 'inputspec.registrationImageTypes') -tbuilder.connect(datasource, 'interpolationMapping', buildTemplateIteration1, - 'inputspec.interpolationMapping') -""" -7. Define the second iteration of template building -""" - -buildTemplateIteration2 = antsRegistrationTemplateBuildSingleIterationWF( - 'iteration02') -BeginANTS = buildTemplateIteration2.get_node("BeginANTS") -BeginANTS.plugin_args = { - 'qsub_args': - '-S /bin/bash -pe smp1 8-12 -l mem_free=6000M -o /dev/null -e /dev/null queue_name', - 'overwrite': - True -} -tbuilder.connect(buildTemplateIteration1, 'outputspec.template', - buildTemplateIteration2, 'inputspec.fixed_image') -tbuilder.connect(datasource, 'ListOfImagesDictionaries', - buildTemplateIteration2, 'inputspec.ListOfImagesDictionaries') -tbuilder.connect(datasource, 'registrationImageTypes', buildTemplateIteration2, - 'inputspec.registrationImageTypes') -tbuilder.connect(datasource, 'interpolationMapping', buildTemplateIteration2, - 'inputspec.interpolationMapping') -""" -8. Move selected files to a designated results folder -""" - -datasink = pe.Node(io.DataSink(), name="datasink") -datasink.inputs.base_directory = os.path.join(requestedPath, "results") - -tbuilder.connect(buildTemplateIteration2, 'outputspec.template', datasink, - 'PrimaryTemplate') -tbuilder.connect(buildTemplateIteration2, - 'outputspec.passive_deformed_templates', datasink, - 'PassiveTemplate') -tbuilder.connect(initAvg, 'output_average_image', datasink, - 'PreRegisterAverage') -""" -9. Run the workflow -""" - -tbuilder.run(plugin="SGE") diff --git a/examples/smri_cbs_skullstripping.py b/examples/smri_cbs_skullstripping.py deleted file mode 100644 index 1471496576..0000000000 --- a/examples/smri_cbs_skullstripping.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- -# vi: set ft=python sts=4 ts=4 sw=4 et: -""" -======================================== -sMRI: USing CBS Tools for skullstripping -======================================== - -This simple workflow uses SPECTRE2010 algorithm to skullstrip an MP2RAGE -anatomical scan. -""" - -import nipype.pipeline.engine as pe -from nipype.interfaces.mipav.developer import (JistIntensityMp2rageMasking, - MedicAlgorithmSPECTRE2010) - -wf = pe.Workflow("skullstripping") - -mask = pe.Node(JistIntensityMp2rageMasking(), name="masking") -folder_path = '/Users/filo/7t_trt/niftis/sub001/session_1/' -mask.inputs.inSecond = folder_path + "MP2RAGE_INV2.nii.gz" -mask.inputs.inQuantitative = folder_path + "MP2RAGE_UNI.nii.gz" -mask.inputs.inT1weighted = folder_path + "MP2RAGE_T1.nii.gz" -mask.inputs.outMasked = True -mask.inputs.outMasked2 = True -mask.inputs.outSignal = True -mask.inputs.outSignal2 = True - -skullstrip = pe.Node(MedicAlgorithmSPECTRE2010(), name="skullstrip") -skullstrip.inputs.outStripped = True -skullstrip.inputs.xDefaultMem = 6000 - -wf.connect(mask, 'outMasked', skullstrip, 'inInput') -wf.run() diff --git a/examples/smri_freesurfer.py b/examples/smri_freesurfer.py deleted file mode 100644 index d365b44dd5..0000000000 --- a/examples/smri_freesurfer.py +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env python -""" -================ -sMRI: FreeSurfer -================ - -This script, smri_freesurfer.py, demonstrates the ability to call reconall on -a set of subjects and then make an average subject:: - - python smri_freesurfer.py - -Import necessary modules from nipype. -""" - -import os - -import nipype.pipeline.engine as pe -import nipype.interfaces.io as nio -from nipype.interfaces.freesurfer.preprocess import ReconAll -from nipype.interfaces.freesurfer.utils import MakeAverageSubject - -subject_list = ['s1', 's3'] -data_dir = os.path.abspath('data') -subjects_dir = os.path.abspath('amri_freesurfer_tutorial/subjects_dir') - -wf = pe.Workflow(name="l1workflow") -wf.base_dir = os.path.abspath('amri_freesurfer_tutorial/workdir') -""" -Grab data -""" - -datasource = pe.MapNode( - interface=nio.DataGrabber(infields=['subject_id'], outfields=['struct']), - name='datasource', - iterfield=['subject_id']) -datasource.inputs.base_directory = data_dir -datasource.inputs.template = '%s/%s.nii' -datasource.inputs.template_args = dict(struct=[['subject_id', 'struct']]) -datasource.inputs.subject_id = subject_list -datasource.inputs.sort_filelist = True -""" -Run recon-all -""" - -recon_all = pe.MapNode( - interface=ReconAll(), - name='recon_all', - iterfield=['subject_id', 'T1_files']) -recon_all.inputs.subject_id = subject_list -if not os.path.exists(subjects_dir): - os.mkdir(subjects_dir) -recon_all.inputs.subjects_dir = subjects_dir - -wf.connect(datasource, 'struct', recon_all, 'T1_files') -""" -Make average subject -""" - -average = pe.Node(interface=MakeAverageSubject(), name="average") -average.inputs.subjects_dir = subjects_dir - -wf.connect(recon_all, 'subject_id', average, 'subjects_ids') - -wf.run("MultiProc", plugin_args={'n_procs': 4}) diff --git a/examples/smri_fsreconall.py b/examples/smri_fsreconall.py deleted file mode 100644 index 16d0b4c9f3..0000000000 --- a/examples/smri_fsreconall.py +++ /dev/null @@ -1,89 +0,0 @@ -#!/usr/bin/env python -""" -================ -sMRI: FSReconAll -================ - -This script, smri_fsreconall.py, demonstrates the ability to use the -create_reconall_workflow function to create a workflow and then run it on a -set of subjects and then make an average subject:: - - python smri_fsreconall.py - -For an example on how to call FreeSurfer's reconall script in Nipype -see smri_freesurfer.py. - -Import necessary modules from nipype. -""" - -import os - -import nipype.pipeline.engine as pe -import nipype.interfaces.io as nio -from niflow.nipype1.workflows.smri.freesurfer import create_reconall_workflow -from nipype.interfaces.freesurfer.utils import MakeAverageSubject -from nipype.interfaces.utility import IdentityInterface -""" -Assign the tutorial directory -""" - -tutorial_dir = os.path.abspath('smri_fsreconall_tutorial') -if not os.path.isdir(tutorial_dir): - os.mkdir(tutorial_dir) -""" -Define the workflow directories -""" - -subject_list = ['s1', 's3'] -data_dir = os.path.abspath('data') -subjects_dir = os.path.join(tutorial_dir, 'subjects_dir') -if not os.path.exists(subjects_dir): - os.mkdir(subjects_dir) - -wf = pe.Workflow(name="l1workflow") -wf.base_dir = os.path.join(tutorial_dir, 'workdir') -""" -Create inputspec -""" - -inputspec = pe.Node( - interface=IdentityInterface(['subject_id']), name="inputspec") -inputspec.iterables = ("subject_id", subject_list) -""" -Grab data -""" - -datasource = pe.Node( - interface=nio.DataGrabber(infields=['subject_id'], outfields=['struct']), - name='datasource') -datasource.inputs.base_directory = data_dir -datasource.inputs.template = '%s/%s.nii' -datasource.inputs.template_args = dict(struct=[['subject_id', 'struct']]) -datasource.inputs.subject_id = subject_list -datasource.inputs.sort_filelist = True - -wf.connect(inputspec, 'subject_id', datasource, 'subject_id') -""" -Run recon-all -""" - -recon_all = create_reconall_workflow() -recon_all.inputs.inputspec.subjects_dir = subjects_dir - -wf.connect(datasource, 'struct', recon_all, 'inputspec.T1_files') -wf.connect(inputspec, 'subject_id', recon_all, 'inputspec.subject_id') -""" -Make average subject -""" - -average = pe.JoinNode( - interface=MakeAverageSubject(), - joinsource="inputspec", - joinfield="subjects_ids", - name="average") -average.inputs.subjects_dir = subjects_dir - -wf.connect(recon_all, 'postdatasink_outputspec.subject_id', average, - 'subjects_ids') - -wf.run("MultiProc", plugin_args={'n_procs': 4}) diff --git a/examples/tessellation_tutorial.py b/examples/tessellation_tutorial.py deleted file mode 100644 index 58bae095cc..0000000000 --- a/examples/tessellation_tutorial.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -""" -================================================= -sMRI: Regional Tessellation and Surface Smoothing -================================================= - -Introduction -============ - -This script, tessellation_tutorial.py, demonstrates the use of create_tessellation_flow from niflow.nipype1.workflows.smri.freesurfer, and it can be run with:: - - python tessellation_tutorial.py - -This example requires that the user has Freesurfer installed, and that the Freesurfer directory for 'fsaverage' is present. - -.. seealso:: - - ConnectomeViewer - The Connectome Viewer connects Multi-Modal Multi-Scale Neuroimaging and Network Datasets For Analysis and Visualization in Python. - - http://www.geuz.org/gmsh/ - Gmsh: a three-dimensional finite element mesh generator with built-in pre- and post-processing facilities - - http://www.blender.org/ - Blender is the free open source 3D content creation suite, available for all major operating systems under the GNU General Public License. - -.. warning:: - - This workflow will take several hours to finish entirely, since smoothing the larger cortical surfaces is very time consuming. - -Packages and Data Setup -======================= - -Import the necessary modules and workflow from nipype. -""" - -import nipype.pipeline.engine as pe # pypeline engine -import nipype.interfaces.cmtk as cmtk -import nipype.interfaces.io as nio # Data i/o -import os -import os.path as op -from niflow.nipype1.workflows.smri.freesurfer import create_tessellation_flow -""" -Directories -=========== - -Set the default directory and lookup table (LUT) paths -""" - -fs_dir = os.environ['FREESURFER_HOME'] -lookup_file = op.join(fs_dir, 'FreeSurferColorLUT.txt') -subjects_dir = op.join(fs_dir, 'subjects/') -output_dir = './tessellate_tutorial' -""" -Inputs -====== - -Create the tessellation workflow and set inputs -Here we will choose Gifti (gii) as the output format, because -we want to able to view the surface in ConnectomeViewer. - -In you intend to view the meshes in gmsh or Blender, you should change -the workflow creation to use stereolithographic (stl) format. -""" - -tessflow = create_tessellation_flow(name='tessflow', out_format='gii') -tessflow.inputs.inputspec.subject_id = 'fsaverage' -tessflow.inputs.inputspec.subjects_dir = subjects_dir -tessflow.inputs.inputspec.lookup_file = lookup_file -""" -We also create a conditional node to package the surfaces for ConnectomeViewer. -Simply set cff to "False" to ignore this step. -""" - -cff = True -if cff: - cff = pe.Node(interface=cmtk.CFFConverter(), name='cff') - cff.inputs.out_file = 'Meshes.cff' -""" -Outputs -======= - -Create a datasink to organize the smoothed meshes -Using regular-expression substitutions we can remove the extraneous folders generated by the mapnode. -""" - -datasink = pe.Node(interface=nio.DataSink(), name="datasink") -datasink.inputs.base_directory = 'meshes' -datasink.inputs.regexp_substitutions = [('_smoother[\d]*/', '')] -""" -Execution -========= - -Finally, create and run another pipeline that connects the workflow and datasink -""" - -tesspipe = pe.Workflow(name='tessellate_tutorial') -tesspipe.base_dir = output_dir -tesspipe.connect([(tessflow, datasink, [('outputspec.meshes', - '@meshes.all')])]) -""" -If the surfaces are to be packaged, this will connect the CFFConverter -node to the tessellation and smoothing workflow, as well as to the datasink. -""" - -if cff: - tesspipe.connect([(tessflow, cff, [('outputspec.meshes', - 'gifti_surfaces')])]) - tesspipe.connect([(cff, datasink, [('connectome_file', '@cff')])]) - -tesspipe.run() diff --git a/examples/test_spm.py b/examples/test_spm.py deleted file mode 100644 index 4c31f144ed..0000000000 --- a/examples/test_spm.py +++ /dev/null @@ -1,77 +0,0 @@ -from __future__ import division -from builtins import range -import nipype.pipeline.engine as pe -from nipype.interfaces import spm -from nipype.interfaces import fsl -from nipype.interfaces import utility as niu -from nipype.interfaces import io as nio -from nipype.algorithms.misc import Gunzip - - -def _get_first(inlist): - if isinstance(inlist, (list, tuple)): - return inlist[0] - return inlist - - -def test_spm(name='test_spm_3d'): - """ - A simple workflow to test SPM's installation. By default will split the 4D volume in - time-steps. - """ - workflow = pe.Workflow(name=name) - - inputnode = pe.Node( - niu.IdentityInterface(fields=['in_data']), name='inputnode') - dgr = pe.Node( - nio.DataGrabber( - template="feeds/data/fmri.nii.gz", - outfields=['out_file'], - sort_filelist=False), - name='datasource') - - stc = pe.Node( - spm.SliceTiming( - num_slices=21, - time_repetition=1.0, - time_acquisition=2. - 2. / 32, - slice_order=list(range(21, 0, -1)), - ref_slice=10), - name='stc') - realign_estimate = pe.Node( - spm.Realign(jobtype='estimate'), name='realign_estimate') - realign_write = pe.Node(spm.Realign(jobtype='write'), name='realign_write') - realign_estwrite = pe.Node( - spm.Realign(jobtype='estwrite'), name='realign_estwrite') - smooth = pe.Node(spm.Smooth(fwhm=[6, 6, 6]), name='smooth') - - if name == 'test_spm_3d': - split = pe.Node( - fsl.Split(dimension="t", output_type="NIFTI"), name="split") - workflow.connect([(dgr, split, [(('out_file', _get_first), - 'in_file')]), - (split, stc, [("out_files", "in_files")])]) - elif name == 'test_spm_4d': - gunzip = pe.Node(Gunzip(), name="gunzip") - workflow.connect([(dgr, gunzip, [(('out_file', _get_first), - 'in_file')]), - (gunzip, stc, [("out_file", "in_files")])]) - else: - raise NotImplementedError( - 'No implementation of the test workflow \'{}\' was found'.format( - name)) - - workflow.connect([(inputnode, dgr, [('in_data', 'base_directory')]), - (stc, realign_estimate, - [('timecorrected_files', - 'in_files')]), (realign_estimate, realign_write, - [('modified_in_files', 'in_files')]), - (stc, realign_estwrite, - [('timecorrected_files', - 'in_files')]), (realign_write, smooth, - [('realigned_files', 'in_files')])]) - return workflow - - -workflow3d = test_spm() -workflow4d = test_spm(name='test_spm_4d') diff --git a/examples/workshop_dartmouth_2010.py b/examples/workshop_dartmouth_2010.py deleted file mode 100644 index 931a633c52..0000000000 --- a/examples/workshop_dartmouth_2010.py +++ /dev/null @@ -1,288 +0,0 @@ -""" -================================ -Workshop: Dartmouth College 2010 -================================ - -First lets go to the directory with the data we'll be working on and start the interactive python interpreter -(with some nipype specific configuration). Note that nipype does not need to be run through ipython - it is -just much nicer to do interactive work in it. - -.. sourcecode:: bash - - cd $TDPATH - ipython -p nipype - -For every neuroimaging procedure supported by nipype there exists a wrapper - a small piece of code managing -the underlying software (FSL, SPM, AFNI etc.). We call those interfaces. They are standarised so we can hook them up -together. Lets have a look at some of them. - -.. sourcecode:: ipython - - In [1]: import nipype.interfaces.fsl as fsl - - In [2]: fsl.BET.help() - Inputs - ------ - - Mandatory: - in_file: input file to skull strip - - Optional: - args: Additional parameters to the command - center: center of gravity in voxels - environ: Environment variables (default={}) - frac: fractional intensity threshold - functional: apply to 4D fMRI data - mutually exclusive: functional, reduce_bias - mask: create binary mask image - mesh: generate a vtk mesh brain surface - no_output: Don't generate segmented output - out_file: name of output skull stripped image - outline: create surface outline image - output_type: FSL output type - radius: head radius - reduce_bias: bias field and neck cleanup - mutually exclusive: functional, reduce_bias - skull: create skull image - threshold: apply thresholding to segmented brain image and mask - vertical_gradient: vertical gradient in fractional intensity threshold (-1, 1) - - Outputs - ------- - mask_file: path/name of binary brain mask (if generated) - meshfile: path/name of vtk mesh file (if generated) - out_file: path/name of skullstripped file - outline_file: path/name of outline file (if generated) - - In [3]: import nipype.interfaces.freesurfer as fs - - In [4]: fs.Smooth.help() - Inputs - ------ - - Mandatory: - in_file: source volume - num_iters: number of iterations instead of fwhm - mutually exclusive: surface_fwhm - reg_file: registers volume to surface anatomical - surface_fwhm: surface FWHM in mm - mutually exclusive: num_iters - requires: reg_file - - Optional: - args: Additional parameters to the command - environ: Environment variables (default={}) - proj_frac: project frac of thickness a long surface normal - mutually exclusive: proj_frac_avg - proj_frac_avg: average a long normal min max delta - mutually exclusive: proj_frac - smoothed_file: output volume - subjects_dir: subjects directory - vol_fwhm: volumesmoothing outside of surface - - Outputs - ------- - args: Additional parameters to the command - environ: Environment variables - smoothed_file: smoothed input volume - subjects_dir: subjects directory - -You can read about all of the interfaces implemented in nipype at our online documentation at http://nipy.sourceforge.net/nipype/documentation.html#documentation . -Check it out now. - -Using interfaces ----------------- - -Having interfaces allows us to use third party software (like FSL BET) as function. Look how simple it is. -""" - -from __future__ import print_function -from builtins import str - -import nipype.interfaces.fsl as fsl -result = fsl.BET(in_file='data/s1/struct.nii').run() -print(result) -""" -Running a single program is not much of a breakthrough. Lets run motion correction followed by smoothing -(isotropic - in other words not using SUSAN). Notice that in the first line we are setting the output data type -for all FSL interfaces. -""" - -fsl.FSLCommand.set_default_output_type('NIFTI_GZ') -result1 = fsl.MCFLIRT(in_file='data/s1/f3.nii').run() -result2 = fsl.Smooth(in_file='f3_mcf.nii.gz', fwhm=6).run() -""" -Simple workflow ---------------- - -In the previous example we knew that fsl.MCFLIRT will produce a file called f3_mcf.nii.gz and we have hard coded -this as an input to fsl.Smooth. This is quite limited, but luckily nipype supports joining interfaces in pipelines. -This way output of one interface will be used as an input of another without having to hard code anything. Before -connecting Interfaces we need to put them into (separate) Nodes and give them unique names. This way every interface will -process data in a separate folder. -""" - -import nipype.pipeline.engine as pe -import os - -motion_correct = pe.Node( - interface=fsl.MCFLIRT(in_file=os.path.abspath('data/s1/f3.nii')), - name="motion_correct") -smooth = pe.Node(interface=fsl.Smooth(fwhm=6), name="smooth") - -motion_correct_and_smooth = pe.Workflow(name="motion_correct_and_smooth") -motion_correct_and_smooth.base_dir = os.path.abspath( - '.') # define where will be the root folder for the workflow -motion_correct_and_smooth.connect([(motion_correct, smooth, [('out_file', - 'in_file')])]) -# we are connecting 'out_file' output of motion_correct to 'in_file' input of smooth -motion_correct_and_smooth.run() -""" -Another workflow ----------------- - -Another example of a simple workflow (calculate the mean of fMRI signal and subtract it). -This time we'll be assigning inputs after defining the workflow. -""" - -calc_mean = pe.Node(interface=fsl.ImageMaths(), name="calc_mean") -calc_mean.inputs.op_string = "-Tmean" -subtract = pe.Node(interface=fsl.ImageMaths(), name="subtract") -subtract.inputs.op_string = "-sub" - -demean = pe.Workflow(name="demean") -demean.base_dir = os.path.abspath('.') -demean.connect([(calc_mean, subtract, [('out_file', 'in_file2')])]) - -demean.inputs.calc_mean.in_file = os.path.abspath('data/s1/f3.nii') -demean.inputs.subtract.in_file = os.path.abspath('data/s1/f3.nii') -demean.run() -""" -Reusing workflows ------------------ - -The beauty of the workflows is that they are reusable. We can just import a workflow made by someone -else and feed it with our data. -""" - -from fmri_fsl import preproc -preproc.base_dir = os.path.abspath('.') -preproc.inputs.inputspec.func = os.path.abspath('data/s1/f3.nii') -preproc.inputs.inputspec.struct = os.path.abspath('data/s1/struct.nii') -preproc.run() -""" -... and we can run it again and it won't actually rerun anything because none of -the parameters have changed. -""" - -preproc.run() -""" -... and we can change a parameter and run it again. Only the dependent nodes -are rerun and that too only if the input state has changed. -""" - -preproc.inputs.meanfuncmask.frac = 0.5 -preproc.run() -""" -Visualizing workflows 1 ------------------------ - -So what did we run in this precanned workflow -""" - -preproc.write_graph() -""" -Datasink --------- - -Datasink is a special interface for copying and arranging results. -""" - -import nipype.interfaces.io as nio - -preproc.inputs.inputspec.func = os.path.abspath('data/s1/f3.nii') -preproc.inputs.inputspec.struct = os.path.abspath('data/s1/struct.nii') -datasink = pe.Node(interface=nio.DataSink(), name='sinker') -preprocess = pe.Workflow(name='preprocout') -preprocess.base_dir = os.path.abspath('.') -preprocess.connect([(preproc, datasink, [('meanfunc2.out_file', 'meanfunc'), - ('maskfunc3.out_file', 'funcruns')])]) -preprocess.run() -""" -Datagrabber ------------ - -Datagrabber is (surprise, surprise) an interface for collecting files from hard drive. It is very flexible and -supports almost any file organisation of your data you can imagine. -""" - -datasource1 = nio.DataGrabber() -datasource1.inputs.template = 'data/s1/f3.nii' -datasource1.inputs.sort_filelist = True -results = datasource1.run() -print(results.outputs) - -datasource2 = nio.DataGrabber() -datasource2.inputs.template = 'data/s*/f*.nii' -datasource2.inputs.sort_filelist = True -results = datasource2.run() -print(results.outputs) - -datasource3 = nio.DataGrabber(infields=['run']) -datasource3.inputs.template = 'data/s1/f%d.nii' -datasource3.inputs.sort_filelist = True -datasource3.inputs.run = [3, 7] -results = datasource3.run() -print(results.outputs) - -datasource4 = nio.DataGrabber(infields=['subject_id', 'run']) -datasource4.inputs.template = 'data/%s/f%d.nii' -datasource4.inputs.sort_filelist = True -datasource4.inputs.run = [3, 7] -datasource4.inputs.subject_id = ['s1', 's3'] -results = datasource4.run() -print(results.outputs) -""" -Iterables ---------- - -Iterables is a special field of the Node class that enables to iterate all workfloes/nodes connected to it over -some parameters. Here we'll use it to iterate over two subjects. -""" - -import nipype.interfaces.utility as util -infosource = pe.Node( - interface=util.IdentityInterface(fields=['subject_id']), name="infosource") -infosource.iterables = ('subject_id', ['s1', 's3']) - -datasource = pe.Node( - nio.DataGrabber(infields=['subject_id'], outfields=['func', 'struct']), - name="datasource") -datasource.inputs.template = '%s/%s.nii' -datasource.inputs.base_directory = os.path.abspath('data') -datasource.inputs.template_args = dict( - func=[['subject_id', 'f3']], struct=[['subject_id', 'struct']]) -datasource.inputs.sort_filelist = True - -my_workflow = pe.Workflow(name="my_workflow") -my_workflow.base_dir = os.path.abspath('.') - -my_workflow.connect([(infosource, datasource, [('subject_id', 'subject_id')]), - (datasource, preproc, [('func', 'inputspec.func'), - ('struct', 'inputspec.struct')])]) -my_workflow.run() -""" -and we can change a node attribute and run it again - -""" - -smoothnode = my_workflow.get_node('preproc.smooth') -assert (str(smoothnode) == 'preproc.smooth') -smoothnode.iterables = ('fwhm', [5., 10.]) -my_workflow.run() -""" -Visualizing workflows 2 ------------------------ - -In the case of nested workflows, we might want to look at expanded forms of the workflow. -""" diff --git a/nipype/__init__.py b/nipype/__init__.py index 43e9011175..54872f193e 100644 --- a/nipype/__init__.py +++ b/nipype/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -12,7 +11,9 @@ """ import os -from distutils.version import LooseVersion + +# No longer used internally but could be used externally. +from looseversion import LooseVersion from .info import URL as __url__, STATUS as __status__, __version__ from .utils.config import NipypeConfig @@ -24,14 +25,14 @@ import faulthandler faulthandler.enable() -except (ImportError, IOError) as e: +except (ImportError, OSError): pass config = NipypeConfig() logging = Logging(config) -class NipypeTester(object): +class NipypeTester: def __call__(self, doctests=True, parallel=False): try: import pytest @@ -83,41 +84,9 @@ def check_latest_version(raise_exception=False): import etelemetry logger = logging.getLogger("nipype.utils") - - INIT_MSG = "Running {packname} version {version} (latest: {latest})".format - - latest = {"version": "Unknown", "bad_versions": []} - result = None - try: - result = etelemetry.get_project("nipy/nipype") - except Exception as e: - logger.warning("Could not check for version updates: \n%s", e) - finally: - if result: - latest.update(**result) - if LooseVersion(__version__) != LooseVersion(latest["version"]): - logger.info( - INIT_MSG( - packname="nipype", version=__version__, latest=latest["version"] - ) - ) - else: - logger.info("No new version available.") - if latest["bad_versions"] and any( - [ - LooseVersion(__version__) == LooseVersion(ver) - for ver in latest["bad_versions"] - ] - ): - message = ( - "You are using a version of Nipype with a critical " - "bug. Please use a different version." - ) - if raise_exception: - raise RuntimeError(message) - else: - logger.critical(message) - return latest + return etelemetry.check_available_version( + "nipy/nipype", __version__, logger, raise_exception + ) # Run telemetry on import for interactive sessions, such as IPython, Jupyter notebooks, Python REPL @@ -128,4 +97,4 @@ def check_latest_version(raise_exception=False): from .interfaces.base import BaseInterface if BaseInterface._etelemetry_version_data is None: - BaseInterface._etelemetry_version_data = check_latest_version() + BaseInterface._etelemetry_version_data = check_latest_version() or "n/a" diff --git a/nipype/algorithms/__init__.py b/nipype/algorithms/__init__.py index b28fc516d2..a701f6fe59 100644 --- a/nipype/algorithms/__init__.py +++ b/nipype/algorithms/__init__.py @@ -1,10 +1,9 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Package contains pure python neuroimaging algorithms -Exaples: artifactdetect +Examples: artifactdetect """ __docformat__ = "restructuredtext" diff --git a/nipype/algorithms/confounds.py b/nipype/algorithms/confounds.py index 4a24ab8224..d2e6168ea7 100644 --- a/nipype/algorithms/confounds.py +++ b/nipype/algorithms/confounds.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -25,8 +24,8 @@ InputMultiPath, OutputMultiPath, SimpleInterface, + Tuple, ) -from ..utils import NUMPY_MMAP from ..utils.misc import normalize_mc_params IFLOGGER = logging.getLogger("nipype.interface") @@ -51,6 +50,11 @@ class ComputeDVARSInputSpec(BaseInterfaceInputSpec): remove_zerovariance = traits.Bool( True, usedefault=True, desc="remove voxels with zero variance" ) + variance_tol = traits.Float( + 1e-7, + usedefault=True, + desc="maximum variance to consider \"close to\" zero for the purposes of removal", + ) save_std = traits.Bool(True, usedefault=True, desc="save standardized DVARS") save_nstd = traits.Bool(False, usedefault=True, desc="save non-standardized DVARS") save_vxstd = traits.Bool( @@ -61,7 +65,7 @@ class ComputeDVARSInputSpec(BaseInterfaceInputSpec): series_tr = traits.Float(desc="repetition time in sec.") save_plot = traits.Bool(False, usedefault=True, desc="write DVARS plot") figdpi = traits.Int(100, usedefault=True, desc="output dpi for the plot") - figsize = traits.Tuple( + figsize = Tuple( traits.Float(11.7), traits.Float(2.3), usedefault=True, @@ -105,7 +109,7 @@ class ComputeDVARS(BaseInterface): input_spec = ComputeDVARSInputSpec output_spec = ComputeDVARSOutputSpec - references_ = [ + _references = [ { "entry": BibTeX( """\ @@ -146,7 +150,7 @@ class ComputeDVARS(BaseInterface): def __init__(self, **inputs): self._results = {} - super(ComputeDVARS, self).__init__(**inputs) + super().__init__(**inputs) def _gen_fname(self, suffix, ext=None): fname, in_ext = op.splitext(op.basename(self.inputs.in_file)) @@ -161,13 +165,14 @@ def _gen_fname(self, suffix, ext=None): if ext.startswith("."): ext = ext[1:] - return op.abspath("{}_{}.{}".format(fname, suffix, ext)) + return op.abspath(f"{fname}_{suffix}.{ext}") def _run_interface(self, runtime): dvars = compute_dvars( self.inputs.in_file, self.inputs.in_mask, remove_zerovariance=self.inputs.remove_zerovariance, + variance_tol=self.inputs.variance_tol, intensity_normalization=self.inputs.intensity_normalization, ) @@ -183,7 +188,7 @@ def _run_interface(self, runtime): if self.inputs.save_std: out_file = self._gen_fname("dvars_std", ext="tsv") - np.savetxt(out_file, dvars[0], fmt=b"%0.6f") + np.savetxt(out_file, dvars[0], fmt="%0.6f") self._results["out_std"] = out_file if self.inputs.save_plot: @@ -203,7 +208,7 @@ def _run_interface(self, runtime): if self.inputs.save_nstd: out_file = self._gen_fname("dvars_nstd", ext="tsv") - np.savetxt(out_file, dvars[1], fmt=b"%0.6f") + np.savetxt(out_file, dvars[1], fmt="%0.6f") self._results["out_nstd"] = out_file if self.inputs.save_plot: @@ -223,7 +228,7 @@ def _run_interface(self, runtime): if self.inputs.save_vxstd: out_file = self._gen_fname("dvars_vxstd", ext="tsv") - np.savetxt(out_file, dvars[2], fmt=b"%0.6f") + np.savetxt(out_file, dvars[2], fmt="%0.6f") self._results["out_vxstd"] = out_file if self.inputs.save_plot: @@ -246,8 +251,8 @@ def _run_interface(self, runtime): np.savetxt( out_file, np.vstack(dvars).T, - fmt=b"%0.8f", - delimiter=b"\t", + fmt="%0.8f", + delimiter="\t", header="std DVARS\tnon-std DVARS\tvx-wise std DVARS", comments="", ) @@ -282,7 +287,7 @@ class FramewiseDisplacementInputSpec(BaseInterfaceInputSpec): save_plot = traits.Bool(False, usedefault=True, desc="write FD plot") normalize = traits.Bool(False, usedefault=True, desc="calculate FD in mm/s") figdpi = traits.Int(100, usedefault=True, desc="output dpi for the FD plot") - figsize = traits.Tuple( + figsize = Tuple( traits.Float(11.7), traits.Float(2.3), usedefault=True, @@ -312,7 +317,7 @@ class FramewiseDisplacement(BaseInterface): input_spec = FramewiseDisplacementInputSpec output_spec = FramewiseDisplacementOutputSpec - references_ = [ + _references = [ { "entry": BibTeX( """\ @@ -461,12 +466,12 @@ class CompCorInputSpec(BaseInterfaceInputSpec): "cosine", False, usedefault=True, - desc="Detrend time series prior to component " "extraction", + desc="Detrend time series prior to component extraction", ) use_regress_poly = traits.Bool( deprecated="0.15.0", new_name="pre_filter", - desc=("use polynomial regression " "pre-component extraction"), + desc=("use polynomial regression pre-component extraction"), ) regress_poly_degree = traits.Range( low=1, value=1, usedefault=True, desc="the degree polynomial to use" @@ -557,7 +562,7 @@ class CompCor(SimpleInterface): input_spec = CompCorInputSpec output_spec = CompCorOutputSpec - references_ = [ + _references = [ { "tags": ["method", "implementation"], "entry": BibTeX( @@ -578,8 +583,8 @@ class CompCor(SimpleInterface): ] def __init__(self, *args, **kwargs): - """ exactly the same as compcor except the header """ - super(CompCor, self).__init__(*args, **kwargs) + """exactly the same as compcor except the header""" + super().__init__(*args, **kwargs) self._header = "CompCor" def _run_interface(self, runtime): @@ -599,7 +604,7 @@ def _run_interface(self, runtime): else 0 ) - imgseries = nb.load(self.inputs.realigned_file, mmap=NUMPY_MMAP) + imgseries = nb.load(self.inputs.realigned_file) if len(imgseries.shape) != 4: raise ValueError( @@ -614,7 +619,7 @@ def _run_interface(self, runtime): if len(mask_images) == 0: img = nb.Nifti1Image( - np.ones(imgseries.shape[:3], dtype=np.bool), + np.ones(imgseries.shape[:3], dtype=bool), affine=imgseries.affine, header=imgseries.header, ) @@ -684,7 +689,7 @@ def _run_interface(self, runtime): np.savetxt( components_file, components, - fmt=b"%.10f", + fmt="%.10f", delimiter="\t", header="\t".join(components_header), comments="", @@ -708,7 +713,7 @@ def _run_interface(self, runtime): self.inputs.pre_filter ] ncols = filter_basis.shape[1] if filter_basis.size > 0 else 0 - header = ["{}{:02d}".format(ftype, i) for i in range(ncols)] + header = [f"{ftype}{i:02d}" for i in range(ncols)] if skip_vols: old_basis = filter_basis # nrows defined above @@ -719,12 +724,12 @@ def _run_interface(self, runtime): filter_basis[skip_vols:, :ncols] = old_basis filter_basis[:skip_vols, -skip_vols:] = np.eye(skip_vols) header.extend( - ["NonSteadyStateOutlier{:02d}".format(i) for i in range(skip_vols)] + [f"NonSteadyStateOutlier{i:02d}" for i in range(skip_vols)] ) np.savetxt( self._results["pre_filter_file"], filter_basis, - fmt=b"%.10f", + fmt="%.10f", delimiter="\t", header="\t".join(header), comments="", @@ -742,7 +747,7 @@ def _run_interface(self, runtime): not_retained = np.where(np.logical_not(metadata["retained"])) components_names[retained] = components_header components_names[not_retained] = [ - "dropped{}".format(i) for i in range(len(not_retained[0])) + f"dropped{i}" for i in range(len(not_retained[0])) ] with open(self._results["metadata_file"], "w") as f: f.write("\t".join(["component"] + list(metadata.keys())) + "\n") @@ -763,7 +768,7 @@ def _make_headers(self, num_col): if isdefined(self.inputs.header_prefix) else self._header ) - headers = ["{}{:02d}".format(header, i) for i in range(num_col)] + headers = [f"{header}{i:02d}" for i in range(num_col)] return headers @@ -775,8 +780,8 @@ class ACompCor(CompCor): """ def __init__(self, *args, **kwargs): - """ exactly the same as compcor except the header """ - super(ACompCor, self).__init__(*args, **kwargs) + """exactly the same as compcor except the header""" + super().__init__(*args, **kwargs) self._header = "aCompCor" @@ -802,7 +807,7 @@ class TCompCorInputSpec(CompCorInputSpec): class TCompCorOutputSpec(CompCorOutputSpec): # and all the fields in CompCorOutputSpec high_variance_masks = OutputMultiPath( - File(exists=True), desc=(("voxels exceeding the variance" " threshold")) + File(exists=True), desc=("voxels exceeding the variance threshold") ) @@ -826,8 +831,8 @@ class TCompCor(CompCor): output_spec = TCompCorOutputSpec def __init__(self, *args, **kwargs): - """ exactly the same as compcor except the header """ - super(TCompCor, self).__init__(*args, **kwargs) + """exactly the same as compcor except the header""" + super().__init__(*args, **kwargs) self._header = "tCompCor" self._mask_files = [] @@ -836,7 +841,7 @@ def _process_masks(self, mask_images, timeseries=None): self._mask_files = [] timeseries = np.asanyarray(timeseries) for i, img in enumerate(mask_images): - mask = np.asanyarray(img.dataobj).astype(np.bool) + mask = np.asanyarray(img.dataobj).astype(bool) imgseries = timeseries[mask, :] imgseries = regress_poly(2, imgseries)[0] tSTD = _compute_tSTD(imgseries, 0, axis=-1) @@ -849,10 +854,10 @@ def _process_masks(self, mask_images, timeseries=None): out_image = nb.Nifti1Image(mask_data, affine=img.affine, header=img.header) # save mask - mask_file = os.path.abspath("mask_{:03d}.nii.gz".format(i)) + mask_file = os.path.abspath(f"mask_{i:03d}.nii.gz") out_image.to_filename(mask_file) IFLOGGER.debug( - "tCompcor computed and saved mask of shape %s to " "mask_file %s", + "tCompcor computed and saved mask of shape %s to mask_file %s", str(mask.shape), mask_file, ) @@ -861,7 +866,7 @@ def _process_masks(self, mask_images, timeseries=None): return out_images def _list_outputs(self): - outputs = super(TCompCor, self)._list_outputs() + outputs = super()._list_outputs() outputs["high_variance_masks"] = self._mask_files return outputs @@ -915,7 +920,7 @@ class TSNR(BaseInterface): output_spec = TSNROutputSpec def _run_interface(self, runtime): - img = nb.load(self.inputs.in_file[0], mmap=NUMPY_MMAP) + img = nb.load(self.inputs.in_file[0]) header = img.header.copy() vollist = [nb.load(filename) for filename in self.inputs.in_file] data = np.concatenate( @@ -995,8 +1000,19 @@ def _list_outputs(self): return self._results +def _AR_est_YW(x, order, rxx=None): + """Retrieve AR coefficients while dropping the sig_sq return value""" + from nitime.algorithms import AR_est_YW + + return AR_est_YW(x, order, rxx=rxx)[0] + + def compute_dvars( - in_file, in_mask, remove_zerovariance=False, intensity_normalization=1000 + in_file, + in_mask, + remove_zerovariance=False, + intensity_normalization=1000, + variance_tol=0.0, ): """ Compute the :abbr:`DVARS (D referring to temporal @@ -1028,36 +1044,41 @@ def compute_dvars( """ import numpy as np import nibabel as nb - from nitime.algorithms import AR_est_YW import warnings - func = nb.load(in_file).get_fdata(dtype=np.float32) - mask = np.asanyarray(nb.load(in_mask).dataobj).astype(np.uint8) + func = np.float32(nb.load(in_file).dataobj) + mask = np.bool_(nb.load(in_mask).dataobj) if len(func.shape) != 4: raise RuntimeError("Input fMRI dataset should be 4-dimensional") - idx = np.where(mask > 0) - mfunc = func[idx[0], idx[1], idx[2], :] + mfunc = func[mask] if intensity_normalization != 0: mfunc = (mfunc / np.median(mfunc)) * intensity_normalization # Robust standard deviation (we are using "lower" interpolation # because this is what FSL is doing - func_sd = ( - np.percentile(mfunc, 75, axis=1, interpolation="lower") - - np.percentile(mfunc, 25, axis=1, interpolation="lower") - ) / 1.349 + try: + func_sd = ( + np.percentile(mfunc, 75, axis=1, method="lower") + - np.percentile(mfunc, 25, axis=1, method="lower") + ) / 1.349 + except TypeError: # NP < 1.22 + func_sd = ( + np.percentile(mfunc, 75, axis=1, interpolation="lower") + - np.percentile(mfunc, 25, axis=1, interpolation="lower") + ) / 1.349 if remove_zerovariance: - mfunc = mfunc[func_sd != 0, :] - func_sd = func_sd[func_sd != 0] + zero_variance_voxels = func_sd > variance_tol + mfunc = mfunc[zero_variance_voxels, :] + func_sd = func_sd[zero_variance_voxels] # Compute (non-robust) estimate of lag-1 autocorrelation ar1 = np.apply_along_axis( - AR_est_YW, 1, regress_poly(0, mfunc, remove_mean=True)[0].astype(np.float32), 1 - )[:, 0] + _AR_est_YW, 1, regress_poly(0, mfunc, remove_mean=True)[0].astype(np.float32), 1 + ) # Compute (predicted) standard deviation of temporal difference time series diff_sdhat = np.squeeze(np.sqrt(((1 - ar1) * 2).tolist())) * func_sd @@ -1115,7 +1136,7 @@ def plot_confound(tseries, figsize, name, units=None, series_tr=None, normalize= xlabel = "Frame #" if series_tr is not None: - xlabel = "Frame # ({} sec TR)".format(series_tr) + xlabel = f"Frame # ({series_tr} sec TR)" ax.set_xlabel(xlabel) ylim = ax.get_ylim() @@ -1137,7 +1158,7 @@ def is_outlier(points, thresh=3.5): a modified z-score (based on the median absolute deviation) greater than this value will be classified as outliers. - :return: A bolean mask, of size numobservations-length array. + :return: A boolean mask, of size numobservations-length array. .. note:: References @@ -1259,25 +1280,18 @@ def combine_mask_files(mask_files, mask_method=None, mask_index=None): mask_index = 0 else: raise ValueError( - ( - "When more than one mask file is provided, " - "one of merge_method or mask_index must be " - "set" - ) + "When more than one mask file is provided, " + "one of merge_method or mask_index must be " + "set" ) if mask_index < len(mask_files): - mask = nb.load(mask_files[mask_index], mmap=NUMPY_MMAP) + mask = nb.load(mask_files[mask_index]) return [mask] raise ValueError( - ("mask_index {0} must be less than number of mask " "files {1}").format( - mask_index, len(mask_files) - ) + f"mask_index {mask_index} must be less than number of mask files {len(mask_files)}" ) - masks = [] if mask_method == "none": - for filename in mask_files: - masks.append(nb.load(filename, mmap=NUMPY_MMAP)) - return masks + return [nb.load(filename) for filename in mask_files] if mask_method == "union": mask = None @@ -1380,7 +1394,7 @@ def compute_noise_components( md_retained = [] for name, img in zip(mask_names, mask_images): - mask = np.asanyarray(nb.squeeze_image(img).dataobj).astype(np.bool) + mask = np.asanyarray(nb.squeeze_image(img).dataobj).astype(bool) if imgseries.shape[:3] != mask.shape: raise ValueError( "Inputs for CompCor, timeseries and mask, do not have " @@ -1436,7 +1450,7 @@ def compute_noise_components( else: u = np.full((M.shape[0], 1), np.nan, dtype=np.float32) - variance_explained = (s ** 2) / np.sum(s ** 2) + variance_explained = (s**2) / np.sum(s**2) cumulative_variance_explained = np.cumsum(variance_explained) num_components = int(components_criterion) diff --git a/nipype/algorithms/icc.py b/nipype/algorithms/icc.py index cd73caa0ca..2ea5f43d87 100644 --- a/nipype/algorithms/icc.py +++ b/nipype/algorithms/icc.py @@ -1,7 +1,7 @@ -# -*- coding: utf-8 -*- import os +from functools import lru_cache import numpy as np -from numpy import ones, kron, mean, eye, hstack, dot, tile +from numpy import ones, kron, mean, eye, hstack, tile from numpy.linalg import pinv import nibabel as nb from ..interfaces.base import ( @@ -11,7 +11,6 @@ traits, File, ) -from ..utils import NUMPY_MMAP class ICCInputSpec(BaseInterfaceInputSpec): @@ -45,10 +44,7 @@ def _run_interface(self, runtime): maskdata = np.logical_not(np.logical_or(maskdata == 0, np.isnan(maskdata))) session_datas = [ - [ - nb.load(fname, mmap=NUMPY_MMAP).get_fdata()[maskdata].reshape(-1, 1) - for fname in sessions - ] + [nb.load(fname).get_fdata()[maskdata].reshape(-1, 1) for fname in sessions] for sessions in self.inputs.subjects_sessions ] list_of_sessions = [np.dstack(session_data) for session_data in session_datas] @@ -90,7 +86,17 @@ def _list_outputs(self): return outputs -def ICC_rep_anova(Y): +@lru_cache(maxsize=1) +def ICC_projection_matrix(shape): + nb_subjects, nb_conditions = shape + + x = kron(eye(nb_conditions), ones((nb_subjects, 1))) # sessions + x0 = tile(eye(nb_subjects), (nb_conditions, 1)) # subjects + X = hstack([x, x0]) + return X @ pinv(X.T @ X, hermitian=True) @ X.T + + +def ICC_rep_anova(Y, projection_matrix=None): """ the data Y are entered as a 'table' ie subjects are in rows and repeated measures in columns @@ -98,36 +104,43 @@ def ICC_rep_anova(Y): One Sample Repeated measure ANOVA Y = XB + E with X = [FaTor / Subjects] - """ + ``ICC_rep_anova`` involves an expensive operation to compute a projection + matrix, which depends only on the shape of ``Y``, which is computed by + calling ``ICC_projection_matrix(Y.shape)``. If arrays of multiple shapes are + expected, it may be worth pre-computing and passing directly as an + argument to ``ICC_rep_anova``. + + If only one ``Y.shape`` will occur, you do not need to explicitly handle + these, as the most recently calculated matrix is cached automatically. + For example, if you are running the same computation on every voxel of + an image, you will see significant speedups. + + If a ``Y`` is passed with a new shape, a new matrix will be calculated + automatically. + """ [nb_subjects, nb_conditions] = Y.shape dfc = nb_conditions - 1 - dfe = (nb_subjects - 1) * dfc dfr = nb_subjects - 1 + dfe = dfr * dfc # Compute the repeated measure effect # ------------------------------------ # Sum Square Total - mean_Y = mean(Y) - SST = ((Y - mean_Y) ** 2).sum() - - # create the design matrix for the different levels - x = kron(eye(nb_conditions), ones((nb_subjects, 1))) # sessions - x0 = tile(eye(nb_subjects), (nb_conditions, 1)) # subjects - X = hstack([x, x0]) + demeaned_Y = Y - mean(Y) + SST = np.sum(demeaned_Y**2) # Sum Square Error - predicted_Y = dot(dot(dot(X, pinv(dot(X.T, X))), X.T), Y.flatten("F")) - residuals = Y.flatten("F") - predicted_Y - SSE = (residuals ** 2).sum() - - residuals.shape = Y.shape + if projection_matrix is None: + projection_matrix = ICC_projection_matrix(Y.shape) + residuals = Y.flatten("F") - (projection_matrix @ Y.flatten("F")) + SSE = np.sum(residuals**2) MSE = SSE / dfe - # Sum square session effect - between colums/sessions - SSC = ((mean(Y, 0) - mean_Y) ** 2).sum() * nb_subjects + # Sum square session effect - between columns/sessions + SSC = np.sum(mean(demeaned_Y, 0) ** 2) * nb_subjects MSC = SSC / dfc / nb_subjects session_effect_F = MSC / MSE @@ -136,8 +149,8 @@ def ICC_rep_anova(Y): SSR = SST - SSC - SSE MSR = SSR / dfr - # ICC(3,1) = (mean square subjeT - mean square error) / - # (mean square subjeT + (k-1)*-mean square error) + # ICC(3,1) = (mean square subject - mean square error) / + # (mean square subject + (k-1)*-mean square error) ICC = (MSR - MSE) / (MSR + dfc * MSE) e_var = MSE # variance of error diff --git a/nipype/algorithms/mesh.py b/nipype/algorithms/mesh.py index ab70237030..5ba00d2675 100644 --- a/nipype/algorithms/mesh.py +++ b/nipype/algorithms/mesh.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -15,6 +14,7 @@ TraitedSpec, File, BaseInterfaceInputSpec, + Tuple, ) from ..interfaces.vtkbase import tvtk from ..interfaces import vtkbase as VTKInfo @@ -23,14 +23,14 @@ class TVTKBaseInterface(BaseInterface): - """ A base class for interfaces using VTK """ + """A base class for interfaces using VTK""" _redirect_x = True def __init__(self, **inputs): if VTKInfo.no_tvtk(): raise ImportError("This interface requires tvtk to run.") - super(TVTKBaseInterface, self).__init__(**inputs) + super().__init__(**inputs) class WarpPointsInputSpec(BaseInterfaceInputSpec): @@ -92,7 +92,7 @@ def _gen_fname(self, in_file, suffix="generated", ext=None): if ext[0] == ".": ext = ext[1:] - return op.abspath("%s_%s.%s" % (fname, suffix, ext)) + return op.abspath(f"{fname}_{suffix}.{ext}") def _run_interface(self, runtime): import nibabel as nb @@ -142,12 +142,12 @@ class ComputeMeshWarpInputSpec(BaseInterfaceInputSpec): surface1 = File( exists=True, mandatory=True, - desc=("Reference surface (vtk format) to which compute " "distance."), + desc=("Reference surface (vtk format) to which compute distance."), ) surface2 = File( exists=True, mandatory=True, - desc=("Test surface (vtk format) from which compute " "distance."), + desc=("Test surface (vtk format) from which compute distance."), ) metric = traits.Enum( "euclidean", "sqeuclidean", usedefault=True, desc="norm used to report distance" @@ -164,7 +164,7 @@ class ComputeMeshWarpInputSpec(BaseInterfaceInputSpec): out_warp = File( "surfwarp.vtk", usedefault=True, - desc="vtk file based on surface1 and warpings mapping it " "to surface2", + desc="vtk file based on surface1 and warpings mapping it to surface2", ) out_file = File( "distance.npy", @@ -177,7 +177,7 @@ class ComputeMeshWarpOutputSpec(TraitedSpec): distance = traits.Float(desc="computed distance") out_warp = File( exists=True, - desc=("vtk file with the vertex-wise " "mapping of surface1 to surface2"), + desc=("vtk file with the vertex-wise mapping of surface1 to surface2"), ) out_file = File( exists=True, desc="numpy file keeping computed distances and weights" @@ -290,7 +290,7 @@ class MeshWarpMathsInputSpec(BaseInterfaceInputSpec): ) float_trait = traits.Either( traits.Float(1.0), - traits.Tuple(traits.Float(1.0), traits.Float(1.0), traits.Float(1.0)), + Tuple(traits.Float(1.0), traits.Float(1.0), traits.Float(1.0)), ) operator = traits.Either( @@ -309,7 +309,7 @@ class MeshWarpMathsInputSpec(BaseInterfaceInputSpec): out_warp = File( "warp_maths.vtk", usedefault=True, - desc="vtk file based on in_surf and warpings mapping it " "to out_file", + desc="vtk file based on in_surf and warpings mapping it to out_file", ) out_file = File("warped_surf.vtk", usedefault=True, desc="vtk with surface warped") @@ -317,7 +317,7 @@ class MeshWarpMathsInputSpec(BaseInterfaceInputSpec): class MeshWarpMathsOutputSpec(TraitedSpec): out_warp = File( exists=True, - desc=("vtk file with the vertex-wise " "mapping of surface1 to surface2"), + desc=("vtk file with the vertex-wise mapping of surface1 to surface2"), ) out_file = File(exists=True, desc="vtk with surface warped") @@ -423,7 +423,7 @@ class P2PDistance(ComputeMeshWarp): """ def __init__(self, **inputs): - super(P2PDistance, self).__init__(**inputs) + super().__init__(**inputs) IFLOGGER.warning( "This interface has been deprecated since 1.0, please " "use ComputeMeshWarp" diff --git a/nipype/algorithms/metrics.py b/nipype/algorithms/metrics.py index 611ec57af5..1f0ca3a9f2 100644 --- a/nipype/algorithms/metrics.py +++ b/nipype/algorithms/metrics.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -42,13 +41,13 @@ class DistanceInputSpec(BaseInterfaceInputSpec): "eucl_wmean", "eucl_max", desc='""eucl_min": Euclidean distance between two closest points\ - "eucl_cog": mean Euclidian distance between the Center of Gravity\ + "eucl_cog": mean Euclidean distance between the Center of Gravity\ of volume1 and CoGs of volume2\ - "eucl_mean": mean Euclidian minimum distance of all volume2 voxels\ + "eucl_mean": mean Euclidean minimum distance of all volume2 voxels\ to volume1\ - "eucl_wmean": mean Euclidian minimum distance of all volume2 voxels\ + "eucl_wmean": mean Euclidean minimum distance of all volume2 voxels\ to volume1 weighted by their values\ - "eucl_max": maximum over minimum Euclidian distances of all volume2\ + "eucl_max": maximum over minimum Euclidean distances of all volume2\ voxels to volume1 (also known as the Hausdorff distance)', usedefault=True, ) @@ -63,8 +62,7 @@ class DistanceOutputSpec(TraitedSpec): class Distance(BaseInterface): - """Calculates distance between two volumes. - """ + """Calculates distance between two volumes.""" input_spec = DistanceInputSpec output_spec = DistanceOutputSpec @@ -89,10 +87,10 @@ def _get_coordinates(self, data, affine): def _eucl_min(self, nii1, nii2): from scipy.spatial.distance import cdist, euclidean - origdata1 = np.asanyarray(nii1.dataobj).astype(np.bool) + origdata1 = np.asanyarray(nii1.dataobj).astype(bool) border1 = self._find_border(origdata1) - origdata2 = np.asanyarray(nii2.dataobj).astype(np.bool) + origdata2 = np.asanyarray(nii2.dataobj).astype(bool) border2 = self._find_border(origdata2) set1_coordinates = self._get_coordinates(border1, nii1.affine) @@ -135,10 +133,10 @@ def _eucl_cog(self, nii1, nii2): def _eucl_mean(self, nii1, nii2, weighted=False): from scipy.spatial.distance import cdist - origdata1 = np.asanyarray(nii1.dataobj).astype(np.bool) + origdata1 = np.asanyarray(nii1.dataobj).astype(bool) border1 = self._find_border(origdata1) - origdata2 = np.asanyarray(nii2.dataobj).astype(np.bool) + origdata2 = np.asanyarray(nii2.dataobj).astype(bool) set1_coordinates = self._get_coordinates(border1, nii1.affine) set2_coordinates = self._get_coordinates(origdata2, nii2.affine) @@ -151,7 +149,7 @@ def _eucl_mean(self, nii1, nii2, weighted=False): import matplotlib.pyplot as plt plt.figure() - plt.hist(min_dist_matrix, 50, normed=1, facecolor="green") + plt.hist(min_dist_matrix, 50, density=True, facecolor="green") plt.savefig(self._hist_filename) plt.clf() plt.close() @@ -338,7 +336,7 @@ def _run_interface(self, runtime): if self.inputs.weighting != "none": weights = weights / np.array(volumes1) if self.inputs.weighting == "squared_vol": - weights = weights ** 2 + weights = weights**2 weights = weights / np.sum(weights) both_data = np.zeros(data1.shape) @@ -480,13 +478,13 @@ def _run_interface(self, runtime): if np.any(refdata > 1.0): iflogger.warning( - 'Values greater than 1.0 found in "in_ref" input, ' "scaling values." + 'Values greater than 1.0 found in "in_ref" input, scaling values.' ) refdata /= refdata.max() if np.any(tstdata > 1.0): iflogger.warning( - 'Values greater than 1.0 found in "in_tst" input, ' "scaling values." + 'Values greater than 1.0 found in "in_tst" input, scaling values.' ) tstdata /= tstdata.max() @@ -501,7 +499,7 @@ def _run_interface(self, runtime): volumes = np.sum((refdata + tstdata) > 0, axis=1).reshape((-1, ncomp)) weights = 1.0 / volumes if self.inputs.weighting == "squared_vol": - weights = weights ** 2 + weights = weights**2 weights = weights / np.sum(weights) dices = 2.0 * jaccards / (jaccards + 1.0) @@ -542,7 +540,7 @@ class ErrorMapOutputSpec(TraitedSpec): class ErrorMap(BaseInterface): - """ Calculates the error (distance) map between two input volumes. + """Calculates the error (distance) map between two input volumes. Example ------- @@ -592,7 +590,7 @@ def _run_interface(self, runtime): # Scale the difference if self.inputs.metric == "sqeuclidean": - errvector = diffvector ** 2 + errvector = diffvector**2 if comps > 1: errvector = np.sum(errvector, axis=1) else: diff --git a/nipype/algorithms/misc.py b/nipype/algorithms/misc.py index 7ba401a130..fe27b877a2 100644 --- a/nipype/algorithms/misc.py +++ b/nipype/algorithms/misc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Miscellaneous algorithms.""" @@ -24,9 +23,9 @@ isdefined, DynamicTraitedSpec, Undefined, + Tuple, ) from ..utils.filemanip import fname_presuffix, split_filename, ensure_list -from ..utils import NUMPY_MMAP from . import confounds @@ -142,8 +141,7 @@ class SimpleThresholdOutputSpec(TraitedSpec): class SimpleThreshold(BaseInterface): - """Applies a threshold to input volumes - """ + """Applies a threshold to input volumes""" input_spec = SimpleThresholdInputSpec output_spec = SimpleThresholdOutputSpec @@ -208,7 +206,7 @@ def _gen_output_filename(self, name): def _run_interface(self, runtime): for fname in self.inputs.volumes: - img = nb.load(fname, mmap=NUMPY_MMAP) + img = nb.load(fname) affine = img.affine affine = np.dot(self.inputs.transformation_matrix, affine) @@ -241,8 +239,7 @@ class CreateNiftiOutputSpec(TraitedSpec): class CreateNifti(BaseInterface): - """Creates a nifti volume - """ + """Creates a nifti volume""" input_spec = CreateNiftiInputSpec output_spec = CreateNiftiOutputSpec @@ -274,43 +271,58 @@ def _list_outputs(self): return outputs -class GunzipInputSpec(BaseInterfaceInputSpec): - in_file = File(exists=True, mandatory=True) +class GzipInputSpec(TraitedSpec): + in_file = File(exists=True, mandatory=True, desc="file to (de)compress") + mode = traits.Enum( + "compress", "decompress", usedefault=True, desc="compress or decompress" + ) -class GunzipOutputSpec(TraitedSpec): - out_file = File(exists=True) +class GzipOutputSpec(TraitedSpec): + out_file = File() -class Gunzip(BaseInterface): - """Gunzip wrapper +class Gzip(BaseInterface): + """Gzip wrapper - >>> from nipype.algorithms.misc import Gunzip - >>> gunzip = Gunzip(in_file='tpms_msk.nii.gz') - >>> res = gunzip.run() + >>> from nipype.algorithms.misc import Gzip + >>> gzip = Gzip(in_file='tpms_msk.nii.gz', mode="decompress") + >>> res = gzip.run() >>> res.outputs.out_file # doctest: +ELLIPSIS '.../tpms_msk.nii' + >>> gzip = Gzip(in_file='tpms_msk.nii') + >>> res = gzip.run() + >>> res.outputs.out_file # doctest: +ELLIPSIS + '.../tpms_msk.nii.gz' + .. testcleanup:: >>> os.unlink('tpms_msk.nii') """ - input_spec = GunzipInputSpec - output_spec = GunzipOutputSpec + input_spec = GzipInputSpec + output_spec = GzipOutputSpec def _gen_output_file_name(self): _, base, ext = split_filename(self.inputs.in_file) - if ext[-3:].lower() == ".gz": + if self.inputs.mode == "decompress" and ext[-3:].lower() == ".gz": ext = ext[:-3] + elif self.inputs.mode == "compress": + ext = f"{ext}.gz" return os.path.abspath(base + ext) def _run_interface(self, runtime): import gzip import shutil - with gzip.open(self.inputs.in_file, "rb") as in_file: - with open(self._gen_output_file_name(), "wb") as out_file: + if self.inputs.mode == "compress": + open_input, open_output = open, gzip.open + else: + open_input, open_output = gzip.open, open + + with open_input(self.inputs.in_file, "rb") as in_file: + with open_output(self._gen_output_file_name(), "wb") as out_file: shutil.copyfileobj(in_file, out_file) return runtime @@ -320,6 +332,27 @@ def _list_outputs(self): return outputs +class GunzipInputSpec(GzipInputSpec): + mode = traits.Enum("decompress", usedefault=True, desc="decompress or compress") + + +class Gunzip(Gzip): + """Gunzip wrapper + + >>> from nipype.algorithms.misc import Gunzip + >>> gunzip = Gunzip(in_file='tpms_msk.nii.gz') + >>> res = gunzip.run() + >>> res.outputs.out_file # doctest: +ELLIPSIS + '.../tpms_msk.nii' + + .. testcleanup:: + + >>> os.unlink('tpms_msk.nii') + """ + + input_spec = GunzipInputSpec + + def replaceext(in_list, ext): out_list = list() for filename in in_list: @@ -461,7 +494,7 @@ def merge_csvs(in_list): try: in_array = np.loadtxt(in_file, delimiter=",", skiprows=1) except ValueError: - with open(in_file, "r") as first: + with open(in_file) as first: header_line = first.readline() header_list = header_line.split(",") @@ -499,7 +532,7 @@ def remove_identical_paths(in_files): commonprefix = op.commonprefix(in_files) lastslash = commonprefix.rfind("/") commonpath = commonprefix[0 : (lastslash + 1)] - for fileidx, in_file in enumerate(in_files): + for in_file in in_files: path, name, ext = split_filename(in_file) in_file = op.join(path, name) name = in_file.replace(commonpath, "") @@ -516,11 +549,9 @@ def maketypelist(rowheadings, shape, extraheadingBool, extraheading): if rowheadings: typelist.append(("heading", "a40")) if len(shape) > 1: - for idx in range(1, (min(shape) + 1)): - typelist.append((str(idx), float)) + typelist.extend((str(idx), float) for idx in range(1, (min(shape) + 1))) else: - for idx in range(1, (shape[0] + 1)): - typelist.append((str(idx), float)) + typelist.extend((str(idx), float) for idx in range(1, (shape[0] + 1))) if extraheadingBool: typelist.append((extraheading, "a40")) iflogger.info(typelist) @@ -636,9 +667,9 @@ def _run_interface(self, runtime): if isdefined(self.inputs.row_headings): iflogger.info( - 'Row headings have been provided. Adding "labels"' "column header." + 'Row headings have been provided. Adding "labels" column header.' ) - prefix = '"{p}","'.format(p=self.inputs.row_heading_title) + prefix = f'"{self.inputs.row_heading_title}","' csv_headings = prefix + '","'.join(itertools.chain(headings)) + '"\n' rowheadingsBool = True else: @@ -653,7 +684,7 @@ def _run_interface(self, runtime): output_array = merge_csvs(self.inputs.in_files) _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".csv": + if ext != ".csv": ext = ".csv" out_file = op.abspath(name + ext) @@ -681,8 +712,7 @@ def _run_interface(self, runtime): mx = shape[0] else: mx = 1 - for idx in range(0, mx): - extrafieldlist.append(self.inputs.extra_field) + extrafieldlist.extend(self.inputs.extra_field for idx in range(mx)) iflogger.info(len(extrafieldlist)) output[extraheading] = extrafieldlist iflogger.info(output) @@ -695,7 +725,7 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self.output_spec().get() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".csv": + if ext != ".csv": ext = ".csv" out_file = op.abspath(name + ext) outputs["csv_file"] = out_file @@ -739,9 +769,9 @@ class AddCSVColumn(BaseInterface): output_spec = AddCSVColumnOutputSpec def _run_interface(self, runtime): - in_file = open(self.inputs.in_file, "r") + in_file = open(self.inputs.in_file) _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".csv": + if ext != ".csv": ext = ".csv" out_file = op.abspath(name + ext) @@ -761,7 +791,7 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self.output_spec().get() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".csv": + if ext != ".csv": ext = ".csv" out_file = op.abspath(name + ext) outputs["csv_file"] = out_file @@ -775,12 +805,12 @@ class AddCSVRowInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): def __setattr__(self, key, value): if key not in self.copyable_trait_names(): if not isdefined(value): - super(AddCSVRowInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) self._outputs[key] = value else: if key in self._outputs: self._outputs[key] = value - super(AddCSVRowInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) class AddCSVRowOutputSpec(TraitedSpec): @@ -817,7 +847,7 @@ class AddCSVRow(BaseInterface): output_spec = AddCSVRowOutputSpec def __init__(self, infields=None, force_run=True, **kwargs): - super(AddCSVRow, self).__init__(**kwargs) + super().__init__(**kwargs) undefined_traits = {} self._infields = infields self._have_lock = False @@ -838,7 +868,7 @@ def _run_interface(self, runtime): import pandas as pd except ImportError as e: raise ImportError( - "This interface requires pandas " "(http://pandas.pydata.org/) to run." + "This interface requires pandas (http://pandas.pydata.org/) to run." ) from e try: @@ -849,10 +879,8 @@ def _run_interface(self, runtime): from warnings import warn warn( - ( - "Python module filelock was not found: AddCSVRow will not be" - " thread-safe in multi-processor execution" - ) + "Python module filelock was not found: AddCSVRow will not be" + " thread-safe in multi-processor execution" ) input_dict = {} @@ -893,7 +921,7 @@ def _list_outputs(self): return outputs def _outputs(self): - return self._add_output_traits(super(AddCSVRow, self)._outputs()) + return self._add_output_traits(super()._outputs()) def _add_output_traits(self, base): return base @@ -935,7 +963,6 @@ class CalculateNormalizedMoments(BaseInterface): output_spec = CalculateNormalizedMomentsOutputSpec def _run_interface(self, runtime): - self._moments = calc_moments(self.inputs.timeseries_file, self.inputs.moment) return runtime @@ -971,7 +998,7 @@ class AddNoiseInputSpec(TraitedSpec): ) in_mask = File( exists=True, - desc=("input mask, voxels outside this mask " "will be considered background"), + desc=("input mask, voxels outside this mask will be considered background"), ) snr = traits.Float(10.0, desc="desired output SNR in dB", usedefault=True) dist = traits.Enum( @@ -986,7 +1013,7 @@ class AddNoiseInputSpec(TraitedSpec): "rayleigh", usedefault=True, mandatory=True, - desc=("desired noise distribution, currently " "only normal is implemented"), + desc=("desired noise distribution, currently only normal is implemented"), ) out_file = File(desc="desired output filename") @@ -1038,7 +1065,7 @@ def _run_interface(self, runtime): def _gen_output_filename(self): if not isdefined(self.inputs.out_file): _, base, ext = split_filename(self.inputs.in_file) - out_file = os.path.abspath("%s_SNR%03.2f%s" % (base, self.inputs.snr, ext)) + out_file = os.path.abspath(f"{base}_SNR{self.inputs.snr:03.2f}{ext}") else: out_file = self.inputs.out_file @@ -1089,7 +1116,7 @@ def gen_noise(self, image, mask=None, snr_db=10.0, dist="normal", bg_dist="norma im_noise = np.sqrt((image + stde_1) ** 2 + (stde_2) ** 2) else: raise NotImplementedError( - ("Only normal and rician distributions " "are supported") + "Only normal and rician distributions are supported" ) return im_noise @@ -1145,9 +1172,9 @@ def _list_outputs(self): class SplitROIsInputSpec(TraitedSpec): - in_file = File(exists=True, mandatory=True, desc="file to be splitted") + in_file = File(exists=True, mandatory=True, desc="file to be split") in_mask = File(exists=True, desc="only process files inside mask") - roi_size = traits.Tuple(traits.Int, traits.Int, traits.Int, desc="desired ROI size") + roi_size = Tuple(traits.Int, traits.Int, traits.Int, desc="desired ROI size") class SplitROIsOutputSpec(TraitedSpec): @@ -1318,13 +1345,13 @@ def split_rois(in_file, mask=None, roishape=None): """ import nibabel as nb import numpy as np - from math import sqrt, ceil + from math import ceil import os.path as op if roishape is None: roishape = (10, 10, 1) - im = nb.load(in_file, mmap=NUMPY_MMAP) + im = nb.load(in_file) imshape = im.shape dshape = imshape[:3] nvols = imshape[-1] @@ -1409,13 +1436,13 @@ def merge_rois(in_files, in_idxs, in_ref, dtype=None, out_file=None): # to avoid memory errors if op.splitext(in_ref)[1] == ".gz": try: - iflogger.info("uncompress %i", in_ref) + iflogger.info("uncompress %s", in_ref) sp.check_call(["gunzip", in_ref], stdout=sp.PIPE, shell=True) in_ref = op.splitext(in_ref)[0] except: pass - ref = nb.load(in_ref, mmap=NUMPY_MMAP) + ref = nb.load(in_ref) aff = ref.affine hdr = ref.header.copy() rsh = ref.shape @@ -1463,17 +1490,16 @@ def merge_rois(in_files, in_idxs, in_ref, dtype=None, out_file=None): for cname, iname in zip(in_files, in_idxs): f = np.load(iname) - idxs = np.squeeze(f["arr_0"]) + idxs = np.atleast_1d(np.squeeze(f["arr_0"])) + nels = len(idxs) for d, fname in enumerate(nii): data = np.asanyarray(nb.load(fname).dataobj).reshape(-1) cdata = nb.load(cname).dataobj[..., d].reshape(-1) - nels = len(idxs) - idata = (idxs,) - data[idata] = cdata[0:nels] + data[idxs] = cdata[:nels] nb.Nifti1Image(data.reshape(rsh[:3]), aff, hdr).to_filename(fname) - imgs = [nb.load(im, mmap=NUMPY_MMAP) for im in nii] + imgs = [nb.load(im) for im in nii] allim = nb.concat_images(imgs) allim.to_filename(out_file) @@ -1515,7 +1541,7 @@ class CalculateMedian(BaseInterface): output_spec = CalculateMedianOutputSpec def __init__(self, *args, **kwargs): - super(CalculateMedian, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self._median_files = [] def _gen_fname(self, suffix, idx=None, ext=None): @@ -1537,10 +1563,10 @@ def _gen_fname(self, suffix, idx=None, ext=None): if self.inputs.median_file: outname = self.inputs.median_file else: - outname = "{}_{}".format(fname, suffix) + outname = f"{fname}_{suffix}" if idx: outname += str(idx) - return op.abspath("{}.{}".format(outname, ext)) + return op.abspath(f"{outname}.{ext}") def _run_interface(self, runtime): total = None diff --git a/nipype/algorithms/modelgen.py b/nipype/algorithms/modelgen.py index f6e73afeeb..78083cb628 100644 --- a/nipype/algorithms/modelgen.py +++ b/nipype/algorithms/modelgen.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -8,12 +7,13 @@ experiments. """ from copy import deepcopy -import csv, math, os +import csv +import math +import os from nibabel import load import numpy as np -from ..utils import NUMPY_MMAP from ..interfaces.base import ( BaseInterface, TraitedSpec, @@ -31,25 +31,6 @@ iflogger = logging.getLogger("nipype.interface") -def gcd(a, b): - """ - Return the greatest common divisor of two integers (uses Euclid's algorithm). - - Examples - -------- - >>> gcd(4, 5) - 1 - >>> gcd(4, 8) - 4 - >>> gcd(22, 55) - 11 - - """ - while b > 0: - a, b = b, a % b - return a - - def spm_hrf(RT, P=None, fMRI_T=16): """ python implementation of spm_hrf @@ -60,13 +41,13 @@ def spm_hrf(RT, P=None, fMRI_T=16): % p - parameters of the response function (two gamma % functions) % defaults (seconds) - % p(0) - delay of response (relative to onset) 6 - % p(1) - delay of undershoot (relative to onset) 16 - % p(2) - dispersion of response 1 - % p(3) - dispersion of undershoot 1 - % p(4) - ratio of response to undershoot 6 - % p(5) - onset (seconds) 0 - % p(6) - length of kernel (seconds) 32 + % p(0) - delay of response (relative to onset) 6 + % p(1) - delay of undershoot (relative to onset) 16 + % p(2) - dispersion of response 1 + % p(3) - dispersion of undershoot 1 + % p(4) - ratio of response to undershoot 6 + % p(5) - onset (seconds) 0 + % p(6) - length of kernel (seconds) 32 % % hrf - hemodynamic response function % p - parameters of the response function @@ -155,7 +136,7 @@ def scale_timings(timelist, input_units, output_units, time_repetition): def bids_gen_info( - bids_event_files, condition_column="", amplitude_column=None, time_repetition=False, + bids_event_files, condition_column="", amplitude_column=None, time_repetition=False ): """ Generate a subject_info structure from a list of BIDS .tsv event files. @@ -182,12 +163,12 @@ def bids_gen_info( for bids_event_file in bids_event_files: with open(bids_event_file) as f: f_events = csv.DictReader(f, skipinitialspace=True, delimiter="\t") - events = [{k: v for k, v in row.items()} for row in f_events] + events = list(f_events) if not condition_column: condition_column = "_trial_type" for i in events: i.update({condition_column: "ev0"}) - conditions = sorted(set([i[condition_column] for i in events])) + conditions = sorted({i[condition_column] for i in events}) runinfo = Bunch(conditions=[], onsets=[], durations=[], amplitudes=[]) for condition in conditions: selected_events = [i for i in events if i[condition_column] == condition] @@ -403,7 +384,7 @@ def _generate_standard_design( for i, info in enumerate(infolist): sessinfo.insert(i, dict(cond=[])) if isdefined(self.inputs.high_pass_filter_cutoff): - sessinfo[i]["hpf"] = np.float(self.inputs.high_pass_filter_cutoff) + sessinfo[i]["hpf"] = float(self.inputs.high_pass_filter_cutoff) if hasattr(info, "conditions") and info.conditions is not None: for cid, cond in enumerate(info.conditions): @@ -438,9 +419,9 @@ def _generate_standard_design( sessinfo[i]["cond"][cid]["pmod"][j]["poly"] = info.pmod[ cid ].poly[j] - sessinfo[i]["cond"][cid]["pmod"][j][ - "param" - ] = info.pmod[cid].param[j] + sessinfo[i]["cond"][cid]["pmod"][j]["param"] = ( + info.pmod[cid].param[j] + ) sessinfo[i]["regress"] = [] if hasattr(info, "regressors") and info.regressors is not None: @@ -469,7 +450,7 @@ def _generate_standard_design( for i, out in enumerate(outliers): numscans = 0 for f in ensure_list(sessinfo[i]["scans"]): - shape = load(f, mmap=NUMPY_MMAP).shape + shape = load(f).shape if len(shape) == 3 or shape[3] == 1: iflogger.warning( "You are using 3D instead of 4D " @@ -491,25 +472,24 @@ def _generate_standard_design( return sessinfo def _generate_design(self, infolist=None): - """Generate design specification for a typical fmri paradigm - """ + """Generate design specification for a typical fmri paradigm""" realignment_parameters = [] if isdefined(self.inputs.realignment_parameters): - for parfile in self.inputs.realignment_parameters: - realignment_parameters.append( - np.apply_along_axis( - func1d=normalize_mc_params, - axis=1, - arr=np.loadtxt(parfile), - source=self.inputs.parameter_source, - ) + realignment_parameters.extend( + np.apply_along_axis( + func1d=normalize_mc_params, + axis=1, + arr=np.loadtxt(parfile), + source=self.inputs.parameter_source, ) + for parfile in self.inputs.realignment_parameters + ) outliers = [] if isdefined(self.inputs.outlier_files): for filename in self.inputs.outlier_files: try: outindices = np.loadtxt(filename, dtype=int) - except IOError: + except OSError: outliers.append([]) else: if outindices.size == 1: @@ -537,8 +517,7 @@ def _generate_design(self, infolist=None): ) def _run_interface(self, runtime): - """ - """ + """ """ self._sessioninfo = None self._generate_design() return runtime @@ -599,7 +578,7 @@ def _concatenate_info(self, infolist): if isinstance(f, list): numscans = len(f) elif isinstance(f, (str, bytes)): - img = load(f, mmap=NUMPY_MMAP) + img = load(f) numscans = img.shape[3] else: raise Exception("Functional input not specified correctly") @@ -637,11 +616,8 @@ def _concatenate_info(self, infolist): infoout.durations[j].extend(info.durations[j]) else: raise ValueError( - "Mismatch in number of onsets and \ - durations for run {0}, condition \ - {1}".format( - i + 2, j + 1 - ) + f"Mismatch in number of onsets and durations for run {i + 2}, " + f"condition {j + 1}" ) if hasattr(info, "amplitudes") and info.amplitudes: @@ -673,7 +649,7 @@ def _generate_design(self, infolist=None): not isdefined(self.inputs.concatenate_runs) or not self.inputs.concatenate_runs ): - super(SpecifySPMModel, self)._generate_design(infolist=infolist) + super()._generate_design(infolist=infolist) return if isdefined(self.inputs.subject_info): @@ -704,7 +680,7 @@ def _generate_design(self, infolist=None): for i, filename in enumerate(self.inputs.outlier_files): try: out = np.loadtxt(filename) - except IOError: + except OSError: iflogger.warning("Error reading outliers file %s", filename) out = np.array([]) @@ -759,7 +735,7 @@ class SpecifySparseModelOutputSpec(SpecifyModelOutputSpec): class SpecifySparseModel(SpecifyModel): - """ Specify a sparse model that is compatible with SPM/FSL designers [1]_. + """Specify a sparse model that is compatible with SPM/FSL designers [1]_. Examples -------- @@ -790,8 +766,7 @@ class SpecifySparseModel(SpecifyModel): output_spec = SpecifySparseModelOutputSpec def _gen_regress(self, i_onsets, i_durations, i_amplitudes, nscans): - """Generates a regressor for a sparse/clustered-sparse acquisition - """ + """Generates a regressor for a sparse/clustered-sparse acquisition""" bplot = False if isdefined(self.inputs.save_plot) and self.inputs.save_plot: bplot = True @@ -800,9 +775,9 @@ def _gen_regress(self, i_onsets, i_durations, i_amplitudes, nscans): matplotlib.use(config.get("execution", "matplotlib_backend")) import matplotlib.pyplot as plt - TR = np.round(self.inputs.time_repetition * 1000) # in ms + TR = int(np.round(self.inputs.time_repetition * 1000)) # in ms if self.inputs.time_acquisition: - TA = np.round(self.inputs.time_acquisition * 1000) # in ms + TA = int(np.round(self.inputs.time_acquisition * 1000)) # in ms else: TA = TR # in ms nvol = self.inputs.volumes_in_cluster @@ -812,20 +787,20 @@ def _gen_regress(self, i_onsets, i_durations, i_amplitudes, nscans): dt = TA / 10.0 durations = np.round(np.array(i_durations) * 1000) if len(durations) == 1: - durations = durations * np.ones((len(i_onsets))) + durations = durations * np.ones(len(i_onsets)) onsets = np.round(np.array(i_onsets) * 1000) - dttemp = gcd(TA, gcd(SILENCE, TR)) + dttemp = math.gcd(TA, math.gcd(SILENCE, TR)) if dt < dttemp: if dttemp % dt != 0: - dt = float(gcd(dttemp, dt)) + dt = float(math.gcd(dttemp, int(dt))) if dt < 1: raise Exception("Time multiple less than 1 ms") iflogger.info("Setting dt = %d ms\n", dt) npts = int(np.ceil(total_time / dt)) times = np.arange(0, total_time, dt) * 1e-3 - timeline = np.zeros((npts)) - timeline2 = np.zeros((npts)) + timeline = np.zeros(npts) + timeline2 = np.zeros(npts) if isdefined(self.inputs.model_hrf) and self.inputs.model_hrf: hrf = spm_hrf(dt * 1e-3) reg_scale = 1.0 @@ -862,7 +837,7 @@ def _gen_regress(self, i_onsets, i_durations, i_amplitudes, nscans): if not self.inputs.stimuli_as_impulses: if durations[i] == 0: durations[i] = TA * nvol - stimdur = np.ones((int(durations[i] / dt))) + stimdur = np.ones(int(durations[i] / dt)) timeline2 = np.convolve(timeline2, stimdur)[0 : len(timeline2)] timeline += timeline2 timeline2[:] = 0 @@ -889,7 +864,7 @@ def _gen_regress(self, i_onsets, i_durations, i_amplitudes, nscans): ): plt.plot(times, timederiv) # sample timeline - timeline2 = np.zeros((npts)) + timeline2 = np.zeros(npts) reg = [] regderiv = [] for i, trial in enumerate(np.arange(nscans) / nvol): @@ -921,8 +896,7 @@ def _gen_regress(self, i_onsets, i_durations, i_amplitudes, nscans): return reg def _cond_to_regress(self, info, nscans): - """Converts condition information to full regressors - """ + """Converts condition information to full regressors""" reg = [] regnames = [] for i, cond in enumerate(info.conditions): @@ -977,7 +951,7 @@ def _generate_clustered_design(self, infolist): infoout[i].onsets = None infoout[i].durations = None if info.conditions: - img = load(self.inputs.functional_runs[i], mmap=NUMPY_MMAP) + img = load(self.inputs.functional_runs[i]) nscans = img.shape[3] reg, regnames = self._cond_to_regress(info, nscans) if hasattr(infoout[i], "regressors") and infoout[i].regressors: @@ -1001,7 +975,7 @@ def _generate_design(self, infolist=None): else: infolist = gen_info(self.inputs.event_files) sparselist = self._generate_clustered_design(infolist) - super(SpecifySparseModel, self)._generate_design(infolist=sparselist) + super()._generate_design(infolist=sparselist) def _list_outputs(self): outputs = self._outputs().get() diff --git a/nipype/algorithms/rapidart.py b/nipype/algorithms/rapidart.py index a13d412481..65aae2ef1c 100644 --- a/nipype/algorithms/rapidart.py +++ b/nipype/algorithms/rapidart.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -18,7 +17,6 @@ from nibabel import load, funcs, Nifti1Image import numpy as np -from ..utils import NUMPY_MMAP from ..interfaces.base import ( BaseInterface, traits, @@ -39,7 +37,7 @@ def _get_affine_matrix(params, source): """Return affine matrix given a set of translation and rotation parameters - params : np.array (upto 12 long) in native package format + params : np.array (up to 12 long) in native package format source : the package that generated the parameters supports SPM, AFNI, FSFAST, FSL, NIPY """ @@ -170,7 +168,7 @@ def _calc_norm_affine(affines, use_differences, brain_pts=None): class ArtifactDetectInputSpec(BaseInterfaceInputSpec): realigned_files = InputMultiPath( File(exists=True), - desc=("Names of realigned functional data " "files"), + desc=("Names of realigned functional data files"), mandatory=True, ) realignment_parameters = InputMultiPath( @@ -191,7 +189,8 @@ class ArtifactDetectInputSpec(BaseInterfaceInputSpec): desc="Source of movement parameters", mandatory=True, ) - use_differences = traits.ListBool( + use_differences = traits.List( + traits.Bool, [True, False], minlen=2, maxlen=2, @@ -226,12 +225,12 @@ class ArtifactDetectInputSpec(BaseInterfaceInputSpec): rotation_threshold = traits.Float( mandatory=True, xor=["norm_threshold"], - desc=("Threshold (in radians) to use to " "detect rotation-related outliers"), + desc=("Threshold (in radians) to use to detect rotation-related outliers"), ) translation_threshold = traits.Float( mandatory=True, xor=["norm_threshold"], - desc=("Threshold (in mm) to use to " "detect translation-related " "outliers"), + desc=("Threshold (in mm) to use to detect translation-related outliers"), ) zintensity_threshold = traits.Float( mandatory=True, @@ -259,12 +258,12 @@ class ArtifactDetectInputSpec(BaseInterfaceInputSpec): ) mask_file = File(exists=True, desc="Mask file to be used if mask_type is 'file'.") mask_threshold = traits.Float( - desc=("Mask threshold to be used if mask_type" " is 'thresh'.") + desc=("Mask threshold to be used if mask_type is 'thresh'.") ) intersect_mask = traits.Bool( True, usedefault=True, - desc=("Intersect the masks when computed from " "spm_global."), + desc=("Intersect the masks when computed from spm_global."), ) save_plot = traits.Bool( True, desc="save plots containing outliers", usedefault=True @@ -290,7 +289,7 @@ class ArtifactDetectInputSpec(BaseInterfaceInputSpec): ) global_threshold = traits.Float( 8.0, - desc=("use this threshold when mask " "type equal's spm_global"), + desc=("use this threshold when mask type equal's spm_global"), usedefault=True, ) @@ -314,7 +313,7 @@ class ArtifactDetectOutputSpec(TraitedSpec): ), ) norm_files = OutputMultiPath( - File, desc=("One file for each functional run " "containing the composite norm") + File, desc=("One file for each functional run containing the composite norm") ) statistic_files = OutputMultiPath( File(exists=True), @@ -331,7 +330,7 @@ class ArtifactDetectOutputSpec(TraitedSpec): plot_files = OutputMultiPath( File, desc=( - "One image file for each functional run " "containing the detected outliers" + "One image file for each functional run containing the detected outliers" ), ) mask_files = OutputMultiPath( @@ -379,7 +378,7 @@ class ArtifactDetect(BaseInterface): output_spec = ArtifactDetectOutputSpec def __init__(self, **inputs): - super(ArtifactDetect, self).__init__(**inputs) + super().__init__(**inputs) def _get_output_filenames(self, motionfile, output_dir): """Generate output files based on motion filenames @@ -399,19 +398,13 @@ def _get_output_filenames(self, motionfile, output_dir): else: raise Exception("Unknown type of file") _, filename, ext = split_filename(infile) - artifactfile = os.path.join( - output_dir, "".join(("art.", filename, "_outliers.txt")) - ) - intensityfile = os.path.join( - output_dir, "".join(("global_intensity.", filename, ".txt")) - ) - statsfile = os.path.join(output_dir, "".join(("stats.", filename, ".txt"))) - normfile = os.path.join(output_dir, "".join(("norm.", filename, ".txt"))) - plotfile = os.path.join( - output_dir, "".join(("plot.", filename, ".", self.inputs.plot_type)) - ) - displacementfile = os.path.join(output_dir, "".join(("disp.", filename, ext))) - maskfile = os.path.join(output_dir, "".join(("mask.", filename, ext))) + artifactfile = os.path.join(output_dir, f"art.{filename}_outliers.txt") + intensityfile = os.path.join(output_dir, f"global_intensity.{filename}.txt") + statsfile = os.path.join(output_dir, f"stats.{filename}.txt") + normfile = os.path.join(output_dir, f"norm.{filename}.txt") + plotfile = os.path.join(output_dir, f"plot.{filename}.{self.inputs.plot_type}") + displacementfile = os.path.join(output_dir, f"disp.{filename}{ext}") + maskfile = os.path.join(output_dir, f"mask.{filename}{ext}") return ( artifactfile, intensityfile, @@ -485,12 +478,12 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): # read in functional image if isinstance(imgfile, (str, bytes)): - nim = load(imgfile, mmap=NUMPY_MMAP) + nim = load(imgfile) elif isinstance(imgfile, list): if len(imgfile) == 1: - nim = load(imgfile[0], mmap=NUMPY_MMAP) + nim = load(imgfile[0]) else: - images = [load(f, mmap=NUMPY_MMAP) for f in imgfile] + images = [load(f) for f in imgfile] nim = funcs.concat_images(images) # compute global intensity signal @@ -584,11 +577,11 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): tidx = find_indices(normval > self.inputs.norm_threshold) ridx = find_indices(normval < 0) if displacement is not None: - dmap = np.zeros((x, y, z, timepoints), dtype=np.float) + dmap = np.zeros((x, y, z, timepoints), dtype=np.float64) for i in range(timepoints): - dmap[ - voxel_coords[0], voxel_coords[1], voxel_coords[2], i - ] = displacement[i, :] + dmap[voxel_coords[0], voxel_coords[1], voxel_coords[2], i] = ( + displacement[i, :] + ) dimg = Nifti1Image(dmap, affine) dimg.to_filename(displacementfile) else: @@ -608,10 +601,10 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): outliers = np.unique(np.union1d(iidx, np.union1d(tidx, ridx))) # write output to outputfile - np.savetxt(artifactfile, outliers, fmt=b"%d", delimiter=" ") - np.savetxt(intensityfile, g, fmt=b"%.2f", delimiter=" ") + np.savetxt(artifactfile, outliers, fmt="%d", delimiter=" ") + np.savetxt(intensityfile, g, fmt="%.2f", delimiter=" ") if self.inputs.use_norm: - np.savetxt(normfile, normval, fmt=b"%.4f", delimiter=" ") + np.savetxt(normfile, normval, fmt="%.4f", delimiter=" ") if isdefined(self.inputs.save_plot) and self.inputs.save_plot: import matplotlib @@ -687,8 +680,7 @@ def _detect_outliers_core(self, imgfile, motionfile, runidx, cwd=None): save_json(statsfile, stats) def _run_interface(self, runtime): - """Execute this module. - """ + """Execute this module.""" funcfilelist = ensure_list(self.inputs.realigned_files) motparamlist = ensure_list(self.inputs.realignment_parameters) for i, imgf in enumerate(funcfilelist): @@ -701,28 +693,27 @@ class StimCorrInputSpec(BaseInterfaceInputSpec): File(exists=True), mandatory=True, desc=( - "Names of realignment " - "parameters corresponding to " + "Names of realignment parameters corresponding to " "the functional data files" ), ) intensity_values = InputMultiPath( File(exists=True), mandatory=True, - desc=("Name of file containing intensity " "values"), + desc=("Name of file containing intensity values"), ) spm_mat_file = File( exists=True, mandatory=True, desc="SPM mat file (use pre-estimate SPM.mat file)" ) concatenated_design = traits.Bool( mandatory=True, - desc=("state if the design matrix " "contains concatenated sessions"), + desc=("state if the design matrix contains concatenated sessions"), ) class StimCorrOutputSpec(TraitedSpec): stimcorr_files = OutputMultiPath( - File(exists=True), desc=("List of files containing " "correlation values") + File(exists=True), desc=("List of files containing correlation values") ) @@ -764,7 +755,7 @@ def _get_output_filenames(self, motionfile, output_dir): """ (_, filename) = os.path.split(motionfile) (filename, _) = os.path.splitext(filename) - corrfile = os.path.join(output_dir, "".join(("qa.", filename, "_stimcorr.txt"))) + corrfile = os.path.join(output_dir, f"qa.{filename}_stimcorr.txt") return corrfile def _stimcorr_core(self, motionfile, intensityfile, designmatrix, cwd=None): @@ -815,8 +806,7 @@ def _get_spm_submatrix(self, spmmat, sessidx, rows=None): return outmatrix def _run_interface(self, runtime): - """Execute this module. - """ + """Execute this module.""" import scipy.io as sio motparamlist = self.inputs.realignment_parameters diff --git a/nipype/algorithms/stats.py b/nipype/algorithms/stats.py index 29ce8d6be4..9fadd6fcf3 100644 --- a/nipype/algorithms/stats.py +++ b/nipype/algorithms/stats.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/algorithms/tests/__init__.py b/nipype/algorithms/tests/__init__.py index 99fb243f19..349937997e 100644 --- a/nipype/algorithms/tests/__init__.py +++ b/nipype/algorithms/tests/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/algorithms/tests/test_CompCor.py b/nipype/algorithms/tests/test_CompCor.py index 314b9ed9bf..f506ded628 100644 --- a/nipype/algorithms/tests/test_CompCor.py +++ b/nipype/algorithms/tests/test_CompCor.py @@ -10,8 +10,45 @@ from ..confounds import CompCor, TCompCor, ACompCor +def close_up_to_column_sign(a, b, rtol=1e-05, atol=1e-08, equal_nan=False): + """SVD can produce sign flips on a per-column basis.""" + a = np.asanyarray(a) + b = np.asanyarray(b) + kwargs = dict(rtol=rtol, atol=atol, equal_nan=equal_nan) + if np.allclose(a, b, **kwargs): + return True + + ret = True + for acol, bcol in zip(a.T, b.T): + ret &= np.allclose(acol, bcol, **kwargs) or np.allclose(acol, -bcol, **kwargs) + if not ret: + break + + return ret + + +@pytest.mark.parametrize( + "a, b, close", + [ + ([[0.1, 0.2], [0.3, 0.4]], [[-0.1, 0.2], [-0.3, 0.4]], True), + ([[0.1, 0.2], [0.3, 0.4]], [[-0.1, 0.2], [0.3, -0.4]], False), + ], +) +def test_close_up_to_column_sign(a, b, close): + a = np.asanyarray(a) + b = np.asanyarray(b) + assert close_up_to_column_sign(a, b) == close + # Sign flips of all columns never changes result + assert close_up_to_column_sign(a, -b) == close + assert close_up_to_column_sign(-a, b) == close + assert close_up_to_column_sign(-a, -b) == close + # Trivial case + assert close_up_to_column_sign(a, a) + assert close_up_to_column_sign(b, b) + + class TestCompCor: - """ Note: Tests currently do a poor job of testing functionality """ + """Note: Tests currently do a poor job of testing functionality""" filenames = { "functionalnii": "compcorfunc.nii", @@ -42,11 +79,11 @@ def setup_class(self, tmpdir): def test_compcor(self): expected_components = [ - ["-0.1989607212", "-0.5753813646"], - ["0.5692369697", "0.5674945949"], - ["-0.6662573243", "0.4675843432"], - ["0.4206466244", "-0.3361270124"], - ["-0.1246655485", "-0.1235705610"], + [-0.1989607212, -0.5753813646], + [0.5692369697, 0.5674945949], + [-0.6662573243, 0.4675843432], + [0.4206466244, -0.3361270124], + [-0.1246655485, -0.1235705610], ] self.run_cc( @@ -73,11 +110,11 @@ def test_compcor(self): def test_compcor_variance_threshold_and_metadata(self): expected_components = [ - ["-0.2027150345", "-0.4954813834"], - ["0.2565929051", "0.7866217875"], - ["-0.3550986008", "-0.0089784905"], - ["0.7512786244", "-0.3599828482"], - ["-0.4500578942", "0.0778209345"], + [-0.2027150345, -0.4954813834], + [0.2565929051, 0.7866217875], + [-0.3550986008, -0.0089784905], + [0.7512786244, -0.3599828482], + [-0.4500578942, 0.0778209345], ] expected_metadata = { "component": "CompCor00", @@ -111,11 +148,11 @@ def test_tcompcor(self): self.run_cc( ccinterface, [ - ["-0.1114536190", "-0.4632908609"], - ["0.4566907310", "0.6983205193"], - ["-0.7132557407", "0.1340170559"], - ["0.5022537643", "-0.5098322262"], - ["-0.1342351356", "0.1407855119"], + [-0.1114536190, -0.4632908609], + [0.4566907310, 0.6983205193], + [-0.7132557407, 0.1340170559], + [0.5022537643, -0.5098322262], + [-0.1342351356, 0.1407855119], ], "tCompCor", ) @@ -138,11 +175,11 @@ def test_compcor_no_regress_poly(self): pre_filter=False, ), [ - ["0.4451946442", "-0.7683311482"], - ["-0.4285129505", "-0.0926034137"], - ["0.5721540256", "0.5608764842"], - ["-0.5367548139", "0.0059943226"], - ["-0.0520809054", "0.2940637551"], + [0.4451946442, -0.7683311482], + [-0.4285129505, -0.0926034137], + [0.5721540256, 0.5608764842], + [-0.5367548139, 0.0059943226], + [-0.0520809054, 0.2940637551], ], ) @@ -224,28 +261,21 @@ def run_cc( assert os.path.exists(expected_file) assert os.path.getsize(expected_file) > 0 - with open(ccresult.outputs.components_file, "r") as components_file: - if expected_n_components is None: - expected_n_components = min( - ccinterface.inputs.num_components, self.fake_data.shape[3] - ) + with open(ccresult.outputs.components_file) as components_file: + header = components_file.readline().rstrip().split("\t") + components_data = np.loadtxt(components_file, delimiter="\t") - components_data = [line.rstrip().split("\t") for line in components_file] + if expected_n_components is None: + expected_n_components = min( + ccinterface.inputs.num_components, self.fake_data.shape[3] + ) - # the first item will be '#', we can throw it out - header = components_data.pop(0) - expected_header = [ - expected_header + "{:02d}".format(i) - for i in range(expected_n_components) - ] - for i, heading in enumerate(header): - assert expected_header[i] in heading + assert header == [ + f"{expected_header}{i:02d}" for i in range(expected_n_components) + ] - num_got_timepoints = len(components_data) - assert num_got_timepoints == self.fake_data.shape[3] - for index, timepoint in enumerate(components_data): - assert len(timepoint) == expected_n_components - assert timepoint[:2] == expected_components[index] + assert components_data.shape == (self.fake_data.shape[3], expected_n_components) + assert close_up_to_column_sign(components_data[:, :2], expected_components) if ccinterface.inputs.save_metadata: expected_metadata_file = ccinterface._list_outputs()["metadata_file"] @@ -253,13 +283,13 @@ def run_cc( assert os.path.exists(expected_metadata_file) assert os.path.getsize(expected_metadata_file) > 0 - with open(ccresult.outputs.metadata_file, "r") as metadata_file: + with open(ccresult.outputs.metadata_file) as metadata_file: components_metadata = [ line.rstrip().split("\t") for line in metadata_file ] - components_metadata = { - i: j for i, j in zip(components_metadata[0], components_metadata[1]) - } + components_metadata = dict( + zip(components_metadata[0], components_metadata[1]) + ) assert components_metadata == expected_metadata return ccresult diff --git a/nipype/algorithms/tests/test_ErrorMap.py b/nipype/algorithms/tests/test_ErrorMap.py index 4ae811008f..4cd0c7ce7e 100644 --- a/nipype/algorithms/tests/test_ErrorMap.py +++ b/nipype/algorithms/tests/test_ErrorMap.py @@ -1,23 +1,18 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -import pytest -from nipype.testing import example_data from nipype.algorithms.metrics import ErrorMap import nibabel as nb import numpy as np -import os def test_errormap(tmpdir): - # Single-Spectual # Make two fake 2*2*2 voxel volumes # John von Neumann's birthday volume1 = np.array([[[2.0, 8.0], [1.0, 2.0]], [[1.0, 9.0], [0.0, 3.0]]]) # Alan Turing's birthday volume2 = np.array([[[0.0, 7.0], [2.0, 3.0]], [[1.0, 9.0], [1.0, 2.0]]]) - mask = np.array([[[1, 0], [0, 1]], [[1, 0], [0, 1]]]) + mask = np.array([[[1, 0], [0, 1]], [[1, 0], [0, 1]]], dtype=np.uint8) img1 = nb.Nifti1Image(volume1, np.eye(4)) img2 = nb.Nifti1Image(volume2, np.eye(4)) @@ -75,4 +70,4 @@ def test_errormap(tmpdir): errmap.inputs.metric = "euclidean" result = errmap.run() - assert result.outputs.distance == np.float32(1.25 * (2 ** 0.5)) + assert result.outputs.distance == np.float32(1.25 * (2**0.5)) diff --git a/nipype/algorithms/tests/test_Overlap.py b/nipype/algorithms/tests/test_Overlap.py index ea3b5a3f5d..93a7cbb68f 100644 --- a/nipype/algorithms/tests/test_Overlap.py +++ b/nipype/algorithms/tests/test_Overlap.py @@ -1,9 +1,7 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -import os from nipype.testing import example_data diff --git a/nipype/algorithms/tests/test_TSNR.py b/nipype/algorithms/tests/test_TSNR.py index e00bf35e05..320bec8ab2 100644 --- a/nipype/algorithms/tests/test_TSNR.py +++ b/nipype/algorithms/tests/test_TSNR.py @@ -7,18 +7,16 @@ import pytest import numpy.testing as npt -import mock +from unittest import mock import nibabel as nb import numpy as np import os class TestTSNR: - """ Note: Tests currently do a poor job of testing functionality """ + """Note: Tests currently do a poor job of testing functionality""" - in_filenames = { - "in_file": "tsnrinfile.nii", - } + in_filenames = {"in_file": "tsnrinfile.nii"} out_filenames = { # default output file names "detrended_file": "detrend.nii.gz", @@ -95,8 +93,8 @@ def test_tsnr_withpoly3(self): @mock.patch("warnings.warn") def test_warning(self, mock_warn): - """ test that usage of misc.TSNR trips a warning to use - confounds.TSNR instead """ + """test that usage of misc.TSNR trips a warning to use + confounds.TSNR instead""" # run misc.TSNR(in_file=self.in_filenames["in_file"]) @@ -133,5 +131,6 @@ def assert_unchanged(self, expected_ranges): [ [[[2, 4, 3, 9, 1], [3, 6, 4, 7, 4]], [[8, 3, 4, 6, 2], [4, 0, 4, 4, 2]]], [[[9, 7, 5, 5, 7], [7, 8, 4, 8, 4]], [[0, 4, 7, 1, 7], [6, 8, 8, 8, 7]]], - ] + ], + dtype=np.int16, ) diff --git a/nipype/algorithms/tests/test_auto_ACompCor.py b/nipype/algorithms/tests/test_auto_ACompCor.py index e2788e97d5..814aa71704 100644 --- a/nipype/algorithms/tests/test_auto_ACompCor.py +++ b/nipype/algorithms/tests/test_auto_ACompCor.py @@ -4,24 +4,56 @@ def test_ACompCor_inputs(): input_map = dict( - components_file=dict(usedefault=True,), - failure_mode=dict(usedefault=True,), + components_file=dict( + usedefault=True, + ), + failure_mode=dict( + usedefault=True, + ), header_prefix=dict(), - high_pass_cutoff=dict(usedefault=True,), - ignore_initial_volumes=dict(usedefault=True,), + high_pass_cutoff=dict( + usedefault=True, + ), + ignore_initial_volumes=dict( + usedefault=True, + ), mask_files=dict(), - mask_index=dict(requires=["mask_files"], xor=["merge_method"],), + mask_index=dict( + requires=["mask_files"], + xor=["merge_method"], + ), mask_names=dict(), - merge_method=dict(requires=["mask_files"], xor=["mask_index"],), - num_components=dict(xor=["variance_threshold"],), - pre_filter=dict(usedefault=True,), - realigned_file=dict(extensions=None, mandatory=True,), - regress_poly_degree=dict(usedefault=True,), + merge_method=dict( + requires=["mask_files"], + xor=["mask_index"], + ), + num_components=dict( + xor=["variance_threshold"], + ), + pre_filter=dict( + usedefault=True, + ), + realigned_file=dict( + extensions=None, + mandatory=True, + ), + regress_poly_degree=dict( + usedefault=True, + ), repetition_time=dict(), - save_metadata=dict(usedefault=True,), - save_pre_filter=dict(usedefault=True,), - use_regress_poly=dict(deprecated="0.15.0", new_name="pre_filter",), - variance_threshold=dict(xor=["num_components"],), + save_metadata=dict( + usedefault=True, + ), + save_pre_filter=dict( + usedefault=True, + ), + use_regress_poly=dict( + deprecated="0.15.0", + new_name="pre_filter", + ), + variance_threshold=dict( + xor=["num_components"], + ), ) inputs = ACompCor.input_spec() @@ -32,9 +64,15 @@ def test_ACompCor_inputs(): def test_ACompCor_outputs(): output_map = dict( - components_file=dict(extensions=None,), - metadata_file=dict(extensions=None,), - pre_filter_file=dict(extensions=None,), + components_file=dict( + extensions=None, + ), + metadata_file=dict( + extensions=None, + ), + pre_filter_file=dict( + extensions=None, + ), ) outputs = ACompCor.output_spec() diff --git a/nipype/algorithms/tests/test_auto_ActivationCount.py b/nipype/algorithms/tests/test_auto_ActivationCount.py index 6fc50301ac..7df84ee122 100644 --- a/nipype/algorithms/tests/test_auto_ActivationCount.py +++ b/nipype/algorithms/tests/test_auto_ActivationCount.py @@ -3,7 +3,14 @@ def test_ActivationCount_inputs(): - input_map = dict(in_files=dict(mandatory=True,), threshold=dict(mandatory=True,),) + input_map = dict( + in_files=dict( + mandatory=True, + ), + threshold=dict( + mandatory=True, + ), + ) inputs = ActivationCount.input_spec() for key, metadata in list(input_map.items()): @@ -13,9 +20,15 @@ def test_ActivationCount_inputs(): def test_ActivationCount_outputs(): output_map = dict( - acm_neg=dict(extensions=None,), - acm_pos=dict(extensions=None,), - out_file=dict(extensions=None,), + acm_neg=dict( + extensions=None, + ), + acm_pos=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = ActivationCount.output_spec() diff --git a/nipype/algorithms/tests/test_auto_AddCSVColumn.py b/nipype/algorithms/tests/test_auto_AddCSVColumn.py index a2d82b6eec..b76fd46457 100644 --- a/nipype/algorithms/tests/test_auto_AddCSVColumn.py +++ b/nipype/algorithms/tests/test_auto_AddCSVColumn.py @@ -6,8 +6,14 @@ def test_AddCSVColumn_inputs(): input_map = dict( extra_column_heading=dict(), extra_field=dict(), - in_file=dict(extensions=None, mandatory=True,), - out_file=dict(extensions=None, usedefault=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), ) inputs = AddCSVColumn.input_spec() @@ -17,7 +23,11 @@ def test_AddCSVColumn_inputs(): def test_AddCSVColumn_outputs(): - output_map = dict(csv_file=dict(extensions=None,),) + output_map = dict( + csv_file=dict( + extensions=None, + ), + ) outputs = AddCSVColumn.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_AddCSVRow.py b/nipype/algorithms/tests/test_auto_AddCSVRow.py index 39d6d40abb..78976f418d 100644 --- a/nipype/algorithms/tests/test_auto_AddCSVRow.py +++ b/nipype/algorithms/tests/test_auto_AddCSVRow.py @@ -4,7 +4,13 @@ def test_AddCSVRow_inputs(): input_map = dict( - _outputs=dict(usedefault=True,), in_file=dict(extensions=None, mandatory=True,), + _outputs=dict( + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = AddCSVRow.input_spec() @@ -14,7 +20,11 @@ def test_AddCSVRow_inputs(): def test_AddCSVRow_outputs(): - output_map = dict(csv_file=dict(extensions=None,),) + output_map = dict( + csv_file=dict( + extensions=None, + ), + ) outputs = AddCSVRow.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_AddNoise.py b/nipype/algorithms/tests/test_auto_AddNoise.py index ad1e8734e8..5cf92e33f7 100644 --- a/nipype/algorithms/tests/test_auto_AddNoise.py +++ b/nipype/algorithms/tests/test_auto_AddNoise.py @@ -4,12 +4,27 @@ def test_AddNoise_inputs(): input_map = dict( - bg_dist=dict(mandatory=True, usedefault=True,), - dist=dict(mandatory=True, usedefault=True,), - in_file=dict(extensions=None, mandatory=True,), - in_mask=dict(extensions=None,), - out_file=dict(extensions=None,), - snr=dict(usedefault=True,), + bg_dist=dict( + mandatory=True, + usedefault=True, + ), + dist=dict( + mandatory=True, + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + in_mask=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + snr=dict( + usedefault=True, + ), ) inputs = AddNoise.input_spec() @@ -19,7 +34,11 @@ def test_AddNoise_inputs(): def test_AddNoise_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AddNoise.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_ArtifactDetect.py b/nipype/algorithms/tests/test_auto_ArtifactDetect.py index 9340982472..4d5a7ca53b 100644 --- a/nipype/algorithms/tests/test_auto_ArtifactDetect.py +++ b/nipype/algorithms/tests/test_auto_ArtifactDetect.py @@ -4,25 +4,59 @@ def test_ArtifactDetect_inputs(): input_map = dict( - bound_by_brainmask=dict(usedefault=True,), - global_threshold=dict(usedefault=True,), - intersect_mask=dict(usedefault=True,), - mask_file=dict(extensions=None,), + bound_by_brainmask=dict( + usedefault=True, + ), + global_threshold=dict( + usedefault=True, + ), + intersect_mask=dict( + usedefault=True, + ), + mask_file=dict( + extensions=None, + ), mask_threshold=dict(), - mask_type=dict(mandatory=True,), + mask_type=dict( + mandatory=True, + ), norm_threshold=dict( - mandatory=True, xor=["rotation_threshold", "translation_threshold"], - ), - parameter_source=dict(mandatory=True,), - plot_type=dict(usedefault=True,), - realigned_files=dict(mandatory=True,), - realignment_parameters=dict(mandatory=True,), - rotation_threshold=dict(mandatory=True, xor=["norm_threshold"],), - save_plot=dict(usedefault=True,), - translation_threshold=dict(mandatory=True, xor=["norm_threshold"],), - use_differences=dict(maxlen=2, minlen=2, usedefault=True,), - use_norm=dict(requires=["norm_threshold"], usedefault=True,), - zintensity_threshold=dict(mandatory=True,), + mandatory=True, + xor=["rotation_threshold", "translation_threshold"], + ), + parameter_source=dict( + mandatory=True, + ), + plot_type=dict( + usedefault=True, + ), + realigned_files=dict( + mandatory=True, + ), + realignment_parameters=dict( + mandatory=True, + ), + rotation_threshold=dict( + mandatory=True, + xor=["norm_threshold"], + ), + save_plot=dict( + usedefault=True, + ), + translation_threshold=dict( + mandatory=True, + xor=["norm_threshold"], + ), + use_differences=dict( + usedefault=True, + ), + use_norm=dict( + requires=["norm_threshold"], + usedefault=True, + ), + zintensity_threshold=dict( + mandatory=True, + ), ) inputs = ArtifactDetect.input_spec() diff --git a/nipype/algorithms/tests/test_auto_CalculateMedian.py b/nipype/algorithms/tests/test_auto_CalculateMedian.py index ff8d9edd7a..ddc8b9814d 100644 --- a/nipype/algorithms/tests/test_auto_CalculateMedian.py +++ b/nipype/algorithms/tests/test_auto_CalculateMedian.py @@ -4,7 +4,11 @@ def test_CalculateMedian_inputs(): input_map = dict( - in_files=dict(), median_file=dict(), median_per_file=dict(usedefault=True,), + in_files=dict(), + median_file=dict(), + median_per_file=dict( + usedefault=True, + ), ) inputs = CalculateMedian.input_spec() @@ -14,7 +18,9 @@ def test_CalculateMedian_inputs(): def test_CalculateMedian_outputs(): - output_map = dict(median_files=dict(),) + output_map = dict( + median_files=dict(), + ) outputs = CalculateMedian.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py b/nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py index 102ec2c205..a67f959176 100644 --- a/nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py +++ b/nipype/algorithms/tests/test_auto_CalculateNormalizedMoments.py @@ -4,8 +4,13 @@ def test_CalculateNormalizedMoments_inputs(): input_map = dict( - moment=dict(mandatory=True,), - timeseries_file=dict(extensions=None, mandatory=True,), + moment=dict( + mandatory=True, + ), + timeseries_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = CalculateNormalizedMoments.input_spec() @@ -15,7 +20,9 @@ def test_CalculateNormalizedMoments_inputs(): def test_CalculateNormalizedMoments_outputs(): - output_map = dict(moments=dict(),) + output_map = dict( + moments=dict(), + ) outputs = CalculateNormalizedMoments.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_ComputeDVARS.py b/nipype/algorithms/tests/test_auto_ComputeDVARS.py index ed51de0b0a..c5e1118341 100644 --- a/nipype/algorithms/tests/test_auto_ComputeDVARS.py +++ b/nipype/algorithms/tests/test_auto_ComputeDVARS.py @@ -4,19 +4,48 @@ def test_ComputeDVARS_inputs(): input_map = dict( - figdpi=dict(usedefault=True,), - figformat=dict(usedefault=True,), - figsize=dict(usedefault=True,), - in_file=dict(extensions=None, mandatory=True,), - in_mask=dict(extensions=None, mandatory=True,), - intensity_normalization=dict(usedefault=True,), - remove_zerovariance=dict(usedefault=True,), - save_all=dict(usedefault=True,), - save_nstd=dict(usedefault=True,), - save_plot=dict(usedefault=True,), - save_std=dict(usedefault=True,), - save_vxstd=dict(usedefault=True,), + figdpi=dict( + usedefault=True, + ), + figformat=dict( + usedefault=True, + ), + figsize=dict( + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + in_mask=dict( + extensions=None, + mandatory=True, + ), + intensity_normalization=dict( + usedefault=True, + ), + remove_zerovariance=dict( + usedefault=True, + ), + save_all=dict( + usedefault=True, + ), + save_nstd=dict( + usedefault=True, + ), + save_plot=dict( + usedefault=True, + ), + save_std=dict( + usedefault=True, + ), + save_vxstd=dict( + usedefault=True, + ), series_tr=dict(), + variance_tol=dict( + usedefault=True, + ), ) inputs = ComputeDVARS.input_spec() @@ -30,13 +59,27 @@ def test_ComputeDVARS_outputs(): avg_nstd=dict(), avg_std=dict(), avg_vxstd=dict(), - fig_nstd=dict(extensions=None,), - fig_std=dict(extensions=None,), - fig_vxstd=dict(extensions=None,), - out_all=dict(extensions=None,), - out_nstd=dict(extensions=None,), - out_std=dict(extensions=None,), - out_vxstd=dict(extensions=None,), + fig_nstd=dict( + extensions=None, + ), + fig_std=dict( + extensions=None, + ), + fig_vxstd=dict( + extensions=None, + ), + out_all=dict( + extensions=None, + ), + out_nstd=dict( + extensions=None, + ), + out_std=dict( + extensions=None, + ), + out_vxstd=dict( + extensions=None, + ), ) outputs = ComputeDVARS.output_spec() diff --git a/nipype/algorithms/tests/test_auto_ComputeMeshWarp.py b/nipype/algorithms/tests/test_auto_ComputeMeshWarp.py index 871564b817..639f03770c 100644 --- a/nipype/algorithms/tests/test_auto_ComputeMeshWarp.py +++ b/nipype/algorithms/tests/test_auto_ComputeMeshWarp.py @@ -4,12 +4,28 @@ def test_ComputeMeshWarp_inputs(): input_map = dict( - metric=dict(usedefault=True,), - out_file=dict(extensions=None, usedefault=True,), - out_warp=dict(extensions=None, usedefault=True,), - surface1=dict(extensions=None, mandatory=True,), - surface2=dict(extensions=None, mandatory=True,), - weighting=dict(usedefault=True,), + metric=dict( + usedefault=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), + out_warp=dict( + extensions=None, + usedefault=True, + ), + surface1=dict( + extensions=None, + mandatory=True, + ), + surface2=dict( + extensions=None, + mandatory=True, + ), + weighting=dict( + usedefault=True, + ), ) inputs = ComputeMeshWarp.input_spec() @@ -21,8 +37,12 @@ def test_ComputeMeshWarp_inputs(): def test_ComputeMeshWarp_outputs(): output_map = dict( distance=dict(), - out_file=dict(extensions=None,), - out_warp=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_warp=dict( + extensions=None, + ), ) outputs = ComputeMeshWarp.output_spec() diff --git a/nipype/algorithms/tests/test_auto_CreateNifti.py b/nipype/algorithms/tests/test_auto_CreateNifti.py index d4989386b4..f5c5c4a2f5 100644 --- a/nipype/algorithms/tests/test_auto_CreateNifti.py +++ b/nipype/algorithms/tests/test_auto_CreateNifti.py @@ -5,8 +5,14 @@ def test_CreateNifti_inputs(): input_map = dict( affine=dict(), - data_file=dict(extensions=None, mandatory=True,), - header_file=dict(extensions=None, mandatory=True,), + data_file=dict( + extensions=None, + mandatory=True, + ), + header_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = CreateNifti.input_spec() @@ -16,7 +22,11 @@ def test_CreateNifti_inputs(): def test_CreateNifti_outputs(): - output_map = dict(nifti_file=dict(extensions=None,),) + output_map = dict( + nifti_file=dict( + extensions=None, + ), + ) outputs = CreateNifti.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_Distance.py b/nipype/algorithms/tests/test_auto_Distance.py index e334e3a0f1..46e48342c4 100644 --- a/nipype/algorithms/tests/test_auto_Distance.py +++ b/nipype/algorithms/tests/test_auto_Distance.py @@ -4,10 +4,20 @@ def test_Distance_inputs(): input_map = dict( - mask_volume=dict(extensions=None,), - method=dict(usedefault=True,), - volume1=dict(extensions=None, mandatory=True,), - volume2=dict(extensions=None, mandatory=True,), + mask_volume=dict( + extensions=None, + ), + method=dict( + usedefault=True, + ), + volume1=dict( + extensions=None, + mandatory=True, + ), + volume2=dict( + extensions=None, + mandatory=True, + ), ) inputs = Distance.input_spec() @@ -18,7 +28,12 @@ def test_Distance_inputs(): def test_Distance_outputs(): output_map = dict( - distance=dict(), histogram=dict(extensions=None,), point1=dict(), point2=dict(), + distance=dict(), + histogram=dict( + extensions=None, + ), + point1=dict(), + point2=dict(), ) outputs = Distance.output_spec() diff --git a/nipype/algorithms/tests/test_auto_FramewiseDisplacement.py b/nipype/algorithms/tests/test_auto_FramewiseDisplacement.py index 1bc46fba64..1308b4d97d 100644 --- a/nipype/algorithms/tests/test_auto_FramewiseDisplacement.py +++ b/nipype/algorithms/tests/test_auto_FramewiseDisplacement.py @@ -4,15 +4,36 @@ def test_FramewiseDisplacement_inputs(): input_map = dict( - figdpi=dict(usedefault=True,), - figsize=dict(usedefault=True,), - in_file=dict(extensions=None, mandatory=True,), - normalize=dict(usedefault=True,), - out_figure=dict(extensions=None, usedefault=True,), - out_file=dict(extensions=None, usedefault=True,), - parameter_source=dict(mandatory=True,), - radius=dict(usedefault=True,), - save_plot=dict(usedefault=True,), + figdpi=dict( + usedefault=True, + ), + figsize=dict( + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + normalize=dict( + usedefault=True, + ), + out_figure=dict( + extensions=None, + usedefault=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), + parameter_source=dict( + mandatory=True, + ), + radius=dict( + usedefault=True, + ), + save_plot=dict( + usedefault=True, + ), series_tr=dict(), ) inputs = FramewiseDisplacement.input_spec() @@ -25,8 +46,12 @@ def test_FramewiseDisplacement_inputs(): def test_FramewiseDisplacement_outputs(): output_map = dict( fd_average=dict(), - out_figure=dict(extensions=None,), - out_file=dict(extensions=None,), + out_figure=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = FramewiseDisplacement.output_spec() diff --git a/nipype/algorithms/tests/test_auto_FuzzyOverlap.py b/nipype/algorithms/tests/test_auto_FuzzyOverlap.py index 877f864bee..e8a7fe5ef1 100644 --- a/nipype/algorithms/tests/test_auto_FuzzyOverlap.py +++ b/nipype/algorithms/tests/test_auto_FuzzyOverlap.py @@ -4,11 +4,22 @@ def test_FuzzyOverlap_inputs(): input_map = dict( - in_mask=dict(extensions=None,), - in_ref=dict(mandatory=True,), - in_tst=dict(mandatory=True,), - out_file=dict(extensions=None, usedefault=True,), - weighting=dict(usedefault=True,), + in_mask=dict( + extensions=None, + ), + in_ref=dict( + mandatory=True, + ), + in_tst=dict( + mandatory=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), + weighting=dict( + usedefault=True, + ), ) inputs = FuzzyOverlap.input_spec() @@ -18,7 +29,12 @@ def test_FuzzyOverlap_inputs(): def test_FuzzyOverlap_outputs(): - output_map = dict(class_fdi=dict(), class_fji=dict(), dice=dict(), jaccard=dict(),) + output_map = dict( + class_fdi=dict(), + class_fji=dict(), + dice=dict(), + jaccard=dict(), + ) outputs = FuzzyOverlap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_Gunzip.py b/nipype/algorithms/tests/test_auto_Gunzip.py index 40a1f44531..2d1b4a4beb 100644 --- a/nipype/algorithms/tests/test_auto_Gunzip.py +++ b/nipype/algorithms/tests/test_auto_Gunzip.py @@ -3,7 +3,15 @@ def test_Gunzip_inputs(): - input_map = dict(in_file=dict(extensions=None, mandatory=True,),) + input_map = dict( + in_file=dict( + extensions=None, + mandatory=True, + ), + mode=dict( + usedefault=True, + ), + ) inputs = Gunzip.input_spec() for key, metadata in list(input_map.items()): @@ -12,7 +20,11 @@ def test_Gunzip_inputs(): def test_Gunzip_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Gunzip.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_Gzip.py b/nipype/algorithms/tests/test_auto_Gzip.py new file mode 100644 index 0000000000..1503f92790 --- /dev/null +++ b/nipype/algorithms/tests/test_auto_Gzip.py @@ -0,0 +1,32 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..misc import Gzip + + +def test_Gzip_inputs(): + input_map = dict( + in_file=dict( + extensions=None, + mandatory=True, + ), + mode=dict( + usedefault=True, + ), + ) + inputs = Gzip.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_Gzip_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = Gzip.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/algorithms/tests/test_auto_ICC.py b/nipype/algorithms/tests/test_auto_ICC.py index 9797fdb4af..4a2389202c 100644 --- a/nipype/algorithms/tests/test_auto_ICC.py +++ b/nipype/algorithms/tests/test_auto_ICC.py @@ -4,8 +4,13 @@ def test_ICC_inputs(): input_map = dict( - mask=dict(extensions=None, mandatory=True,), - subjects_sessions=dict(mandatory=True,), + mask=dict( + extensions=None, + mandatory=True, + ), + subjects_sessions=dict( + mandatory=True, + ), ) inputs = ICC.input_spec() @@ -16,9 +21,15 @@ def test_ICC_inputs(): def test_ICC_outputs(): output_map = dict( - icc_map=dict(extensions=None,), - session_var_map=dict(extensions=None,), - subject_var_map=dict(extensions=None,), + icc_map=dict( + extensions=None, + ), + session_var_map=dict( + extensions=None, + ), + subject_var_map=dict( + extensions=None, + ), ) outputs = ICC.output_spec() diff --git a/nipype/algorithms/tests/test_auto_Matlab2CSV.py b/nipype/algorithms/tests/test_auto_Matlab2CSV.py index 665dbc3fed..42acbd514a 100644 --- a/nipype/algorithms/tests/test_auto_Matlab2CSV.py +++ b/nipype/algorithms/tests/test_auto_Matlab2CSV.py @@ -4,8 +4,13 @@ def test_Matlab2CSV_inputs(): input_map = dict( - in_file=dict(extensions=None, mandatory=True,), - reshape_matrix=dict(usedefault=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), + reshape_matrix=dict( + usedefault=True, + ), ) inputs = Matlab2CSV.input_spec() @@ -15,7 +20,9 @@ def test_Matlab2CSV_inputs(): def test_Matlab2CSV_outputs(): - output_map = dict(csv_files=dict(),) + output_map = dict( + csv_files=dict(), + ) outputs = Matlab2CSV.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_MergeCSVFiles.py b/nipype/algorithms/tests/test_auto_MergeCSVFiles.py index f4f7bc54a0..bb7e9ed65a 100644 --- a/nipype/algorithms/tests/test_auto_MergeCSVFiles.py +++ b/nipype/algorithms/tests/test_auto_MergeCSVFiles.py @@ -7,9 +7,16 @@ def test_MergeCSVFiles_inputs(): column_headings=dict(), extra_column_heading=dict(), extra_field=dict(), - in_files=dict(mandatory=True,), - out_file=dict(extensions=None, usedefault=True,), - row_heading_title=dict(usedefault=True,), + in_files=dict( + mandatory=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), + row_heading_title=dict( + usedefault=True, + ), row_headings=dict(), ) inputs = MergeCSVFiles.input_spec() @@ -20,7 +27,11 @@ def test_MergeCSVFiles_inputs(): def test_MergeCSVFiles_outputs(): - output_map = dict(csv_file=dict(extensions=None,),) + output_map = dict( + csv_file=dict( + extensions=None, + ), + ) outputs = MergeCSVFiles.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_MergeROIs.py b/nipype/algorithms/tests/test_auto_MergeROIs.py index 7f56b9d08c..c43a33b686 100644 --- a/nipype/algorithms/tests/test_auto_MergeROIs.py +++ b/nipype/algorithms/tests/test_auto_MergeROIs.py @@ -4,7 +4,11 @@ def test_MergeROIs_inputs(): input_map = dict( - in_files=dict(), in_index=dict(), in_reference=dict(extensions=None,), + in_files=dict(), + in_index=dict(), + in_reference=dict( + extensions=None, + ), ) inputs = MergeROIs.input_spec() @@ -14,7 +18,11 @@ def test_MergeROIs_inputs(): def test_MergeROIs_outputs(): - output_map = dict(merged_file=dict(extensions=None,),) + output_map = dict( + merged_file=dict( + extensions=None, + ), + ) outputs = MergeROIs.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_MeshWarpMaths.py b/nipype/algorithms/tests/test_auto_MeshWarpMaths.py index be0de9e541..a4295b8f46 100644 --- a/nipype/algorithms/tests/test_auto_MeshWarpMaths.py +++ b/nipype/algorithms/tests/test_auto_MeshWarpMaths.py @@ -5,11 +5,25 @@ def test_MeshWarpMaths_inputs(): input_map = dict( float_trait=dict(), - in_surf=dict(extensions=None, mandatory=True,), - operation=dict(usedefault=True,), - operator=dict(mandatory=True, usedefault=True,), - out_file=dict(extensions=None, usedefault=True,), - out_warp=dict(extensions=None, usedefault=True,), + in_surf=dict( + extensions=None, + mandatory=True, + ), + operation=dict( + usedefault=True, + ), + operator=dict( + mandatory=True, + usedefault=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), + out_warp=dict( + extensions=None, + usedefault=True, + ), ) inputs = MeshWarpMaths.input_spec() @@ -19,7 +33,14 @@ def test_MeshWarpMaths_inputs(): def test_MeshWarpMaths_outputs(): - output_map = dict(out_file=dict(extensions=None,), out_warp=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + out_warp=dict( + extensions=None, + ), + ) outputs = MeshWarpMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_ModifyAffine.py b/nipype/algorithms/tests/test_auto_ModifyAffine.py index a4a441e662..6592e28690 100644 --- a/nipype/algorithms/tests/test_auto_ModifyAffine.py +++ b/nipype/algorithms/tests/test_auto_ModifyAffine.py @@ -4,7 +4,12 @@ def test_ModifyAffine_inputs(): input_map = dict( - transformation_matrix=dict(usedefault=True,), volumes=dict(mandatory=True,), + transformation_matrix=dict( + usedefault=True, + ), + volumes=dict( + mandatory=True, + ), ) inputs = ModifyAffine.input_spec() @@ -14,7 +19,9 @@ def test_ModifyAffine_inputs(): def test_ModifyAffine_outputs(): - output_map = dict(transformed_volumes=dict(),) + output_map = dict( + transformed_volumes=dict(), + ) outputs = ModifyAffine.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_NonSteadyStateDetector.py b/nipype/algorithms/tests/test_auto_NonSteadyStateDetector.py index 5d42bcf0e7..9e14e00595 100644 --- a/nipype/algorithms/tests/test_auto_NonSteadyStateDetector.py +++ b/nipype/algorithms/tests/test_auto_NonSteadyStateDetector.py @@ -3,7 +3,12 @@ def test_NonSteadyStateDetector_inputs(): - input_map = dict(in_file=dict(extensions=None, mandatory=True,),) + input_map = dict( + in_file=dict( + extensions=None, + mandatory=True, + ), + ) inputs = NonSteadyStateDetector.input_spec() for key, metadata in list(input_map.items()): @@ -12,7 +17,9 @@ def test_NonSteadyStateDetector_inputs(): def test_NonSteadyStateDetector_outputs(): - output_map = dict(n_volumes_to_discard=dict(),) + output_map = dict( + n_volumes_to_discard=dict(), + ) outputs = NonSteadyStateDetector.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_NormalizeProbabilityMapSet.py b/nipype/algorithms/tests/test_auto_NormalizeProbabilityMapSet.py index 41b8cc030d..be18979a85 100644 --- a/nipype/algorithms/tests/test_auto_NormalizeProbabilityMapSet.py +++ b/nipype/algorithms/tests/test_auto_NormalizeProbabilityMapSet.py @@ -3,7 +3,12 @@ def test_NormalizeProbabilityMapSet_inputs(): - input_map = dict(in_files=dict(), in_mask=dict(extensions=None,),) + input_map = dict( + in_files=dict(), + in_mask=dict( + extensions=None, + ), + ) inputs = NormalizeProbabilityMapSet.input_spec() for key, metadata in list(input_map.items()): @@ -12,7 +17,9 @@ def test_NormalizeProbabilityMapSet_inputs(): def test_NormalizeProbabilityMapSet_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = NormalizeProbabilityMapSet.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_P2PDistance.py b/nipype/algorithms/tests/test_auto_P2PDistance.py index 0c11648576..a5623353ec 100644 --- a/nipype/algorithms/tests/test_auto_P2PDistance.py +++ b/nipype/algorithms/tests/test_auto_P2PDistance.py @@ -4,12 +4,28 @@ def test_P2PDistance_inputs(): input_map = dict( - metric=dict(usedefault=True,), - out_file=dict(extensions=None, usedefault=True,), - out_warp=dict(extensions=None, usedefault=True,), - surface1=dict(extensions=None, mandatory=True,), - surface2=dict(extensions=None, mandatory=True,), - weighting=dict(usedefault=True,), + metric=dict( + usedefault=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), + out_warp=dict( + extensions=None, + usedefault=True, + ), + surface1=dict( + extensions=None, + mandatory=True, + ), + surface2=dict( + extensions=None, + mandatory=True, + ), + weighting=dict( + usedefault=True, + ), ) inputs = P2PDistance.input_spec() @@ -21,8 +37,12 @@ def test_P2PDistance_inputs(): def test_P2PDistance_outputs(): output_map = dict( distance=dict(), - out_file=dict(extensions=None,), - out_warp=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_warp=dict( + extensions=None, + ), ) outputs = P2PDistance.output_spec() diff --git a/nipype/algorithms/tests/test_auto_PickAtlas.py b/nipype/algorithms/tests/test_auto_PickAtlas.py index 71a76aba5c..2a29ca8d23 100644 --- a/nipype/algorithms/tests/test_auto_PickAtlas.py +++ b/nipype/algorithms/tests/test_auto_PickAtlas.py @@ -4,11 +4,22 @@ def test_PickAtlas_inputs(): input_map = dict( - atlas=dict(extensions=None, mandatory=True,), - dilation_size=dict(usedefault=True,), - hemi=dict(usedefault=True,), - labels=dict(mandatory=True,), - output_file=dict(extensions=None,), + atlas=dict( + extensions=None, + mandatory=True, + ), + dilation_size=dict( + usedefault=True, + ), + hemi=dict( + usedefault=True, + ), + labels=dict( + mandatory=True, + ), + output_file=dict( + extensions=None, + ), ) inputs = PickAtlas.input_spec() @@ -18,7 +29,11 @@ def test_PickAtlas_inputs(): def test_PickAtlas_outputs(): - output_map = dict(mask_file=dict(extensions=None,),) + output_map = dict( + mask_file=dict( + extensions=None, + ), + ) outputs = PickAtlas.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_Similarity.py b/nipype/algorithms/tests/test_auto_Similarity.py index 3a851d0d30..a5e5f583d5 100644 --- a/nipype/algorithms/tests/test_auto_Similarity.py +++ b/nipype/algorithms/tests/test_auto_Similarity.py @@ -4,11 +4,23 @@ def test_Similarity_inputs(): input_map = dict( - mask1=dict(extensions=None,), - mask2=dict(extensions=None,), - metric=dict(usedefault=True,), - volume1=dict(extensions=None, mandatory=True,), - volume2=dict(extensions=None, mandatory=True,), + mask1=dict( + extensions=None, + ), + mask2=dict( + extensions=None, + ), + metric=dict( + usedefault=True, + ), + volume1=dict( + extensions=None, + mandatory=True, + ), + volume2=dict( + extensions=None, + mandatory=True, + ), ) inputs = Similarity.input_spec() @@ -18,7 +30,9 @@ def test_Similarity_inputs(): def test_Similarity_outputs(): - output_map = dict(similarity=dict(),) + output_map = dict( + similarity=dict(), + ) outputs = Similarity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_SimpleThreshold.py b/nipype/algorithms/tests/test_auto_SimpleThreshold.py index 7a1c531c3d..ab7141f0de 100644 --- a/nipype/algorithms/tests/test_auto_SimpleThreshold.py +++ b/nipype/algorithms/tests/test_auto_SimpleThreshold.py @@ -3,7 +3,14 @@ def test_SimpleThreshold_inputs(): - input_map = dict(threshold=dict(mandatory=True,), volumes=dict(mandatory=True,),) + input_map = dict( + threshold=dict( + mandatory=True, + ), + volumes=dict( + mandatory=True, + ), + ) inputs = SimpleThreshold.input_spec() for key, metadata in list(input_map.items()): @@ -12,7 +19,9 @@ def test_SimpleThreshold_inputs(): def test_SimpleThreshold_outputs(): - output_map = dict(thresholded_volumes=dict(),) + output_map = dict( + thresholded_volumes=dict(), + ) outputs = SimpleThreshold.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_SpecifyModel.py b/nipype/algorithms/tests/test_auto_SpecifyModel.py index fd583f42bc..15d9e4994e 100644 --- a/nipype/algorithms/tests/test_auto_SpecifyModel.py +++ b/nipype/algorithms/tests/test_auto_SpecifyModel.py @@ -5,23 +5,43 @@ def test_SpecifyModel_inputs(): input_map = dict( bids_amplitude_column=dict(), - bids_condition_column=dict(usedefault=True,), + bids_condition_column=dict( + usedefault=True, + ), bids_event_file=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], ), event_files=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], - ), - functional_runs=dict(copyfile=False, mandatory=True,), - high_pass_filter_cutoff=dict(mandatory=True,), - input_units=dict(mandatory=True,), - outlier_files=dict(copyfile=False,), - parameter_source=dict(usedefault=True,), - realignment_parameters=dict(copyfile=False,), + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], + ), + functional_runs=dict( + copyfile=False, + mandatory=True, + ), + high_pass_filter_cutoff=dict( + mandatory=True, + ), + input_units=dict( + mandatory=True, + ), + outlier_files=dict( + copyfile=False, + ), + parameter_source=dict( + usedefault=True, + ), + realignment_parameters=dict( + copyfile=False, + ), subject_info=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], + ), + time_repetition=dict( + mandatory=True, ), - time_repetition=dict(mandatory=True,), ) inputs = SpecifyModel.input_spec() @@ -31,7 +51,9 @@ def test_SpecifyModel_inputs(): def test_SpecifyModel_outputs(): - output_map = dict(session_info=dict(),) + output_map = dict( + session_info=dict(), + ) outputs = SpecifyModel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_SpecifySPMModel.py b/nipype/algorithms/tests/test_auto_SpecifySPMModel.py index cb8c5f7a17..64bb206359 100644 --- a/nipype/algorithms/tests/test_auto_SpecifySPMModel.py +++ b/nipype/algorithms/tests/test_auto_SpecifySPMModel.py @@ -5,25 +5,49 @@ def test_SpecifySPMModel_inputs(): input_map = dict( bids_amplitude_column=dict(), - bids_condition_column=dict(usedefault=True,), + bids_condition_column=dict( + usedefault=True, + ), bids_event_file=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], + ), + concatenate_runs=dict( + usedefault=True, ), - concatenate_runs=dict(usedefault=True,), event_files=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], - ), - functional_runs=dict(copyfile=False, mandatory=True,), - high_pass_filter_cutoff=dict(mandatory=True,), - input_units=dict(mandatory=True,), - outlier_files=dict(copyfile=False,), - output_units=dict(usedefault=True,), - parameter_source=dict(usedefault=True,), - realignment_parameters=dict(copyfile=False,), + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], + ), + functional_runs=dict( + copyfile=False, + mandatory=True, + ), + high_pass_filter_cutoff=dict( + mandatory=True, + ), + input_units=dict( + mandatory=True, + ), + outlier_files=dict( + copyfile=False, + ), + output_units=dict( + usedefault=True, + ), + parameter_source=dict( + usedefault=True, + ), + realignment_parameters=dict( + copyfile=False, + ), subject_info=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], + ), + time_repetition=dict( + mandatory=True, ), - time_repetition=dict(mandatory=True,), ) inputs = SpecifySPMModel.input_spec() @@ -33,7 +57,9 @@ def test_SpecifySPMModel_inputs(): def test_SpecifySPMModel_outputs(): - output_map = dict(session_info=dict(),) + output_map = dict( + session_info=dict(), + ) outputs = SpecifySPMModel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_SpecifySparseModel.py b/nipype/algorithms/tests/test_auto_SpecifySparseModel.py index ad116a86b1..cac4ce5770 100644 --- a/nipype/algorithms/tests/test_auto_SpecifySparseModel.py +++ b/nipype/algorithms/tests/test_auto_SpecifySparseModel.py @@ -5,31 +5,63 @@ def test_SpecifySparseModel_inputs(): input_map = dict( bids_amplitude_column=dict(), - bids_condition_column=dict(usedefault=True,), + bids_condition_column=dict( + usedefault=True, + ), bids_event_file=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], ), event_files=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], + ), + functional_runs=dict( + copyfile=False, + mandatory=True, + ), + high_pass_filter_cutoff=dict( + mandatory=True, + ), + input_units=dict( + mandatory=True, ), - functional_runs=dict(copyfile=False, mandatory=True,), - high_pass_filter_cutoff=dict(mandatory=True,), - input_units=dict(mandatory=True,), model_hrf=dict(), - outlier_files=dict(copyfile=False,), - parameter_source=dict(usedefault=True,), - realignment_parameters=dict(copyfile=False,), + outlier_files=dict( + copyfile=False, + ), + parameter_source=dict( + usedefault=True, + ), + realignment_parameters=dict( + copyfile=False, + ), save_plot=dict(), - scale_regressors=dict(usedefault=True,), - scan_onset=dict(usedefault=True,), - stimuli_as_impulses=dict(usedefault=True,), + scale_regressors=dict( + usedefault=True, + ), + scan_onset=dict( + usedefault=True, + ), + stimuli_as_impulses=dict( + usedefault=True, + ), subject_info=dict( - mandatory=True, xor=["subject_info", "event_files", "bids_event_file"], + mandatory=True, + xor=["subject_info", "event_files", "bids_event_file"], + ), + time_acquisition=dict( + mandatory=True, + ), + time_repetition=dict( + mandatory=True, + ), + use_temporal_deriv=dict( + requires=["model_hrf"], + ), + volumes_in_cluster=dict( + usedefault=True, ), - time_acquisition=dict(mandatory=True,), - time_repetition=dict(mandatory=True,), - use_temporal_deriv=dict(requires=["model_hrf"],), - volumes_in_cluster=dict(usedefault=True,), ) inputs = SpecifySparseModel.input_spec() @@ -41,8 +73,12 @@ def test_SpecifySparseModel_inputs(): def test_SpecifySparseModel_outputs(): output_map = dict( session_info=dict(), - sparse_png_file=dict(extensions=None,), - sparse_svg_file=dict(extensions=None,), + sparse_png_file=dict( + extensions=None, + ), + sparse_svg_file=dict( + extensions=None, + ), ) outputs = SpecifySparseModel.output_spec() diff --git a/nipype/algorithms/tests/test_auto_SplitROIs.py b/nipype/algorithms/tests/test_auto_SplitROIs.py index a9f3844775..c9eec86058 100644 --- a/nipype/algorithms/tests/test_auto_SplitROIs.py +++ b/nipype/algorithms/tests/test_auto_SplitROIs.py @@ -4,8 +4,13 @@ def test_SplitROIs_inputs(): input_map = dict( - in_file=dict(extensions=None, mandatory=True,), - in_mask=dict(extensions=None,), + in_file=dict( + extensions=None, + mandatory=True, + ), + in_mask=dict( + extensions=None, + ), roi_size=dict(), ) inputs = SplitROIs.input_spec() @@ -16,7 +21,11 @@ def test_SplitROIs_inputs(): def test_SplitROIs_outputs(): - output_map = dict(out_files=dict(), out_index=dict(), out_masks=dict(),) + output_map = dict( + out_files=dict(), + out_index=dict(), + out_masks=dict(), + ) outputs = SplitROIs.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_StimulusCorrelation.py b/nipype/algorithms/tests/test_auto_StimulusCorrelation.py index 2e95175ca8..19cec418c4 100644 --- a/nipype/algorithms/tests/test_auto_StimulusCorrelation.py +++ b/nipype/algorithms/tests/test_auto_StimulusCorrelation.py @@ -4,10 +4,19 @@ def test_StimulusCorrelation_inputs(): input_map = dict( - concatenated_design=dict(mandatory=True,), - intensity_values=dict(mandatory=True,), - realignment_parameters=dict(mandatory=True,), - spm_mat_file=dict(extensions=None, mandatory=True,), + concatenated_design=dict( + mandatory=True, + ), + intensity_values=dict( + mandatory=True, + ), + realignment_parameters=dict( + mandatory=True, + ), + spm_mat_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = StimulusCorrelation.input_spec() @@ -17,7 +26,9 @@ def test_StimulusCorrelation_inputs(): def test_StimulusCorrelation_outputs(): - output_map = dict(stimcorr_files=dict(),) + output_map = dict( + stimcorr_files=dict(), + ) outputs = StimulusCorrelation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_auto_TCompCor.py b/nipype/algorithms/tests/test_auto_TCompCor.py index d8cb0d7ae6..0f802cc92e 100644 --- a/nipype/algorithms/tests/test_auto_TCompCor.py +++ b/nipype/algorithms/tests/test_auto_TCompCor.py @@ -4,25 +4,59 @@ def test_TCompCor_inputs(): input_map = dict( - components_file=dict(usedefault=True,), - failure_mode=dict(usedefault=True,), + components_file=dict( + usedefault=True, + ), + failure_mode=dict( + usedefault=True, + ), header_prefix=dict(), - high_pass_cutoff=dict(usedefault=True,), - ignore_initial_volumes=dict(usedefault=True,), + high_pass_cutoff=dict( + usedefault=True, + ), + ignore_initial_volumes=dict( + usedefault=True, + ), mask_files=dict(), - mask_index=dict(requires=["mask_files"], xor=["merge_method"],), + mask_index=dict( + requires=["mask_files"], + xor=["merge_method"], + ), mask_names=dict(), - merge_method=dict(requires=["mask_files"], xor=["mask_index"],), - num_components=dict(xor=["variance_threshold"],), - percentile_threshold=dict(usedefault=True,), - pre_filter=dict(usedefault=True,), - realigned_file=dict(extensions=None, mandatory=True,), - regress_poly_degree=dict(usedefault=True,), + merge_method=dict( + requires=["mask_files"], + xor=["mask_index"], + ), + num_components=dict( + xor=["variance_threshold"], + ), + percentile_threshold=dict( + usedefault=True, + ), + pre_filter=dict( + usedefault=True, + ), + realigned_file=dict( + extensions=None, + mandatory=True, + ), + regress_poly_degree=dict( + usedefault=True, + ), repetition_time=dict(), - save_metadata=dict(usedefault=True,), - save_pre_filter=dict(usedefault=True,), - use_regress_poly=dict(deprecated="0.15.0", new_name="pre_filter",), - variance_threshold=dict(xor=["num_components"],), + save_metadata=dict( + usedefault=True, + ), + save_pre_filter=dict( + usedefault=True, + ), + use_regress_poly=dict( + deprecated="0.15.0", + new_name="pre_filter", + ), + variance_threshold=dict( + xor=["num_components"], + ), ) inputs = TCompCor.input_spec() @@ -33,10 +67,16 @@ def test_TCompCor_inputs(): def test_TCompCor_outputs(): output_map = dict( - components_file=dict(extensions=None,), + components_file=dict( + extensions=None, + ), high_variance_masks=dict(), - metadata_file=dict(extensions=None,), - pre_filter_file=dict(extensions=None,), + metadata_file=dict( + extensions=None, + ), + pre_filter_file=dict( + extensions=None, + ), ) outputs = TCompCor.output_spec() diff --git a/nipype/algorithms/tests/test_auto_WarpPoints.py b/nipype/algorithms/tests/test_auto_WarpPoints.py index 493f9fb26f..fc72866d83 100644 --- a/nipype/algorithms/tests/test_auto_WarpPoints.py +++ b/nipype/algorithms/tests/test_auto_WarpPoints.py @@ -4,7 +4,10 @@ def test_WarpPoints_inputs(): input_map = dict( - interp=dict(mandatory=True, usedefault=True,), + interp=dict( + mandatory=True, + usedefault=True, + ), out_points=dict( extensions=None, keep_extension=True, @@ -12,8 +15,14 @@ def test_WarpPoints_inputs(): name_template="%s_warped", output_name="out_points", ), - points=dict(extensions=None, mandatory=True,), - warp=dict(extensions=None, mandatory=True,), + points=dict( + extensions=None, + mandatory=True, + ), + warp=dict( + extensions=None, + mandatory=True, + ), ) inputs = WarpPoints.input_spec() @@ -23,7 +32,11 @@ def test_WarpPoints_inputs(): def test_WarpPoints_outputs(): - output_map = dict(out_points=dict(extensions=None,),) + output_map = dict( + out_points=dict( + extensions=None, + ), + ) outputs = WarpPoints.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/algorithms/tests/test_confounds.py b/nipype/algorithms/tests/test_confounds.py index 29f18c9221..b3fb198707 100644 --- a/nipype/algorithms/tests/test_confounds.py +++ b/nipype/algorithms/tests/test_confounds.py @@ -1,6 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- -import os import pytest from nipype.testing import example_data diff --git a/nipype/algorithms/tests/test_icc_anova.py b/nipype/algorithms/tests/test_icc_anova.py index bd0fe3525b..34e8c5c3e9 100644 --- a/nipype/algorithms/tests/test_icc_anova.py +++ b/nipype/algorithms/tests/test_icc_anova.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import numpy as np from nipype.algorithms.icc import ICC_rep_anova diff --git a/nipype/algorithms/tests/test_mesh_ops.py b/nipype/algorithms/tests/test_mesh_ops.py index 8be59e08c0..f626cc6c0c 100644 --- a/nipype/algorithms/tests/test_mesh_ops.py +++ b/nipype/algorithms/tests/test_mesh_ops.py @@ -1,12 +1,8 @@ -# -*- coding: utf-8 -*- -# coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -import os import pytest -import nipype.testing as npt from nipype.testing import example_data import numpy as np from nipype.algorithms import mesh as m diff --git a/nipype/algorithms/tests/test_metrics.py b/nipype/algorithms/tests/test_metrics.py index ad7502992e..3652fc2ce5 100644 --- a/nipype/algorithms/tests/test_metrics.py +++ b/nipype/algorithms/tests/test_metrics.py @@ -45,7 +45,7 @@ def test_fuzzy_overlap(tmpdir): # Just considering the mask, the central pixel # that raised the index now is left aside. - data = np.zeros((3, 3, 3), dtype=int) + data = np.zeros((3, 3, 3), dtype=np.uint8) data[0, 0, 0] = 1 data[2, 2, 2] = 1 nb.Nifti1Image(data, np.eye(4)).to_filename("mask.nii.gz") diff --git a/nipype/algorithms/tests/test_misc.py b/nipype/algorithms/tests/test_misc.py index 40aab24b2a..3303344ef6 100644 --- a/nipype/algorithms/tests/test_misc.py +++ b/nipype/algorithms/tests/test_misc.py @@ -9,12 +9,10 @@ from nipype.algorithms import misc from nipype.utils.filemanip import fname_presuffix from nipype.testing.fixtures import create_analyze_pair_file_in_directory -from nipype.utils import NUMPY_MMAP from nipype.testing import example_data def test_CreateNifti(create_analyze_pair_file_in_directory): - filelist, outdir = create_analyze_pair_file_in_directory create_nifti = misc.CreateNifti() @@ -32,11 +30,10 @@ def test_CreateNifti(create_analyze_pair_file_in_directory): result = create_nifti.run() assert os.path.exists(result.outputs.nifti_file) - assert nb.load(result.outputs.nifti_file, mmap=NUMPY_MMAP) + assert nb.load(result.outputs.nifti_file) def test_CalculateMedian(create_analyze_pair_file_in_directory): - mean = misc.CalculateMedian() with pytest.raises(TypeError): @@ -46,4 +43,4 @@ def test_CalculateMedian(create_analyze_pair_file_in_directory): eg = mean.run() assert os.path.exists(eg.outputs.median_files) - assert nb.load(eg.outputs.median_files, mmap=NUMPY_MMAP) + assert nb.load(eg.outputs.median_files) diff --git a/nipype/algorithms/tests/test_modelgen.py b/nipype/algorithms/tests/test_modelgen.py index a2c85f6747..1b1aacae00 100644 --- a/nipype/algorithms/tests/test_modelgen.py +++ b/nipype/algorithms/tests/test_modelgen.py @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from copy import deepcopy -import os from nibabel import Nifti1Image import numpy as np @@ -105,7 +103,7 @@ def test_modelgen1(tmpdir): np.array([6.0, 6.0]), ) npt.assert_almost_equal( - np.array(res.outputs.session_info[0]["cond"][1]["duration"]), np.array([6.0,]) + np.array(res.outputs.session_info[0]["cond"][1]["duration"]), np.array([6.0]) ) npt.assert_almost_equal( np.array(res.outputs.session_info[1]["cond"][1]["duration"]), @@ -123,7 +121,7 @@ def test_modelgen_spm_concat(tmpdir): s = SpecifySPMModel() s.inputs.input_units = "secs" s.inputs.concatenate_runs = True - setattr(s.inputs, "output_units", "secs") + s.inputs.output_units = "secs" assert s.inputs.output_units == "secs" s.inputs.functional_runs = [filename1, filename2] s.inputs.time_repetition = 6 @@ -148,7 +146,7 @@ def test_modelgen_spm_concat(tmpdir): ) # Test case of scans as output units instead of seconds - setattr(s.inputs, "output_units", "scans") + s.inputs.output_units = "scans" assert s.inputs.output_units == "scans" s.inputs.subject_info = deepcopy(info) res = s.run() @@ -191,14 +189,14 @@ def test_modelgen_spm_concat(tmpdir): np.array([1.0, 1.0]), ) npt.assert_almost_equal( - np.array(res.outputs.session_info[0]["cond"][1]["duration"]), np.array([1.0,]) + np.array(res.outputs.session_info[0]["cond"][1]["duration"]), np.array([1.0]) ) npt.assert_almost_equal( np.array(res.outputs.session_info[1]["cond"][1]["duration"]), np.array([1.0, 1.0]), ) npt.assert_almost_equal( - np.array(res.outputs.session_info[2]["cond"][1]["duration"]), np.array([1.0,]) + np.array(res.outputs.session_info[2]["cond"][1]["duration"]), np.array([1.0]) ) # Test case for variable number of events in concatenated runs, sometimes unique. diff --git a/nipype/algorithms/tests/test_moments.py b/nipype/algorithms/tests/test_moments.py index 91e6313193..6fe60c4e61 100644 --- a/nipype/algorithms/tests/test_moments.py +++ b/nipype/algorithms/tests/test_moments.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import numpy as np from nipype.algorithms.misc import calc_moments diff --git a/nipype/algorithms/tests/test_normalize_tpms.py b/nipype/algorithms/tests/test_normalize_tpms.py index c9b206361d..37eb9bb51b 100644 --- a/nipype/algorithms/tests/test_normalize_tpms.py +++ b/nipype/algorithms/tests/test_normalize_tpms.py @@ -1,23 +1,16 @@ -# -*- coding: utf-8 -*- -# coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -import os -import pytest from nipype.testing import example_data import numpy as np import nibabel as nb -import nipype.testing as nit from nipype.algorithms.misc import normalize_tpms -from nipype.utils import NUMPY_MMAP def test_normalize_tpms(tmpdir): - in_mask = example_data("tpms_msk.nii.gz") mskdata = np.asanyarray(nb.load(in_mask).dataobj) mskdata[mskdata > 0.0] = 1.0 diff --git a/nipype/algorithms/tests/test_rapidart.py b/nipype/algorithms/tests/test_rapidart.py index fdf0716805..322d32ad2e 100644 --- a/nipype/algorithms/tests/test_rapidart.py +++ b/nipype/algorithms/tests/test_rapidart.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import numpy as np diff --git a/nipype/algorithms/tests/test_splitmerge.py b/nipype/algorithms/tests/test_splitmerge.py index 5b06484e2c..af4a920be5 100644 --- a/nipype/algorithms/tests/test_splitmerge.py +++ b/nipype/algorithms/tests/test_splitmerge.py @@ -1,15 +1,11 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- from nipype.testing import example_data -from nipype.utils import NUMPY_MMAP def test_split_and_merge(tmpdir): import numpy as np import nibabel as nb - import os.path as op - import os from nipype.algorithms.misc import split_rois, merge_rois diff --git a/nipype/algorithms/tests/test_stats.py b/nipype/algorithms/tests/test_stats.py index 752fadf307..ed698d47cf 100644 --- a/nipype/algorithms/tests/test_stats.py +++ b/nipype/algorithms/tests/test_stats.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -10,7 +9,7 @@ def test_ActivationCount(tmpdir): tmpdir.chdir() - in_files = ["{:d}.nii".format(i) for i in range(3)] + in_files = [f"{i:d}.nii" for i in range(3)] for fname in in_files: nb.Nifti1Image(np.random.normal(size=(5, 5, 5)), np.eye(4)).to_filename(fname) @@ -32,7 +31,7 @@ def test_ActivationCount(tmpdir): ) def test_ActivationCount_normaldistr(tmpdir, threshold, above_thresh): tmpdir.chdir() - in_files = ["{:d}.nii".format(i) for i in range(3)] + in_files = [f"{i:d}.nii" for i in range(3)] for fname in in_files: nb.Nifti1Image(np.random.normal(size=(100, 100, 100)), np.eye(4)).to_filename( fname diff --git a/nipype/caching/__init__.py b/nipype/caching/__init__.py index 1e99ed4428..db0261ebea 100644 --- a/nipype/caching/__init__.py +++ b/nipype/caching/__init__.py @@ -1,2 +1 @@ -# -*- coding: utf-8 -*- from .memory import Memory diff --git a/nipype/caching/memory.py b/nipype/caching/memory.py index 4f773f0c3c..a1d45ffff2 100644 --- a/nipype/caching/memory.py +++ b/nipype/caching/memory.py @@ -1,8 +1,8 @@ -# -*- coding: utf-8 -*- """ Using nipype with persistence and lazy recomputation but without explicit name-steps pipeline: getting back scope in command-line based programming. """ + import os import hashlib import pickle @@ -18,29 +18,29 @@ # PipeFunc object: callable interface to nipype.interface objects -class PipeFunc(object): - """ Callable interface to nipype.interface objects +class PipeFunc: + """Callable interface to nipype.interface objects - Use this to wrap nipype.interface object and call them - specifying their input with keyword arguments:: + Use this to wrap nipype.interface object and call them + specifying their input with keyword arguments:: - fsl_merge = PipeFunc(fsl.Merge, base_dir='.') - out = fsl_merge(in_files=files, dimension='t') + fsl_merge = PipeFunc(fsl.Merge, base_dir='.') + out = fsl_merge(in_files=files, dimension='t') """ def __init__(self, interface, base_dir, callback=None): """ - Parameters - =========== - interface: a nipype interface class - The interface class to wrap - base_dir: a string - The directory in which the computation will be - stored - callback: a callable - An optional callable called each time after the function - is called. + Parameters + =========== + interface: a nipype interface class + The interface class to wrap + base_dir: a string + The directory in which the computation will be + stored + callback: a callable + An optional callable called each time after the function + is called. """ if not (isinstance(interface, type) and issubclass(interface, BaseInterface)): raise ValueError( @@ -53,7 +53,7 @@ def __init__(self, interface, base_dir, callback=None): if not os.path.exists(base_dir) and os.path.isdir(base_dir): raise ValueError("base_dir should be an existing directory") self.base_dir = base_dir - doc = "%s\n%s" % (self.interface.__doc__, self.interface.help(returnhelp=True)) + doc = f"{self.interface.__doc__}\n{self.interface.help(returnhelp=True)}" self.__doc__ = doc self.callback = callback @@ -66,7 +66,7 @@ def __call__(self, **kwargs): inputs = interface.inputs.get_hashval() hasher = hashlib.new("md5") hasher.update(pickle.dumps(inputs)) - dir_name = "%s-%s" % ( + dir_name = "{}-{}".format( interface.__class__.__module__.replace(".", "-"), interface.__class__.__name__, ) @@ -103,7 +103,7 @@ def read_log(filename, run_dict=None): if run_dict is None: run_dict = dict() - with open(filename, "r") as logfile: + with open(filename) as logfile: for line in logfile: dir_name, job_name = line[:-1].split("/") jobs = run_dict.get(dir_name, set()) @@ -113,14 +113,14 @@ def read_log(filename, run_dict=None): def rm_all_but(base_dir, dirs_to_keep, warn=False): - """ Remove all the sub-directories of base_dir, but those listed - - Parameters - ============ - base_dir: string - The base directory - dirs_to_keep: set - The names of the directories to keep + """Remove all the sub-directories of base_dir, but those listed + + Parameters + ============ + base_dir: string + The base directory + dirs_to_keep: set + The names of the directories to keep """ try: all_dirs = os.listdir(base_dir) @@ -137,7 +137,7 @@ def rm_all_but(base_dir, dirs_to_keep, warn=False): shutil.rmtree(dir_name) -class _MemoryCallback(object): +class _MemoryCallback: "An object to avoid closures and have everything pickle" def __init__(self, memory): @@ -147,24 +147,24 @@ def __call__(self, dir_name, job_name): self.memory._log_name(dir_name, job_name) -class Memory(object): - """ Memory context to provide caching for interfaces - - Parameters - ========== - base_dir: string - The directory name of the location for the caching - - Methods - ======= - cache - Creates a cacheable function from an nipype Interface class - clear_previous_runs - Removes from the disk all the runs that where not used after - the creation time of the specific Memory instance - clear_previous_runs - Removes from the disk all the runs that where not used after - the given time +class Memory: + """Memory context to provide caching for interfaces + + Parameters + ========== + base_dir: string + The directory name of the location for the caching + + Methods + ======= + cache + Creates a cacheable function from an nipype Interface class + clear_previous_runs + Removes from the disk all the runs that where not used after + the creation time of the specific Memory instance + clear_previous_runs + Removes from the disk all the runs that where not used after + the given time """ def __init__(self, base_dir): @@ -177,55 +177,54 @@ def __init__(self, base_dir): open(os.path.join(base_dir, "log.current"), "a").close() def cache(self, interface): - """ Returns a callable that caches the output of an interface + """Returns a callable that caches the output of an interface - Parameters - ========== - interface: nipype interface - The nipype interface class to be wrapped and cached + Parameters + ========== + interface: nipype interface + The nipype interface class to be wrapped and cached - Returns - ======= - pipe_func: a PipeFunc callable object - An object that can be used as a function to apply the - interface to arguments. Inputs of the interface are given - as keyword arguments, bearing the same name as the name - in the inputs specs of the interface. + Returns + ======= + pipe_func: a PipeFunc callable object + An object that can be used as a function to apply the + interface to arguments. Inputs of the interface are given + as keyword arguments, bearing the same name as the name + in the inputs specs of the interface. - Examples - ======== + Examples + ======== - >>> from tempfile import mkdtemp - >>> mem = Memory(mkdtemp()) - >>> from nipype.interfaces import fsl + >>> from tempfile import mkdtemp + >>> mem = Memory(mkdtemp()) + >>> from nipype.interfaces import fsl - Here we create a callable that can be used to apply an - fsl.Merge interface to files + Here we create a callable that can be used to apply an + fsl.Merge interface to files - >>> fsl_merge = mem.cache(fsl.Merge) + >>> fsl_merge = mem.cache(fsl.Merge) - Now we apply it to a list of files. We need to specify the - list of input files and the dimension along which the files - should be merged. + Now we apply it to a list of files. We need to specify the + list of input files and the dimension along which the files + should be merged. - >>> results = fsl_merge(in_files=['a.nii', 'b.nii'], - ... dimension='t') # doctest: +SKIP + >>> results = fsl_merge(in_files=['a.nii', 'b.nii'], + ... dimension='t') # doctest: +SKIP - We can retrieve the resulting file from the outputs: - >>> results.outputs.merged_file # doctest: +SKIP - '...' + We can retrieve the resulting file from the outputs: + >>> results.outputs.merged_file # doctest: +SKIP + '...' """ return PipeFunc(interface, self.base_dir, _MemoryCallback(self)) def _log_name(self, dir_name, job_name): - """ Increment counters tracking which cached function get executed. - """ + """Increment counters tracking which cached function get executed.""" base_dir = self.base_dir # Every counter is a file opened in append mode and closed # immediately to avoid race conditions in parallel computing: # file appends are atomic with open(os.path.join(base_dir, "log.current"), "a") as currentlog: - currentlog.write("%s/%s\n" % (dir_name, job_name)) + currentlog.write(f"{dir_name}/{job_name}\n") t = time.localtime() year_dir = os.path.join(base_dir, "log.%i" % t.tm_year) @@ -240,35 +239,35 @@ def _log_name(self, dir_name, job_name): "Dir exists" with open(os.path.join(month_dir, "%02i.log" % t.tm_mday), "a") as rotatefile: - rotatefile.write("%s/%s\n" % (dir_name, job_name)) + rotatefile.write(f"{dir_name}/{job_name}\n") def clear_previous_runs(self, warn=True): - """ Remove all the cache that where not used in the latest run of - the memory object: i.e. since the corresponding Python object - was created. - - Parameters - ========== - warn: boolean, optional - If true, echoes warning messages for all directory - removed + """Remove all the cache that where not used in the latest run of + the memory object: i.e. since the corresponding Python object + was created. + + Parameters + ========== + warn: boolean, optional + If true, echoes warning messages for all directory + removed """ base_dir = self.base_dir latest_runs = read_log(os.path.join(base_dir, "log.current")) self._clear_all_but(latest_runs, warn=warn) def clear_runs_since(self, day=None, month=None, year=None, warn=True): - """ Remove all the cache that where not used since the given date - - Parameters - ========== - day, month, year: integers, optional - The integers specifying the latest day (in localtime) that - a node should have been accessed to be kept. If not - given, the current date is used. - warn: boolean, optional - If true, echoes warning messages for all directory - removed + """Remove all the cache that where not used since the given date + + Parameters + ========== + day, month, year: integers, optional + The integers specifying the latest day (in localtime) that + a node should have been accessed to be kept. If not + given, the current date is used. + warn: boolean, optional + If true, echoes warning messages for all directory + removed """ t = time.localtime() day = day if day is not None else t.tm_mday @@ -288,12 +287,12 @@ def clear_runs_since(self, day=None, month=None, year=None, warn=True): os.remove(log_name) def _clear_all_but(self, runs, warn=True): - """ Remove all the runs appart from those given to the function - input. + """Remove all the runs apart from those given to the function + input. """ rm_all_but(self.base_dir, set(runs.keys()), warn=warn) for dir_name, job_names in list(runs.items()): rm_all_but(os.path.join(self.base_dir, dir_name), job_names, warn=warn) def __repr__(self): - return "{}(base_dir={})".format(self.__class__.__name__, self.base_dir) + return f"{self.__class__.__name__}(base_dir={self.base_dir})" diff --git a/nipype/caching/tests/__init__.py b/nipype/caching/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/caching/tests/__init__.py +++ b/nipype/caching/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/caching/tests/test_memory.py b/nipype/caching/tests/test_memory.py index ef80869f03..cd5b8f8075 100644 --- a/nipype/caching/tests/test_memory.py +++ b/nipype/caching/tests/test_memory.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- -""" Test the nipype interface caching mechanism -""" +"""Test the nipype interface caching mechanism""" from .. import Memory from ...pipeline.engine.tests.test_engine import EngineTestInterface @@ -16,7 +14,7 @@ class SideEffectInterface(EngineTestInterface): def _run_interface(self, runtime): global nb_runs nb_runs += 1 - return super(SideEffectInterface, self)._run_interface(runtime) + return super()._run_interface(runtime) def test_caching(tmpdir): diff --git a/nipype/conftest.py b/nipype/conftest.py index b099fd0078..151906678f 100644 --- a/nipype/conftest.py +++ b/nipype/conftest.py @@ -2,7 +2,7 @@ import shutil from tempfile import mkdtemp import pytest -import numpy +import numpy as np import py.path as pp NIPYPE_DATADIR = os.path.realpath( @@ -15,18 +15,23 @@ @pytest.fixture(autouse=True) def add_np(doctest_namespace): - doctest_namespace["np"] = numpy + doctest_namespace["np"] = np doctest_namespace["os"] = os + doctest_namespace["pytest"] = pytest doctest_namespace["datadir"] = data_dir +@pytest.fixture(scope='session', autouse=True) +def legacy_printoptions(): + np.set_printoptions(legacy='1.21') + + @pytest.fixture(autouse=True) def _docdir(request): """Grabbed from https://stackoverflow.com/a/46991331""" # Trigger ONLY for the doctests. doctest_plugin = request.config.pluginmanager.getplugin("doctest") if isinstance(request.node, doctest_plugin.DoctestItem): - # Get the fixture dynamically by its name. tmpdir = pp.local(data_dir) diff --git a/nipype/external/__init__.py b/nipype/external/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/external/__init__.py +++ b/nipype/external/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/external/cloghandler.py b/nipype/external/cloghandler.py index c5ee9d7a6f..680ba30e2e 100644 --- a/nipype/external/cloghandler.py +++ b/nipype/external/cloghandler.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Copyright 2008 Lowell Alleman # # Licensed under the Apache License, Version 2.0 (the "License"); you may not @@ -10,7 +9,7 @@ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. -""" cloghandler.py: A smart replacement for the standard RotatingFileHandler +"""cloghandler.py: A smart replacement for the standard RotatingFileHandler ConcurrentRotatingFileHandler: This class is a log handler which is a drop-in replacement for the python standard log handler 'RotateFileHandler', the primary @@ -40,13 +39,10 @@ """ -from builtins import range __version__ = "$Id: cloghandler.py 6175 2009-11-02 18:40:35Z lowell $" __author__ = "Lowell Alleman" -__all__ = [ - "ConcurrentRotatingFileHandler", -] +__all__ = ["ConcurrentRotatingFileHandler"] import os import sys @@ -153,7 +149,9 @@ def __init__( ) try: BaseRotatingHandler.__init__(self, filename, mode, encoding) - except TypeError: # Due to a different logging release without encoding support (Python 2.4.1 and earlier?) + except ( + TypeError + ): # Due to a different logging release without encoding support (Python 2.4.1 and earlier?) BaseRotatingHandler.__init__(self, filename, mode) self.encoding = encoding @@ -175,8 +173,8 @@ def _openFile(self, mode): self.stream = open(self.baseFilename, mode) def acquire(self): - """ Acquire thread and file locks. Also re-opening log file when running - in 'degraded' mode. """ + """Acquire thread and file locks. Also re-opening log file when running + in 'degraded' mode.""" # handle thread lock Handler.acquire(self) self.stream_lock.acquire() @@ -184,14 +182,14 @@ def acquire(self): self._openFile(self.mode) def release(self): - """ Release file and thread locks. Flush stream and take care of closing - stream in 'degraded' mode. """ + """Release file and thread locks. Flush stream and take care of closing + stream in 'degraded' mode.""" try: if not self.stream.closed: self.stream.flush() if self._rotateFailed: self.stream.close() - except IOError: + except OSError: if self._rotateFailed: self.stream.close() finally: @@ -211,7 +209,7 @@ def close(self): Handler.close(self) def flush(self): - """ flush(): Do nothing. + """flush(): Do nothing. Since a flush is issued in release(), we don't do it here. To do a flush here, it would be necessary to re-lock everything, and it is just easier @@ -220,16 +218,16 @@ def flush(self): Doing a flush() here would also introduces a window of opportunity for another process to write to the log file in between calling - stream.write() and stream.flush(), which seems like a bad thing. """ + stream.write() and stream.flush(), which seems like a bad thing.""" pass def _degrade(self, degrade, msg, *args): - """ Set degrade mode or not. Ignore msg. """ + """Set degrade mode or not. Ignore msg.""" self._rotateFailed = degrade del msg, args # avoid pychecker warnings def _degrade_debug(self, degrade, msg, *args): - """ A more colorful version of _degade(). (This is enabled by passing + """A more colorful version of _degade(). (This is enabled by passing "debug=True" at initialization). """ if degrade: @@ -266,10 +264,10 @@ def doRollover(self): try: # Do a rename test to determine if we can successfully rename the log file os.rename(self.baseFilename, tmpname) - except (IOError, OSError): + except OSError: exc_value = sys.exc_info()[1] self._degrade( - True, "rename failed. File in use? " "exception=%s", exc_value + True, "rename failed. File in use? exception=%s", exc_value ) return @@ -319,7 +317,7 @@ def _shouldRollover(self): if self.maxBytes > 0: # are we rolling over? try: self.stream.seek(0, 2) # due to non-posix-compliant Windows feature - except IOError: + except OSError: return True if self.stream.tell() >= self.maxBytes: return True diff --git a/nipype/external/due.py b/nipype/external/due.py index fc436d5d45..47a0ae4e0f 100644 --- a/nipype/external/due.py +++ b/nipype/external/due.py @@ -27,7 +27,7 @@ __version__ = "0.0.5" -class InactiveDueCreditCollector(object): +class InactiveDueCreditCollector: """Just a stub at the Collector which would not do anything""" def _donothing(self, *args, **kwargs): @@ -45,7 +45,7 @@ def nondecorating_decorator(func): cite = load = add = _donothing def __repr__(self): - return "{}()".format(self.__class__.__name__) + return f"{self.__class__.__name__}()" def _donothing_func(*args, **kwargs): diff --git a/nipype/external/fsl_imglob.py b/nipype/external/fsl_imglob.py index 3707e4750d..46ae5f2549 100755 --- a/nipype/external/fsl_imglob.py +++ b/nipype/external/fsl_imglob.py @@ -65,7 +65,6 @@ # innovation@isis.ox.ac.uk quoting reference DE/9564. import sys import glob -from builtins import range def usage(): @@ -92,14 +91,6 @@ def main(): if len(sys.argv) <= 1: usage() - if sys.version_info < (2, 4): - import sets - from sets import Set - - setAvailable = False - else: - setAvailable = True - deleteExtensions = True primaryExtensions = [".nii.gz", ".nii", ".hdr.gz", ".hdr"] secondaryExtensions = [".img.gz", ".img"] @@ -132,18 +123,10 @@ def main(): ) if deleteExtensions: - for file in range(0, len(filelist)): - filelist[file] = removeImageExtension(filelist[file], allExtensions) - if setAvailable: - filelist = list(set(filelist)) - else: - filelist = list(Set(filelist)) - filelist.sort() + filelist = [removeImageExtension(f, allExtensions) for f in filelist] + filelist = sorted(set(filelist)) - for file in range(0, len(filelist)): - print(filelist[file], end=" ") - if file < len(filelist) - 1: - print(" ", end=" ") + print(*filelist, sep=" ", end=" ") if __name__ == "__main__": diff --git a/nipype/info.py b/nipype/info.py index 400480d9c5..7ad5aba5bb 100644 --- a/nipype/info.py +++ b/nipype/info.py @@ -1,11 +1,11 @@ -""" This file contains defines parameters for nipy that we use to fill +"""This file contains defines parameters for nipy that we use to fill settings in setup.py, the nipy top-level docstring, and for building the docs. In setup.py in particular, we exec this file, so it cannot import nipy """ # nipype version information -# Remove -dev for release -__version__ = "1.4.3-dev" +# Remove .dev0 for release +__version__ = "1.11.0.dev0" def get_nipype_gitversion(): @@ -45,7 +45,7 @@ def get_nipype_gitversion(): if __version__.endswith("-dev"): gitversion = get_nipype_gitversion() if gitversion: - __version__ = "{}+{}".format(__version__, gitversion) + __version__ = f"{__version__}+{gitversion}" CLASSIFIERS = [ "Development Status :: 5 - Production/Stable", @@ -54,12 +54,14 @@ def get_nipype_gitversion(): "License :: OSI Approved :: Apache Software License", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX :: Linux", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", "Topic :: Scientific/Engineering", ] -PYTHON_REQUIRES = ">= 3.5" +PYTHON_REQUIRES = ">= 3.9" description = "Neuroimaging in Python: Pipelines and Interfaces" @@ -98,18 +100,15 @@ def get_nipype_gitversion(): """ # versions -NIBABEL_MIN_VERSION = "2.1.0" -NETWORKX_MIN_VERSION = "1.9" -NUMPY_MIN_VERSION = "1.12" -# Numpy bug in python 3.7: -# https://www.opensourceanswers.com/blog/you-shouldnt-use-python-37-for-data-science-right-now.html -NUMPY_MIN_VERSION_37 = "1.15.3" -SCIPY_MIN_VERSION = "0.14" -TRAITS_MIN_VERSION = "4.6" +NIBABEL_MIN_VERSION = "3.0" +NETWORKX_MIN_VERSION = "2.5" +NUMPY_MIN_VERSION = "1.21" +SCIPY_MIN_VERSION = "1.8" +TRAITS_MIN_VERSION = "6.2" DATEUTIL_MIN_VERSION = "2.2" -FUTURE_MIN_VERSION = "0.16.0" SIMPLEJSON_MIN_VERSION = "3.8.0" -PROV_VERSION = "1.5.2" +PROV_MIN_VERSION = "1.5.2" +RDFLIB_MIN_VERSION = "5.0.0" CLICK_MIN_VERSION = "6.6.0" PYDOT_MIN_VERSION = "1.2.3" @@ -137,32 +136,32 @@ def get_nipype_gitversion(): "click>=%s" % CLICK_MIN_VERSION, "networkx>=%s" % NETWORKX_MIN_VERSION, "nibabel>=%s" % NIBABEL_MIN_VERSION, - 'numpy>=%s ; python_version < "3.7"' % NUMPY_MIN_VERSION, - 'numpy>=%s ; python_version >= "3.7"' % NUMPY_MIN_VERSION_37, + "numpy>=%s" % NUMPY_MIN_VERSION, "packaging", - "prov>=%s" % PROV_VERSION, + "prov>=%s" % PROV_MIN_VERSION, "pydot>=%s" % PYDOT_MIN_VERSION, - "pydotplus", "python-dateutil>=%s" % DATEUTIL_MIN_VERSION, + "rdflib>=%s" % RDFLIB_MIN_VERSION, "scipy>=%s" % SCIPY_MIN_VERSION, "simplejson>=%s" % SIMPLEJSON_MIN_VERSION, - "traits>=%s,!=5.0" % TRAITS_MIN_VERSION, + "traits>=%s" % TRAITS_MIN_VERSION, "filelock>=3.0.0", - "etelemetry", + "acres", + "etelemetry>=0.3.1", + "looseversion!=1.2", + "puremagic", ] -# neurdflib has to come after prov -# https://github.com/nipy/nipype/pull/2961#issuecomment-512035484 -REQUIRES += ["neurdflib"] - TESTS_REQUIRES = [ - "codecov", - "coverage<5", - "mock", - "pytest", - "pytest-cov", + "coverage >= 5.2.1", + "pandas >= 1.5.0", + "pytest >= 6", + "pytest-cov >=2.11", "pytest-env", - "pytest-timeout", + "pytest-timeout >=1.4", + "pytest-doctestplus", + "pytest-xdist >= 2.5", + "sphinx >=7", ] EXTRA_REQUIRES = { @@ -175,10 +174,10 @@ def get_nipype_gitversion(): "sphinx-argparse", "sphinx>=2.1.2", "sphinxcontrib-apidoc", - "sphinxcontrib-napoleon", ], "duecredit": ["duecredit"], - "nipy": ["nitime", "nilearn<0.5.0", "dipy", "nipy", "matplotlib"], + "maint": ["GitPython", "fuzzywuzzy"], + "nipy": ["nitime", "nilearn", "dipy", "nipy", "matplotlib"], "profiler": ["psutil>=5.0"], "pybids": ["pybids>=0.7.0"], "specs": ["black"], @@ -190,7 +189,7 @@ def get_nipype_gitversion(): def _list_union(iterable): - return list(set(sum(iterable, []))) + return list(set(x for sublist in iterable for x in sublist)) # Enable a handle to install all extra dependencies at once diff --git a/nipype/interfaces/__init__.py b/nipype/interfaces/__init__.py index fe1bf9c9e5..d72a463882 100644 --- a/nipype/interfaces/__init__.py +++ b/nipype/interfaces/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/interfaces/afni/__init__.py b/nipype/interfaces/afni/__init__.py index d5f2bb4361..7e6df345bc 100644 --- a/nipype/interfaces/afni/__init__.py +++ b/nipype/interfaces/afni/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -29,6 +28,7 @@ LFCD, Maskave, Means, + NetCorr, OutlierCount, QualityIndex, ROIStats, diff --git a/nipype/interfaces/afni/base.py b/nipype/interfaces/afni/base.py index 20a4a9b4d6..e883b22c6e 100644 --- a/nipype/interfaces/afni/base.py +++ b/nipype/interfaces/afni/base.py @@ -1,12 +1,13 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Provide a base interface to AFNI commands.""" import os from sys import platform -from distutils import spawn +import shutil -from ... import logging, LooseVersion +from looseversion import LooseVersion + +from ... import logging from ...utils.filemanip import split_filename, fname_presuffix from ..base import ( CommandLine, @@ -98,7 +99,7 @@ def standard_image(img_name): resource_monitor=False, terminal_output="allatonce", ).run() - if clout.runtime.returncode is not 0: + if clout.runtime.returncode != 0: return None out = clout.runtime.stdout @@ -121,9 +122,7 @@ class AFNICommandBase(CommandLine): def _run_interface(self, runtime, correct_return_codes=(0,)): if platform == "darwin": runtime.environ["DYLD_FALLBACK_LIBRARY_PATH"] = "/usr/local/afni/" - return super(AFNICommandBase, self)._run_interface( - runtime, correct_return_codes - ) + return super()._run_interface(runtime, correct_return_codes) class AFNICommandInputSpec(CommandLineInputSpec): @@ -151,7 +150,7 @@ class AFNICommand(AFNICommandBase): input_spec = AFNICommandInputSpec _outputtype = None - references_ = [ + _references = [ { "entry": BibTeX( "@article{Cox1996," @@ -211,7 +210,7 @@ def set_default_output_type(cls, outputtype): def __init__(self, **inputs): """Instantiate an AFNI command tool wrapper.""" - super(AFNICommand, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._output_update, "outputtype") if hasattr(self.inputs, "num_threads"): @@ -246,7 +245,7 @@ def _overload_extension(self, value, name=None): ) def _list_outputs(self): - outputs = super(AFNICommand, self)._list_outputs() + outputs = super()._list_outputs() metadata = dict(name_source=lambda t: t is not None) out_names = list(self.inputs.traits(**metadata).keys()) if out_names: @@ -262,8 +261,8 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, ext=None) Generate a filename based on the given parameters. The filename will take the form: cwd/basename. - If change_ext is True, it will use the extentions specified in - intputs.output_type. + If change_ext is True, it will use the extensions specified in + inputs.output_type. Parameters ---------- @@ -293,7 +292,7 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, ext=None) if ext is None: ext = Info.output_type_to_ext(self.inputs.outputtype) if change_ext: - suffix = "".join((suffix, ext)) if suffix else ext + suffix = f"{suffix}{ext}" if suffix else ext if suffix is None: suffix = "" @@ -316,17 +315,15 @@ class AFNIPythonCommand(AFNICommand): @property def cmd(self): """Revise the command path.""" - orig_cmd = super(AFNIPythonCommand, self).cmd - found = spawn.find_executable(orig_cmd) + orig_cmd = super().cmd + found = shutil.which(orig_cmd) return found if found is not None else orig_cmd @property def _cmd_prefix(self): - return "{} ".format(self.inputs.py27_path) + return f"{self.inputs.py27_path} " def no_afni(): """Check whether AFNI is not available.""" - if Info.version() is None: - return True - return False + return Info.version() is None diff --git a/nipype/interfaces/afni/model.py b/nipype/interfaces/afni/model.py index 2e6d2fc15a..e3a7348b3b 100644 --- a/nipype/interfaces/afni/model.py +++ b/nipype/interfaces/afni/model.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft = python sts = 4 ts = 4 sw = 4 et: """ @@ -13,25 +12,19 @@ import os from ..base import ( - CommandLineInputSpec, - CommandLine, - Directory, TraitedSpec, traits, isdefined, File, InputMultiPath, - Undefined, Str, + Tuple, ) -from ...external.due import BibTeX from .base import ( - AFNICommandBase, AFNICommand, AFNICommandInputSpec, AFNICommandOutputSpec, - Info, ) @@ -128,7 +121,7 @@ class DeconvolveInputSpec(AFNICommandInputSpec): "that 'gotforit' is needed to ignore.", argstr="-allzero_OK", ) - dname = traits.Tuple( + dname = Tuple( Str, Str, desc="set environmental variable to provided value", argstr="-D%s=%s" ) mask = File( @@ -163,7 +156,7 @@ class DeconvolveInputSpec(AFNICommandInputSpec): "[default: 1]", argstr="-polort %d", ) - ortvec = traits.Tuple( + ortvec = Tuple( File(desc="filename", exists=True), Str(desc="label"), desc="this option lets you input a rectangular array of 1 or more " @@ -197,7 +190,7 @@ class DeconvolveInputSpec(AFNICommandInputSpec): desc="output the sample variance (MSE) for each stimulus", argstr="-vout" ) nofdr = traits.Bool( - desc="Don't compute the statistic-vs-FDR curves for the bucket " "dataset.", + desc="Don't compute the statistic-vs-FDR curves for the bucket dataset.", argstr="-noFDR", ) global_times = traits.Bool( @@ -214,19 +207,17 @@ class DeconvolveInputSpec(AFNICommandInputSpec): desc="number of stimulus timing files", argstr="-num_stimts %d", position=-6 ) stim_times = traits.List( - traits.Tuple( + Tuple( traits.Int(desc="k-th response model"), File(desc="stimulus timing file", exists=True), Str(desc="model"), ), - desc="generate a response model from a set of stimulus times" " given in file.", + desc="generate a response model from a set of stimulus times given in file.", argstr="-stim_times %d %s '%s'...", position=-5, ) stim_label = traits.List( - traits.Tuple( - traits.Int(desc="k-th input stimulus"), Str(desc="stimulus label") - ), + Tuple(traits.Int(desc="k-th input stimulus"), Str(desc="stimulus label")), desc="label for kth input stimulus (e.g., Label1)", argstr="-stim_label %d %s...", requires=["stim_times"], @@ -252,9 +243,7 @@ class DeconvolveInputSpec(AFNICommandInputSpec): position=-2, ) glt_label = traits.List( - traits.Tuple( - traits.Int(desc="k-th general linear test"), Str(desc="GLT label") - ), + Tuple(traits.Int(desc="k-th general linear test"), Str(desc="GLT label")), desc="general linear test (i.e., contrast) labels", argstr="-glt_label %d %s...", requires=["gltsym"], @@ -265,7 +254,7 @@ class DeconvolveInputSpec(AFNICommandInputSpec): class DeconvolveOutputSpec(TraitedSpec): out_file = File(desc="output statistics file", exists=True) reml_script = File( - desc="automatical generated script to run 3dREMLfit", exists=True + desc="automatically generated script to run 3dREMLfit", exists=True ) x1D = File(desc="save out X matrix", exists=True) cbucket = File(desc="output regression coefficients file (if generated)") @@ -305,7 +294,7 @@ def _format_arg(self, name, trait_spec, value): if val.startswith("SYM: "): value[n] = val.lstrip("SYM: ") - return super(Deconvolve, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _parse_inputs(self, skip=None): if skip is None: @@ -317,7 +306,7 @@ def _parse_inputs(self, skip=None): if not isdefined(self.inputs.out_file): self.inputs.out_file = "Decon.nii" - return super(Deconvolve, self)._parse_inputs(skip) + return super()._parse_inputs(skip) def _list_outputs(self): outputs = self.output_spec().get() @@ -489,9 +478,7 @@ class RemlfitInputSpec(AFNICommandInputSpec): argstr="-nobout", ) gltsym = traits.List( - traits.Either( - traits.Tuple(File(exists=True), Str()), traits.Tuple(Str(), Str()) - ), + traits.Either(Tuple(File(exists=True), Str()), Tuple(Str(), Str())), desc="read a symbolic GLT from input file and associate it with a " "label. As in Deconvolve, you can also use the 'SYM:' method " "to provide the definition of the GLT directly as a string " @@ -528,7 +515,7 @@ class RemlfitInputSpec(AFNICommandInputSpec): "be included.", argstr="-Rglt %s", ) - fitts_file = File(desc="ouput dataset for REML fitted model", argstr="-Rfitts %s") + fitts_file = File(desc="output dataset for REML fitted model", argstr="-Rfitts %s") errts_file = File( desc="output dataset for REML residuals = data - fitted model", argstr="-Rerrts %s", @@ -570,23 +557,23 @@ class RemlfitInputSpec(AFNICommandInputSpec): class RemlfitOutputSpec(AFNICommandOutputSpec): out_file = File( - desc="dataset for beta + statistics from the REML estimation (if " "generated" + desc="dataset for beta + statistics from the REML estimation (if generated)" ) var_file = File(desc="dataset for REML variance parameters (if generated)") rbeta_file = File( - desc="dataset for beta weights from the REML estimation (if " "generated)" + desc="dataset for beta weights from the REML estimation (if generated)" ) rbeta_file = File( - desc="output dataset for beta weights from the REML estimation (if " "generated" + desc="output dataset for beta weights from the REML estimation (if generated)" ) glt_file = File( desc="output dataset for beta + statistics from the REML estimation, " "but ONLY for the GLTs added on the REMLfit command " "line itself via 'gltsym' (if generated)" ) - fitts_file = File(desc="ouput dataset for REML fitted model (if generated)") + fitts_file = File(desc="output dataset for REML fitted model (if generated)") errts_file = File( - desc="output dataset for REML residuals = data - fitted model (if " "generated" + desc="output dataset for REML residuals = data - fitted model (if generated)" ) wherr_file = File( desc="dataset for REML residual, whitened using the estimated " @@ -594,17 +581,17 @@ class RemlfitOutputSpec(AFNICommandOutputSpec): ) ovar = File(desc="dataset for OLSQ st.dev. parameter (if generated)") obeta = File( - desc="dataset for beta weights from the OLSQ estimation (if " "generated)" + desc="dataset for beta weights from the OLSQ estimation (if generated)" ) obuck = File( - desc="dataset for beta + statistics from the OLSQ estimation (if " "generated)" + desc="dataset for beta + statistics from the OLSQ estimation (if generated)" ) oglt = File( - desc="dataset for beta + statistics from 'gltsym' options (if " "generated" + desc="dataset for beta + statistics from 'gltsym' options (if generated)" ) ofitts = File(desc="dataset for OLSQ fitted model (if generated)") oerrts = File( - desc="dataset for OLSQ residuals = data - fitted model (if " "generated" + desc="dataset for OLSQ residuals = data - fitted model (if generated)" ) @@ -637,12 +624,12 @@ class Remlfit(AFNICommand): def _parse_inputs(self, skip=None): if skip is None: skip = [] - return super(Remlfit, self)._parse_inputs(skip) + return super()._parse_inputs(skip) def _list_outputs(self): outputs = self.output_spec().get() - for key in outputs.keys(): + for key in outputs: if isdefined(self.inputs.get()[key]): outputs[key] = os.path.abspath(self.inputs.get()[key]) @@ -651,13 +638,13 @@ def _list_outputs(self): class SynthesizeInputSpec(AFNICommandInputSpec): cbucket = File( - desc="Read the dataset output from " "3dDeconvolve via the '-cbucket' option.", + desc="Read the dataset output from 3dDeconvolve via the '-cbucket' option.", argstr="-cbucket %s", copyfile=False, mandatory=True, ) matrix = File( - desc="Read the matrix output from " "3dDeconvolve via the '-x1D' option.", + desc="Read the matrix output from 3dDeconvolve via the '-x1D' option.", argstr="-matrix %s", copyfile=False, mandatory=True, @@ -682,7 +669,7 @@ class SynthesizeInputSpec(AFNICommandInputSpec): argstr="-prefix %s", ) dry_run = traits.Bool( - desc="Don't compute the output, just " "check the inputs.", argstr="-dry" + desc="Don't compute the output, just check the inputs.", argstr="-dry" ) TR = traits.Float( desc="TR to set in the output. The default value of " @@ -728,7 +715,7 @@ class Synthesize(AFNICommand): def _list_outputs(self): outputs = self.output_spec().get() - for key in outputs.keys(): + for key in outputs: if isdefined(self.inputs.get()[key]): outputs[key] = os.path.abspath(self.inputs.get()[key]) diff --git a/nipype/interfaces/afni/preprocess.py b/nipype/interfaces/afni/preprocess.py index 1d53aac98c..b5e27ea53a 100644 --- a/nipype/interfaces/afni/preprocess.py +++ b/nipype/interfaces/afni/preprocess.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """AFNI preprocessing interfaces.""" @@ -12,6 +11,7 @@ CommandLine, TraitedSpec, traits, + Tuple, isdefined, File, InputMultiPath, @@ -37,8 +37,7 @@ class CentralityInputSpec(AFNICommandInputSpec): - """Common input spec class for all centrality-related commands - """ + """Common input spec class for all centrality-related commands""" mask = File(desc="mask file to mask input data", argstr="-mask %s", exists=True) thresh = traits.Float( @@ -182,7 +181,7 @@ class AlignEpiAnatPy(AFNIPythonCommand): >>> al_ea.cmdline # doctest: +ELLIPSIS 'python2 ...align_epi_anat.py -anat structural.nii -epi_base 0 -epi_strip 3dAutomask -epi \ functional.nii -save_skullstrip -suffix _al -tshift off -volreg off' - >>> res = allineate.run() # doctest: +SKIP + >>> res = al_ea.run() # doctest: +SKIP See Also -------- @@ -585,7 +584,7 @@ class Allineate(AFNICommand): output_spec = AllineateOutputSpec def _list_outputs(self): - outputs = super(Allineate, self)._list_outputs() + outputs = super()._list_outputs() if self.inputs.out_weight_file: outputs["out_weight_file"] = op.abspath(self.inputs.out_weight_file) @@ -623,7 +622,7 @@ class AutoTcorrelateInputSpec(AFNICommandInputSpec): copyfile=False, ) polort = traits.Int( - desc="Remove polynomical trend of order m or -1 for no detrending", + desc="Remove polynomial trend of order m or -1 for no detrending", argstr="-polort %d", ) eta2 = traits.Bool(desc="eta^2 similarity", argstr="-eta2") @@ -822,7 +821,7 @@ class AutoTLRCInputSpec(CommandLineInputSpec): class AutoTLRC(AFNICommand): - """A minmal wrapper for the AutoTLRC script + """A minimal wrapper for the AutoTLRC script The only option currently supported is no_ss. For complete details, see the `3dQwarp Documentation. `_ @@ -1134,7 +1133,6 @@ class ClipLevel(AFNICommandBase): output_spec = ClipLevelOutputSpec def aggregate_outputs(self, runtime=None, needed_outputs=None): - outputs = self._outputs() outfile = os.path.join(os.getcwd(), "stat_result.json") @@ -1142,7 +1140,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): if runtime is None: try: clip_val = load_json(outfile)["stat"] - except IOError: + except OSError: return self.run().outputs else: clip_val = [] @@ -1163,8 +1161,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): class DegreeCentralityInputSpec(CentralityInputSpec): - """DegreeCentrality inputspec - """ + """DegreeCentrality inputspec""" in_file = File( desc="input file to 3dDegreeCentrality", @@ -1183,8 +1180,7 @@ class DegreeCentralityInputSpec(CentralityInputSpec): class DegreeCentralityOutputSpec(AFNICommandOutputSpec): - """DegreeCentrality outputspec - """ + """DegreeCentrality outputspec""" oned_file = File( desc="The text output of the similarity matrix computed after " @@ -1221,7 +1217,7 @@ class DegreeCentrality(AFNICommand): # Re-define generated inputs def _list_outputs(self): # Update outputs dictionary if oned file is defined - outputs = super(DegreeCentrality, self)._list_outputs() + outputs = super()._list_outputs() if self.inputs.oned_file: outputs["oned_file"] = os.path.abspath(self.inputs.oned_file) @@ -1310,8 +1306,7 @@ class Detrend(AFNICommand): class ECMInputSpec(CentralityInputSpec): - """ECM inputspec - """ + """ECM inputspec""" in_file = File( desc="input file to 3dECM", @@ -1331,7 +1326,7 @@ class ECMInputSpec(CentralityInputSpec): ) fecm = traits.Bool( desc="Fast centrality method; substantial speed increase but cannot " - "accomodate thresholding; automatically selected if -thresh or " + "accommodate thresholding; automatically selected if -thresh or " "-sparsity are not set", argstr="-fecm", ) @@ -1559,7 +1554,7 @@ class Hist(AFNICommandBase): _redirect_x = True def __init__(self, **inputs): - super(Hist, self).__init__(**inputs) + super().__init__(**inputs) if not no_afni(): version = Info.version() @@ -1572,10 +1567,10 @@ def _parse_inputs(self, skip=None): if skip is None: skip = [] skip += ["out_show"] - return super(Hist, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _list_outputs(self): - outputs = super(Hist, self)._list_outputs() + outputs = super()._list_outputs() outputs["out_file"] += ".niml.hist" if not self.inputs.showhist: outputs["out_show"] = Undefined @@ -1583,8 +1578,7 @@ def _list_outputs(self): class LFCDInputSpec(CentralityInputSpec): - """LFCD inputspec - """ + """LFCD inputspec""" in_file = File( desc="input file to 3dLFCD", @@ -1839,12 +1833,10 @@ def _parse_inputs(self, skip=None): if not self.inputs.save_outliers: skip += ["outliers_file"] - return super(OutlierCount, self)._parse_inputs(skip) + return super()._parse_inputs(skip) def _run_interface(self, runtime, correct_return_codes=(0,)): - runtime = super(OutlierCount, self)._run_interface( - runtime, correct_return_codes - ) + runtime = super()._run_interface(runtime, correct_return_codes) # Read from runtime.stdout or runtime.merged with open(op.abspath(self.inputs.out_file), "w") as outfh: @@ -2112,7 +2104,7 @@ def _format_arg(self, name, trait_spec, value): } if name == "stat": value = [_stat_dict[v] for v in value] - return super(ROIStats, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) class RetroicorInputSpec(AFNICommandInputSpec): @@ -2212,7 +2204,7 @@ def _format_arg(self, name, trait_spec, value): if name == "in_file": if not isdefined(self.inputs.card) and not isdefined(self.inputs.resp): return None - return super(Retroicor, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) class SegInputSpec(CommandLineInputSpec): @@ -2300,7 +2292,6 @@ class Seg(AFNICommandBase): output_spec = AFNICommandOutputSpec def aggregate_outputs(self, runtime=None, needed_outputs=None): - import glob outputs = self._outputs() @@ -2358,7 +2349,7 @@ class SkullStrip(AFNICommand): output_spec = AFNICommandOutputSpec def __init__(self, **inputs): - super(SkullStrip, self).__init__(**inputs) + super().__init__(**inputs) if not no_afni(): v = Info.version() @@ -2449,7 +2440,7 @@ class TCorrMapInputSpec(AFNICommandInputSpec): mask = File(exists=True, argstr="-mask %s") automask = traits.Bool(argstr="-automask") polort = traits.Int(argstr="-polort %d") - bandpass = traits.Tuple((traits.Float(), traits.Float()), argstr="-bpass %f %f") + bandpass = Tuple((traits.Float(), traits.Float()), argstr="-bpass %f %f") regress_out_timeseries = File(exists=True, argstr="-ort %s") blur_fwhm = traits.Float(argstr="-Gblur %f") seeds_width = traits.Float(argstr="-Mseed %f", xor=("seeds")) @@ -2553,7 +2544,208 @@ def _format_arg(self, name, trait_spec, value): elif name == "histogram": return trait_spec.argstr % (self.inputs.histogram_bin_numbers, value) else: - return super(TCorrMap, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) + + +class NetCorrInputSpec(AFNICommandInputSpec): + in_file = File( + desc="input time series file (4D data set)", + exists=True, + argstr="-inset %s", + mandatory=True, + ) + in_rois = File( + desc="input set of ROIs, each labelled with distinct integers", + exists=True, + argstr="-in_rois %s", + mandatory=True, + ) + mask = File( + desc="can include a whole brain mask within which to " + "calculate correlation. Otherwise, data should be " + "masked already", + exists=True, + argstr="-mask %s", + ) + weight_ts = File( + desc="input a 1D file WTS of weights that will be applied " + "multiplicatively to each ROI's average time series. " + "WTS can be a column- or row-file of values, but it " + "must have the same length as the input time series " + "volume. " + "If the initial average time series was A[n] for " + "n=0,..,(N-1) time points, then applying a set of " + "weights W[n] of the same length from WTS would " + "produce a new time series: B[n] = A[n] * W[n]", + exists=True, + argstr="-weight_ts %s", + ) + fish_z = traits.Bool( + desc="switch to also output a matrix of Fisher Z-transform " + "values for the corr coefs (r): " + "Z = atanh(r) , " + "(with Z=4 being output along matrix diagonals where " + "r=1, as the r-to-Z conversion is ceilinged at " + "Z = atanh(r=0.999329) = 4, which is still *quite* a " + "high Pearson-r value", + argstr="-fish_z", + ) + part_corr = traits.Bool( + desc="output the partial correlation matrix", argstr="-part_corr" + ) + ts_out = traits.Bool( + desc="switch to output the mean time series of the ROIs that " + "have been used to generate the correlation matrices. " + "Output filenames mirror those of the correlation " + "matrix files, with a '.netts' postfix", + argstr="-ts_out", + ) + ts_label = traits.Bool( + desc="additional switch when using '-ts_out'. Using this " + "option will insert the integer ROI label at the start " + "of each line of the *.netts file created. Thus, for " + "a time series of length N, each line will have N+1 " + "numbers, where the first is the integer ROI label " + "and the subsequent N are scientific notation values", + argstr="-ts_label", + ) + ts_indiv = traits.Bool( + desc="switch to create a directory for each network that " + "contains the average time series for each ROI in " + "individual files (each file has one line). " + "The directories are labelled PREFIX_000_INDIV/, " + "PREFIX_001_INDIV/, etc. (one per network). Within each " + "directory, the files are labelled ROI_001.netts, " + "ROI_002.netts, etc., with the numbers given by the " + "actual ROI integer labels", + argstr="-ts_indiv", + ) + ts_wb_corr = traits.Bool( + desc="switch to create a set of whole brain correlation maps. " + "Performs whole brain correlation for each " + "ROI's average time series; this will automatically " + "create a directory for each network that contains the " + "set of whole brain correlation maps (Pearson 'r's). " + "The directories are labelled as above for '-ts_indiv' " + "Within each directory, the files are labelled " + "WB_CORR_ROI_001+orig, WB_CORR_ROI_002+orig, etc., with " + "the numbers given by the actual ROI integer labels", + argstr="-ts_wb_corr", + ) + ts_wb_Z = traits.Bool( + desc="same as above in '-ts_wb_corr', except that the maps " + "have been Fisher transformed to Z-scores the relation: " + "Z=atanh(r). " + "To avoid infinities in the transform, Pearson values " + "are effectively capped at |r| = 0.999329 (where |Z| = 4.0). " + "Files are labelled WB_Z_ROI_001+orig, etc", + argstr="-ts_wb_Z", + ) + ts_wb_strlabel = traits.Bool( + desc="by default, '-ts_wb_{corr,Z}' output files are named " + "using the int number of a given ROI, such as: " + "WB_Z_ROI_001+orig. " + "With this option, one can replace the int (such as '001') " + "with the string label (such as 'L-thalamus') " + "*if* one has a labeltable attached to the file", + argstr="-ts_wb_strlabel", + ) + nifti = traits.Bool( + desc="output any correlation map files as NIFTI files " + "(default is BRIK/HEAD). Only useful if using " + "'-ts_wb_corr' and/or '-ts_wb_Z'", + argstr="-nifti", + ) + output_mask_nonnull = traits.Bool( + desc="internally, this program checks for where there are " + "nonnull time series, because we don't like those, in " + "general. With this flag, the user can output the " + "determined mask of non-null time series.", + argstr="-output_mask_nonnull", + ) + push_thru_many_zeros = traits.Bool( + desc="by default, this program will grind to a halt and " + "refuse to calculate if any ROI contains >10 percent " + "of voxels with null times series (i.e., each point is " + "0), as of April, 2017. This is because it seems most " + "likely that hidden badness is responsible. However, " + "if the user still wants to carry on the calculation " + "anyways, then this option will allow one to push on " + "through. However, if any ROI *only* has null time " + "series, then the program will not calculate and the " + "user will really, really, really need to address their masking", + argstr="-push_thru_many_zeros", + ) + ignore_LT = traits.Bool( + desc="switch to ignore any label table labels in the " + "'-in_rois' file, if there are any labels attached", + argstr="-ignore_LT", + ) + out_file = File( + desc="output file name part", + name_template="%s_netcorr", + argstr="-prefix %s", + position=1, + name_source="in_file", + ) + + +class NetCorrOutputSpec(TraitedSpec): + out_corr_matrix = File( + desc="output correlation matrix between ROIs written to a text file with .netcc suffix" + ) + out_corr_maps = traits.List( + File(), desc="output correlation maps in Pearson and/or Z-scores" + ) + + +class NetCorr(AFNICommand): + """Calculate correlation matrix of a set of ROIs (using mean time series of + each). Several networks may be analyzed simultaneously, one per brick. + + For complete details, see the `3dNetCorr Documentation + `_. + + Examples + -------- + >>> from nipype.interfaces import afni + >>> ncorr = afni.NetCorr() + >>> ncorr.inputs.in_file = 'functional.nii' + >>> ncorr.inputs.mask = 'mask.nii' + >>> ncorr.inputs.in_rois = 'maps.nii' + >>> ncorr.inputs.ts_wb_corr = True + >>> ncorr.inputs.ts_wb_Z = True + >>> ncorr.inputs.fish_z = True + >>> ncorr.inputs.out_file = 'sub0.tp1.ncorr' + >>> ncorr.cmdline + '3dNetCorr -prefix sub0.tp1.ncorr -fish_z -inset functional.nii -in_rois maps.nii -mask mask.nii -ts_wb_Z -ts_wb_corr' + >>> res = ncorr.run() # doctest: +SKIP + + """ + + _cmd = "3dNetCorr" + input_spec = NetCorrInputSpec + output_spec = NetCorrOutputSpec + + def _list_outputs(self): + import glob + + outputs = self.output_spec().get() + + if not isdefined(self.inputs.out_file): + prefix = self._gen_fname(self.inputs.in_file, suffix="_netcorr") + else: + prefix = self.inputs.out_file + + # All outputs should be in the same directory as the prefix + odir = os.path.dirname(os.path.abspath(prefix)) + outputs["out_corr_matrix"] = glob.glob(os.path.join(odir, "*.netcc"))[0] + + if self.inputs.ts_wb_corr or self.inputs.ts_wb_Z: + corrdir = os.path.join(odir, prefix + "_000_INDIV") + outputs["out_corr_maps"] = glob.glob(os.path.join(corrdir, "*.nii.gz")) + + return outputs class TCorrelateInputSpec(AFNICommandInputSpec): @@ -2583,7 +2775,7 @@ class TCorrelateInputSpec(AFNICommandInputSpec): desc="Correlation is the normal Pearson correlation coefficient", argstr="-pearson", ) - polort = traits.Int(desc="Remove polynomical trend of order m", argstr="-polort %d") + polort = traits.Int(desc="Remove polynomial trend of order m", argstr="-polort %d") class TCorrelate(AFNICommand): @@ -2737,7 +2929,7 @@ class TProjectInputSpec(AFNICommandInputSpec): the output dataset: * mode = ZERO -- put zero values in their place; - output datset is same length as input + output dataset is same length as input * mode = KILL -- remove those time points; output dataset is shorter than input * mode = NTRP -- censored values are replaced by interpolated @@ -2820,13 +3012,13 @@ class TProjectInputSpec(AFNICommandInputSpec): """, ) - bandpass = traits.Tuple( + bandpass = Tuple( traits.Float, traits.Float, desc="""Remove all frequencies EXCEPT those in the range""", argstr="-bandpass %g %g", ) - stopband = traits.Tuple( + stopband = Tuple( traits.Float, traits.Float, desc="""Remove all frequencies in the range""", @@ -2877,7 +3069,7 @@ class TProject(AFNICommand): as ``-passband``. In this way, you can bandpass time-censored data, and at the same time, remove other time series of no interest (e.g., physiological estimates, motion parameters). - Shifts voxel time series from input so that seperate slices are aligned to + Shifts voxel time series from input so that separate slices are aligned to the same temporal origin. Examples @@ -2992,7 +3184,7 @@ class TShiftOutputSpec(AFNICommandOutputSpec): class TShift(AFNICommand): - """Shifts voxel time series from input so that seperate slices are aligned + """Shifts voxel time series from input so that separate slices are aligned to the same temporal origin. For complete details, see the `3dTshift Documentation. @@ -3093,7 +3285,7 @@ def _format_arg(self, name, trait_spec, value): ) elif name == "slice_timing" and isinstance(value, list): value = self._write_slice_timing() - return super(TShift, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _write_slice_timing(self): slice_timing = list(self.inputs.slice_timing) @@ -3106,7 +3298,7 @@ def _write_slice_timing(self): return fname def _list_outputs(self): - outputs = super(TShift, self)._list_outputs() + outputs = super()._list_outputs() if isdefined(self.inputs.slice_timing): if isinstance(self.inputs.slice_timing, list): outputs["timing_file"] = os.path.abspath("slice_timing.1D") @@ -3203,7 +3395,7 @@ class VolregInputSpec(AFNICommandInputSpec): copyfile=False, ) in_weight_volume = traits.Either( - traits.Tuple(File(exists=True), traits.Int), + Tuple(File(exists=True), traits.Int), File(exists=True), desc="weights for each voxel specified by a file with an " "optional volume number (defaults to 0)", @@ -3313,7 +3505,7 @@ class Volreg(AFNICommand): def _format_arg(self, name, trait_spec, value): if name == "in_weight_volume" and not isinstance(value, tuple): value = (value, 0) - return super(Volreg, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) class WarpInputSpec(AFNICommandInputSpec): @@ -3409,17 +3601,17 @@ class Warp(AFNICommand): output_spec = WarpOutputSpec def _run_interface(self, runtime, correct_return_codes=(0,)): - runtime = super(Warp, self)._run_interface(runtime, correct_return_codes) + runtime = super()._run_interface(runtime, correct_return_codes) if self.inputs.save_warp: import numpy as np warp_file = self._list_outputs()["warp_file"] - np.savetxt(warp_file, [runtime.stdout], fmt=str("%s")) + np.savetxt(warp_file, [runtime.stdout], fmt="%s") return runtime def _list_outputs(self): - outputs = super(Warp, self)._list_outputs() + outputs = super()._list_outputs() if self.inputs.save_warp: outputs["warp_file"] = fname_presuffix( outputs["out_file"], suffix="_transform.mat", use_ext=False @@ -3462,7 +3654,7 @@ class QwarpInputSpec(AFNICommandInputSpec): with 3dNwarpApply and 3dNwarpCat, for example. * To be clear, this is the warp from source dataset coordinates to base dataset coordinates, where the - values at each base grid point are the xyz displacments + values at each base grid point are the xyz displacements needed to move that grid point's xyz values to the corresponding xyz values in the source dataset: base( (x,y,z) + WARP(x,y,z) ) matches source(x,y,z) @@ -3630,8 +3822,8 @@ class QwarpInputSpec(AFNICommandInputSpec): maxlen=5, xor=["wmask"], ) - traits.Tuple((traits.Float(), traits.Float()), argstr="-bpass %f %f") - wmask = traits.Tuple( + bandpass = Tuple((traits.Float(), traits.Float()), argstr="-bpass %f %f") + wmask = Tuple( (File(exists=True), traits.Float()), desc="""\ Similar to '-wball', but here, you provide a dataset 'ws' @@ -3838,7 +4030,7 @@ class QwarpInputSpec(AFNICommandInputSpec): The goal is greater speed, and it seems to help this" positively piggish program to be more expeditious." * However, accuracy is somewhat lower with '-duplo'," - for reasons that currenly elude Zhark; for this reason," + for reasons that currently elude Zhark; for this reason," the Emperor does not usually use '-duplo'. """, @@ -4029,21 +4221,21 @@ class QwarpInputSpec(AFNICommandInputSpec): ) hel = traits.Bool( desc="Hellinger distance: a matching function for the adventurous" - "This option has NOT be extensively tested for usefullness" + "This option has NOT be extensively tested for usefulness" "and should be considered experimental at this infundibulum.", argstr="-hel", xor=["nmi", "mi", "lpc", "lpa", "pear"], ) mi = traits.Bool( desc="Mutual Information: a matching function for the adventurous" - "This option has NOT be extensively tested for usefullness" + "This option has NOT be extensively tested for usefulness" "and should be considered experimental at this infundibulum.", argstr="-mi", xor=["mi", "hel", "lpc", "lpa", "pear"], ) nmi = traits.Bool( desc="Normalized Mutual Information: a matching function for the adventurous" - "This option has NOT been extensively tested for usefullness" + "This option has NOT been extensively tested for usefulness" "and should be considered experimental at this infundibulum.", argstr="-nmi", xor=["nmi", "hel", "lpc", "lpa", "pear"], @@ -4173,7 +4365,7 @@ class Qwarp(AFNICommand): def _format_arg(self, name, trait_spec, value): if name == "allineate_opts": return trait_spec.argstr % ("'" + value + "'") - return super(Qwarp, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/afni/svm.py b/nipype/interfaces/afni/svm.py index 13c83af51c..e7bd3c520a 100644 --- a/nipype/interfaces/afni/svm.py +++ b/nipype/interfaces/afni/svm.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """AFNI's svm interfaces.""" @@ -107,7 +106,7 @@ class SVMTrain(AFNICommand): _additional_metadata = ["suffix"] def _format_arg(self, name, trait_spec, value): - return super(SVMTrain, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) class SVMTestInputSpec(AFNICommandInputSpec): diff --git a/nipype/interfaces/afni/tests/__init__.py b/nipype/interfaces/afni/tests/__init__.py index 99fb243f19..349937997e 100644 --- a/nipype/interfaces/afni/tests/__init__.py +++ b/nipype/interfaces/afni/tests/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/interfaces/afni/tests/test_auto_ABoverlap.py b/nipype/interfaces/afni/tests/test_auto_ABoverlap.py index 63e2e8d652..501f5331b7 100644 --- a/nipype/interfaces/afni/tests/test_auto_ABoverlap.py +++ b/nipype/interfaces/afni/tests/test_auto_ABoverlap.py @@ -4,20 +4,46 @@ def test_ABoverlap_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file_a=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-3, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-3, ), in_file_b=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-2, + ), + no_automask=dict( + argstr="-no_automask", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr=" |& tee %s", + extensions=None, + position=-1, ), - no_automask=dict(argstr="-no_automask",), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr=" |& tee %s", extensions=None, position=-1,), outputtype=dict(), - quiet=dict(argstr="-quiet",), - verb=dict(argstr="-verb",), + quiet=dict( + argstr="-quiet", + ), + verb=dict( + argstr="-verb", + ), ) inputs = ABoverlap.input_spec() @@ -27,7 +53,11 @@ def test_ABoverlap_inputs(): def test_ABoverlap_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ABoverlap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_AFNICommand.py b/nipype/interfaces/afni/tests/test_auto_AFNICommand.py index 0764b4947b..941667f49f 100644 --- a/nipype/interfaces/afni/tests/test_auto_AFNICommand.py +++ b/nipype/interfaces/afni/tests/test_auto_AFNICommand.py @@ -4,9 +4,17 @@ def test_AFNICommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, diff --git a/nipype/interfaces/afni/tests/test_auto_AFNICommandBase.py b/nipype/interfaces/afni/tests/test_auto_AFNICommandBase.py index 58de0b425a..de23f6c05b 100644 --- a/nipype/interfaces/afni/tests/test_auto_AFNICommandBase.py +++ b/nipype/interfaces/afni/tests/test_auto_AFNICommandBase.py @@ -4,7 +4,13 @@ def test_AFNICommandBase_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = AFNICommandBase.input_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_AFNIPythonCommand.py b/nipype/interfaces/afni/tests/test_auto_AFNIPythonCommand.py index e437676286..fd4682947b 100644 --- a/nipype/interfaces/afni/tests/test_auto_AFNIPythonCommand.py +++ b/nipype/interfaces/afni/tests/test_auto_AFNIPythonCommand.py @@ -4,9 +4,17 @@ def test_AFNIPythonCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, diff --git a/nipype/interfaces/afni/tests/test_auto_AFNItoNIFTI.py b/nipype/interfaces/afni/tests/test_auto_AFNItoNIFTI.py index 19012ff364..6983e839fb 100644 --- a/nipype/interfaces/afni/tests/test_auto_AFNItoNIFTI.py +++ b/nipype/interfaces/afni/tests/test_auto_AFNItoNIFTI.py @@ -4,15 +4,35 @@ def test_AFNItoNIFTI_inputs(): input_map = dict( - args=dict(argstr="%s",), - denote=dict(argstr="-denote",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + denote=dict( + argstr="-denote", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + newid=dict( + argstr="-newid", + xor=["oldid"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oldid=dict( + argstr="-oldid", + xor=["newid"], ), - newid=dict(argstr="-newid", xor=["oldid"],), - num_threads=dict(nohash=True, usedefault=True,), - oldid=dict(argstr="-oldid", xor=["newid"],), out_file=dict( argstr="-prefix %s", extensions=None, @@ -21,7 +41,9 @@ def test_AFNItoNIFTI_inputs(): name_template="%s.nii", ), outputtype=dict(), - pure=dict(argstr="-pure",), + pure=dict( + argstr="-pure", + ), ) inputs = AFNItoNIFTI.input_spec() @@ -31,7 +53,11 @@ def test_AFNItoNIFTI_inputs(): def test_AFNItoNIFTI_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AFNItoNIFTI.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_AlignEpiAnatPy.py b/nipype/interfaces/afni/tests/test_auto_AlignEpiAnatPy.py index e2b8f5a3c9..a3b376f55b 100644 --- a/nipype/interfaces/afni/tests/test_auto_AlignEpiAnatPy.py +++ b/nipype/interfaces/afni/tests/test_auto_AlignEpiAnatPy.py @@ -4,22 +4,57 @@ def test_AlignEpiAnatPy_inputs(): input_map = dict( - anat=dict(argstr="-anat %s", copyfile=False, extensions=None, mandatory=True,), - anat2epi=dict(argstr="-anat2epi",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - epi2anat=dict(argstr="-epi2anat",), - epi_base=dict(argstr="-epi_base %s", mandatory=True,), - epi_strip=dict(argstr="-epi_strip %s",), + anat=dict( + argstr="-anat %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + anat2epi=dict( + argstr="-anat2epi", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi2anat=dict( + argstr="-epi2anat", + ), + epi_base=dict( + argstr="-epi_base %s", + mandatory=True, + ), + epi_strip=dict( + argstr="-epi_strip %s", + ), in_file=dict( - argstr="-epi %s", copyfile=False, extensions=None, mandatory=True, + argstr="-epi %s", + copyfile=False, + extensions=None, + mandatory=True, ), outputtype=dict(), - py27_path=dict(usedefault=True,), - save_skullstrip=dict(argstr="-save_skullstrip",), - suffix=dict(argstr="-suffix %s", usedefault=True,), - tshift=dict(argstr="-tshift %s", usedefault=True,), - volreg=dict(argstr="-volreg %s", usedefault=True,), + py27_path=dict( + usedefault=True, + ), + save_skullstrip=dict( + argstr="-save_skullstrip", + ), + suffix=dict( + argstr="-suffix %s", + usedefault=True, + ), + tshift=dict( + argstr="-tshift %s", + usedefault=True, + ), + volreg=dict( + argstr="-volreg %s", + usedefault=True, + ), ) inputs = AlignEpiAnatPy.input_spec() @@ -30,16 +65,36 @@ def test_AlignEpiAnatPy_inputs(): def test_AlignEpiAnatPy_outputs(): output_map = dict( - anat_al_mat=dict(extensions=None,), - anat_al_orig=dict(extensions=None,), - epi_al_mat=dict(extensions=None,), - epi_al_orig=dict(extensions=None,), - epi_al_tlrc_mat=dict(extensions=None,), - epi_reg_al_mat=dict(extensions=None,), - epi_tlrc_al=dict(extensions=None,), - epi_vr_al_mat=dict(extensions=None,), - epi_vr_motion=dict(extensions=None,), - skullstrip=dict(extensions=None,), + anat_al_mat=dict( + extensions=None, + ), + anat_al_orig=dict( + extensions=None, + ), + epi_al_mat=dict( + extensions=None, + ), + epi_al_orig=dict( + extensions=None, + ), + epi_al_tlrc_mat=dict( + extensions=None, + ), + epi_reg_al_mat=dict( + extensions=None, + ), + epi_tlrc_al=dict( + extensions=None, + ), + epi_vr_al_mat=dict( + extensions=None, + ), + epi_vr_motion=dict( + extensions=None, + ), + skullstrip=dict( + extensions=None, + ), ) outputs = AlignEpiAnatPy.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Allineate.py b/nipype/interfaces/afni/tests/test_auto_Allineate.py index 356e7d52a0..afe6c3f24d 100644 --- a/nipype/interfaces/afni/tests/test_auto_Allineate.py +++ b/nipype/interfaces/afni/tests/test_auto_Allineate.py @@ -10,20 +10,48 @@ def test_Allineate_inputs(): position=-1, xor=["out_file", "out_matrix", "out_param_file", "out_weight_file"], ), - args=dict(argstr="%s",), - autobox=dict(argstr="-autobox",), - automask=dict(argstr="-automask+%d",), - autoweight=dict(argstr="-autoweight%s",), - center_of_mass=dict(argstr="-cmass%s",), - check=dict(argstr="-check %s",), - convergence=dict(argstr="-conv %f",), - cost=dict(argstr="-cost %s",), - environ=dict(nohash=True, usedefault=True,), - epi=dict(argstr="-EPI",), - final_interpolation=dict(argstr="-final %s",), - fine_blur=dict(argstr="-fineblur %f",), + args=dict( + argstr="%s", + ), + autobox=dict( + argstr="-autobox", + ), + automask=dict( + argstr="-automask+%d", + ), + autoweight=dict( + argstr="-autoweight%s", + ), + center_of_mass=dict( + argstr="-cmass%s", + ), + check=dict( + argstr="-check %s", + ), + convergence=dict( + argstr="-conv %f", + ), + cost=dict( + argstr="-cost %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi=dict( + argstr="-EPI", + ), + final_interpolation=dict( + argstr="-final %s", + ), + fine_blur=dict( + argstr="-fineblur %f", + ), in_file=dict( - argstr="-source %s", copyfile=False, extensions=None, mandatory=True, + argstr="-source %s", + copyfile=False, + extensions=None, + mandatory=True, ), in_matrix=dict( argstr="-1Dmatrix_apply %s", @@ -32,23 +60,57 @@ def test_Allineate_inputs(): xor=["out_matrix"], ), in_param_file=dict( - argstr="-1Dparam_apply %s", extensions=None, xor=["out_param_file"], - ), - interpolation=dict(argstr="-interp %s",), - master=dict(argstr="-master %s", extensions=None,), - maxrot=dict(argstr="-maxrot %f",), - maxscl=dict(argstr="-maxscl %f",), - maxshf=dict(argstr="-maxshf %f",), - maxshr=dict(argstr="-maxshr %f",), - newgrid=dict(argstr="-newgrid %f",), - nmatch=dict(argstr="-nmatch %d",), - no_pad=dict(argstr="-nopad",), - nomask=dict(argstr="-nomask",), - num_threads=dict(nohash=True, usedefault=True,), - nwarp=dict(argstr="-nwarp %s",), - nwarp_fixdep=dict(argstr="-nwarp_fixdep%s...",), - nwarp_fixmot=dict(argstr="-nwarp_fixmot%s...",), - one_pass=dict(argstr="-onepass",), + argstr="-1Dparam_apply %s", + extensions=None, + xor=["out_param_file"], + ), + interpolation=dict( + argstr="-interp %s", + ), + master=dict( + argstr="-master %s", + extensions=None, + ), + maxrot=dict( + argstr="-maxrot %f", + ), + maxscl=dict( + argstr="-maxscl %f", + ), + maxshf=dict( + argstr="-maxshf %f", + ), + maxshr=dict( + argstr="-maxshr %f", + ), + newgrid=dict( + argstr="-newgrid %f", + ), + nmatch=dict( + argstr="-nmatch %d", + ), + no_pad=dict( + argstr="-nopad", + ), + nomask=dict( + argstr="-nomask", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + nwarp=dict( + argstr="-nwarp %s", + ), + nwarp_fixdep=dict( + argstr="-nwarp_fixdep%s...", + ), + nwarp_fixmot=dict( + argstr="-nwarp_fixmot%s...", + ), + one_pass=dict( + argstr="-onepass", + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -58,35 +120,80 @@ def test_Allineate_inputs(): xor=["allcostx"], ), out_matrix=dict( - argstr="-1Dmatrix_save %s", extensions=None, xor=["in_matrix", "allcostx"], + argstr="-1Dmatrix_save %s", + extensions=None, + xor=["in_matrix", "allcostx"], ), out_param_file=dict( argstr="-1Dparam_save %s", extensions=None, xor=["in_param_file", "allcostx"], ), - out_weight_file=dict(argstr="-wtprefix %s", extensions=None, xor=["allcostx"],), + out_weight_file=dict( + argstr="-wtprefix %s", + extensions=None, + xor=["allcostx"], + ), outputtype=dict(), - overwrite=dict(argstr="-overwrite",), - quiet=dict(argstr="-quiet",), - reference=dict(argstr="-base %s", extensions=None,), - replacebase=dict(argstr="-replacebase",), - replacemeth=dict(argstr="-replacemeth %s",), - source_automask=dict(argstr="-source_automask+%d",), - source_mask=dict(argstr="-source_mask %s", extensions=None,), - two_best=dict(argstr="-twobest %d",), - two_blur=dict(argstr="-twoblur %f",), - two_first=dict(argstr="-twofirst",), - two_pass=dict(argstr="-twopass",), - usetemp=dict(argstr="-usetemp",), - verbose=dict(argstr="-verb",), - warp_type=dict(argstr="-warp %s",), - warpfreeze=dict(argstr="-warpfreeze",), - weight=dict(argstr="-weight %s",), + overwrite=dict( + argstr="-overwrite", + ), + quiet=dict( + argstr="-quiet", + ), + reference=dict( + argstr="-base %s", + extensions=None, + ), + replacebase=dict( + argstr="-replacebase", + ), + replacemeth=dict( + argstr="-replacemeth %s", + ), + source_automask=dict( + argstr="-source_automask+%d", + ), + source_mask=dict( + argstr="-source_mask %s", + extensions=None, + ), + two_best=dict( + argstr="-twobest %d", + ), + two_blur=dict( + argstr="-twoblur %f", + ), + two_first=dict( + argstr="-twofirst", + ), + two_pass=dict( + argstr="-twopass", + ), + usetemp=dict( + argstr="-usetemp", + ), + verbose=dict( + argstr="-verb", + ), + warp_type=dict( + argstr="-warp %s", + ), + warpfreeze=dict( + argstr="-warpfreeze", + ), + weight=dict( + argstr="-weight %s", + ), weight_file=dict( - argstr="-weight %s", deprecated="1.0.0", extensions=None, new_name="weight", + argstr="-weight %s", + deprecated="1.0.0", + extensions=None, + new_name="weight", + ), + zclip=dict( + argstr="-zclip", ), - zclip=dict(argstr="-zclip",), ) inputs = Allineate.input_spec() @@ -97,11 +204,21 @@ def test_Allineate_inputs(): def test_Allineate_outputs(): output_map = dict( - allcostx=dict(extensions=None,), - out_file=dict(extensions=None,), - out_matrix=dict(extensions=None,), - out_param_file=dict(extensions=None,), - out_weight_file=dict(extensions=None,), + allcostx=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + out_matrix=dict( + extensions=None, + ), + out_param_file=dict( + extensions=None, + ), + out_weight_file=dict( + extensions=None, + ), ) outputs = Allineate.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_AutoTLRC.py b/nipype/interfaces/afni/tests/test_auto_AutoTLRC.py index a2b13596e6..eebfc73b6b 100644 --- a/nipype/interfaces/afni/tests/test_auto_AutoTLRC.py +++ b/nipype/interfaces/afni/tests/test_auto_AutoTLRC.py @@ -4,13 +4,26 @@ def test_AutoTLRC_inputs(): input_map = dict( - args=dict(argstr="%s",), - base=dict(argstr="-base %s", mandatory=True,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + base=dict( + argstr="-base %s", + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="-input %s", copyfile=False, extensions=None, mandatory=True, + argstr="-input %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + no_ss=dict( + argstr="-no_ss", ), - no_ss=dict(argstr="-no_ss",), outputtype=dict(), ) inputs = AutoTLRC.input_spec() @@ -21,7 +34,11 @@ def test_AutoTLRC_inputs(): def test_AutoTLRC_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AutoTLRC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py b/nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py index 344ec503ce..14c59cba0c 100644 --- a/nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py +++ b/nipype/interfaces/afni/tests/test_auto_AutoTcorrelate.py @@ -4,18 +4,40 @@ def test_AutoTcorrelate_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - eta2=dict(argstr="-eta2",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + eta2=dict( + argstr="-eta2", + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + mask_only_targets=dict( + argstr="-mask_only_targets", + xor=["mask_source"], ), - mask=dict(argstr="-mask %s", extensions=None,), - mask_only_targets=dict(argstr="-mask_only_targets", xor=["mask_source"],), mask_source=dict( - argstr="-mask_source %s", extensions=None, xor=["mask_only_targets"], + argstr="-mask_source %s", + extensions=None, + xor=["mask_only_targets"], + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -23,7 +45,9 @@ def test_AutoTcorrelate_inputs(): name_template="%s_similarity_matrix.1D", ), outputtype=dict(), - polort=dict(argstr="-polort %d",), + polort=dict( + argstr="-polort %d", + ), ) inputs = AutoTcorrelate.input_spec() @@ -33,7 +57,11 @@ def test_AutoTcorrelate_inputs(): def test_AutoTcorrelate_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AutoTcorrelate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Autobox.py b/nipype/interfaces/afni/tests/test_auto_Autobox.py index 91eca4d811..8a13b14742 100644 --- a/nipype/interfaces/afni/tests/test_auto_Autobox.py +++ b/nipype/interfaces/afni/tests/test_auto_Autobox.py @@ -4,13 +4,26 @@ def test_Autobox_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="-input %s", copyfile=False, extensions=None, mandatory=True, + argstr="-input %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + no_clustering=dict( + argstr="-noclust", + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - no_clustering=dict(argstr="-noclust",), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -18,7 +31,9 @@ def test_Autobox_inputs(): name_template="%s_autobox", ), outputtype=dict(), - padding=dict(argstr="-npad %d",), + padding=dict( + argstr="-npad %d", + ), ) inputs = Autobox.input_spec() @@ -29,7 +44,9 @@ def test_Autobox_inputs(): def test_Autobox_outputs(): output_map = dict( - out_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), x_max=dict(), x_min=dict(), y_max=dict(), diff --git a/nipype/interfaces/afni/tests/test_auto_Automask.py b/nipype/interfaces/afni/tests/test_auto_Automask.py index 27f8040695..1c2a3c4ee9 100644 --- a/nipype/interfaces/afni/tests/test_auto_Automask.py +++ b/nipype/interfaces/afni/tests/test_auto_Automask.py @@ -4,21 +4,39 @@ def test_Automask_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), brain_file=dict( argstr="-apply_prefix %s", extensions=None, name_source="in_file", name_template="%s_masked", ), - clfrac=dict(argstr="-clfrac %s",), - dilate=dict(argstr="-dilate %s",), - environ=dict(nohash=True, usedefault=True,), - erode=dict(argstr="-erode %s",), + clfrac=dict( + argstr="-clfrac %s", + ), + dilate=dict( + argstr="-dilate %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + erode=dict( + argstr="-erode %s", + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -36,7 +54,12 @@ def test_Automask_inputs(): def test_Automask_outputs(): output_map = dict( - brain_file=dict(extensions=None,), out_file=dict(extensions=None,), + brain_file=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = Automask.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Axialize.py b/nipype/interfaces/afni/tests/test_auto_Axialize.py index 2c4fafbb5b..bac640d601 100644 --- a/nipype/interfaces/afni/tests/test_auto_Axialize.py +++ b/nipype/interfaces/afni/tests/test_auto_Axialize.py @@ -4,15 +4,35 @@ def test_Axialize_inputs(): input_map = dict( - args=dict(argstr="%s",), - axial=dict(argstr="-axial", xor=["coronal", "sagittal"],), - coronal=dict(argstr="-coronal", xor=["sagittal", "axial"],), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + axial=dict( + argstr="-axial", + xor=["coronal", "sagittal"], + ), + coronal=dict( + argstr="-coronal", + xor=["sagittal", "axial"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + orientation=dict( + argstr="-orient %s", ), - num_threads=dict(nohash=True, usedefault=True,), - orientation=dict(argstr="-orient %s",), out_file=dict( argstr="-prefix %s", extensions=None, @@ -20,8 +40,13 @@ def test_Axialize_inputs(): name_template="%s_axialize", ), outputtype=dict(), - sagittal=dict(argstr="-sagittal", xor=["coronal", "axial"],), - verb=dict(argstr="-verb",), + sagittal=dict( + argstr="-sagittal", + xor=["coronal", "axial"], + ), + verb=dict( + argstr="-verb", + ), ) inputs = Axialize.input_spec() @@ -31,7 +56,11 @@ def test_Axialize_inputs(): def test_Axialize_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Axialize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Bandpass.py b/nipype/interfaces/afni/tests/test_auto_Bandpass.py index b17a8433ca..8ae9966240 100644 --- a/nipype/interfaces/afni/tests/test_auto_Bandpass.py +++ b/nipype/interfaces/afni/tests/test_auto_Bandpass.py @@ -4,25 +4,70 @@ def test_Bandpass_inputs(): input_map = dict( - args=dict(argstr="%s",), - automask=dict(argstr="-automask",), - blur=dict(argstr="-blur %f",), - despike=dict(argstr="-despike",), - environ=dict(nohash=True, usedefault=True,), - highpass=dict(argstr="%f", mandatory=True, position=-3,), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + ), + blur=dict( + argstr="-blur %f", + ), + despike=dict( + argstr="-despike", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + highpass=dict( + argstr="%f", + mandatory=True, + position=-3, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, - ), - localPV=dict(argstr="-localPV %f",), - lowpass=dict(argstr="%f", mandatory=True, position=-2,), - mask=dict(argstr="-mask %s", extensions=None, position=2,), - nfft=dict(argstr="-nfft %d",), - no_detrend=dict(argstr="-nodetrend",), - normalize=dict(argstr="-norm",), - notrans=dict(argstr="-notrans",), - num_threads=dict(nohash=True, usedefault=True,), - orthogonalize_dset=dict(argstr="-dsort %s", extensions=None,), - orthogonalize_file=dict(argstr="-ort %s",), + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + localPV=dict( + argstr="-localPV %f", + ), + lowpass=dict( + argstr="%f", + mandatory=True, + position=-2, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + position=2, + ), + nfft=dict( + argstr="-nfft %d", + ), + no_detrend=dict( + argstr="-nodetrend", + ), + normalize=dict( + argstr="-norm", + ), + notrans=dict( + argstr="-notrans", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + orthogonalize_dset=dict( + argstr="-dsort %s", + extensions=None, + ), + orthogonalize_file=dict( + argstr="-ort %s", + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -31,7 +76,9 @@ def test_Bandpass_inputs(): position=1, ), outputtype=dict(), - tr=dict(argstr="-dt %f",), + tr=dict( + argstr="-dt %f", + ), ) inputs = Bandpass.input_spec() @@ -41,7 +88,11 @@ def test_Bandpass_inputs(): def test_Bandpass_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Bandpass.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_BlurInMask.py b/nipype/interfaces/afni/tests/test_auto_BlurInMask.py index ec44fed3ee..91114611dc 100644 --- a/nipype/interfaces/afni/tests/test_auto_BlurInMask.py +++ b/nipype/interfaces/afni/tests/test_auto_BlurInMask.py @@ -4,11 +4,23 @@ def test_BlurInMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - automask=dict(argstr="-automask",), - environ=dict(nohash=True, usedefault=True,), - float_out=dict(argstr="-float",), - fwhm=dict(argstr="-FWHM %f", mandatory=True,), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + float_out=dict( + argstr="-float", + ), + fwhm=dict( + argstr="-FWHM %f", + mandatory=True, + ), in_file=dict( argstr="-input %s", copyfile=False, @@ -16,10 +28,22 @@ def test_BlurInMask_inputs(): mandatory=True, position=1, ), - mask=dict(argstr="-mask %s", extensions=None,), - multimask=dict(argstr="-Mmask %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), - options=dict(argstr="%s", position=2,), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + multimask=dict( + argstr="-Mmask %s", + extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + options=dict( + argstr="%s", + position=2, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -28,7 +52,9 @@ def test_BlurInMask_inputs(): position=-1, ), outputtype=dict(), - preserve=dict(argstr="-preserve",), + preserve=dict( + argstr="-preserve", + ), ) inputs = BlurInMask.input_spec() @@ -38,7 +64,11 @@ def test_BlurInMask_inputs(): def test_BlurInMask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BlurInMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_BlurToFWHM.py b/nipype/interfaces/afni/tests/test_auto_BlurToFWHM.py index 87788b8b3d..f164ae815e 100644 --- a/nipype/interfaces/afni/tests/test_auto_BlurToFWHM.py +++ b/nipype/interfaces/afni/tests/test_auto_BlurToFWHM.py @@ -4,15 +4,39 @@ def test_BlurToFWHM_inputs(): input_map = dict( - args=dict(argstr="%s",), - automask=dict(argstr="-automask",), - blurmaster=dict(argstr="-blurmaster %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - fwhm=dict(argstr="-FWHM %f",), - fwhmxy=dict(argstr="-FWHMxy %f",), - in_file=dict(argstr="-input %s", extensions=None, mandatory=True,), - mask=dict(argstr="-mask %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + ), + blurmaster=dict( + argstr="-blurmaster %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr="-FWHM %f", + ), + fwhmxy=dict( + argstr="-FWHMxy %f", + ), + in_file=dict( + argstr="-input %s", + extensions=None, + mandatory=True, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -29,7 +53,11 @@ def test_BlurToFWHM_inputs(): def test_BlurToFWHM_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BlurToFWHM.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_BrickStat.py b/nipype/interfaces/afni/tests/test_auto_BrickStat.py index 0d3bc11c21..a366953a5b 100644 --- a/nipype/interfaces/afni/tests/test_auto_BrickStat.py +++ b/nipype/interfaces/afni/tests/test_auto_BrickStat.py @@ -4,17 +4,46 @@ def test_BrickStat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - mask=dict(argstr="-mask %s", extensions=None, position=2,), - max=dict(argstr="-max",), - mean=dict(argstr="-mean",), - min=dict(argstr="-min", position=1,), - percentile=dict(argstr="-percentile %.3f %.3f %.3f",), - slow=dict(argstr="-slow",), - sum=dict(argstr="-sum",), - var=dict(argstr="-var",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + position=2, + ), + max=dict( + argstr="-max", + ), + mean=dict( + argstr="-mean", + ), + min=dict( + argstr="-min", + position=1, + ), + percentile=dict( + argstr="-percentile %.3f %.3f %.3f", + ), + slow=dict( + argstr="-slow", + ), + sum=dict( + argstr="-sum", + ), + var=dict( + argstr="-var", + ), ) inputs = BrickStat.input_spec() @@ -24,7 +53,9 @@ def test_BrickStat_inputs(): def test_BrickStat_outputs(): - output_map = dict(min_val=dict(),) + output_map = dict( + min_val=dict(), + ) outputs = BrickStat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Bucket.py b/nipype/interfaces/afni/tests/test_auto_Bucket.py index de301feaed..34dbd18bc2 100644 --- a/nipype/interfaces/afni/tests/test_auto_Bucket.py +++ b/nipype/interfaces/afni/tests/test_auto_Bucket.py @@ -4,11 +4,27 @@ def test_Bucket_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", mandatory=True, position=-1,), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="-prefix %s", extensions=None, name_template="buck",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="-prefix %s", + extensions=None, + name_template="buck", + ), outputtype=dict(), ) inputs = Bucket.input_spec() @@ -19,7 +35,11 @@ def test_Bucket_inputs(): def test_Bucket_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Bucket.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Calc.py b/nipype/interfaces/afni/tests/test_auto_Calc.py index 5b49623773..dc50380317 100644 --- a/nipype/interfaces/afni/tests/test_auto_Calc.py +++ b/nipype/interfaces/afni/tests/test_auto_Calc.py @@ -4,14 +4,42 @@ def test_Calc_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - expr=dict(argstr='-expr "%s"', mandatory=True, position=3,), - in_file_a=dict(argstr="-a %s", extensions=None, mandatory=True, position=0,), - in_file_b=dict(argstr="-b %s", extensions=None, position=1,), - in_file_c=dict(argstr="-c %s", extensions=None, position=2,), - num_threads=dict(nohash=True, usedefault=True,), - other=dict(argstr="", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expr=dict( + argstr='-expr "%s"', + mandatory=True, + position=3, + ), + in_file_a=dict( + argstr="-a %s", + extensions=None, + mandatory=True, + position=0, + ), + in_file_b=dict( + argstr="-b %s", + extensions=None, + position=1, + ), + in_file_c=dict( + argstr="-c %s", + extensions=None, + position=2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + other=dict( + argstr="", + extensions=None, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -19,10 +47,16 @@ def test_Calc_inputs(): name_template="%s_calc", ), outputtype=dict(), - overwrite=dict(argstr="-overwrite",), + overwrite=dict( + argstr="-overwrite", + ), single_idx=dict(), - start_idx=dict(requires=["stop_idx"],), - stop_idx=dict(requires=["start_idx"],), + start_idx=dict( + requires=["stop_idx"], + ), + stop_idx=dict( + requires=["start_idx"], + ), ) inputs = Calc.input_spec() @@ -32,7 +66,11 @@ def test_Calc_inputs(): def test_Calc_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Calc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Cat.py b/nipype/interfaces/afni/tests/test_auto_Cat.py index 07a1d2979c..e5c76b34b1 100644 --- a/nipype/interfaces/afni/tests/test_auto_Cat.py +++ b/nipype/interfaces/afni/tests/test_auto_Cat.py @@ -4,12 +4,28 @@ def test_Cat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="%s", mandatory=True, position=-2,), - keepfree=dict(argstr="-nonfixed",), - num_threads=dict(nohash=True, usedefault=True,), - omitconst=dict(argstr="-nonconst",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + keepfree=dict( + argstr="-nonfixed", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + omitconst=dict( + argstr="-nonconst", + ), out_cint=dict( xor=["out_format", "out_nice", "out_double", "out_fint", "out_int"], ), @@ -41,8 +57,12 @@ def test_Cat_inputs(): xor=["out_format", "out_int", "out_double", "out_fint", "out_cint"], ), outputtype=dict(), - sel=dict(argstr="-sel %s",), - stack=dict(argstr="-stack",), + sel=dict( + argstr="-sel %s", + ), + stack=dict( + argstr="-stack", + ), ) inputs = Cat.input_spec() @@ -52,7 +72,11 @@ def test_Cat_inputs(): def test_Cat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Cat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_CatMatvec.py b/nipype/interfaces/afni/tests/test_auto_CatMatvec.py index f1716f6084..6b6c2630f6 100644 --- a/nipype/interfaces/afni/tests/test_auto_CatMatvec.py +++ b/nipype/interfaces/afni/tests/test_auto_CatMatvec.py @@ -4,13 +4,34 @@ def test_CatMatvec_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fourxfour=dict(argstr="-4x4", xor=["matrix", "oneline"],), - in_file=dict(argstr="%s", mandatory=True, position=-2,), - matrix=dict(argstr="-MATRIX", xor=["oneline", "fourxfour"],), - num_threads=dict(nohash=True, usedefault=True,), - oneline=dict(argstr="-ONELINE", xor=["matrix", "fourxfour"],), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fourxfour=dict( + argstr="-4x4", + xor=["matrix", "oneline"], + ), + in_file=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + matrix=dict( + argstr="-MATRIX", + xor=["oneline", "fourxfour"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oneline=dict( + argstr="-ONELINE", + xor=["matrix", "fourxfour"], + ), out_file=dict( argstr=" > %s", extensions=None, @@ -30,7 +51,11 @@ def test_CatMatvec_inputs(): def test_CatMatvec_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = CatMatvec.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_CenterMass.py b/nipype/interfaces/afni/tests/test_auto_CenterMass.py index 07975af563..7ec95938b4 100644 --- a/nipype/interfaces/afni/tests/test_auto_CenterMass.py +++ b/nipype/interfaces/afni/tests/test_auto_CenterMass.py @@ -4,9 +4,15 @@ def test_CenterMass_inputs(): input_map = dict( - all_rois=dict(argstr="-all_rois",), - args=dict(argstr="%s",), - automask=dict(argstr="-automask",), + all_rois=dict( + argstr="-all_rois", + ), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + ), cm_file=dict( argstr="> %s", extensions=None, @@ -16,14 +22,30 @@ def test_CenterMass_inputs(): name_template="%s_cm.out", position=-1, ), - environ=dict(nohash=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=-2, + ), + local_ijk=dict( + argstr="-local_ijk", + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + roi_vals=dict( + argstr="-roi_vals %s", + ), + set_cm=dict( + argstr="-set %f %f %f", ), - local_ijk=dict(argstr="-local_ijk",), - mask_file=dict(argstr="-mask %s", extensions=None,), - roi_vals=dict(argstr="-roi_vals %s",), - set_cm=dict(argstr="-set %f %f %f",), ) inputs = CenterMass.input_spec() @@ -34,7 +56,13 @@ def test_CenterMass_inputs(): def test_CenterMass_outputs(): output_map = dict( - cm=dict(), cm_file=dict(extensions=None,), out_file=dict(extensions=None,), + cm=dict(), + cm_file=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = CenterMass.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_ClipLevel.py b/nipype/interfaces/afni/tests/test_auto_ClipLevel.py index 576ea68f89..7a324fe7d4 100644 --- a/nipype/interfaces/afni/tests/test_auto_ClipLevel.py +++ b/nipype/interfaces/afni/tests/test_auto_ClipLevel.py @@ -4,12 +4,34 @@ def test_ClipLevel_inputs(): input_map = dict( - args=dict(argstr="%s",), - doall=dict(argstr="-doall", position=3, xor="grad",), - environ=dict(nohash=True, usedefault=True,), - grad=dict(argstr="-grad %s", extensions=None, position=3, xor="doall",), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - mfrac=dict(argstr="-mfrac %s", position=2,), + args=dict( + argstr="%s", + ), + doall=dict( + argstr="-doall", + position=3, + xor="grad", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad=dict( + argstr="-grad %s", + extensions=None, + position=3, + xor="doall", + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + mfrac=dict( + argstr="-mfrac %s", + position=2, + ), ) inputs = ClipLevel.input_spec() @@ -19,7 +41,9 @@ def test_ClipLevel_inputs(): def test_ClipLevel_outputs(): - output_map = dict(clip_val=dict(),) + output_map = dict( + clip_val=dict(), + ) outputs = ClipLevel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_ConvertDset.py b/nipype/interfaces/afni/tests/test_auto_ConvertDset.py index 249fe47843..226eac97b5 100644 --- a/nipype/interfaces/afni/tests/test_auto_ConvertDset.py +++ b/nipype/interfaces/afni/tests/test_auto_ConvertDset.py @@ -4,14 +4,34 @@ def test_ConvertDset_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-input %s", extensions=None, mandatory=True, position=-2,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-input %s", + extensions=None, + mandatory=True, + position=-2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( - argstr="-prefix %s", extensions=None, mandatory=True, position=-1, + argstr="-prefix %s", + extensions=None, + mandatory=True, + position=-1, + ), + out_type=dict( + argstr="-o_%s", + mandatory=True, + position=0, ), - out_type=dict(argstr="-o_%s", mandatory=True, position=0,), outputtype=dict(), ) inputs = ConvertDset.input_spec() @@ -22,7 +42,11 @@ def test_ConvertDset_inputs(): def test_ConvertDset_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ConvertDset.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Copy.py b/nipype/interfaces/afni/tests/test_auto_Copy.py index a601202c48..e96592b184 100644 --- a/nipype/interfaces/afni/tests/test_auto_Copy.py +++ b/nipype/interfaces/afni/tests/test_auto_Copy.py @@ -4,12 +4,24 @@ def test_Copy_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-2, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="%s", extensions=None, @@ -18,7 +30,9 @@ def test_Copy_inputs(): position=-1, ), outputtype=dict(), - verbose=dict(argstr="-verb",), + verbose=dict( + argstr="-verb", + ), ) inputs = Copy.input_spec() @@ -28,7 +42,11 @@ def test_Copy_inputs(): def test_Copy_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Copy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Deconvolve.py b/nipype/interfaces/afni/tests/test_auto_Deconvolve.py index c03fafcf46..c4195807eb 100644 --- a/nipype/interfaces/afni/tests/test_auto_Deconvolve.py +++ b/nipype/interfaces/afni/tests/test_auto_Deconvolve.py @@ -4,55 +4,169 @@ def test_Deconvolve_inputs(): input_map = dict( - STATmask=dict(argstr="-STATmask %s", extensions=None,), - TR_1D=dict(argstr="-TR_1D %f",), - allzero_OK=dict(argstr="-allzero_OK",), - args=dict(argstr="%s",), - automask=dict(argstr="-automask",), - cbucket=dict(argstr="-cbucket %s",), - censor=dict(argstr="-censor %s", extensions=None,), - dmbase=dict(argstr="-dmbase",), - dname=dict(argstr="-D%s=%s",), - environ=dict(nohash=True, usedefault=True,), - force_TR=dict(argstr="-force_TR %f", position=0,), - fout=dict(argstr="-fout",), - global_times=dict(argstr="-global_times", xor=["local_times"],), - glt_label=dict(argstr="-glt_label %d %s...", position=-1, requires=["gltsym"],), - gltsym=dict(argstr="-gltsym 'SYM: %s'...", position=-2,), - goforit=dict(argstr="-GOFORIT %i",), - in_files=dict(argstr="-input %s", copyfile=False, position=1, sep=" ",), - input1D=dict(argstr="-input1D %s", extensions=None,), - legendre=dict(argstr="-legendre",), - local_times=dict(argstr="-local_times", xor=["global_times"],), - mask=dict(argstr="-mask %s", extensions=None,), - noblock=dict(argstr="-noblock",), - nocond=dict(argstr="-nocond",), - nodmbase=dict(argstr="-nodmbase",), - nofdr=dict(argstr="-noFDR",), - nolegendre=dict(argstr="-nolegendre",), - nosvd=dict(argstr="-nosvd",), - num_glt=dict(argstr="-num_glt %d", position=-3,), - num_stimts=dict(argstr="-num_stimts %d", position=-6,), - num_threads=dict(argstr="-jobs %d", nohash=True,), - ortvec=dict(argstr="-ortvec %s %s",), - out_file=dict(argstr="-bucket %s", extensions=None,), + STATmask=dict( + argstr="-STATmask %s", + extensions=None, + ), + TR_1D=dict( + argstr="-TR_1D %f", + ), + allzero_OK=dict( + argstr="-allzero_OK", + ), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + ), + cbucket=dict( + argstr="-cbucket %s", + ), + censor=dict( + argstr="-censor %s", + extensions=None, + ), + dmbase=dict( + argstr="-dmbase", + ), + dname=dict( + argstr="-D%s=%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + force_TR=dict( + argstr="-force_TR %f", + position=0, + ), + fout=dict( + argstr="-fout", + ), + global_times=dict( + argstr="-global_times", + xor=["local_times"], + ), + glt_label=dict( + argstr="-glt_label %d %s...", + position=-1, + requires=["gltsym"], + ), + gltsym=dict( + argstr="-gltsym 'SYM: %s'...", + position=-2, + ), + goforit=dict( + argstr="-GOFORIT %i", + ), + in_files=dict( + argstr="-input %s", + copyfile=False, + position=1, + sep=" ", + ), + input1D=dict( + argstr="-input1D %s", + extensions=None, + ), + legendre=dict( + argstr="-legendre", + ), + local_times=dict( + argstr="-local_times", + xor=["global_times"], + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + noblock=dict( + argstr="-noblock", + ), + nocond=dict( + argstr="-nocond", + ), + nodmbase=dict( + argstr="-nodmbase", + ), + nofdr=dict( + argstr="-noFDR", + ), + nolegendre=dict( + argstr="-nolegendre", + ), + nosvd=dict( + argstr="-nosvd", + ), + num_glt=dict( + argstr="-num_glt %d", + position=-3, + ), + num_stimts=dict( + argstr="-num_stimts %d", + position=-6, + ), + num_threads=dict( + argstr="-jobs %d", + nohash=True, + ), + ortvec=dict( + argstr="-ortvec %s %s", + ), + out_file=dict( + argstr="-bucket %s", + extensions=None, + ), outputtype=dict(), - polort=dict(argstr="-polort %d",), - rmsmin=dict(argstr="-rmsmin %f",), - rout=dict(argstr="-rout",), - sat=dict(argstr="-sat", xor=["trans"],), - singvals=dict(argstr="-singvals",), + polort=dict( + argstr="-polort %d", + ), + rmsmin=dict( + argstr="-rmsmin %f", + ), + rout=dict( + argstr="-rout", + ), + sat=dict( + argstr="-sat", + xor=["trans"], + ), + singvals=dict( + argstr="-singvals", + ), stim_label=dict( - argstr="-stim_label %d %s...", position=-4, requires=["stim_times"], - ), - stim_times=dict(argstr="-stim_times %d %s '%s'...", position=-5,), - stim_times_subtract=dict(argstr="-stim_times_subtract %f",), - svd=dict(argstr="-svd",), - tout=dict(argstr="-tout",), - trans=dict(argstr="-trans", xor=["sat"],), - vout=dict(argstr="-vout",), - x1D=dict(argstr="-x1D %s", extensions=None,), - x1D_stop=dict(argstr="-x1D_stop",), + argstr="-stim_label %d %s...", + position=-4, + requires=["stim_times"], + ), + stim_times=dict( + argstr="-stim_times %d %s '%s'...", + position=-5, + ), + stim_times_subtract=dict( + argstr="-stim_times_subtract %f", + ), + svd=dict( + argstr="-svd", + ), + tout=dict( + argstr="-tout", + ), + trans=dict( + argstr="-trans", + xor=["sat"], + ), + vout=dict( + argstr="-vout", + ), + x1D=dict( + argstr="-x1D %s", + extensions=None, + ), + x1D_stop=dict( + argstr="-x1D_stop", + ), ) inputs = Deconvolve.input_spec() @@ -63,10 +177,18 @@ def test_Deconvolve_inputs(): def test_Deconvolve_outputs(): output_map = dict( - cbucket=dict(extensions=None,), - out_file=dict(extensions=None,), - reml_script=dict(extensions=None,), - x1D=dict(extensions=None,), + cbucket=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + reml_script=dict( + extensions=None, + ), + x1D=dict( + extensions=None, + ), ) outputs = Deconvolve.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_DegreeCentrality.py b/nipype/interfaces/afni/tests/test_auto_DegreeCentrality.py index 0fb10a0713..afbc5a7d4f 100644 --- a/nipype/interfaces/afni/tests/test_auto_DegreeCentrality.py +++ b/nipype/interfaces/afni/tests/test_auto_DegreeCentrality.py @@ -4,16 +4,37 @@ def test_DegreeCentrality_inputs(): input_map = dict( - args=dict(argstr="%s",), - autoclip=dict(argstr="-autoclip",), - automask=dict(argstr="-automask",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + autoclip=dict( + argstr="-autoclip", + ), + automask=dict( + argstr="-automask", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oned_file=dict( + argstr="-out1D %s", ), - mask=dict(argstr="-mask %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), - oned_file=dict(argstr="-out1D %s",), out_file=dict( argstr="-prefix %s", extensions=None, @@ -21,9 +42,15 @@ def test_DegreeCentrality_inputs(): name_template="%s_afni", ), outputtype=dict(), - polort=dict(argstr="-polort %d",), - sparsity=dict(argstr="-sparsity %f",), - thresh=dict(argstr="-thresh %f",), + polort=dict( + argstr="-polort %d", + ), + sparsity=dict( + argstr="-sparsity %f", + ), + thresh=dict( + argstr="-thresh %f", + ), ) inputs = DegreeCentrality.input_spec() @@ -34,7 +61,12 @@ def test_DegreeCentrality_inputs(): def test_DegreeCentrality_outputs(): output_map = dict( - oned_file=dict(extensions=None,), out_file=dict(extensions=None,), + oned_file=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = DegreeCentrality.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Despike.py b/nipype/interfaces/afni/tests/test_auto_Despike.py index 00a6666894..8835dd7e07 100644 --- a/nipype/interfaces/afni/tests/test_auto_Despike.py +++ b/nipype/interfaces/afni/tests/test_auto_Despike.py @@ -4,12 +4,24 @@ def test_Despike_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -26,7 +38,11 @@ def test_Despike_inputs(): def test_Despike_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Despike.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Detrend.py b/nipype/interfaces/afni/tests/test_auto_Detrend.py index 275c45208b..5edbdd74ee 100644 --- a/nipype/interfaces/afni/tests/test_auto_Detrend.py +++ b/nipype/interfaces/afni/tests/test_auto_Detrend.py @@ -4,12 +4,24 @@ def test_Detrend_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -26,7 +38,11 @@ def test_Detrend_inputs(): def test_Detrend_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Detrend.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Dot.py b/nipype/interfaces/afni/tests/test_auto_Dot.py index d1c7812cdd..9cf8083ab9 100644 --- a/nipype/interfaces/afni/tests/test_auto_Dot.py +++ b/nipype/interfaces/afni/tests/test_auto_Dot.py @@ -4,24 +4,64 @@ def test_Dot_inputs(): input_map = dict( - args=dict(argstr="%s",), - demean=dict(argstr="-demean",), - docoef=dict(argstr="-docoef",), - docor=dict(argstr="-docor",), - dodice=dict(argstr="-dodice",), - dodot=dict(argstr="-dodot",), - doeta2=dict(argstr="-doeta2",), - dosums=dict(argstr="-dosums",), - environ=dict(nohash=True, usedefault=True,), - full=dict(argstr="-full",), - in_files=dict(argstr="%s ...", position=-2,), - mask=dict(argstr="-mask %s", extensions=None,), - mrange=dict(argstr="-mrange %s %s",), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr=" |& tee %s", extensions=None, position=-1,), + args=dict( + argstr="%s", + ), + demean=dict( + argstr="-demean", + ), + docoef=dict( + argstr="-docoef", + ), + docor=dict( + argstr="-docor", + ), + dodice=dict( + argstr="-dodice", + ), + dodot=dict( + argstr="-dodot", + ), + doeta2=dict( + argstr="-doeta2", + ), + dosums=dict( + argstr="-dosums", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + full=dict( + argstr="-full", + ), + in_files=dict( + argstr="%s ...", + position=-2, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + mrange=dict( + argstr="-mrange %s %s", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr=" |& tee %s", + extensions=None, + position=-1, + ), outputtype=dict(), - show_labels=dict(argstr="-show_labels",), - upper=dict(argstr="-upper",), + show_labels=dict( + argstr="-show_labels", + ), + upper=dict( + argstr="-upper", + ), ) inputs = Dot.input_spec() @@ -31,7 +71,11 @@ def test_Dot_inputs(): def test_Dot_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Dot.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_ECM.py b/nipype/interfaces/afni/tests/test_auto_ECM.py index 83d5508bae..030aaffe6a 100644 --- a/nipype/interfaces/afni/tests/test_auto_ECM.py +++ b/nipype/interfaces/afni/tests/test_auto_ECM.py @@ -4,20 +4,49 @@ def test_ECM_inputs(): input_map = dict( - args=dict(argstr="%s",), - autoclip=dict(argstr="-autoclip",), - automask=dict(argstr="-automask",), - environ=dict(nohash=True, usedefault=True,), - eps=dict(argstr="-eps %f",), - fecm=dict(argstr="-fecm",), - full=dict(argstr="-full",), + args=dict( + argstr="%s", + ), + autoclip=dict( + argstr="-autoclip", + ), + automask=dict( + argstr="-automask", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + eps=dict( + argstr="-eps %f", + ), + fecm=dict( + argstr="-fecm", + ), + full=dict( + argstr="-full", + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + max_iter=dict( + argstr="-max_iter %d", + ), + memory=dict( + argstr="-memory %f", + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - mask=dict(argstr="-mask %s", extensions=None,), - max_iter=dict(argstr="-max_iter %d",), - memory=dict(argstr="-memory %f",), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -25,11 +54,21 @@ def test_ECM_inputs(): name_template="%s_afni", ), outputtype=dict(), - polort=dict(argstr="-polort %d",), - scale=dict(argstr="-scale %f",), - shift=dict(argstr="-shift %f",), - sparsity=dict(argstr="-sparsity %f",), - thresh=dict(argstr="-thresh %f",), + polort=dict( + argstr="-polort %d", + ), + scale=dict( + argstr="-scale %f", + ), + shift=dict( + argstr="-shift %f", + ), + sparsity=dict( + argstr="-sparsity %f", + ), + thresh=dict( + argstr="-thresh %f", + ), ) inputs = ECM.input_spec() @@ -39,7 +78,11 @@ def test_ECM_inputs(): def test_ECM_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ECM.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Edge3.py b/nipype/interfaces/afni/tests/test_auto_Edge3.py index 484920d596..45b49fd243 100644 --- a/nipype/interfaces/afni/tests/test_auto_Edge3.py +++ b/nipype/interfaces/afni/tests/test_auto_Edge3.py @@ -4,11 +4,24 @@ def test_Edge3_inputs(): input_map = dict( - args=dict(argstr="%s",), - datum=dict(argstr="-datum %s",), - environ=dict(nohash=True, usedefault=True,), - fscale=dict(argstr="-fscale", xor=["gscale", "nscale", "scale_floats"],), - gscale=dict(argstr="-gscale", xor=["fscale", "nscale", "scale_floats"],), + args=dict( + argstr="%s", + ), + datum=dict( + argstr="-datum %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fscale=dict( + argstr="-fscale", + xor=["gscale", "nscale", "scale_floats"], + ), + gscale=dict( + argstr="-gscale", + xor=["fscale", "nscale", "scale_floats"], + ), in_file=dict( argstr="-input %s", copyfile=False, @@ -16,14 +29,27 @@ def test_Edge3_inputs(): mandatory=True, position=0, ), - nscale=dict(argstr="-nscale", xor=["fscale", "gscale", "scale_floats"],), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="-prefix %s", extensions=None, position=-1,), + nscale=dict( + argstr="-nscale", + xor=["fscale", "gscale", "scale_floats"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="-prefix %s", + extensions=None, + position=-1, + ), outputtype=dict(), scale_floats=dict( - argstr="-scale_floats %f", xor=["fscale", "gscale", "nscale"], + argstr="-scale_floats %f", + xor=["fscale", "gscale", "nscale"], + ), + verbose=dict( + argstr="-verbose", ), - verbose=dict(argstr="-verbose",), ) inputs = Edge3.input_spec() @@ -33,7 +59,11 @@ def test_Edge3_inputs(): def test_Edge3_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Edge3.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Eval.py b/nipype/interfaces/afni/tests/test_auto_Eval.py index 1bc22fcb6c..748bf05dfd 100644 --- a/nipype/interfaces/afni/tests/test_auto_Eval.py +++ b/nipype/interfaces/afni/tests/test_auto_Eval.py @@ -4,15 +4,45 @@ def test_Eval_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - expr=dict(argstr='-expr "%s"', mandatory=True, position=3,), - in_file_a=dict(argstr="-a %s", extensions=None, mandatory=True, position=0,), - in_file_b=dict(argstr="-b %s", extensions=None, position=1,), - in_file_c=dict(argstr="-c %s", extensions=None, position=2,), - num_threads=dict(nohash=True, usedefault=True,), - other=dict(argstr="", extensions=None,), - out1D=dict(argstr="-1D",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expr=dict( + argstr='-expr "%s"', + mandatory=True, + position=3, + ), + in_file_a=dict( + argstr="-a %s", + extensions=None, + mandatory=True, + position=0, + ), + in_file_b=dict( + argstr="-b %s", + extensions=None, + position=1, + ), + in_file_c=dict( + argstr="-c %s", + extensions=None, + position=2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + other=dict( + argstr="", + extensions=None, + ), + out1D=dict( + argstr="-1D", + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -21,8 +51,12 @@ def test_Eval_inputs(): ), outputtype=dict(), single_idx=dict(), - start_idx=dict(requires=["stop_idx"],), - stop_idx=dict(requires=["start_idx"],), + start_idx=dict( + requires=["stop_idx"], + ), + stop_idx=dict( + requires=["start_idx"], + ), ) inputs = Eval.input_spec() @@ -32,7 +66,11 @@ def test_Eval_inputs(): def test_Eval_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Eval.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_FWHMx.py b/nipype/interfaces/afni/tests/test_auto_FWHMx.py index 1785a675b5..06151c569a 100644 --- a/nipype/interfaces/afni/tests/test_auto_FWHMx.py +++ b/nipype/interfaces/afni/tests/test_auto_FWHMx.py @@ -4,18 +4,53 @@ def test_FWHMx_inputs(): input_map = dict( - acf=dict(argstr="-acf", usedefault=True,), - args=dict(argstr="%s",), - arith=dict(argstr="-arith", xor=["geom"],), - automask=dict(argstr="-automask", usedefault=True,), - combine=dict(argstr="-combine",), - compat=dict(argstr="-compat",), - demed=dict(argstr="-demed", xor=["detrend"],), - detrend=dict(argstr="-detrend", usedefault=True, xor=["demed"],), - environ=dict(nohash=True, usedefault=True,), - geom=dict(argstr="-geom", xor=["arith"],), - in_file=dict(argstr="-input %s", extensions=None, mandatory=True,), - mask=dict(argstr="-mask %s", extensions=None,), + acf=dict( + argstr="-acf", + usedefault=True, + ), + args=dict( + argstr="%s", + ), + arith=dict( + argstr="-arith", + xor=["geom"], + ), + automask=dict( + argstr="-automask", + usedefault=True, + ), + combine=dict( + argstr="-combine", + ), + compat=dict( + argstr="-compat", + ), + demed=dict( + argstr="-demed", + xor=["detrend"], + ), + detrend=dict( + argstr="-detrend", + usedefault=True, + xor=["demed"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + geom=dict( + argstr="-geom", + xor=["arith"], + ), + in_file=dict( + argstr="-input %s", + extensions=None, + mandatory=True, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), out_detrend=dict( argstr="-detprefix %s", extensions=None, @@ -38,7 +73,9 @@ def test_FWHMx_inputs(): name_source="in_file", name_template="%s_subbricks.out", ), - unif=dict(argstr="-unif",), + unif=dict( + argstr="-unif", + ), ) inputs = FWHMx.input_spec() @@ -51,10 +88,18 @@ def test_FWHMx_outputs(): output_map = dict( acf_param=dict(), fwhm=dict(), - out_acf=dict(extensions=None,), - out_detrend=dict(extensions=None,), - out_file=dict(extensions=None,), - out_subbricks=dict(extensions=None,), + out_acf=dict( + extensions=None, + ), + out_detrend=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + out_subbricks=dict( + extensions=None, + ), ) outputs = FWHMx.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Fim.py b/nipype/interfaces/afni/tests/test_auto_Fim.py index 6a07de12e5..aea43391bc 100644 --- a/nipype/interfaces/afni/tests/test_auto_Fim.py +++ b/nipype/interfaces/afni/tests/test_auto_Fim.py @@ -4,11 +4,22 @@ def test_Fim_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fim_thr=dict(argstr="-fim_thr %f", position=3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fim_thr=dict( + argstr="-fim_thr %f", + position=3, + ), ideal_file=dict( - argstr="-ideal_file %s", extensions=None, mandatory=True, position=2, + argstr="-ideal_file %s", + extensions=None, + mandatory=True, + position=2, ), in_file=dict( argstr="-input %s", @@ -17,8 +28,14 @@ def test_Fim_inputs(): mandatory=True, position=1, ), - num_threads=dict(nohash=True, usedefault=True,), - out=dict(argstr="-out %s", position=4,), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out=dict( + argstr="-out %s", + position=4, + ), out_file=dict( argstr="-bucket %s", extensions=None, @@ -35,7 +52,11 @@ def test_Fim_inputs(): def test_Fim_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Fim.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Fourier.py b/nipype/interfaces/afni/tests/test_auto_Fourier.py index 0c648fb149..97764a2b9b 100644 --- a/nipype/interfaces/afni/tests/test_auto_Fourier.py +++ b/nipype/interfaces/afni/tests/test_auto_Fourier.py @@ -4,14 +4,32 @@ def test_Fourier_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - highpass=dict(argstr="-highpass %f", mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + highpass=dict( + argstr="-highpass %f", + mandatory=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + lowpass=dict( + argstr="-lowpass %f", + mandatory=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - lowpass=dict(argstr="-lowpass %f", mandatory=True,), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -19,7 +37,9 @@ def test_Fourier_inputs(): name_template="%s_fourier", ), outputtype=dict(), - retrend=dict(argstr="-retrend",), + retrend=dict( + argstr="-retrend", + ), ) inputs = Fourier.input_spec() @@ -29,7 +49,11 @@ def test_Fourier_inputs(): def test_Fourier_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Fourier.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_GCOR.py b/nipype/interfaces/afni/tests/test_auto_GCOR.py index b63b269d6a..2e5f0f372d 100644 --- a/nipype/interfaces/afni/tests/test_auto_GCOR.py +++ b/nipype/interfaces/afni/tests/test_auto_GCOR.py @@ -4,8 +4,13 @@ def test_GCOR_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( argstr="-input %s", copyfile=False, @@ -13,9 +18,17 @@ def test_GCOR_inputs(): mandatory=True, position=-1, ), - mask=dict(argstr="-mask %s", copyfile=False, extensions=None,), - nfirst=dict(argstr="-nfirst %d",), - no_demean=dict(argstr="-no_demean",), + mask=dict( + argstr="-mask %s", + copyfile=False, + extensions=None, + ), + nfirst=dict( + argstr="-nfirst %d", + ), + no_demean=dict( + argstr="-no_demean", + ), ) inputs = GCOR.input_spec() @@ -25,7 +38,9 @@ def test_GCOR_inputs(): def test_GCOR_outputs(): - output_map = dict(out=dict(),) + output_map = dict( + out=dict(), + ) outputs = GCOR.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Hist.py b/nipype/interfaces/afni/tests/test_auto_Hist.py index 30443b3a44..2263f3632b 100644 --- a/nipype/interfaces/afni/tests/test_auto_Hist.py +++ b/nipype/interfaces/afni/tests/test_auto_Hist.py @@ -4,9 +4,16 @@ def test_Hist_inputs(): input_map = dict( - args=dict(argstr="%s",), - bin_width=dict(argstr="-binwidth %f",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + bin_width=dict( + argstr="-binwidth %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( argstr="-input %s", copyfile=False, @@ -14,10 +21,19 @@ def test_Hist_inputs(): mandatory=True, position=1, ), - mask=dict(argstr="-mask %s", extensions=None,), - max_value=dict(argstr="-max %f",), - min_value=dict(argstr="-min %f",), - nbin=dict(argstr="-nbin %d",), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + max_value=dict( + argstr="-max %f", + ), + min_value=dict( + argstr="-min %f", + ), + nbin=dict( + argstr="-nbin %d", + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -33,7 +49,10 @@ def test_Hist_inputs(): name_template="%s_hist.out", position=-1, ), - showhist=dict(argstr="-showhist", usedefault=True,), + showhist=dict( + argstr="-showhist", + usedefault=True, + ), ) inputs = Hist.input_spec() @@ -43,7 +62,14 @@ def test_Hist_inputs(): def test_Hist_outputs(): - output_map = dict(out_file=dict(extensions=None,), out_show=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + out_show=dict( + extensions=None, + ), + ) outputs = Hist.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_LFCD.py b/nipype/interfaces/afni/tests/test_auto_LFCD.py index aebe0dcded..bd4b76baee 100644 --- a/nipype/interfaces/afni/tests/test_auto_LFCD.py +++ b/nipype/interfaces/afni/tests/test_auto_LFCD.py @@ -4,15 +4,34 @@ def test_LFCD_inputs(): input_map = dict( - args=dict(argstr="%s",), - autoclip=dict(argstr="-autoclip",), - automask=dict(argstr="-automask",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + autoclip=dict( + argstr="-autoclip", + ), + automask=dict( + argstr="-automask", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - mask=dict(argstr="-mask %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -20,8 +39,12 @@ def test_LFCD_inputs(): name_template="%s_afni", ), outputtype=dict(), - polort=dict(argstr="-polort %d",), - thresh=dict(argstr="-thresh %f",), + polort=dict( + argstr="-polort %d", + ), + thresh=dict( + argstr="-thresh %f", + ), ) inputs = LFCD.input_spec() @@ -31,7 +54,11 @@ def test_LFCD_inputs(): def test_LFCD_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = LFCD.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_LocalBistat.py b/nipype/interfaces/afni/tests/test_auto_LocalBistat.py index ea718b9d1c..2ffe29dda0 100644 --- a/nipype/interfaces/afni/tests/test_auto_LocalBistat.py +++ b/nipype/interfaces/afni/tests/test_auto_LocalBistat.py @@ -4,14 +4,41 @@ def test_LocalBistat_inputs(): input_map = dict( - args=dict(argstr="%s",), - automask=dict(argstr="-automask", xor=["weight_file"],), - environ=dict(nohash=True, usedefault=True,), - in_file1=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - in_file2=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - mask_file=dict(argstr="-mask %s", extensions=None,), - neighborhood=dict(argstr="-nbhd '%s(%s)'", mandatory=True,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + xor=["weight_file"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file1=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + in_file2=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + neighborhood=dict( + argstr="-nbhd '%s(%s)'", + mandatory=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -21,8 +48,15 @@ def test_LocalBistat_inputs(): position=0, ), outputtype=dict(), - stat=dict(argstr="-stat %s...", mandatory=True,), - weight_file=dict(argstr="-weight %s", extensions=None, xor=["automask"],), + stat=dict( + argstr="-stat %s...", + mandatory=True, + ), + weight_file=dict( + argstr="-weight %s", + extensions=None, + xor=["automask"], + ), ) inputs = LocalBistat.input_spec() @@ -32,7 +66,11 @@ def test_LocalBistat_inputs(): def test_LocalBistat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = LocalBistat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Localstat.py b/nipype/interfaces/afni/tests/test_auto_Localstat.py index 4b036e6d84..54c99b434d 100644 --- a/nipype/interfaces/afni/tests/test_auto_Localstat.py +++ b/nipype/interfaces/afni/tests/test_auto_Localstat.py @@ -4,15 +4,41 @@ def test_Localstat_inputs(): input_map = dict( - args=dict(argstr="%s",), - automask=dict(argstr="-automask",), - environ=dict(nohash=True, usedefault=True,), - grid_rmode=dict(argstr="-grid_rmode %s", requires=["reduce_restore_grid"],), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - mask_file=dict(argstr="-mask %s", extensions=None,), - neighborhood=dict(argstr="-nbhd '%s(%s)'", mandatory=True,), - nonmask=dict(argstr="-use_nonmask",), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grid_rmode=dict( + argstr="-grid_rmode %s", + requires=["reduce_restore_grid"], + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + neighborhood=dict( + argstr="-nbhd '%s(%s)'", + mandatory=True, + ), + nonmask=dict( + argstr="-use_nonmask", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -22,18 +48,28 @@ def test_Localstat_inputs(): position=0, ), outputtype=dict(), - overwrite=dict(argstr="-overwrite",), - quiet=dict(argstr="-quiet",), + overwrite=dict( + argstr="-overwrite", + ), + quiet=dict( + argstr="-quiet", + ), reduce_grid=dict( - argstr="-reduce_grid %s", xor=["reduce_restore_grid", "reduce_max_vox"], + argstr="-reduce_grid %s", + xor=["reduce_restore_grid", "reduce_max_vox"], ), reduce_max_vox=dict( - argstr="-reduce_max_vox %s", xor=["reduce_restore_grid", "reduce_grid"], + argstr="-reduce_max_vox %s", + xor=["reduce_restore_grid", "reduce_grid"], ), reduce_restore_grid=dict( - argstr="-reduce_restore_grid %s", xor=["reduce_max_vox", "reduce_grid"], + argstr="-reduce_restore_grid %s", + xor=["reduce_max_vox", "reduce_grid"], + ), + stat=dict( + argstr="-stat %s...", + mandatory=True, ), - stat=dict(argstr="-stat %s...", mandatory=True,), ) inputs = Localstat.input_spec() @@ -43,7 +79,11 @@ def test_Localstat_inputs(): def test_Localstat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Localstat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_MaskTool.py b/nipype/interfaces/afni/tests/test_auto_MaskTool.py index dffe07ff32..a0520df606 100644 --- a/nipype/interfaces/afni/tests/test_auto_MaskTool.py +++ b/nipype/interfaces/afni/tests/test_auto_MaskTool.py @@ -4,18 +4,49 @@ def test_MaskTool_inputs(): input_map = dict( - args=dict(argstr="%s",), - count=dict(argstr="-count", position=2,), - datum=dict(argstr="-datum %s",), - dilate_inputs=dict(argstr="-dilate_inputs %s",), - dilate_results=dict(argstr="-dilate_results %s",), - environ=dict(nohash=True, usedefault=True,), - fill_dirs=dict(argstr="-fill_dirs %s", requires=["fill_holes"],), - fill_holes=dict(argstr="-fill_holes",), - frac=dict(argstr="-frac %s",), - in_file=dict(argstr="-input %s", copyfile=False, mandatory=True, position=-1,), - inter=dict(argstr="-inter",), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + count=dict( + argstr="-count", + position=2, + ), + datum=dict( + argstr="-datum %s", + ), + dilate_inputs=dict( + argstr="-dilate_inputs %s", + ), + dilate_results=dict( + argstr="-dilate_results %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_dirs=dict( + argstr="-fill_dirs %s", + requires=["fill_holes"], + ), + fill_holes=dict( + argstr="-fill_holes", + ), + frac=dict( + argstr="-frac %s", + ), + in_file=dict( + argstr="-input %s", + copyfile=False, + mandatory=True, + position=-1, + ), + inter=dict( + argstr="-inter", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -23,8 +54,12 @@ def test_MaskTool_inputs(): name_template="%s_mask", ), outputtype=dict(), - union=dict(argstr="-union",), - verbose=dict(argstr="-verb %s",), + union=dict( + argstr="-union", + ), + verbose=dict( + argstr="-verb %s", + ), ) inputs = MaskTool.input_spec() @@ -34,7 +69,11 @@ def test_MaskTool_inputs(): def test_MaskTool_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MaskTool.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Maskave.py b/nipype/interfaces/afni/tests/test_auto_Maskave.py index b882cfdba9..ce7a07c95e 100644 --- a/nipype/interfaces/afni/tests/test_auto_Maskave.py +++ b/nipype/interfaces/afni/tests/test_auto_Maskave.py @@ -4,13 +4,29 @@ def test_Maskave_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-2, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - mask=dict(argstr="-mask %s", extensions=None, position=1,), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="> %s", extensions=None, @@ -20,7 +36,10 @@ def test_Maskave_inputs(): position=-1, ), outputtype=dict(), - quiet=dict(argstr="-quiet", position=2,), + quiet=dict( + argstr="-quiet", + position=2, + ), ) inputs = Maskave.input_spec() @@ -30,7 +49,11 @@ def test_Maskave_inputs(): def test_Maskave_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Maskave.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Means.py b/nipype/interfaces/afni/tests/test_auto_Means.py index b88957fef3..3aa3ada375 100644 --- a/nipype/interfaces/afni/tests/test_auto_Means.py +++ b/nipype/interfaces/afni/tests/test_auto_Means.py @@ -4,16 +4,43 @@ def test_Means_inputs(): input_map = dict( - args=dict(argstr="%s",), - count=dict(argstr="-count",), - datum=dict(argstr="-datum %s",), - environ=dict(nohash=True, usedefault=True,), - in_file_a=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - in_file_b=dict(argstr="%s", extensions=None, position=-1,), - mask_inter=dict(argstr="-mask_inter",), - mask_union=dict(argstr="-mask_union",), - non_zero=dict(argstr="-non_zero",), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + count=dict( + argstr="-count", + ), + datum=dict( + argstr="-datum %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file_a=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + in_file_b=dict( + argstr="%s", + extensions=None, + position=-1, + ), + mask_inter=dict( + argstr="-mask_inter", + ), + mask_union=dict( + argstr="-mask_union", + ), + non_zero=dict( + argstr="-non_zero", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -21,10 +48,18 @@ def test_Means_inputs(): name_template="%s_mean", ), outputtype=dict(), - scale=dict(argstr="-%sscale",), - sqr=dict(argstr="-sqr",), - std_dev=dict(argstr="-stdev",), - summ=dict(argstr="-sum",), + scale=dict( + argstr="-%sscale", + ), + sqr=dict( + argstr="-sqr", + ), + std_dev=dict( + argstr="-stdev", + ), + summ=dict( + argstr="-sum", + ), ) inputs = Means.input_spec() @@ -34,7 +69,11 @@ def test_Means_inputs(): def test_Means_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Means.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Merge.py b/nipype/interfaces/afni/tests/test_auto_Merge.py index 9ccaf8d4d4..ac974184ea 100644 --- a/nipype/interfaces/afni/tests/test_auto_Merge.py +++ b/nipype/interfaces/afni/tests/test_auto_Merge.py @@ -4,12 +4,30 @@ def test_Merge_inputs(): input_map = dict( - args=dict(argstr="%s",), - blurfwhm=dict(argstr="-1blur_fwhm %d", units="mm",), - doall=dict(argstr="-doall",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="%s", copyfile=False, mandatory=True, position=-1,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + blurfwhm=dict( + argstr="-1blur_fwhm %d", + units="mm", + ), + doall=dict( + argstr="-doall", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="%s", + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -26,7 +44,11 @@ def test_Merge_inputs(): def test_Merge_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Merge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_NetCorr.py b/nipype/interfaces/afni/tests/test_auto_NetCorr.py new file mode 100644 index 0000000000..e613dc13eb --- /dev/null +++ b/nipype/interfaces/afni/tests/test_auto_NetCorr.py @@ -0,0 +1,99 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..preprocess import NetCorr + + +def test_NetCorr_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fish_z=dict( + argstr="-fish_z", + ), + ignore_LT=dict( + argstr="-ignore_LT", + ), + in_file=dict( + argstr="-inset %s", + extensions=None, + mandatory=True, + ), + in_rois=dict( + argstr="-in_rois %s", + extensions=None, + mandatory=True, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + nifti=dict( + argstr="-nifti", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="-prefix %s", + extensions=None, + name_source="in_file", + name_template="%s_netcorr", + position=1, + ), + output_mask_nonnull=dict( + argstr="-output_mask_nonnull", + ), + outputtype=dict(), + part_corr=dict( + argstr="-part_corr", + ), + push_thru_many_zeros=dict( + argstr="-push_thru_many_zeros", + ), + ts_indiv=dict( + argstr="-ts_indiv", + ), + ts_label=dict( + argstr="-ts_label", + ), + ts_out=dict( + argstr="-ts_out", + ), + ts_wb_Z=dict( + argstr="-ts_wb_Z", + ), + ts_wb_corr=dict( + argstr="-ts_wb_corr", + ), + ts_wb_strlabel=dict( + argstr="-ts_wb_strlabel", + ), + weight_ts=dict( + argstr="-weight_ts %s", + extensions=None, + ), + ) + inputs = NetCorr.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_NetCorr_outputs(): + output_map = dict( + out_corr_maps=dict(), + out_corr_matrix=dict( + extensions=None, + ), + ) + outputs = NetCorr.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/afni/tests/test_auto_Notes.py b/nipype/interfaces/afni/tests/test_auto_Notes.py index a51727578d..c83a70f0f2 100644 --- a/nipype/interfaces/afni/tests/test_auto_Notes.py +++ b/nipype/interfaces/afni/tests/test_auto_Notes.py @@ -4,19 +4,46 @@ def test_Notes_inputs(): input_map = dict( - add=dict(argstr='-a "%s"',), - add_history=dict(argstr='-h "%s"', xor=["rep_history"],), - args=dict(argstr="%s",), - delete=dict(argstr="-d %d",), - environ=dict(nohash=True, usedefault=True,), + add=dict( + argstr='-a "%s"', + ), + add_history=dict( + argstr='-h "%s"', + xor=["rep_history"], + ), + args=dict( + argstr="%s", + ), + delete=dict( + argstr="-d %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="%s", + extensions=None, ), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="%s", extensions=None,), outputtype=dict(), - rep_history=dict(argstr='-HH "%s"', xor=["add_history"],), - ses=dict(argstr="-ses",), + rep_history=dict( + argstr='-HH "%s"', + xor=["add_history"], + ), + ses=dict( + argstr="-ses", + ), ) inputs = Notes.input_spec() @@ -26,7 +53,11 @@ def test_Notes_inputs(): def test_Notes_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Notes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_NwarpAdjust.py b/nipype/interfaces/afni/tests/test_auto_NwarpAdjust.py index 265e3720a2..85fb2d3495 100644 --- a/nipype/interfaces/afni/tests/test_auto_NwarpAdjust.py +++ b/nipype/interfaces/afni/tests/test_auto_NwarpAdjust.py @@ -4,10 +4,20 @@ def test_NwarpAdjust_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="-source %s",), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="-source %s", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -17,7 +27,10 @@ def test_NwarpAdjust_inputs(): requires=["in_files"], ), outputtype=dict(), - warps=dict(argstr="-nwarp %s", mandatory=True,), + warps=dict( + argstr="-nwarp %s", + mandatory=True, + ), ) inputs = NwarpAdjust.input_spec() @@ -27,7 +40,11 @@ def test_NwarpAdjust_inputs(): def test_NwarpAdjust_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = NwarpAdjust.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_NwarpApply.py b/nipype/interfaces/afni/tests/test_auto_NwarpApply.py index 727b210c4e..c9ebd2853e 100644 --- a/nipype/interfaces/afni/tests/test_auto_NwarpApply.py +++ b/nipype/interfaces/afni/tests/test_auto_NwarpApply.py @@ -4,23 +4,52 @@ def test_NwarpApply_inputs(): input_map = dict( - ainterp=dict(argstr="-ainterp %s",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-source %s", mandatory=True,), - interp=dict(argstr="-interp %s", usedefault=True,), - inv_warp=dict(argstr="-iwarp",), - master=dict(argstr="-master %s", extensions=None,), + ainterp=dict( + argstr="-ainterp %s", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-source %s", + mandatory=True, + ), + interp=dict( + argstr="-interp %s", + usedefault=True, + ), + inv_warp=dict( + argstr="-iwarp", + ), + master=dict( + argstr="-master %s", + extensions=None, + ), out_file=dict( argstr="-prefix %s", extensions=None, name_source="in_file", name_template="%s_Nwarp", ), - quiet=dict(argstr="-quiet", xor=["verb"],), - short=dict(argstr="-short",), - verb=dict(argstr="-verb", xor=["quiet"],), - warp=dict(argstr="-nwarp %s", mandatory=True,), + quiet=dict( + argstr="-quiet", + xor=["verb"], + ), + short=dict( + argstr="-short", + ), + verb=dict( + argstr="-verb", + xor=["quiet"], + ), + warp=dict( + argstr="-nwarp %s", + mandatory=True, + ), ) inputs = NwarpApply.input_spec() @@ -30,7 +59,11 @@ def test_NwarpApply_inputs(): def test_NwarpApply_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = NwarpApply.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_NwarpCat.py b/nipype/interfaces/afni/tests/test_auto_NwarpCat.py index 82b1e6a125..b89aade9b0 100644 --- a/nipype/interfaces/afni/tests/test_auto_NwarpCat.py +++ b/nipype/interfaces/afni/tests/test_auto_NwarpCat.py @@ -4,13 +4,32 @@ def test_NwarpCat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - expad=dict(argstr="-expad %d",), - in_files=dict(argstr="%s", mandatory=True, position=-1,), - interp=dict(argstr="-interp %s", usedefault=True,), - inv_warp=dict(argstr="-iwarp",), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expad=dict( + argstr="-expad %d", + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-1, + ), + interp=dict( + argstr="-interp %s", + usedefault=True, + ), + inv_warp=dict( + argstr="-iwarp", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -18,8 +37,12 @@ def test_NwarpCat_inputs(): name_template="%s_NwarpCat", ), outputtype=dict(), - space=dict(argstr="-space %s",), - verb=dict(argstr="-verb",), + space=dict( + argstr="-space %s", + ), + verb=dict( + argstr="-verb", + ), ) inputs = NwarpCat.input_spec() @@ -29,7 +52,11 @@ def test_NwarpCat_inputs(): def test_NwarpCat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = NwarpCat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_OneDToolPy.py b/nipype/interfaces/afni/tests/test_auto_OneDToolPy.py index e9ae2472be..bb47517e27 100644 --- a/nipype/interfaces/afni/tests/test_auto_OneDToolPy.py +++ b/nipype/interfaces/afni/tests/test_auto_OneDToolPy.py @@ -4,29 +4,60 @@ def test_OneDToolPy_inputs(): input_map = dict( - args=dict(argstr="%s",), - censor_motion=dict(argstr="-censor_motion %f %s",), - censor_prev_TR=dict(argstr="-censor_prev_TR",), - demean=dict(argstr="-demean",), - derivative=dict(argstr="-derivative",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-infile %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + censor_motion=dict( + argstr="-censor_motion %f %s", + ), + censor_prev_TR=dict( + argstr="-censor_prev_TR", + ), + demean=dict( + argstr="-demean", + ), + derivative=dict( + argstr="-derivative", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-infile %s", + extensions=None, + mandatory=True, + ), out_file=dict( - argstr="-write %s", extensions=None, xor=["show_cormat_warnings"], + argstr="-write %s", + extensions=None, + xor=["show_cormat_warnings"], ), outputtype=dict(), - py27_path=dict(usedefault=True,), - set_nruns=dict(argstr="-set_nruns %d",), - show_censor_count=dict(argstr="-show_censor_count",), + py27_path=dict( + usedefault=True, + ), + set_nruns=dict( + argstr="-set_nruns %d", + ), + show_censor_count=dict( + argstr="-show_censor_count", + ), show_cormat_warnings=dict( argstr="-show_cormat_warnings |& tee %s", extensions=None, position=-1, xor=["out_file"], ), - show_indices_interest=dict(argstr="-show_indices_interest",), - show_trs_run=dict(argstr="-show_trs_run %d",), - show_trs_uncensored=dict(argstr="-show_trs_uncensored %s",), + show_indices_interest=dict( + argstr="-show_indices_interest", + ), + show_trs_run=dict( + argstr="-show_trs_run %d", + ), + show_trs_uncensored=dict( + argstr="-show_trs_uncensored %s", + ), ) inputs = OneDToolPy.input_spec() @@ -36,7 +67,11 @@ def test_OneDToolPy_inputs(): def test_OneDToolPy_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = OneDToolPy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_OutlierCount.py b/nipype/interfaces/afni/tests/test_auto_OutlierCount.py index 3b90e076d7..511c1ca8f2 100644 --- a/nipype/interfaces/afni/tests/test_auto_OutlierCount.py +++ b/nipype/interfaces/afni/tests/test_auto_OutlierCount.py @@ -4,15 +4,46 @@ def test_OutlierCount_inputs(): input_map = dict( - args=dict(argstr="%s",), - autoclip=dict(argstr="-autoclip", usedefault=True, xor=["mask"],), - automask=dict(argstr="-automask", usedefault=True, xor=["mask"],), - environ=dict(nohash=True, usedefault=True,), - fraction=dict(argstr="-fraction", usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - interval=dict(argstr="-range", usedefault=True,), - legendre=dict(argstr="-legendre", usedefault=True,), - mask=dict(argstr="-mask %s", extensions=None, xor=["autoclip", "automask"],), + args=dict( + argstr="%s", + ), + autoclip=dict( + argstr="-autoclip", + usedefault=True, + xor=["mask"], + ), + automask=dict( + argstr="-automask", + usedefault=True, + xor=["mask"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fraction=dict( + argstr="-fraction", + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + interval=dict( + argstr="-range", + usedefault=True, + ), + legendre=dict( + argstr="-legendre", + usedefault=True, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + xor=["autoclip", "automask"], + ), out_file=dict( extensions=None, keep_extension=False, @@ -27,9 +58,16 @@ def test_OutlierCount_inputs(): name_template="%s_outliers", output_name="out_outliers", ), - polort=dict(argstr="-polort %d",), - qthr=dict(argstr="-qthr %.5f", usedefault=True,), - save_outliers=dict(usedefault=True,), + polort=dict( + argstr="-polort %d", + ), + qthr=dict( + argstr="-qthr %.5f", + usedefault=True, + ), + save_outliers=dict( + usedefault=True, + ), ) inputs = OutlierCount.input_spec() @@ -40,7 +78,12 @@ def test_OutlierCount_inputs(): def test_OutlierCount_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_outliers=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_outliers=dict( + extensions=None, + ), ) outputs = OutlierCount.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_QualityIndex.py b/nipype/interfaces/afni/tests/test_auto_QualityIndex.py index 359743b19f..c759be87a4 100644 --- a/nipype/interfaces/afni/tests/test_auto_QualityIndex.py +++ b/nipype/interfaces/afni/tests/test_auto_QualityIndex.py @@ -4,14 +4,41 @@ def test_QualityIndex_inputs(): input_map = dict( - args=dict(argstr="%s",), - autoclip=dict(argstr="-autoclip", usedefault=True, xor=["mask"],), - automask=dict(argstr="-automask", usedefault=True, xor=["mask"],), - clip=dict(argstr="-clip %f",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - interval=dict(argstr="-range", usedefault=True,), - mask=dict(argstr="-mask %s", extensions=None, xor=["autoclip", "automask"],), + args=dict( + argstr="%s", + ), + autoclip=dict( + argstr="-autoclip", + usedefault=True, + xor=["mask"], + ), + automask=dict( + argstr="-automask", + usedefault=True, + xor=["mask"], + ), + clip=dict( + argstr="-clip %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + interval=dict( + argstr="-range", + usedefault=True, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + xor=["autoclip", "automask"], + ), out_file=dict( argstr="> %s", extensions=None, @@ -20,8 +47,14 @@ def test_QualityIndex_inputs(): name_template="%s_tqual", position=-1, ), - quadrant=dict(argstr="-quadrant", usedefault=True,), - spearman=dict(argstr="-spearman", usedefault=True,), + quadrant=dict( + argstr="-quadrant", + usedefault=True, + ), + spearman=dict( + argstr="-spearman", + usedefault=True, + ), ) inputs = QualityIndex.input_spec() @@ -31,7 +64,11 @@ def test_QualityIndex_inputs(): def test_QualityIndex_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = QualityIndex.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Qwarp.py b/nipype/interfaces/afni/tests/test_auto_Qwarp.py index e8659ec4c3..01b7e32e17 100644 --- a/nipype/interfaces/afni/tests/test_auto_Qwarp.py +++ b/nipype/interfaces/afni/tests/test_auto_Qwarp.py @@ -4,74 +4,202 @@ def test_Qwarp_inputs(): input_map = dict( - Qfinal=dict(argstr="-Qfinal",), - Qonly=dict(argstr="-Qonly",), - allineate=dict(argstr="-allineate",), - allineate_opts=dict(argstr="-allineate_opts %s", requires=["allineate"],), - allsave=dict(argstr="-allsave", xor=["nopadWARP", "duplo", "plusminus"],), - args=dict(argstr="%s",), - ballopt=dict(argstr="-ballopt", xor=["workhard", "boxopt"],), + Qfinal=dict( + argstr="-Qfinal", + ), + Qonly=dict( + argstr="-Qonly", + ), + allineate=dict( + argstr="-allineate", + ), + allineate_opts=dict( + argstr="-allineate_opts %s", + requires=["allineate"], + ), + allsave=dict( + argstr="-allsave", + xor=["nopadWARP", "duplo", "plusminus"], + ), + args=dict( + argstr="%s", + ), + ballopt=dict( + argstr="-ballopt", + xor=["workhard", "boxopt"], + ), + bandpass=dict( + argstr="-bpass %f %f", + ), base_file=dict( - argstr="-base %s", copyfile=False, extensions=None, mandatory=True, + argstr="-base %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + baxopt=dict( + argstr="-boxopt", + xor=["workhard", "ballopt"], + ), + blur=dict( + argstr="-blur %s", ), - baxopt=dict(argstr="-boxopt", xor=["workhard", "ballopt"],), - blur=dict(argstr="-blur %s",), duplo=dict( argstr="-duplo", xor=["gridlist", "maxlev", "inilev", "iniwarp", "plusminus", "allsave"], ), - emask=dict(argstr="-emask %s", copyfile=False, extensions=None,), - environ=dict(nohash=True, usedefault=True,), - expad=dict(argstr="-expad %d", xor=["nopadWARP"],), + emask=dict( + argstr="-emask %s", + copyfile=False, + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expad=dict( + argstr="-expad %d", + xor=["nopadWARP"], + ), gridlist=dict( argstr="-gridlist %s", copyfile=False, extensions=None, xor=["duplo", "plusminus"], ), - hel=dict(argstr="-hel", xor=["nmi", "mi", "lpc", "lpa", "pear"],), + hel=dict( + argstr="-hel", + xor=["nmi", "mi", "lpc", "lpa", "pear"], + ), in_file=dict( - argstr="-source %s", copyfile=False, extensions=None, mandatory=True, - ), - inilev=dict(argstr="-inilev %d", xor=["duplo"],), - iniwarp=dict(argstr="-iniwarp %s", xor=["duplo"],), - iwarp=dict(argstr="-iwarp", xor=["plusminus"],), - lpa=dict(argstr="-lpa", xor=["nmi", "mi", "lpc", "hel", "pear"],), - lpc=dict(argstr="-lpc", position=-2, xor=["nmi", "mi", "hel", "lpa", "pear"],), - maxlev=dict(argstr="-maxlev %d", position=-1, xor=["duplo"],), - mi=dict(argstr="-mi", xor=["mi", "hel", "lpc", "lpa", "pear"],), - minpatch=dict(argstr="-minpatch %d",), - nmi=dict(argstr="-nmi", xor=["nmi", "hel", "lpc", "lpa", "pear"],), - noXdis=dict(argstr="-noXdis",), - noYdis=dict(argstr="-noYdis",), - noZdis=dict(argstr="-noZdis",), - noneg=dict(argstr="-noneg",), - nopad=dict(argstr="-nopad",), - nopadWARP=dict(argstr="-nopadWARP", xor=["allsave", "expad"],), - nopenalty=dict(argstr="-nopenalty",), - nowarp=dict(argstr="-nowarp",), - noweight=dict(argstr="-noweight",), - num_threads=dict(nohash=True, usedefault=True,), + argstr="-source %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + inilev=dict( + argstr="-inilev %d", + xor=["duplo"], + ), + iniwarp=dict( + argstr="-iniwarp %s", + xor=["duplo"], + ), + iwarp=dict( + argstr="-iwarp", + xor=["plusminus"], + ), + lpa=dict( + argstr="-lpa", + xor=["nmi", "mi", "lpc", "hel", "pear"], + ), + lpc=dict( + argstr="-lpc", + position=-2, + xor=["nmi", "mi", "hel", "lpa", "pear"], + ), + maxlev=dict( + argstr="-maxlev %d", + position=-1, + xor=["duplo"], + ), + mi=dict( + argstr="-mi", + xor=["mi", "hel", "lpc", "lpa", "pear"], + ), + minpatch=dict( + argstr="-minpatch %d", + ), + nmi=dict( + argstr="-nmi", + xor=["nmi", "hel", "lpc", "lpa", "pear"], + ), + noXdis=dict( + argstr="-noXdis", + ), + noYdis=dict( + argstr="-noYdis", + ), + noZdis=dict( + argstr="-noZdis", + ), + noneg=dict( + argstr="-noneg", + ), + nopad=dict( + argstr="-nopad", + ), + nopadWARP=dict( + argstr="-nopadWARP", + xor=["allsave", "expad"], + ), + nopenalty=dict( + argstr="-nopenalty", + ), + nowarp=dict( + argstr="-nowarp", + ), + noweight=dict( + argstr="-noweight", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, name_source=["in_file"], name_template="ppp_%s", ), - out_weight_file=dict(argstr="-wtprefix %s", extensions=None,), + out_weight_file=dict( + argstr="-wtprefix %s", + extensions=None, + ), outputtype=dict(), - overwrite=dict(argstr="-overwrite",), - pblur=dict(argstr="-pblur %s",), - pear=dict(argstr="-pear",), - penfac=dict(argstr="-penfac %f",), - plusminus=dict(argstr="-plusminus", xor=["duplo", "allsave", "iwarp"],), - quiet=dict(argstr="-quiet", xor=["verb"],), - resample=dict(argstr="-resample",), - verb=dict(argstr="-verb", xor=["quiet"],), - wball=dict(argstr="-wball %s", xor=["wmask"],), - weight=dict(argstr="-weight %s", extensions=None,), - wmask=dict(argstr="-wpass %s %f", xor=["wball"],), - workhard=dict(argstr="-workhard", xor=["boxopt", "ballopt"],), + overwrite=dict( + argstr="-overwrite", + ), + pblur=dict( + argstr="-pblur %s", + ), + pear=dict( + argstr="-pear", + ), + penfac=dict( + argstr="-penfac %f", + ), + plusminus=dict( + argstr="-plusminus", + xor=["duplo", "allsave", "iwarp"], + ), + quiet=dict( + argstr="-quiet", + xor=["verb"], + ), + resample=dict( + argstr="-resample", + ), + verb=dict( + argstr="-verb", + xor=["quiet"], + ), + wball=dict( + argstr="-wball %s", + xor=["wmask"], + ), + weight=dict( + argstr="-weight %s", + extensions=None, + ), + wmask=dict( + argstr="-wpass %s %f", + xor=["wball"], + ), + workhard=dict( + argstr="-workhard", + xor=["boxopt", "ballopt"], + ), ) inputs = Qwarp.input_spec() @@ -82,11 +210,21 @@ def test_Qwarp_inputs(): def test_Qwarp_outputs(): output_map = dict( - base_warp=dict(extensions=None,), - source_warp=dict(extensions=None,), - warped_base=dict(extensions=None,), - warped_source=dict(extensions=None,), - weights=dict(extensions=None,), + base_warp=dict( + extensions=None, + ), + source_warp=dict( + extensions=None, + ), + warped_base=dict( + extensions=None, + ), + warped_source=dict( + extensions=None, + ), + weights=dict( + extensions=None, + ), ) outputs = Qwarp.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_QwarpPlusMinus.py b/nipype/interfaces/afni/tests/test_auto_QwarpPlusMinus.py index c74e192b8f..7e89576a3f 100644 --- a/nipype/interfaces/afni/tests/test_auto_QwarpPlusMinus.py +++ b/nipype/interfaces/afni/tests/test_auto_QwarpPlusMinus.py @@ -4,71 +4,184 @@ def test_QwarpPlusMinus_inputs(): input_map = dict( - Qfinal=dict(argstr="-Qfinal",), - Qonly=dict(argstr="-Qonly",), - allineate=dict(argstr="-allineate",), - allineate_opts=dict(argstr="-allineate_opts %s", requires=["allineate"],), - allsave=dict(argstr="-allsave", xor=["nopadWARP", "duplo", "plusminus"],), - args=dict(argstr="%s",), - ballopt=dict(argstr="-ballopt", xor=["workhard", "boxopt"],), + Qfinal=dict( + argstr="-Qfinal", + ), + Qonly=dict( + argstr="-Qonly", + ), + allineate=dict( + argstr="-allineate", + ), + allineate_opts=dict( + argstr="-allineate_opts %s", + requires=["allineate"], + ), + allsave=dict( + argstr="-allsave", + xor=["nopadWARP", "duplo", "plusminus"], + ), + args=dict( + argstr="%s", + ), + ballopt=dict( + argstr="-ballopt", + xor=["workhard", "boxopt"], + ), + bandpass=dict( + argstr="-bpass %f %f", + ), base_file=dict( - argstr="-base %s", copyfile=False, extensions=None, mandatory=True, + argstr="-base %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + baxopt=dict( + argstr="-boxopt", + xor=["workhard", "ballopt"], + ), + blur=dict( + argstr="-blur %s", ), - baxopt=dict(argstr="-boxopt", xor=["workhard", "ballopt"],), - blur=dict(argstr="-blur %s",), duplo=dict( argstr="-duplo", xor=["gridlist", "maxlev", "inilev", "iniwarp", "plusminus", "allsave"], ), - emask=dict(argstr="-emask %s", copyfile=False, extensions=None,), - environ=dict(nohash=True, usedefault=True,), - expad=dict(argstr="-expad %d", xor=["nopadWARP"],), + emask=dict( + argstr="-emask %s", + copyfile=False, + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expad=dict( + argstr="-expad %d", + xor=["nopadWARP"], + ), gridlist=dict( argstr="-gridlist %s", copyfile=False, extensions=None, xor=["duplo", "plusminus"], ), - hel=dict(argstr="-hel", xor=["nmi", "mi", "lpc", "lpa", "pear"],), + hel=dict( + argstr="-hel", + xor=["nmi", "mi", "lpc", "lpa", "pear"], + ), in_file=dict( - argstr="-source %s", copyfile=False, extensions=None, mandatory=True, - ), - inilev=dict(argstr="-inilev %d", xor=["duplo"],), - iniwarp=dict(argstr="-iniwarp %s", xor=["duplo"],), - iwarp=dict(argstr="-iwarp", xor=["plusminus"],), - lpa=dict(argstr="-lpa", xor=["nmi", "mi", "lpc", "hel", "pear"],), - lpc=dict(argstr="-lpc", position=-2, xor=["nmi", "mi", "hel", "lpa", "pear"],), - maxlev=dict(argstr="-maxlev %d", position=-1, xor=["duplo"],), - mi=dict(argstr="-mi", xor=["mi", "hel", "lpc", "lpa", "pear"],), - minpatch=dict(argstr="-minpatch %d",), - nmi=dict(argstr="-nmi", xor=["nmi", "hel", "lpc", "lpa", "pear"],), - noXdis=dict(argstr="-noXdis",), - noYdis=dict(argstr="-noYdis",), - noZdis=dict(argstr="-noZdis",), - noneg=dict(argstr="-noneg",), - nopad=dict(argstr="-nopad",), - nopadWARP=dict(argstr="-nopadWARP", xor=["allsave", "expad"],), - nopenalty=dict(argstr="-nopenalty",), - nowarp=dict(argstr="-nowarp",), - noweight=dict(argstr="-noweight",), - num_threads=dict(nohash=True, usedefault=True,), + argstr="-source %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + inilev=dict( + argstr="-inilev %d", + xor=["duplo"], + ), + iniwarp=dict( + argstr="-iniwarp %s", + xor=["duplo"], + ), + iwarp=dict( + argstr="-iwarp", + xor=["plusminus"], + ), + lpa=dict( + argstr="-lpa", + xor=["nmi", "mi", "lpc", "hel", "pear"], + ), + lpc=dict( + argstr="-lpc", + position=-2, + xor=["nmi", "mi", "hel", "lpa", "pear"], + ), + maxlev=dict( + argstr="-maxlev %d", + position=-1, + xor=["duplo"], + ), + mi=dict( + argstr="-mi", + xor=["mi", "hel", "lpc", "lpa", "pear"], + ), + minpatch=dict( + argstr="-minpatch %d", + ), + nmi=dict( + argstr="-nmi", + xor=["nmi", "hel", "lpc", "lpa", "pear"], + ), + noXdis=dict( + argstr="-noXdis", + ), + noYdis=dict( + argstr="-noYdis", + ), + noZdis=dict( + argstr="-noZdis", + ), + noneg=dict( + argstr="-noneg", + ), + nopad=dict( + argstr="-nopad", + ), + nopadWARP=dict( + argstr="-nopadWARP", + xor=["allsave", "expad"], + ), + nopenalty=dict( + argstr="-nopenalty", + ), + nowarp=dict( + argstr="-nowarp", + ), + noweight=dict( + argstr="-noweight", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( - argstr="-prefix %s", extensions=None, position=0, usedefault=True, + argstr="-prefix %s", + extensions=None, + position=0, + usedefault=True, + ), + out_weight_file=dict( + argstr="-wtprefix %s", + extensions=None, ), - out_weight_file=dict(argstr="-wtprefix %s", extensions=None,), outputtype=dict(), - overwrite=dict(argstr="-overwrite",), - pblur=dict(argstr="-pblur %s",), - pear=dict(argstr="-pear",), - penfac=dict(argstr="-penfac %f",), + overwrite=dict( + argstr="-overwrite", + ), + pblur=dict( + argstr="-pblur %s", + ), + pear=dict( + argstr="-pear", + ), + penfac=dict( + argstr="-penfac %f", + ), plusminus=dict( argstr="-plusminus", position=1, usedefault=True, xor=["duplo", "allsave", "iwarp"], ), - quiet=dict(argstr="-quiet", xor=["verb"],), - resample=dict(argstr="-resample",), + quiet=dict( + argstr="-quiet", + xor=["verb"], + ), + resample=dict( + argstr="-resample", + ), source_file=dict( argstr="-source %s", copyfile=False, @@ -76,11 +189,26 @@ def test_QwarpPlusMinus_inputs(): extensions=None, new_name="in_file", ), - verb=dict(argstr="-verb", xor=["quiet"],), - wball=dict(argstr="-wball %s", xor=["wmask"],), - weight=dict(argstr="-weight %s", extensions=None,), - wmask=dict(argstr="-wpass %s %f", xor=["wball"],), - workhard=dict(argstr="-workhard", xor=["boxopt", "ballopt"],), + verb=dict( + argstr="-verb", + xor=["quiet"], + ), + wball=dict( + argstr="-wball %s", + xor=["wmask"], + ), + weight=dict( + argstr="-weight %s", + extensions=None, + ), + wmask=dict( + argstr="-wpass %s %f", + xor=["wball"], + ), + workhard=dict( + argstr="-workhard", + xor=["boxopt", "ballopt"], + ), ) inputs = QwarpPlusMinus.input_spec() @@ -91,11 +219,21 @@ def test_QwarpPlusMinus_inputs(): def test_QwarpPlusMinus_outputs(): output_map = dict( - base_warp=dict(extensions=None,), - source_warp=dict(extensions=None,), - warped_base=dict(extensions=None,), - warped_source=dict(extensions=None,), - weights=dict(extensions=None,), + base_warp=dict( + extensions=None, + ), + source_warp=dict( + extensions=None, + ), + warped_base=dict( + extensions=None, + ), + warped_source=dict( + extensions=None, + ), + weights=dict( + extensions=None, + ), ) outputs = QwarpPlusMinus.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_ROIStats.py b/nipype/interfaces/afni/tests/test_auto_ROIStats.py index 026e3ff076..36e7546990 100644 --- a/nipype/interfaces/afni/tests/test_auto_ROIStats.py +++ b/nipype/interfaces/afni/tests/test_auto_ROIStats.py @@ -4,12 +4,30 @@ def test_ROIStats_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug",), - environ=dict(nohash=True, usedefault=True,), - format1D=dict(argstr="-1Dformat", xor=["format1DR"],), - format1DR=dict(argstr="-1DRformat", xor=["format1D"],), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + format1D=dict( + argstr="-1Dformat", + xor=["format1DR"], + ), + format1DR=dict( + argstr="-1DRformat", + xor=["format1D"], + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), mask=dict( argstr="-mask %s", deprecated="1.1.4", @@ -17,11 +35,22 @@ def test_ROIStats_inputs(): new_name="mask_file", position=3, ), - mask_f2short=dict(argstr="-mask_f2short",), - mask_file=dict(argstr="-mask %s", extensions=None,), - nobriklab=dict(argstr="-nobriklab",), - nomeanout=dict(argstr="-nomeanout",), - num_roi=dict(argstr="-numroi %s",), + mask_f2short=dict( + argstr="-mask_f2short", + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + nobriklab=dict( + argstr="-nobriklab", + ), + nomeanout=dict( + argstr="-nomeanout", + ), + num_roi=dict( + argstr="-numroi %s", + ), out_file=dict( argstr="> %s", extensions=None, @@ -30,10 +59,20 @@ def test_ROIStats_inputs(): name_template="%s_roistat.1D", position=-1, ), - quiet=dict(argstr="-quiet",), - roisel=dict(argstr="-roisel %s", extensions=None,), - stat=dict(argstr="%s...",), - zerofill=dict(argstr="-zerofill %s", requires=["num_roi"],), + quiet=dict( + argstr="-quiet", + ), + roisel=dict( + argstr="-roisel %s", + extensions=None, + ), + stat=dict( + argstr="%s...", + ), + zerofill=dict( + argstr="-zerofill %s", + requires=["num_roi"], + ), ) inputs = ROIStats.input_spec() @@ -43,7 +82,11 @@ def test_ROIStats_inputs(): def test_ROIStats_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ROIStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_ReHo.py b/nipype/interfaces/afni/tests/test_auto_ReHo.py index 1200399a1d..f9a1993ce1 100644 --- a/nipype/interfaces/afni/tests/test_auto_ReHo.py +++ b/nipype/interfaces/afni/tests/test_auto_ReHo.py @@ -4,17 +4,38 @@ def test_ReHo_inputs(): input_map = dict( - args=dict(argstr="%s",), - chi_sq=dict(argstr="-chi_sq",), + args=dict( + argstr="%s", + ), + chi_sq=dict( + argstr="-chi_sq", + ), ellipsoid=dict( argstr="-neigh_X %s -neigh_Y %s -neigh_Z %s", xor=["sphere", "neighborhood"], ), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-inset %s", extensions=None, mandatory=True, position=1,), - label_set=dict(argstr="-in_rois %s", extensions=None,), - mask_file=dict(argstr="-mask %s", extensions=None,), - neighborhood=dict(argstr="-nneigh %s", xor=["sphere", "ellipsoid"],), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-inset %s", + extensions=None, + mandatory=True, + position=1, + ), + label_set=dict( + argstr="-in_rois %s", + extensions=None, + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + neighborhood=dict( + argstr="-nneigh %s", + xor=["sphere", "ellipsoid"], + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -23,8 +44,13 @@ def test_ReHo_inputs(): name_template="%s_reho", position=0, ), - overwrite=dict(argstr="-overwrite",), - sphere=dict(argstr="-neigh_RAD %s", xor=["neighborhood", "ellipsoid"],), + overwrite=dict( + argstr="-overwrite", + ), + sphere=dict( + argstr="-neigh_RAD %s", + xor=["neighborhood", "ellipsoid"], + ), ) inputs = ReHo.input_spec() @@ -34,7 +60,14 @@ def test_ReHo_inputs(): def test_ReHo_outputs(): - output_map = dict(out_file=dict(extensions=None,), out_vals=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + out_vals=dict( + extensions=None, + ), + ) outputs = ReHo.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Refit.py b/nipype/interfaces/afni/tests/test_auto_Refit.py index 65952d85fa..205f7e0190 100644 --- a/nipype/interfaces/afni/tests/test_auto_Refit.py +++ b/nipype/interfaces/afni/tests/test_auto_Refit.py @@ -4,27 +4,69 @@ def test_Refit_inputs(): input_map = dict( - args=dict(argstr="%s",), - atrcopy=dict(argstr="-atrcopy %s %s",), - atrfloat=dict(argstr="-atrfloat %s %s",), - atrint=dict(argstr="-atrint %s %s",), - atrstring=dict(argstr="-atrstring %s %s",), - deoblique=dict(argstr="-deoblique",), - duporigin_file=dict(argstr="-duporigin %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + atrcopy=dict( + argstr="-atrcopy %s %s", + ), + atrfloat=dict( + argstr="-atrfloat %s %s", + ), + atrint=dict( + argstr="-atrint %s %s", + ), + atrstring=dict( + argstr="-atrstring %s %s", + ), + deoblique=dict( + argstr="-deoblique", + ), + duporigin_file=dict( + argstr="-duporigin %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=-1, - ), - nosaveatr=dict(argstr="-nosaveatr",), - saveatr=dict(argstr="-saveatr",), - space=dict(argstr="-space %s",), - xdel=dict(argstr="-xdel %f",), - xorigin=dict(argstr="-xorigin %s",), - xyzscale=dict(argstr="-xyzscale %f",), - ydel=dict(argstr="-ydel %f",), - yorigin=dict(argstr="-yorigin %s",), - zdel=dict(argstr="-zdel %f",), - zorigin=dict(argstr="-zorigin %s",), + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=-1, + ), + nosaveatr=dict( + argstr="-nosaveatr", + ), + saveatr=dict( + argstr="-saveatr", + ), + space=dict( + argstr="-space %s", + ), + xdel=dict( + argstr="-xdel %f", + ), + xorigin=dict( + argstr="-xorigin %s", + ), + xyzscale=dict( + argstr="-xyzscale %f", + ), + ydel=dict( + argstr="-ydel %f", + ), + yorigin=dict( + argstr="-yorigin %s", + ), + zdel=dict( + argstr="-zdel %f", + ), + zorigin=dict( + argstr="-zorigin %s", + ), ) inputs = Refit.input_spec() @@ -34,7 +76,11 @@ def test_Refit_inputs(): def test_Refit_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Refit.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Remlfit.py b/nipype/interfaces/afni/tests/test_auto_Remlfit.py index 3040c1f48e..cfffeeb40e 100644 --- a/nipype/interfaces/afni/tests/test_auto_Remlfit.py +++ b/nipype/interfaces/afni/tests/test_auto_Remlfit.py @@ -4,46 +4,156 @@ def test_Remlfit_inputs(): input_map = dict( - STATmask=dict(argstr="-STATmask %s", extensions=None,), - addbase=dict(argstr="-addbase %s", copyfile=False, sep=" ",), - args=dict(argstr="%s",), - automask=dict(argstr="-automask", usedefault=True,), - dsort=dict(argstr="-dsort %s", copyfile=False, extensions=None,), - dsort_nods=dict(argstr="-dsort_nods", requires=["dsort"],), - environ=dict(nohash=True, usedefault=True,), - errts_file=dict(argstr="-Rerrts %s", extensions=None,), - fitts_file=dict(argstr="-Rfitts %s", extensions=None,), - fout=dict(argstr="-fout",), - glt_file=dict(argstr="-Rglt %s", extensions=None,), - gltsym=dict(argstr='-gltsym "%s" %s...',), - goforit=dict(argstr="-GOFORIT",), - in_files=dict(argstr='-input "%s"', copyfile=False, mandatory=True, sep=" ",), - mask=dict(argstr="-mask %s", extensions=None,), - matim=dict(argstr="-matim %s", extensions=None, xor=["matrix"],), - matrix=dict(argstr="-matrix %s", extensions=None, mandatory=True,), - nobout=dict(argstr="-nobout",), - nodmbase=dict(argstr="-nodmbase", requires=["addbase", "dsort"],), - nofdr=dict(argstr="-noFDR",), - num_threads=dict(nohash=True, usedefault=True,), - obeta=dict(argstr="-Obeta %s", extensions=None,), - obuck=dict(argstr="-Obuck %s", extensions=None,), - oerrts=dict(argstr="-Oerrts %s", extensions=None,), - ofitts=dict(argstr="-Ofitts %s", extensions=None,), - oglt=dict(argstr="-Oglt %s", extensions=None,), - out_file=dict(argstr="-Rbuck %s", extensions=None,), + STATmask=dict( + argstr="-STATmask %s", + extensions=None, + ), + addbase=dict( + argstr="-addbase %s", + copyfile=False, + sep=" ", + ), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + usedefault=True, + ), + dsort=dict( + argstr="-dsort %s", + copyfile=False, + extensions=None, + ), + dsort_nods=dict( + argstr="-dsort_nods", + requires=["dsort"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + errts_file=dict( + argstr="-Rerrts %s", + extensions=None, + ), + fitts_file=dict( + argstr="-Rfitts %s", + extensions=None, + ), + fout=dict( + argstr="-fout", + ), + glt_file=dict( + argstr="-Rglt %s", + extensions=None, + ), + gltsym=dict( + argstr='-gltsym "%s" %s...', + ), + goforit=dict( + argstr="-GOFORIT", + ), + in_files=dict( + argstr='-input "%s"', + copyfile=False, + mandatory=True, + sep=" ", + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + matim=dict( + argstr="-matim %s", + extensions=None, + xor=["matrix"], + ), + matrix=dict( + argstr="-matrix %s", + extensions=None, + mandatory=True, + ), + nobout=dict( + argstr="-nobout", + ), + nodmbase=dict( + argstr="-nodmbase", + requires=["addbase", "dsort"], + ), + nofdr=dict( + argstr="-noFDR", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + obeta=dict( + argstr="-Obeta %s", + extensions=None, + ), + obuck=dict( + argstr="-Obuck %s", + extensions=None, + ), + oerrts=dict( + argstr="-Oerrts %s", + extensions=None, + ), + ofitts=dict( + argstr="-Ofitts %s", + extensions=None, + ), + oglt=dict( + argstr="-Oglt %s", + extensions=None, + ), + out_file=dict( + argstr="-Rbuck %s", + extensions=None, + ), outputtype=dict(), - ovar=dict(argstr="-Ovar %s", extensions=None,), - polort=dict(argstr="-polort %d", xor=["matrix"],), - quiet=dict(argstr="-quiet",), - rbeta_file=dict(argstr="-Rbeta %s", extensions=None,), - rout=dict(argstr="-rout",), - slibase=dict(argstr="-slibase %s",), - slibase_sm=dict(argstr="-slibase_sm %s",), - tout=dict(argstr="-tout",), - usetemp=dict(argstr="-usetemp",), - var_file=dict(argstr="-Rvar %s", extensions=None,), - verb=dict(argstr="-verb",), - wherr_file=dict(argstr="-Rwherr %s", extensions=None,), + ovar=dict( + argstr="-Ovar %s", + extensions=None, + ), + polort=dict( + argstr="-polort %d", + xor=["matrix"], + ), + quiet=dict( + argstr="-quiet", + ), + rbeta_file=dict( + argstr="-Rbeta %s", + extensions=None, + ), + rout=dict( + argstr="-rout", + ), + slibase=dict( + argstr="-slibase %s", + ), + slibase_sm=dict( + argstr="-slibase_sm %s", + ), + tout=dict( + argstr="-tout", + ), + usetemp=dict( + argstr="-usetemp", + ), + var_file=dict( + argstr="-Rvar %s", + extensions=None, + ), + verb=dict( + argstr="-verb", + ), + wherr_file=dict( + argstr="-Rwherr %s", + extensions=None, + ), ) inputs = Remlfit.input_spec() @@ -54,19 +164,45 @@ def test_Remlfit_inputs(): def test_Remlfit_outputs(): output_map = dict( - errts_file=dict(extensions=None,), - fitts_file=dict(extensions=None,), - glt_file=dict(extensions=None,), - obeta=dict(extensions=None,), - obuck=dict(extensions=None,), - oerrts=dict(extensions=None,), - ofitts=dict(extensions=None,), - oglt=dict(extensions=None,), - out_file=dict(extensions=None,), - ovar=dict(extensions=None,), - rbeta_file=dict(extensions=None,), - var_file=dict(extensions=None,), - wherr_file=dict(extensions=None,), + errts_file=dict( + extensions=None, + ), + fitts_file=dict( + extensions=None, + ), + glt_file=dict( + extensions=None, + ), + obeta=dict( + extensions=None, + ), + obuck=dict( + extensions=None, + ), + oerrts=dict( + extensions=None, + ), + ofitts=dict( + extensions=None, + ), + oglt=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + ovar=dict( + extensions=None, + ), + rbeta_file=dict( + extensions=None, + ), + var_file=dict( + extensions=None, + ), + wherr_file=dict( + extensions=None, + ), ) outputs = Remlfit.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Resample.py b/nipype/interfaces/afni/tests/test_auto_Resample.py index 3053112816..792c03aa9f 100644 --- a/nipype/interfaces/afni/tests/test_auto_Resample.py +++ b/nipype/interfaces/afni/tests/test_auto_Resample.py @@ -4,8 +4,13 @@ def test_Resample_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( argstr="-inset %s", copyfile=False, @@ -13,9 +18,17 @@ def test_Resample_inputs(): mandatory=True, position=-1, ), - master=dict(argstr="-master %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), - orientation=dict(argstr="-orient %s",), + master=dict( + argstr="-master %s", + extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + orientation=dict( + argstr="-orient %s", + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -23,8 +36,12 @@ def test_Resample_inputs(): name_template="%s_resample", ), outputtype=dict(), - resample_mode=dict(argstr="-rmode %s",), - voxel_size=dict(argstr="-dxyz %f %f %f",), + resample_mode=dict( + argstr="-rmode %s", + ), + voxel_size=dict( + argstr="-dxyz %f %f %f", + ), ) inputs = Resample.input_spec() @@ -34,7 +51,11 @@ def test_Resample_inputs(): def test_Resample_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Resample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Retroicor.py b/nipype/interfaces/afni/tests/test_auto_Retroicor.py index 9c95116d09..03039a291f 100644 --- a/nipype/interfaces/afni/tests/test_auto_Retroicor.py +++ b/nipype/interfaces/afni/tests/test_auto_Retroicor.py @@ -4,17 +4,39 @@ def test_Retroicor_inputs(): input_map = dict( - args=dict(argstr="%s",), - card=dict(argstr="-card %s", extensions=None, position=-2,), + args=dict( + argstr="%s", + ), + card=dict( + argstr="-card %s", + extensions=None, + position=-2, + ), cardphase=dict( - argstr="-cardphase %s", extensions=None, hash_files=False, position=-6, + argstr="-cardphase %s", + extensions=None, + hash_files=False, + position=-6, + ), + environ=dict( + nohash=True, + usedefault=True, ), - environ=dict(nohash=True, usedefault=True,), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + order=dict( + argstr="-order %s", + position=-5, ), - num_threads=dict(nohash=True, usedefault=True,), - order=dict(argstr="-order %s", position=-5,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -23,11 +45,21 @@ def test_Retroicor_inputs(): position=1, ), outputtype=dict(), - resp=dict(argstr="-resp %s", extensions=None, position=-3,), + resp=dict( + argstr="-resp %s", + extensions=None, + position=-3, + ), respphase=dict( - argstr="-respphase %s", extensions=None, hash_files=False, position=-7, + argstr="-respphase %s", + extensions=None, + hash_files=False, + position=-7, + ), + threshold=dict( + argstr="-threshold %d", + position=-4, ), - threshold=dict(argstr="-threshold %d", position=-4,), ) inputs = Retroicor.input_spec() @@ -37,7 +69,11 @@ def test_Retroicor_inputs(): def test_Retroicor_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Retroicor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_SVMTest.py b/nipype/interfaces/afni/tests/test_auto_SVMTest.py index e4ab1e00bc..665a4a6156 100644 --- a/nipype/interfaces/afni/tests/test_auto_SVMTest.py +++ b/nipype/interfaces/afni/tests/test_auto_SVMTest.py @@ -4,21 +4,51 @@ def test_SVMTest_inputs(): input_map = dict( - args=dict(argstr="%s",), - classout=dict(argstr="-classout",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-testvol %s", extensions=None, mandatory=True,), - model=dict(argstr="-model %s", mandatory=True,), - multiclass=dict(argstr="-multiclass %s",), - nodetrend=dict(argstr="-nodetrend",), - nopredcensord=dict(argstr="-nopredcensord",), - num_threads=dict(nohash=True, usedefault=True,), - options=dict(argstr="%s",), + args=dict( + argstr="%s", + ), + classout=dict( + argstr="-classout", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-testvol %s", + extensions=None, + mandatory=True, + ), + model=dict( + argstr="-model %s", + mandatory=True, + ), + multiclass=dict( + argstr="-multiclass %s", + ), + nodetrend=dict( + argstr="-nodetrend", + ), + nopredcensord=dict( + argstr="-nopredcensord", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + options=dict( + argstr="%s", + ), out_file=dict( - argstr="-predictions %s", extensions=None, name_template="%s_predictions", + argstr="-predictions %s", + extensions=None, + name_template="%s_predictions", ), outputtype=dict(), - testlabels=dict(argstr="-testlabels %s", extensions=None,), + testlabels=dict( + argstr="-testlabels %s", + extensions=None, + ), ) inputs = SVMTest.input_spec() @@ -28,7 +58,11 @@ def test_SVMTest_inputs(): def test_SVMTest_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SVMTest.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_SVMTrain.py b/nipype/interfaces/afni/tests/test_auto_SVMTrain.py index 5edf36b7fa..f79bf1b9ac 100644 --- a/nipype/interfaces/afni/tests/test_auto_SVMTrain.py +++ b/nipype/interfaces/afni/tests/test_auto_SVMTrain.py @@ -11,15 +11,35 @@ def test_SVMTrain_inputs(): name_template="%s_alphas", suffix="_alphas", ), - args=dict(argstr="%s",), - censor=dict(argstr="-censor %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + censor=dict( + argstr="-censor %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="-trainvol %s", copyfile=False, extensions=None, mandatory=True, + argstr="-trainvol %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + kernel=dict( + argstr="-kernel %s", + ), + mask=dict( + argstr="-mask %s", + copyfile=False, + extensions=None, + position=-1, + ), + max_iterations=dict( + argstr="-max_iterations %d", ), - kernel=dict(argstr="-kernel %s",), - mask=dict(argstr="-mask %s", copyfile=False, extensions=None, position=-1,), - max_iterations=dict(argstr="-max_iterations %d",), model=dict( argstr="-model %s", extensions=None, @@ -27,9 +47,16 @@ def test_SVMTrain_inputs(): name_template="%s_model", suffix="_model", ), - nomodelmask=dict(argstr="-nomodelmask",), - num_threads=dict(nohash=True, usedefault=True,), - options=dict(argstr="%s",), + nomodelmask=dict( + argstr="-nomodelmask", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + options=dict( + argstr="%s", + ), out_file=dict( argstr="-bucket %s", extensions=None, @@ -38,9 +65,17 @@ def test_SVMTrain_inputs(): suffix="_bucket", ), outputtype=dict(), - trainlabels=dict(argstr="-trainlabels %s", extensions=None,), - ttype=dict(argstr="-type %s", mandatory=True,), - w_out=dict(argstr="-wout",), + trainlabels=dict( + argstr="-trainlabels %s", + extensions=None, + ), + ttype=dict( + argstr="-type %s", + mandatory=True, + ), + w_out=dict( + argstr="-wout", + ), ) inputs = SVMTrain.input_spec() @@ -51,9 +86,15 @@ def test_SVMTrain_inputs(): def test_SVMTrain_outputs(): output_map = dict( - alphas=dict(extensions=None,), - model=dict(extensions=None,), - out_file=dict(extensions=None,), + alphas=dict( + extensions=None, + ), + model=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = SVMTrain.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Seg.py b/nipype/interfaces/afni/tests/test_auto_Seg.py index f243aac8c7..38b256d1ea 100644 --- a/nipype/interfaces/afni/tests/test_auto_Seg.py +++ b/nipype/interfaces/afni/tests/test_auto_Seg.py @@ -4,13 +4,28 @@ def test_Seg_inputs(): input_map = dict( - args=dict(argstr="%s",), - bias_classes=dict(argstr="-bias_classes %s",), - bias_fwhm=dict(argstr="-bias_fwhm %f",), - blur_meth=dict(argstr="-blur_meth %s",), - bmrf=dict(argstr="-bmrf %f",), - classes=dict(argstr="-classes %s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + bias_classes=dict( + argstr="-bias_classes %s", + ), + bias_fwhm=dict( + argstr="-bias_fwhm %f", + ), + blur_meth=dict( + argstr="-blur_meth %s", + ), + bmrf=dict( + argstr="-bmrf %f", + ), + classes=dict( + argstr="-classes %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( argstr="-anat %s", copyfile=True, @@ -18,11 +33,23 @@ def test_Seg_inputs(): mandatory=True, position=-1, ), - main_N=dict(argstr="-main_N %d",), - mask=dict(argstr="-mask %s", mandatory=True, position=-2,), - mixfloor=dict(argstr="-mixfloor %f",), - mixfrac=dict(argstr="-mixfrac %s",), - prefix=dict(argstr="-prefix %s",), + main_N=dict( + argstr="-main_N %d", + ), + mask=dict( + argstr="-mask %s", + mandatory=True, + position=-2, + ), + mixfloor=dict( + argstr="-mixfloor %f", + ), + mixfrac=dict( + argstr="-mixfrac %s", + ), + prefix=dict( + argstr="-prefix %s", + ), ) inputs = Seg.input_spec() @@ -32,7 +59,11 @@ def test_Seg_inputs(): def test_Seg_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Seg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_SkullStrip.py b/nipype/interfaces/afni/tests/test_auto_SkullStrip.py index 4fbf078da5..4f78254e47 100644 --- a/nipype/interfaces/afni/tests/test_auto_SkullStrip.py +++ b/nipype/interfaces/afni/tests/test_auto_SkullStrip.py @@ -4,8 +4,13 @@ def test_SkullStrip_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( argstr="-input %s", copyfile=False, @@ -13,7 +18,10 @@ def test_SkullStrip_inputs(): mandatory=True, position=1, ), - num_threads=dict(nohash=True, usedefault=True,), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -30,7 +38,11 @@ def test_SkullStrip_inputs(): def test_SkullStrip_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SkullStrip.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Synthesize.py b/nipype/interfaces/afni/tests/test_auto_Synthesize.py index df23d9923b..9f787edbfc 100644 --- a/nipype/interfaces/afni/tests/test_auto_Synthesize.py +++ b/nipype/interfaces/afni/tests/test_auto_Synthesize.py @@ -4,21 +4,48 @@ def test_Synthesize_inputs(): input_map = dict( - TR=dict(argstr="-TR %f",), - args=dict(argstr="%s",), + TR=dict( + argstr="-TR %f", + ), + args=dict( + argstr="%s", + ), cbucket=dict( - argstr="-cbucket %s", copyfile=False, extensions=None, mandatory=True, + argstr="-cbucket %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + cenfill=dict( + argstr="-cenfill %s", + ), + dry_run=dict( + argstr="-dry", + ), + environ=dict( + nohash=True, + usedefault=True, ), - cenfill=dict(argstr="-cenfill %s",), - dry_run=dict(argstr="-dry",), - environ=dict(nohash=True, usedefault=True,), matrix=dict( - argstr="-matrix %s", copyfile=False, extensions=None, mandatory=True, + argstr="-matrix %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="-prefix %s", + extensions=None, + name_template="syn", ), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="-prefix %s", extensions=None, name_template="syn",), outputtype=dict(), - select=dict(argstr="-select %s", mandatory=True,), + select=dict( + argstr="-select %s", + mandatory=True, + ), ) inputs = Synthesize.input_spec() @@ -28,7 +55,11 @@ def test_Synthesize_inputs(): def test_Synthesize_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Synthesize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TCat.py b/nipype/interfaces/afni/tests/test_auto_TCat.py index b9a4a16054..595e91383e 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCat.py +++ b/nipype/interfaces/afni/tests/test_auto_TCat.py @@ -4,10 +4,23 @@ def test_TCat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr=" %s", copyfile=False, mandatory=True, position=-1,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr=" %s", + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -15,8 +28,13 @@ def test_TCat_inputs(): name_template="%s_tcat", ), outputtype=dict(), - rlt=dict(argstr="-rlt%s", position=1,), - verbose=dict(argstr="-verb",), + rlt=dict( + argstr="-rlt%s", + position=1, + ), + verbose=dict( + argstr="-verb", + ), ) inputs = TCat.input_spec() @@ -26,7 +44,11 @@ def test_TCat_inputs(): def test_TCat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TCat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TCatSubBrick.py b/nipype/interfaces/afni/tests/test_auto_TCatSubBrick.py index 7644b191a6..728d281d27 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCatSubBrick.py +++ b/nipype/interfaces/afni/tests/test_auto_TCatSubBrick.py @@ -4,13 +4,33 @@ def test_TCatSubBrick_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="%s%s ...", copyfile=False, mandatory=True, position=-1,), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="-prefix %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="%s%s ...", + copyfile=False, + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="-prefix %s", + extensions=None, + genfile=True, + ), outputtype=dict(), - rlt=dict(argstr="-rlt%s", position=1,), + rlt=dict( + argstr="-rlt%s", + position=1, + ), ) inputs = TCatSubBrick.input_spec() @@ -20,7 +40,11 @@ def test_TCatSubBrick_inputs(): def test_TCatSubBrick_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TCatSubBrick.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TCorr1D.py b/nipype/interfaces/afni/tests/test_auto_TCorr1D.py index 0a306ceca3..665a0dfc3d 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCorr1D.py +++ b/nipype/interfaces/afni/tests/test_auto_TCorr1D.py @@ -4,12 +4,22 @@ def test_TCorr1D_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ktaub=dict( - argstr=" -ktaub", position=1, xor=["pearson", "spearman", "quadrant"], + argstr=" -ktaub", + position=1, + xor=["pearson", "spearman", "quadrant"], + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -19,18 +29,33 @@ def test_TCorr1D_inputs(): ), outputtype=dict(), pearson=dict( - argstr=" -pearson", position=1, xor=["spearman", "quadrant", "ktaub"], + argstr=" -pearson", + position=1, + xor=["spearman", "quadrant", "ktaub"], ), quadrant=dict( - argstr=" -quadrant", position=1, xor=["pearson", "spearman", "ktaub"], + argstr=" -quadrant", + position=1, + xor=["pearson", "spearman", "ktaub"], ), spearman=dict( - argstr=" -spearman", position=1, xor=["pearson", "quadrant", "ktaub"], + argstr=" -spearman", + position=1, + xor=["pearson", "quadrant", "ktaub"], ), xset=dict( - argstr=" %s", copyfile=False, extensions=None, mandatory=True, position=-2, + argstr=" %s", + copyfile=False, + extensions=None, + mandatory=True, + position=-2, + ), + y_1d=dict( + argstr=" %s", + extensions=None, + mandatory=True, + position=-1, ), - y_1d=dict(argstr=" %s", extensions=None, mandatory=True, position=-1,), ) inputs = TCorr1D.input_spec() @@ -40,7 +65,11 @@ def test_TCorr1D_inputs(): def test_TCorr1D_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TCorr1D.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TCorrMap.py b/nipype/interfaces/afni/tests/test_auto_TCorrMap.py index 5a03aa3732..8e6b1860ff 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCorrMap.py +++ b/nipype/interfaces/afni/tests/test_auto_TCorrMap.py @@ -15,8 +15,12 @@ def test_TCorrMap_inputs(): "var_absolute_threshold_normalize", ), ), - args=dict(argstr="%s",), - automask=dict(argstr="-automask",), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + ), average_expr=dict( argstr="-Aexpr %s %s", extensions=None, @@ -31,15 +35,26 @@ def test_TCorrMap_inputs(): suffix="_cexpr", xor=("average_expr", "average_expr_nonzero", "sum_expr"), ), - bandpass=dict(argstr="-bpass %f %f",), - blur_fwhm=dict(argstr="-Gblur %f",), + bandpass=dict( + argstr="-bpass %f %f", + ), + blur_fwhm=dict( + argstr="-Gblur %f", + ), correlation_maps=dict( - argstr="-CorrMap %s", extensions=None, name_source="in_file", + argstr="-CorrMap %s", + extensions=None, + name_source="in_file", ), correlation_maps_masked=dict( - argstr="-CorrMask %s", extensions=None, name_source="in_file", + argstr="-CorrMask %s", + extensions=None, + name_source="in_file", + ), + environ=dict( + nohash=True, + usedefault=True, ), - environ=dict(nohash=True, usedefault=True,), expr=dict(), histogram=dict( argstr="-Hist %d %s", @@ -49,13 +64,25 @@ def test_TCorrMap_inputs(): ), histogram_bin_numbers=dict(), in_file=dict( - argstr="-input %s", copyfile=False, extensions=None, mandatory=True, + argstr="-input %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + mask=dict( + argstr="-mask %s", + extensions=None, ), - mask=dict(argstr="-mask %s", extensions=None,), mean_file=dict( - argstr="-Mean %s", extensions=None, name_source="in_file", suffix="_mean", + argstr="-Mean %s", + extensions=None, + name_source="in_file", + suffix="_mean", + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -64,15 +91,33 @@ def test_TCorrMap_inputs(): ), outputtype=dict(), pmean=dict( - argstr="-Pmean %s", extensions=None, name_source="in_file", suffix="_pmean", + argstr="-Pmean %s", + extensions=None, + name_source="in_file", + suffix="_pmean", + ), + polort=dict( + argstr="-polort %d", ), - polort=dict(argstr="-polort %d",), qmean=dict( - argstr="-Qmean %s", extensions=None, name_source="in_file", suffix="_qmean", + argstr="-Qmean %s", + extensions=None, + name_source="in_file", + suffix="_qmean", + ), + regress_out_timeseries=dict( + argstr="-ort %s", + extensions=None, + ), + seeds=dict( + argstr="-seed %s", + extensions=None, + xor="seeds_width", + ), + seeds_width=dict( + argstr="-Mseed %f", + xor="seeds", ), - regress_out_timeseries=dict(argstr="-ort %s", extensions=None,), - seeds=dict(argstr="-seed %s", extensions=None, xor="seeds_width",), - seeds_width=dict(argstr="-Mseed %f", xor="seeds",), sum_expr=dict( argstr="-Sexpr %s %s", extensions=None, @@ -104,7 +149,10 @@ def test_TCorrMap_inputs(): ), ), zmean=dict( - argstr="-Zmean %s", extensions=None, name_source="in_file", suffix="_zmean", + argstr="-Zmean %s", + extensions=None, + name_source="in_file", + suffix="_zmean", ), ) inputs = TCorrMap.input_spec() @@ -116,19 +164,45 @@ def test_TCorrMap_inputs(): def test_TCorrMap_outputs(): output_map = dict( - absolute_threshold=dict(extensions=None,), - average_expr=dict(extensions=None,), - average_expr_nonzero=dict(extensions=None,), - correlation_maps=dict(extensions=None,), - correlation_maps_masked=dict(extensions=None,), - histogram=dict(extensions=None,), - mean_file=dict(extensions=None,), - pmean=dict(extensions=None,), - qmean=dict(extensions=None,), - sum_expr=dict(extensions=None,), - var_absolute_threshold=dict(extensions=None,), - var_absolute_threshold_normalize=dict(extensions=None,), - zmean=dict(extensions=None,), + absolute_threshold=dict( + extensions=None, + ), + average_expr=dict( + extensions=None, + ), + average_expr_nonzero=dict( + extensions=None, + ), + correlation_maps=dict( + extensions=None, + ), + correlation_maps_masked=dict( + extensions=None, + ), + histogram=dict( + extensions=None, + ), + mean_file=dict( + extensions=None, + ), + pmean=dict( + extensions=None, + ), + qmean=dict( + extensions=None, + ), + sum_expr=dict( + extensions=None, + ), + var_absolute_threshold=dict( + extensions=None, + ), + var_absolute_threshold_normalize=dict( + extensions=None, + ), + zmean=dict( + extensions=None, + ), ) outputs = TCorrMap.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_TCorrelate.py b/nipype/interfaces/afni/tests/test_auto_TCorrelate.py index 0bf794886b..1e85d44b68 100644 --- a/nipype/interfaces/afni/tests/test_auto_TCorrelate.py +++ b/nipype/interfaces/afni/tests/test_auto_TCorrelate.py @@ -4,9 +4,17 @@ def test_TCorrelate_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -14,13 +22,25 @@ def test_TCorrelate_inputs(): name_template="%s_tcorr", ), outputtype=dict(), - pearson=dict(argstr="-pearson",), - polort=dict(argstr="-polort %d",), + pearson=dict( + argstr="-pearson", + ), + polort=dict( + argstr="-polort %d", + ), xset=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-2, ), yset=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, ), ) inputs = TCorrelate.input_spec() @@ -31,7 +51,11 @@ def test_TCorrelate_inputs(): def test_TCorrelate_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TCorrelate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TNorm.py b/nipype/interfaces/afni/tests/test_auto_TNorm.py index 8a8493f927..975345d92a 100644 --- a/nipype/interfaces/afni/tests/test_auto_TNorm.py +++ b/nipype/interfaces/afni/tests/test_auto_TNorm.py @@ -4,17 +4,39 @@ def test_TNorm_inputs(): input_map = dict( - L1fit=dict(argstr="-L1fit",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + L1fit=dict( + argstr="-L1fit", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + norm1=dict( + argstr="-norm1", + ), + norm2=dict( + argstr="-norm2", + ), + normR=dict( + argstr="-normR", + ), + normx=dict( + argstr="-normx", + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - norm1=dict(argstr="-norm1",), - norm2=dict(argstr="-norm2",), - normR=dict(argstr="-normR",), - normx=dict(argstr="-normx",), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -22,7 +44,9 @@ def test_TNorm_inputs(): name_template="%s_tnorm", ), outputtype=dict(), - polort=dict(argstr="-polort %s",), + polort=dict( + argstr="-polort %s", + ), ) inputs = TNorm.input_spec() @@ -32,7 +56,11 @@ def test_TNorm_inputs(): def test_TNorm_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TNorm.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TProject.py b/nipype/interfaces/afni/tests/test_auto_TProject.py index e300cb16be..d8f9990817 100644 --- a/nipype/interfaces/afni/tests/test_auto_TProject.py +++ b/nipype/interfaces/afni/tests/test_auto_TProject.py @@ -4,17 +4,43 @@ def test_TProject_inputs(): input_map = dict( - TR=dict(argstr="-TR %g",), - args=dict(argstr="%s",), - automask=dict(argstr="-automask", xor=["mask"],), - bandpass=dict(argstr="-bandpass %g %g",), - blur=dict(argstr="-blur %g",), - cenmode=dict(argstr="-cenmode %s",), - censor=dict(argstr="-censor %s", extensions=None,), - censortr=dict(argstr="-CENSORTR %s",), - concat=dict(argstr="-concat %s", extensions=None,), - dsort=dict(argstr="-dsort %s...",), - environ=dict(nohash=True, usedefault=True,), + TR=dict( + argstr="-TR %g", + ), + args=dict( + argstr="%s", + ), + automask=dict( + argstr="-automask", + xor=["mask"], + ), + bandpass=dict( + argstr="-bandpass %g %g", + ), + blur=dict( + argstr="-blur %g", + ), + cenmode=dict( + argstr="-cenmode %s", + ), + censor=dict( + argstr="-censor %s", + extensions=None, + ), + censortr=dict( + argstr="-CENSORTR %s", + ), + concat=dict( + argstr="-concat %s", + extensions=None, + ), + dsort=dict( + argstr="-dsort %s...", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( argstr="-input %s", copyfile=False, @@ -22,11 +48,24 @@ def test_TProject_inputs(): mandatory=True, position=1, ), - mask=dict(argstr="-mask %s", extensions=None,), - noblock=dict(argstr="-noblock",), - norm=dict(argstr="-norm",), - num_threads=dict(nohash=True, usedefault=True,), - ort=dict(argstr="-ort %s", extensions=None,), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + noblock=dict( + argstr="-noblock", + ), + norm=dict( + argstr="-norm", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + ort=dict( + argstr="-ort %s", + extensions=None, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -35,8 +74,12 @@ def test_TProject_inputs(): position=-1, ), outputtype=dict(), - polort=dict(argstr="-polort %d",), - stopband=dict(argstr="-stopband %g %g",), + polort=dict( + argstr="-polort %d", + ), + stopband=dict( + argstr="-stopband %g %g", + ), ) inputs = TProject.input_spec() @@ -46,7 +89,11 @@ def test_TProject_inputs(): def test_TProject_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TProject.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TShift.py b/nipype/interfaces/afni/tests/test_auto_TShift.py index 9f1e6c3342..78af699c7c 100644 --- a/nipype/interfaces/afni/tests/test_auto_TShift.py +++ b/nipype/interfaces/afni/tests/test_auto_TShift.py @@ -4,14 +4,30 @@ def test_TShift_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - ignore=dict(argstr="-ignore %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore=dict( + argstr="-ignore %s", + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + interp=dict( + argstr="-%s", + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - interp=dict(argstr="-%s",), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -19,14 +35,34 @@ def test_TShift_inputs(): name_template="%s_tshift", ), outputtype=dict(), - rlt=dict(argstr="-rlt",), - rltplus=dict(argstr="-rlt+",), - slice_encoding_direction=dict(usedefault=True,), - slice_timing=dict(argstr="-tpattern @%s", xor=["tpattern"],), - tpattern=dict(argstr="-tpattern %s", xor=["slice_timing"],), - tr=dict(argstr="-TR %s",), - tslice=dict(argstr="-slice %s", xor=["tzero"],), - tzero=dict(argstr="-tzero %s", xor=["tslice"],), + rlt=dict( + argstr="-rlt", + ), + rltplus=dict( + argstr="-rlt+", + ), + slice_encoding_direction=dict( + usedefault=True, + ), + slice_timing=dict( + argstr="-tpattern @%s", + xor=["tpattern"], + ), + tpattern=dict( + argstr="-tpattern %s", + xor=["slice_timing"], + ), + tr=dict( + argstr="-TR %s", + ), + tslice=dict( + argstr="-slice %s", + xor=["tzero"], + ), + tzero=dict( + argstr="-tzero %s", + xor=["tslice"], + ), ) inputs = TShift.input_spec() @@ -37,7 +73,12 @@ def test_TShift_inputs(): def test_TShift_outputs(): output_map = dict( - out_file=dict(extensions=None,), timing_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + timing_file=dict( + extensions=None, + ), ) outputs = TShift.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_TSmooth.py b/nipype/interfaces/afni/tests/test_auto_TSmooth.py index 1223686b83..1836d31c22 100644 --- a/nipype/interfaces/afni/tests/test_auto_TSmooth.py +++ b/nipype/interfaces/afni/tests/test_auto_TSmooth.py @@ -4,21 +4,52 @@ def test_TSmooth_inputs(): input_map = dict( - adaptive=dict(argstr="-adaptive %d",), - args=dict(argstr="%s",), - blackman=dict(argstr="-blackman %d",), - custom=dict(argstr="-custom %s", extensions=None,), - datum=dict(argstr="-datum %s",), - environ=dict(nohash=True, usedefault=True,), - hamming=dict(argstr="-hamming %d",), + adaptive=dict( + argstr="-adaptive %d", + ), + args=dict( + argstr="%s", + ), + blackman=dict( + argstr="-blackman %d", + ), + custom=dict( + argstr="-custom %s", + extensions=None, + ), + datum=dict( + argstr="-datum %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hamming=dict( + argstr="-hamming %d", + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + lin=dict( + argstr="-lin", + ), + lin3=dict( + argstr="-3lin %d", + ), + med=dict( + argstr="-med", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + osf=dict( + argstr="-osf", ), - lin=dict(argstr="-lin",), - lin3=dict(argstr="-3lin %d",), - med=dict(argstr="-med",), - num_threads=dict(nohash=True, usedefault=True,), - osf=dict(argstr="-osf",), out_file=dict( argstr="-prefix %s", extensions=None, @@ -35,7 +66,11 @@ def test_TSmooth_inputs(): def test_TSmooth_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TSmooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_TStat.py b/nipype/interfaces/afni/tests/test_auto_TStat.py index 0a7a99da76..b7499c5442 100644 --- a/nipype/interfaces/afni/tests/test_auto_TStat.py +++ b/nipype/interfaces/afni/tests/test_auto_TStat.py @@ -4,14 +4,31 @@ def test_TStat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + options=dict( + argstr="%s", ), - mask=dict(argstr="-mask %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), - options=dict(argstr="%s",), out_file=dict( argstr="-prefix %s", extensions=None, @@ -28,7 +45,11 @@ def test_TStat_inputs(): def test_TStat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TStat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_To3D.py b/nipype/interfaces/afni/tests/test_auto_To3D.py index ffed9ba623..6121efbe57 100644 --- a/nipype/interfaces/afni/tests/test_auto_To3D.py +++ b/nipype/interfaces/afni/tests/test_auto_To3D.py @@ -4,14 +4,34 @@ def test_To3D_inputs(): input_map = dict( - args=dict(argstr="%s",), - assumemosaic=dict(argstr="-assume_dicom_mosaic",), - datatype=dict(argstr="-datum %s",), - environ=dict(nohash=True, usedefault=True,), - filetype=dict(argstr="-%s",), - funcparams=dict(argstr="-time:zt %s alt+z2",), - in_folder=dict(argstr="%s/*.dcm", mandatory=True, position=-1,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + assumemosaic=dict( + argstr="-assume_dicom_mosaic", + ), + datatype=dict( + argstr="-datum %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filetype=dict( + argstr="-%s", + ), + funcparams=dict( + argstr="-time:zt %s alt+z2", + ), + in_folder=dict( + argstr="%s/*.dcm", + mandatory=True, + position=-1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -19,7 +39,9 @@ def test_To3D_inputs(): name_template="%s", ), outputtype=dict(), - skipoutliers=dict(argstr="-skip_outliers",), + skipoutliers=dict( + argstr="-skip_outliers", + ), ) inputs = To3D.input_spec() @@ -29,7 +51,11 @@ def test_To3D_inputs(): def test_To3D_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = To3D.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Undump.py b/nipype/interfaces/afni/tests/test_auto_Undump.py index 3679a118fe..64c98cf25a 100644 --- a/nipype/interfaces/afni/tests/test_auto_Undump.py +++ b/nipype/interfaces/afni/tests/test_auto_Undump.py @@ -4,13 +4,28 @@ def test_Undump_inputs(): input_map = dict( - args=dict(argstr="%s",), - coordinates_specification=dict(argstr="-%s",), - datatype=dict(argstr="-datum %s",), - default_value=dict(argstr="-dval %f",), - environ=dict(nohash=True, usedefault=True,), - fill_value=dict(argstr="-fval %f",), - head_only=dict(argstr="-head_only",), + args=dict( + argstr="%s", + ), + coordinates_specification=dict( + argstr="-%s", + ), + datatype=dict( + argstr="-datum %s", + ), + default_value=dict( + argstr="-dval %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_value=dict( + argstr="-fval %f", + ), + head_only=dict( + argstr="-head_only", + ), in_file=dict( argstr="-master %s", copyfile=False, @@ -18,12 +33,26 @@ def test_Undump_inputs(): mandatory=True, position=-1, ), - mask_file=dict(argstr="-mask %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), - orient=dict(argstr="-orient %s",), - out_file=dict(argstr="-prefix %s", extensions=None, name_source="in_file",), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + orient=dict( + argstr="-orient %s", + ), + out_file=dict( + argstr="-prefix %s", + extensions=None, + name_source="in_file", + ), outputtype=dict(), - srad=dict(argstr="-srad %f",), + srad=dict( + argstr="-srad %f", + ), ) inputs = Undump.input_spec() @@ -33,7 +62,11 @@ def test_Undump_inputs(): def test_Undump_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Undump.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Unifize.py b/nipype/interfaces/afni/tests/test_auto_Unifize.py index 71331215b7..15832152c2 100644 --- a/nipype/interfaces/afni/tests/test_auto_Unifize.py +++ b/nipype/interfaces/afni/tests/test_auto_Unifize.py @@ -4,11 +4,24 @@ def test_Unifize_inputs(): input_map = dict( - args=dict(argstr="%s",), - cl_frac=dict(argstr="-clfrac %f",), - environ=dict(nohash=True, usedefault=True,), - epi=dict(argstr="-EPI", requires=["no_duplo", "t2"], xor=["gm"],), - gm=dict(argstr="-GM",), + args=dict( + argstr="%s", + ), + cl_frac=dict( + argstr="-clfrac %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi=dict( + argstr="-EPI", + requires=["no_duplo", "t2"], + xor=["gm"], + ), + gm=dict( + argstr="-GM", + ), in_file=dict( argstr="-input %s", copyfile=False, @@ -16,8 +29,13 @@ def test_Unifize_inputs(): mandatory=True, position=-1, ), - no_duplo=dict(argstr="-noduplo",), - num_threads=dict(nohash=True, usedefault=True,), + no_duplo=dict( + argstr="-noduplo", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -25,12 +43,25 @@ def test_Unifize_inputs(): name_template="%s_unifized", ), outputtype=dict(), - quiet=dict(argstr="-quiet",), - rbt=dict(argstr="-rbt %f %f %f",), - scale_file=dict(argstr="-ssave %s", extensions=None,), - t2=dict(argstr="-T2",), - t2_up=dict(argstr="-T2up %f",), - urad=dict(argstr="-Urad %s",), + quiet=dict( + argstr="-quiet", + ), + rbt=dict( + argstr="-rbt %f %f %f", + ), + scale_file=dict( + argstr="-ssave %s", + extensions=None, + ), + t2=dict( + argstr="-T2", + ), + t2_up=dict( + argstr="-T2up %f", + ), + urad=dict( + argstr="-Urad %s", + ), ) inputs = Unifize.input_spec() @@ -41,7 +72,12 @@ def test_Unifize_inputs(): def test_Unifize_outputs(): output_map = dict( - out_file=dict(extensions=None,), scale_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + scale_file=dict( + extensions=None, + ), ) outputs = Unifize.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Volreg.py b/nipype/interfaces/afni/tests/test_auto_Volreg.py index 9d7c6aa69b..658b933391 100644 --- a/nipype/interfaces/afni/tests/test_auto_Volreg.py +++ b/nipype/interfaces/afni/tests/test_auto_Volreg.py @@ -4,15 +4,34 @@ def test_Volreg_inputs(): input_map = dict( - args=dict(argstr="%s",), - basefile=dict(argstr="-base %s", extensions=None, position=-6,), - copyorigin=dict(argstr="-twodup",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + basefile=dict( + argstr="-base %s", + extensions=None, + position=-6, + ), + copyorigin=dict( + argstr="-twodup", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + in_weight_volume=dict( + argstr="-weight '%s[%d]'", + ), + interp=dict( + argstr="-%s", ), - in_weight_volume=dict(argstr="-weight '%s[%d]'",), - interp=dict(argstr="-%s",), md1d_file=dict( argstr="-maxdisp1D %s", extensions=None, @@ -21,7 +40,10 @@ def test_Volreg_inputs(): name_template="%s_md.1D", position=-4, ), - num_threads=dict(nohash=True, usedefault=True,), + num_threads=dict( + nohash=True, + usedefault=True, + ), oned_file=dict( argstr="-1Dfile %s", extensions=None, @@ -43,9 +65,16 @@ def test_Volreg_inputs(): name_template="%s_volreg", ), outputtype=dict(), - timeshift=dict(argstr="-tshift 0",), - verbose=dict(argstr="-verbose",), - zpad=dict(argstr="-zpad %d", position=-5,), + timeshift=dict( + argstr="-tshift 0", + ), + verbose=dict( + argstr="-verbose", + ), + zpad=dict( + argstr="-zpad %d", + position=-5, + ), ) inputs = Volreg.input_spec() @@ -56,10 +85,18 @@ def test_Volreg_inputs(): def test_Volreg_outputs(): output_map = dict( - md1d_file=dict(extensions=None,), - oned_file=dict(extensions=None,), - oned_matrix_save=dict(extensions=None,), - out_file=dict(extensions=None,), + md1d_file=dict( + extensions=None, + ), + oned_file=dict( + extensions=None, + ), + oned_matrix_save=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = Volreg.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_Warp.py b/nipype/interfaces/afni/tests/test_auto_Warp.py index 5b5e9ded71..9d694f8425 100644 --- a/nipype/interfaces/afni/tests/test_auto_Warp.py +++ b/nipype/interfaces/afni/tests/test_auto_Warp.py @@ -4,19 +4,48 @@ def test_Warp_inputs(): input_map = dict( - args=dict(argstr="%s",), - deoblique=dict(argstr="-deoblique",), - environ=dict(nohash=True, usedefault=True,), - gridset=dict(argstr="-gridset %s", extensions=None,), + args=dict( + argstr="%s", + ), + deoblique=dict( + argstr="-deoblique", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gridset=dict( + argstr="-gridset %s", + extensions=None, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, - ), - interp=dict(argstr="-%s",), - matparent=dict(argstr="-matparent %s", extensions=None,), - mni2tta=dict(argstr="-mni2tta",), - newgrid=dict(argstr="-newgrid %f",), - num_threads=dict(nohash=True, usedefault=True,), - oblique_parent=dict(argstr="-oblique_parent %s", extensions=None,), + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + interp=dict( + argstr="-%s", + ), + matparent=dict( + argstr="-matparent %s", + extensions=None, + ), + mni2tta=dict( + argstr="-mni2tta", + ), + newgrid=dict( + argstr="-newgrid %f", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + oblique_parent=dict( + argstr="-oblique_parent %s", + extensions=None, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -25,10 +54,18 @@ def test_Warp_inputs(): name_template="%s_warp", ), outputtype=dict(), - save_warp=dict(requires=["verbose"],), - tta2mni=dict(argstr="-tta2mni",), - verbose=dict(argstr="-verb",), - zpad=dict(argstr="-zpad %d",), + save_warp=dict( + requires=["verbose"], + ), + tta2mni=dict( + argstr="-tta2mni", + ), + verbose=dict( + argstr="-verb", + ), + zpad=dict( + argstr="-zpad %d", + ), ) inputs = Warp.input_spec() @@ -39,7 +76,12 @@ def test_Warp_inputs(): def test_Warp_outputs(): output_map = dict( - out_file=dict(extensions=None,), warp_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + warp_file=dict( + extensions=None, + ), ) outputs = Warp.output_spec() diff --git a/nipype/interfaces/afni/tests/test_auto_ZCutUp.py b/nipype/interfaces/afni/tests/test_auto_ZCutUp.py index d234da5a50..3c51d6dd1d 100644 --- a/nipype/interfaces/afni/tests/test_auto_ZCutUp.py +++ b/nipype/interfaces/afni/tests/test_auto_ZCutUp.py @@ -4,13 +4,27 @@ def test_ZCutUp_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, + ), + keep=dict( + argstr="-keep %s", + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - keep=dict(argstr="-keep %s",), - num_threads=dict(nohash=True, usedefault=True,), out_file=dict( argstr="-prefix %s", extensions=None, @@ -27,7 +41,11 @@ def test_ZCutUp_inputs(): def test_ZCutUp_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ZCutUp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Zcat.py b/nipype/interfaces/afni/tests/test_auto_Zcat.py index 81251acfe8..e06f343591 100644 --- a/nipype/interfaces/afni/tests/test_auto_Zcat.py +++ b/nipype/interfaces/afni/tests/test_auto_Zcat.py @@ -4,13 +4,34 @@ def test_Zcat_inputs(): input_map = dict( - args=dict(argstr="%s",), - datum=dict(argstr="-datum %s",), - environ=dict(nohash=True, usedefault=True,), - fscale=dict(argstr="-fscale", xor=["nscale"],), - in_files=dict(argstr="%s", copyfile=False, mandatory=True, position=-1,), - nscale=dict(argstr="-nscale", xor=["fscale"],), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + datum=dict( + argstr="-datum %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fscale=dict( + argstr="-fscale", + xor=["nscale"], + ), + in_files=dict( + argstr="%s", + copyfile=False, + mandatory=True, + position=-1, + ), + nscale=dict( + argstr="-nscale", + xor=["fscale"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_file=dict( argstr="-prefix %s", extensions=None, @@ -18,7 +39,9 @@ def test_Zcat_inputs(): name_template="%s_zcat", ), outputtype=dict(), - verb=dict(argstr="-verb",), + verb=dict( + argstr="-verb", + ), ) inputs = Zcat.input_spec() @@ -28,7 +51,11 @@ def test_Zcat_inputs(): def test_Zcat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Zcat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/tests/test_auto_Zeropad.py b/nipype/interfaces/afni/tests/test_auto_Zeropad.py index 6f59445034..4d6742f21e 100644 --- a/nipype/interfaces/afni/tests/test_auto_Zeropad.py +++ b/nipype/interfaces/afni/tests/test_auto_Zeropad.py @@ -4,30 +4,79 @@ def test_Zeropad_inputs(): input_map = dict( - A=dict(argstr="-A %i", xor=["master"],), - AP=dict(argstr="-AP %i", xor=["master"],), - I=dict(argstr="-I %i", xor=["master"],), - IS=dict(argstr="-IS %i", xor=["master"],), - L=dict(argstr="-L %i", xor=["master"],), - P=dict(argstr="-P %i", xor=["master"],), - R=dict(argstr="-R %i", xor=["master"],), - RL=dict(argstr="-RL %i", xor=["master"],), - S=dict(argstr="-S %i", xor=["master"],), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + A=dict( + argstr="-A %i", + xor=["master"], + ), + AP=dict( + argstr="-AP %i", + xor=["master"], + ), + I=dict( + argstr="-I %i", + xor=["master"], + ), + IS=dict( + argstr="-IS %i", + xor=["master"], + ), + L=dict( + argstr="-L %i", + xor=["master"], + ), + P=dict( + argstr="-P %i", + xor=["master"], + ), + R=dict( + argstr="-R %i", + xor=["master"], + ), + RL=dict( + argstr="-RL %i", + xor=["master"], + ), + S=dict( + argstr="-S %i", + xor=["master"], + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_files=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-1, ), master=dict( argstr="-master %s", extensions=None, xor=["I", "S", "A", "P", "L", "R", "z", "RL", "AP", "IS", "mm"], ), - mm=dict(argstr="-mm", xor=["master"],), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="-prefix %s", extensions=None, name_template="zeropad",), + mm=dict( + argstr="-mm", + xor=["master"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="-prefix %s", + extensions=None, + name_template="zeropad", + ), outputtype=dict(), - z=dict(argstr="-z %i", xor=["master"],), + z=dict( + argstr="-z %i", + xor=["master"], + ), ) inputs = Zeropad.input_spec() @@ -37,7 +86,11 @@ def test_Zeropad_inputs(): def test_Zeropad_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Zeropad.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/afni/utils.py b/nipype/interfaces/afni/utils.py index 8ece6a8765..54c6b44b49 100644 --- a/nipype/interfaces/afni/utils.py +++ b/nipype/interfaces/afni/utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """AFNI utility interfaces.""" @@ -14,6 +13,7 @@ Directory, TraitedSpec, traits, + Tuple, isdefined, File, InputMultiObject, @@ -121,7 +121,7 @@ class AFNItoNIFTIInputSpec(AFNICommandInputSpec): argstr="-denote", ) oldid = traits.Bool( - desc="Give the new dataset the input dataset" "s AFNI ID code.", + desc="Give the new dataset the input datasets AFNI ID code.", argstr="-oldid", xor=["newid"], ) @@ -163,7 +163,7 @@ def _overload_extension(self, value, name=None): return os.path.join(path, base + ext) def _gen_filename(self, name): - return os.path.abspath(super(AFNItoNIFTI, self)._gen_filename(name)) + return os.path.abspath(super()._gen_filename(name)) class AutoboxInputSpec(AFNICommandInputSpec): @@ -224,7 +224,7 @@ class Autobox(AFNICommand): output_spec = AutoboxOutputSpec def aggregate_outputs(self, runtime=None, needed_outputs=None): - outputs = super(Autobox, self).aggregate_outputs(runtime, needed_outputs) + outputs = super().aggregate_outputs(runtime, needed_outputs) pattern = ( r"x=(?P-?\d+)\.\.(?P-?\d+) " r"y=(?P-?\d+)\.\.(?P-?\d+) " @@ -234,7 +234,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): m = re.search(pattern, line) if m: d = m.groupdict() - outputs.trait_set(**{k: int(d[k]) for k in d.keys()}) + outputs.trait_set(**{k: int(v) for k, v in d.items()}) return outputs @@ -262,7 +262,7 @@ class BrickStatInputSpec(CommandLineInputSpec): mean = traits.Bool(desc="print the mean value in the dataset", argstr="-mean") sum = traits.Bool(desc="print the sum of values in the dataset", argstr="-sum") var = traits.Bool(desc="print the variance in the dataset", argstr="-var") - percentile = traits.Tuple( + percentile = Tuple( traits.Float, traits.Float, traits.Float, @@ -302,7 +302,6 @@ class BrickStat(AFNICommandBase): output_spec = BrickStatOutputSpec def aggregate_outputs(self, runtime=None, needed_outputs=None): - outputs = self._outputs() outfile = os.path.join(os.getcwd(), "stat_result.json") @@ -310,7 +309,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): if runtime is None: try: min_val = load_json(outfile)["stat"] - except IOError: + except OSError: return self.run().outputs else: min_val = [] @@ -332,7 +331,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): class BucketInputSpec(AFNICommandInputSpec): in_file = traits.List( - traits.Tuple( + Tuple( (File(exists=True, copyfile=False), traits.Str(argstr="'%s'")), artstr="%s%s", ), @@ -419,7 +418,7 @@ class Bucket(AFNICommand): def _format_arg(self, name, spec, value): if name == "in_file": return spec.argstr % (" ".join([i[0] + "'" + i[1] + "'" for i in value])) - return super(Bucket, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class CalcInputSpec(AFNICommandInputSpec): @@ -493,12 +492,11 @@ def _format_arg(self, name, trait_spec, value): if isdefined(self.inputs.single_idx): arg += "[%d]" % (self.inputs.single_idx) return arg - return super(Calc, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _parse_inputs(self, skip=None): - """Skip the arguments without argstr metadata - """ - return super(Calc, self)._parse_inputs(skip=("start_idx", "stop_idx", "other")) + """Skip the arguments without argstr metadata""" + return super()._parse_inputs(skip=("start_idx", "stop_idx", "other")) class CatInputSpec(AFNICommandInputSpec): @@ -540,27 +538,27 @@ class CatInputSpec(AFNICommandInputSpec): argstr="-sel %s", ) out_int = traits.Bool( - desc="specifiy int data type for output", + desc="specify int data type for output", argstr="-i", xor=["out_format", "out_nice", "out_double", "out_fint", "out_cint"], ) out_nice = traits.Bool( - desc="specifiy nice data type for output", + desc="specify nice data type for output", argstr="-n", xor=["out_format", "out_int", "out_double", "out_fint", "out_cint"], ) out_double = traits.Bool( - desc="specifiy double data type for output", + desc="specify double data type for output", argstr="-d", xor=["out_format", "out_nice", "out_int", "out_fint", "out_cint"], ) out_fint = traits.Bool( - desc="specifiy int, rounded down, data type for output", + desc="specify int, rounded down, data type for output", argstr="-f", xor=["out_format", "out_nice", "out_double", "out_int", "out_cint"], ) out_cint = traits.Bool( - desc="specifiy int, rounded up, data type for output", + desc="specify int, rounded up, data type for output", xor=["out_format", "out_nice", "out_double", "out_fint", "out_int"], ) @@ -593,7 +591,7 @@ class Cat(AFNICommand): class CatMatvecInputSpec(AFNICommandInputSpec): in_file = traits.List( - traits.Tuple(traits.Str(), traits.Str()), + Tuple(traits.Str(), traits.Str()), desc="list of tuples of mfiles and associated opkeys", mandatory=True, argstr="%s", @@ -656,9 +654,9 @@ def _format_arg(self, name, spec, value): if name == "in_file": # Concatenate a series of filenames, with optional opkeys return " ".join( - "%s -%s" % (mfile, opkey) if opkey else mfile for mfile, opkey in value + f"{mfile} -{opkey}" if opkey else mfile for mfile, opkey in value ) - return super(CatMatvec, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class CenterMassInputSpec(CommandLineInputSpec): @@ -686,7 +684,7 @@ class CenterMassInputSpec(CommandLineInputSpec): exists=True, ) automask = traits.Bool(desc="Generate the mask automatically", argstr="-automask") - set_cm = traits.Tuple( + set_cm = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="After computing the center of mass, set the origin fields in " "the header so that the center of mass will be at (x,y,z) in " @@ -694,7 +692,7 @@ class CenterMassInputSpec(CommandLineInputSpec): argstr="-set %f %f %f", ) local_ijk = traits.Bool( - desc="Output values as (i,j,k) in local orienation", argstr="-local_ijk" + desc="Output values as (i,j,k) in local orientation", argstr="-local_ijk" ) roi_vals = traits.List( traits.Int, @@ -714,7 +712,7 @@ class CenterMassOutputSpec(TraitedSpec): out_file = File(exists=True, desc="output file") cm_file = File(desc="file with the center of mass coordinates") cm = traits.List( - traits.Tuple(traits.Float(), traits.Float(), traits.Float()), + Tuple(traits.Float(), traits.Float(), traits.Float()), desc="center of mass", ) @@ -749,7 +747,7 @@ class CenterMass(AFNICommandBase): output_spec = CenterMassOutputSpec def _list_outputs(self): - outputs = super(CenterMass, self)._list_outputs() + outputs = super()._list_outputs() outputs["out_file"] = os.path.abspath(self.inputs.in_file) outputs["cm_file"] = os.path.abspath(self.inputs.cm_file) sout = np.loadtxt(outputs["cm_file"], ndmin=2) @@ -892,7 +890,7 @@ class DotInputSpec(AFNICommandInputSpec): ) out_file = File(desc="collect output to a file", argstr=" |& tee %s", position=-1) mask = File(desc="Use this dataset as a mask", argstr="-mask %s") - mrange = traits.Tuple( + mrange = Tuple( (traits.Float(), traits.Float()), desc="Means to further restrict the voxels from 'mset' so that" "only those mask values within this range (inclusive) willbe used.", @@ -1033,7 +1031,7 @@ class Edge3(AFNICommand): _cmd = "3dedge3" input_spec = Edge3InputSpec output_spec = AFNICommandOutputSpec - references_ = [ + _references = [ { "entry": BibTeX( """\ @@ -1127,12 +1125,11 @@ def _format_arg(self, name, trait_spec, value): if isdefined(self.inputs.single_idx): arg += "[%d]" % (self.inputs.single_idx) return arg - return super(Eval, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _parse_inputs(self, skip=None): - """Skip the arguments without argstr metadata - """ - return super(Eval, self)._parse_inputs(skip=("start_idx", "stop_idx", "other")) + """Skip the arguments without argstr metadata""" + return super()._parse_inputs(skip=("start_idx", "stop_idx", "other")) class FWHMxInputSpec(CommandLineInputSpec): @@ -1218,7 +1215,7 @@ class FWHMxInputSpec(CommandLineInputSpec): acf = traits.Either( traits.Bool(), File(), - traits.Tuple(File(exists=True), traits.Float()), + Tuple(File(exists=True), traits.Float()), default=False, usedefault=True, argstr="-acf", @@ -1231,13 +1228,13 @@ class FWHMxOutputSpec(TraitedSpec): out_subbricks = File(exists=True, desc="output file (subbricks)") out_detrend = File(desc="output file, detrended") fwhm = traits.Either( - traits.Tuple(traits.Float(), traits.Float(), traits.Float()), - traits.Tuple(traits.Float(), traits.Float(), traits.Float(), traits.Float()), + Tuple(traits.Float(), traits.Float(), traits.Float()), + Tuple(traits.Float(), traits.Float(), traits.Float(), traits.Float()), desc="FWHM along each axis", ) acf_param = traits.Either( - traits.Tuple(traits.Float(), traits.Float(), traits.Float()), - traits.Tuple(traits.Float(), traits.Float(), traits.Float(), traits.Float()), + Tuple(traits.Float(), traits.Float(), traits.Float()), + Tuple(traits.Float(), traits.Float(), traits.Float(), traits.Float()), desc="fitted ACF model parameters", ) out_acf = File(exists=True, desc="output acf file") @@ -1343,7 +1340,7 @@ class FWHMx(AFNICommandBase): input_spec = FWHMxInputSpec output_spec = FWHMxOutputSpec - references_ = [ + _references = [ { "entry": BibTeX( "@article{CoxReynoldsTaylor2016," @@ -1354,7 +1351,7 @@ class FWHMx(AFNICommandBase): "}" ), "tags": ["method"], - }, + } ] _acf = True @@ -1363,7 +1360,7 @@ def _parse_inputs(self, skip=None): if skip is None: skip = [] skip += ["out_detrend"] - return super(FWHMx, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _format_arg(self, name, trait_spec, value): if name == "detrend": @@ -1384,10 +1381,10 @@ def _format_arg(self, name, trait_spec, value): return trait_spec.argstr + " %s %f" % value elif isinstance(value, (str, bytes)): return trait_spec.argstr + " " + value - return super(FWHMx, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _list_outputs(self): - outputs = super(FWHMx, self)._list_outputs() + outputs = super()._list_outputs() if self.inputs.detrend: fname, ext = op.splitext(self.inputs.in_file) @@ -1433,10 +1430,10 @@ class LocalBistatInputSpec(AFNICommandInputSpec): desc="Filename of the second image", ) neighborhood = traits.Either( - traits.Tuple(traits.Enum("SPHERE", "RHDD", "TOHD"), traits.Float()), - traits.Tuple( + Tuple(traits.Enum("SPHERE", "RHDD", "TOHD"), traits.Float()), + Tuple( traits.Enum("RECT"), - traits.Tuple(traits.Float(), traits.Float(), traits.Float()), + Tuple(traits.Float(), traits.Float(), traits.Float()), ), mandatory=True, desc="The region around each voxel that will be extracted for " @@ -1553,7 +1550,7 @@ def _format_arg(self, name, spec, value): if name == "neighborhood" and value[0] == "RECT": value = ("RECT", "%s,%s,%s" % value[1]) - return super(LocalBistat, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class LocalstatInputSpec(AFNICommandInputSpec): @@ -1561,10 +1558,10 @@ class LocalstatInputSpec(AFNICommandInputSpec): exists=True, mandatory=True, argstr="%s", position=-1, desc="input dataset" ) neighborhood = traits.Either( - traits.Tuple(traits.Enum("SPHERE", "RHDD", "TOHD"), traits.Float()), - traits.Tuple( + Tuple(traits.Enum("SPHERE", "RHDD", "TOHD"), traits.Float()), + Tuple( traits.Enum("RECT"), - traits.Tuple(traits.Float(), traits.Float(), traits.Float()), + Tuple(traits.Float(), traits.Float(), traits.Float()), ), mandatory=True, desc="The region around each voxel that will be extracted for " @@ -1598,9 +1595,9 @@ class LocalstatInputSpec(AFNICommandInputSpec): stat = InputMultiObject( traits.Either( traits.Enum(_stat_names), - traits.Tuple( + Tuple( traits.Enum("perc"), - traits.Tuple(traits.Float, traits.Float, traits.Float), + Tuple(traits.Float, traits.Float, traits.Float), ), ), mandatory=True, @@ -1673,7 +1670,7 @@ class LocalstatInputSpec(AFNICommandInputSpec): ) reduce_grid = traits.Either( traits.Float, - traits.Tuple(traits.Float, traits.Float, traits.Float), + Tuple(traits.Float, traits.Float, traits.Float), argstr="-reduce_grid %s", xor=["reduce_restore_grid", "reduce_max_vox"], desc="Compute output on a grid that is reduced by the specified " @@ -1687,10 +1684,10 @@ class LocalstatInputSpec(AFNICommandInputSpec): ) reduce_restore_grid = traits.Either( traits.Float, - traits.Tuple(traits.Float, traits.Float, traits.Float), + Tuple(traits.Float, traits.Float, traits.Float), argstr="-reduce_restore_grid %s", xor=["reduce_max_vox", "reduce_grid"], - desc="Like reduce_grid, but also resample output back to input" "grid.", + desc="Like reduce_grid, but also resample output back to input grid.", ) reduce_max_vox = traits.Float( argstr="-reduce_max_vox %s", @@ -1764,7 +1761,7 @@ def _format_arg(self, name, spec, value): if len(value) == 3: value = "%s %s %s" % value - return super(Localstat, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class MaskToolInputSpec(AFNICommandInputSpec): @@ -2014,7 +2011,7 @@ def _parse_inputs(self, skip=None): if skip is None: skip = [] skip += ["out_file"] - return super(NwarpAdjust, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _list_outputs(self): outputs = self.output_spec().get() @@ -2040,7 +2037,7 @@ class NwarpApplyInputSpec(CommandLineInputSpec): traits.List(File(exists=True)), mandatory=True, argstr="-source %s", - desc="the name of the dataset to be warped " "can be multiple datasets", + desc="the name of the dataset to be warped can be multiple datasets", ) warp = traits.String( desc="the name of the warp dataset. " @@ -2131,7 +2128,7 @@ class NwarpApply(AFNICommandBase): class NwarpCatInputSpec(AFNICommandInputSpec): in_files = traits.List( traits.Either( - File(), traits.Tuple(traits.Enum("IDENT", "INV", "SQRT", "SQRTINV"), File()) + File(), Tuple(traits.Enum("IDENT", "INV", "SQRT", "SQRTINV"), File()) ), desc="list of tuples of 3D warps and associated functions", mandatory=True, @@ -2139,7 +2136,7 @@ class NwarpCatInputSpec(AFNICommandInputSpec): position=-1, ) space = traits.String( - desc="string to attach to the output dataset as its atlas space " "marker.", + desc="string to attach to the output dataset as its atlas space marker.", argstr="-space %s", ) inv_warp = traits.Bool(desc="invert the final warp before output", argstr="-iwarp") @@ -2153,7 +2150,7 @@ class NwarpCatInputSpec(AFNICommandInputSpec): usedefault=True, ) expad = traits.Int( - desc="Pad the nonlinear warps by the given number of voxels voxels in " + desc="Pad the nonlinear warps by the given number of voxels in " "all directions. The warp displacements are extended by linear " "extrapolation from the faces of the input grid..", argstr="-expad %d", @@ -2233,7 +2230,7 @@ def _format_arg(self, name, spec, value): ] ) ) - return super(NwarpCat, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_filename(self, name): if name == "out_file": @@ -2277,7 +2274,7 @@ class OneDToolPyInputSpec(AFNIPythonCommandInputSpec): "file, and zeros are simply counted.", argstr="-show_censor_count", ) - censor_motion = traits.Tuple( + censor_motion = Tuple( (traits.Float(), File()), desc="Tuple of motion limit and outfile prefix. need to also set set_nruns -r set_run_lengths", argstr="-censor_motion %f %s", @@ -2325,8 +2322,7 @@ class OneDToolPy(AFNIPythonCommand): >>> odt.inputs.out_file = 'motion_dmean.1D' >>> odt.cmdline # doctest: +ELLIPSIS 'python2 ...1d_tool.py -demean -infile f1.1D -write motion_dmean.1D -set_nruns 3' - >>> res = odt.run() # doctest: +SKIP -""" + >>> res = odt.run() # doctest: +SKIP""" _cmd = "1d_tool.py" @@ -2386,7 +2382,7 @@ class RefitInputSpec(CommandLineInputSpec): desc="Associates the dataset with a specific template type, e.g. " "TLRC, MNI, ORIG", ) - atrcopy = traits.Tuple( + atrcopy = Tuple( File(exists=True), traits.Str(), argstr="-atrcopy %s %s", @@ -2397,7 +2393,7 @@ class RefitInputSpec(CommandLineInputSpec): "advanced users only. Do NOT use -atrcopy or -atrstring with " "other modification options. See also -copyaux.", ) - atrstring = traits.Tuple( + atrstring = Tuple( traits.Str(), traits.Str(), argstr="-atrstring %s %s", @@ -2405,7 +2401,7 @@ class RefitInputSpec(CommandLineInputSpec): "giving it the attribute name given by the last string." "To be safe, the last string should be in quotes.", ) - atrfloat = traits.Tuple( + atrfloat = Tuple( traits.Str(), traits.Str(), argstr="-atrfloat %s %s", @@ -2415,7 +2411,7 @@ class RefitInputSpec(CommandLineInputSpec): "'1 0.2 0 0 -0.2 1 0 0 0 0 1 0' or " "flipZ.1D or '1D:1,0.2,2@0,-0.2,1,2@0,2@0,1,0'", ) - atrint = traits.Tuple( + atrint = Tuple( traits.Str(), traits.Str(), argstr="-atrint %s %s", @@ -2529,7 +2525,7 @@ class ReHoInputSpec(CommandLineInputSpec): but you can choose most any value.""", ) - ellipsoid = traits.Tuple( + ellipsoid = Tuple( traits.Float, traits.Float, traits.Float, @@ -2557,11 +2553,11 @@ class ReHoInputSpec(CommandLineInputSpec): class ReHoOutputSpec(TraitedSpec): out_file = File(exists=True, desc="Voxelwise regional homogeneity map") - out_vals = File(desc="Table of labelwise regional homogenity values") + out_vals = File(desc="Table of labelwise regional homogeneity values") class ReHo(AFNICommandBase): - """Compute regional homogenity for a given neighbourhood.l, + """Compute regional homogeneity for a given neighbourhood.l, based on a local neighborhood of that voxel. For complete details, see the `3dReHo Documentation. @@ -2585,24 +2581,19 @@ class ReHo(AFNICommandBase): output_spec = ReHoOutputSpec def _list_outputs(self): - outputs = super(ReHo, self)._list_outputs() + outputs = super()._list_outputs() if self.inputs.label_set: outputs["out_vals"] = outputs["out_file"] + "_ROI_reho.vals" return outputs def _format_arg(self, name, spec, value): - _neigh_dict = { - "faces": 7, - "edges": 19, - "vertices": 27, - } + _neigh_dict = {"faces": 7, "edges": 19, "vertices": 27} if name == "neighborhood": value = _neigh_dict[value] - return super(ReHo, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class ResampleInputSpec(AFNICommandInputSpec): - in_file = File( desc="input file to 3dresample", argstr="-inset %s", @@ -2628,10 +2619,10 @@ class ResampleInputSpec(AFNICommandInputSpec): 'for "Nearest Neighbor", "Linear", "Cubic" and "Blocky"' "interpolation, respectively. Default is NN.", ) - voxel_size = traits.Tuple( + voxel_size = Tuple( *[traits.Float()] * 3, argstr="-dxyz %f %f %f", - desc="resample to new dx, dy and dz" + desc="resample to new dx, dy and dz", ) master = File(argstr="-master %s", desc="align dataset grid to a reference file") @@ -2721,7 +2712,7 @@ class TCat(AFNICommand): class TCatSBInputSpec(AFNICommandInputSpec): in_files = traits.List( - traits.Tuple(File(exists=True), Str()), + Tuple(File(exists=True), Str()), desc="List of tuples of file names and subbrick selectors as strings." "Don't forget to protect the single quotes in the subbrick selector" "so the contents are protected from the command line interpreter.", @@ -2747,7 +2738,7 @@ class TCatSBInputSpec(AFNICommandInputSpec): class TCatSubBrick(AFNICommand): """Hopefully a temporary function to allow sub-brick selection until - afni file managment is improved. + afni file management is improved. For complete details, see the `3dTcat Documentation. `_ @@ -2892,7 +2883,7 @@ class To3D(AFNICommand): 'to3d -datum float -anat -prefix dicomdir.nii ./*.dcm' >>> res = to3d.run() # doctest: +SKIP - """ + """ _cmd = "to3d" input_spec = To3DInputSpec @@ -2943,7 +2934,7 @@ class UndumpInputSpec(AFNICommandInputSpec): "then each input data line sets the value in only one voxel.", argstr="-srad %f", ) - orient = traits.Tuple( + orient = Tuple( traits.Enum("R", "L"), traits.Enum("A", "P"), traits.Enum("I", "S"), @@ -3067,7 +3058,7 @@ class UnifizeInputSpec(AFNICommandInputSpec): requires=["no_duplo", "t2"], xor=["gm"], ) - rbt = traits.Tuple( + rbt = Tuple( traits.Float(), traits.Float(), traits.Float(), @@ -3246,18 +3237,18 @@ class GCOR(CommandLine): output_spec = GCOROutputSpec def _run_interface(self, runtime): - runtime = super(GCOR, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) gcor_line = [ line.strip() for line in runtime.stdout.split("\n") if line.strip().startswith("GCOR = ") ][-1] - setattr(self, "_gcor", float(gcor_line[len("GCOR = ") :])) + self._gcor = float(gcor_line[len("GCOR = ") :]) return runtime def _list_outputs(self): - return {"out": getattr(self, "_gcor")} + return {"out": self._gcor} class AxializeInputSpec(AFNICommandInputSpec): diff --git a/nipype/interfaces/ants/__init__.py b/nipype/interfaces/ants/__init__.py index 389a5f1371..e8157a0312 100644 --- a/nipype/interfaces/ants/__init__.py +++ b/nipype/interfaces/ants/__init__.py @@ -1,15 +1,14 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Top-level namespace for ants.""" -# Registraiton programs +# Registration programs from .registration import ( ANTS, - Registration, - RegistrationSynQuick, CompositeTransformUtil, MeasureImageSimilarity, + Registration, + RegistrationSynQuick, ) # Resampling Programs @@ -22,14 +21,14 @@ # Segmentation Programs from .segmentation import ( + AntsJointFusion, Atropos, - LaplacianThickness, - N4BiasFieldCorrection, - JointFusion, - CorticalThickness, BrainExtraction, + CorticalThickness, DenoiseImage, - AntsJointFusion, + JointFusion, + LaplacianThickness, + N4BiasFieldCorrection, ) # Visualization Programs @@ -37,11 +36,48 @@ # Utility Programs from .utils import ( + AffineInitializer, + AI, AverageAffineTransform, AverageImages, - MultiplyImages, - CreateJacobianDeterminantImage, - AffineInitializer, ComposeMultiTransform, + CreateJacobianDeterminantImage, + ImageMath, LabelGeometry, + MultiplyImages, + ResampleImageBySpacing, + ThresholdImage, ) + +__all__ = [ + "AI", + "ANTS", + "AffineInitializer", + "AntsJointFusion", + "ApplyTransforms", + "ApplyTransformsToPoints", + "Atropos", + "AverageAffineTransform", + "AverageImages", + "BrainExtraction", + "ComposeMultiTransform", + "CompositeTransformUtil", + "ConvertScalarImageToRGB", + "CorticalThickness", + "CreateJacobianDeterminantImage", + "CreateTiledMosaic", + "DenoiseImage", + "ImageMath", + "JointFusion", + "LabelGeometry", + "LaplacianThickness", + "MeasureImageSimilarity", + "MultiplyImages", + "N4BiasFieldCorrection", + "Registration", + "RegistrationSynQuick", + "ResampleImageBySpacing", + "ThresholdImage", + "WarpImageMultiTransform", + "WarpTimeSeriesImageMultiTransform", +] diff --git a/nipype/interfaces/ants/base.py b/nipype/interfaces/ants/base.py index 4b5e5ef8db..c78a375b02 100644 --- a/nipype/interfaces/ants/base.py +++ b/nipype/interfaces/ants/base.py @@ -1,16 +1,16 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The ants module provides basic functions for interfacing with ANTS tools.""" import os +from packaging.version import parse # Local imports -from ... import logging, LooseVersion +from ... import logging from ..base import CommandLine, CommandLineInputSpec, traits, isdefined, PackageInfo iflogger = logging.getLogger("nipype.interface") -# -Using -1 gives primary responsibilty to ITKv4 to do the correct +# -Using -1 gives primary responsibility to ITKv4 to do the correct # thread limitings. # -Using 1 takes a very conservative approach to avoid overloading # the computer (when running MultiProc) by forcing everything to @@ -19,7 +19,7 @@ LOCAL_DEFAULT_NUMBER_OF_THREADS = 1 # -Using NSLOTS has the same behavior as ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS # as long as ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS is not set. Otherwise -# ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS takes precidence. +# ITK_GLOBAL_DEFAULT_NUMBER_OF_THREADS takes precedence. # This behavior states that you the user explicitly specifies # num_threads, then respect that no matter what SGE tries to limit. PREFERED_ITKv4_THREAD_LIMIT_VARIABLE = "NSLOTS" @@ -43,18 +43,20 @@ def parse_version(raw_info): # -githash may or may not be appended v_string = v_string.split("-")[0] - # 2.2.0-equivalent version string - if "post" in v_string and LooseVersion(v_string) >= LooseVersion( - "2.1.0.post789" - ): - return "2.2.0" - else: - return ".".join(v_string.split(".")[:3]) + version = parse(v_string) + + # Known mislabeled versions + if version.is_postrelease: + if version.base_version == "2.1.0" and version.post >= 789: + return "2.2.0" + + # Unless we know of a specific reason to re-version, we will + # treat the base version (before pre/post/dev) as authoritative + return version.base_version class ANTSCommandInputSpec(CommandLineInputSpec): - """Base Input Specification for all ANTS Commands - """ + """Base Input Specification for all ANTS Commands""" num_threads = traits.Int( LOCAL_DEFAULT_NUMBER_OF_THREADS, @@ -65,14 +67,13 @@ class ANTSCommandInputSpec(CommandLineInputSpec): class ANTSCommand(CommandLine): - """Base class for ANTS interfaces - """ + """Base class for ANTS interfaces""" input_spec = ANTSCommandInputSpec _num_threads = LOCAL_DEFAULT_NUMBER_OF_THREADS def __init__(self, **inputs): - super(ANTSCommand, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._num_threads_update, "num_threads") if not isdefined(self.inputs.num_threads): @@ -103,8 +104,8 @@ def _num_threads_update(self): @staticmethod def _format_xarray(val): - """ Convenience method for converting input arrays [1,2,3] to - commandline format '1x2x3' """ + """Convenience method for converting input arrays [1,2,3] to + commandline format '1x2x3'""" return "x".join([str(x) for x in val]) @classmethod diff --git a/nipype/interfaces/ants/legacy.py b/nipype/interfaces/ants/legacy.py new file mode 100644 index 0000000000..373ca4982a --- /dev/null +++ b/nipype/interfaces/ants/legacy.py @@ -0,0 +1,367 @@ +"""ANTS Legacy Interfaces + +These interfaces are for programs that have been deprecated by ANTs, but +are preserved for backwards compatibility. +""" + +import os +from glob import glob + +from .base import ANTSCommand, ANTSCommandInputSpec +from ..base import TraitedSpec, File, traits, isdefined, OutputMultiPath +from ...utils.filemanip import split_filename + + +class antsIntroductionInputSpec(ANTSCommandInputSpec): + dimension = traits.Enum( + 3, + 2, + argstr="-d %d", + usedefault=True, + desc="image dimension (2 or 3)", + position=1, + ) + reference_image = File( + exists=True, + argstr="-r %s", + desc="template file to warp to", + mandatory=True, + copyfile=True, + ) + input_image = File( + exists=True, + argstr="-i %s", + desc="input image to warp to template", + mandatory=True, + copyfile=False, + ) + force_proceed = traits.Bool( + argstr="-f 1", + desc=("force script to proceed even if headers may be incompatible"), + ) + inverse_warp_template_labels = traits.Bool( + argstr="-l", + desc=( + "Applies inverse warp to the template labels " + "to estimate label positions in target space (use " + "for template-based segmentation)" + ), + ) + max_iterations = traits.List( + traits.Int, + argstr="-m %s", + sep="x", + desc=( + "maximum number of iterations (must be " + "list of integers in the form [J,K,L...]: " + "J = coarsest resolution iterations, K = " + "middle resolution iterations, L = fine " + "resolution iterations" + ), + ) + bias_field_correction = traits.Bool( + argstr="-n 1", desc=("Applies bias field correction to moving image") + ) + similarity_metric = traits.Enum( + "PR", + "CC", + "MI", + "MSQ", + argstr="-s %s", + desc=( + "Type of similartiy metric used for registration " + "(CC = cross correlation, MI = mutual information, " + "PR = probability mapping, MSQ = mean square difference)" + ), + ) + transformation_model = traits.Enum( + "GR", + "EL", + "SY", + "S2", + "EX", + "DD", + "RI", + "RA", + argstr="-t %s", + usedefault=True, + desc=( + "Type of transofmration model used for registration " + "(EL = elastic transformation model, SY = SyN with time, " + "arbitrary number of time points, S2 = SyN with time " + "optimized for 2 time points, GR = greedy SyN, EX = " + "exponential, DD = diffeomorphic demons style exponential " + "mapping, RI = purely rigid, RA = affine rigid" + ), + ) + out_prefix = traits.Str( + "ants_", + argstr="-o %s", + usedefault=True, + desc=("Prefix that is prepended to all output files (default = ants_)"), + ) + quality_check = traits.Bool( + argstr="-q 1", desc="Perform a quality check of the result" + ) + + +class antsIntroductionOutputSpec(TraitedSpec): + affine_transformation = File(exists=True, desc="affine (prefix_Affine.txt)") + warp_field = File(exists=True, desc="warp field (prefix_Warp.nii)") + inverse_warp_field = File( + exists=True, desc="inverse warp field (prefix_InverseWarp.nii)" + ) + input_file = File(exists=True, desc="input image (prefix_repaired.nii)") + output_file = File(exists=True, desc="output image (prefix_deformed.nii)") + + +class antsIntroduction(ANTSCommand): + """Uses ANTS to generate matrices to warp data from one space to another. + + Examples + -------- + + >>> from nipype.interfaces.ants.legacy import antsIntroduction + >>> warp = antsIntroduction() + >>> warp.inputs.reference_image = 'Template_6.nii' + >>> warp.inputs.input_image = 'structural.nii' + >>> warp.inputs.max_iterations = [30,90,20] + >>> warp.cmdline + 'antsIntroduction.sh -d 3 -i structural.nii -m 30x90x20 -o ants_ -r Template_6.nii -t GR' + + """ + + _cmd = "antsIntroduction.sh" + input_spec = antsIntroductionInputSpec + output_spec = antsIntroductionOutputSpec + + def _list_outputs(self): + outputs = self._outputs().get() + transmodel = self.inputs.transformation_model + + # When transform is set as 'RI'/'RA', wrap fields should not be expected + # The default transformation is GR, which outputs the wrap fields + if not isdefined(transmodel) or ( + isdefined(transmodel) and transmodel not in ["RI", "RA"] + ): + outputs["warp_field"] = os.path.join( + os.getcwd(), self.inputs.out_prefix + "Warp.nii.gz" + ) + outputs["inverse_warp_field"] = os.path.join( + os.getcwd(), self.inputs.out_prefix + "InverseWarp.nii.gz" + ) + + outputs["affine_transformation"] = os.path.join( + os.getcwd(), self.inputs.out_prefix + "Affine.txt" + ) + outputs["input_file"] = os.path.join( + os.getcwd(), self.inputs.out_prefix + "repaired.nii.gz" + ) + outputs["output_file"] = os.path.join( + os.getcwd(), self.inputs.out_prefix + "deformed.nii.gz" + ) + + return outputs + + +# How do we make a pass through so that GenWarpFields is just an alias for antsIntroduction ? + + +class GenWarpFields(antsIntroduction): + pass + + +class buildtemplateparallelInputSpec(ANTSCommandInputSpec): + dimension = traits.Enum( + 3, + 2, + 4, + argstr="-d %d", + usedefault=True, + desc="image dimension (2, 3 or 4)", + position=1, + ) + out_prefix = traits.Str( + "antsTMPL_", + argstr="-o %s", + usedefault=True, + desc=("Prefix that is prepended to all output files (default = antsTMPL_)"), + ) + in_files = traits.List( + File(exists=True), + mandatory=True, + desc="list of images to generate template from", + argstr="%s", + position=-1, + ) + parallelization = traits.Enum( + 0, + 1, + 2, + argstr="-c %d", + usedefault=True, + desc=( + "control for parallel processing (0 = " + "serial, 1 = use PBS, 2 = use PEXEC, 3 = " + "use Apple XGrid" + ), + ) + gradient_step_size = traits.Float( + argstr="-g %f", + desc=("smaller magnitude results in more cautious steps (default = .25)"), + ) + iteration_limit = traits.Int( + 4, argstr="-i %d", usedefault=True, desc="iterations of template construction" + ) + num_cores = traits.Int( + argstr="-j %d", + requires=["parallelization"], + desc=("Requires parallelization = 2 (PEXEC). Sets number of cpu cores to use"), + ) + max_iterations = traits.List( + traits.Int, + argstr="-m %s", + sep="x", + desc=( + "maximum number of iterations (must be " + "list of integers in the form [J,K,L...]: " + "J = coarsest resolution iterations, K = " + "middle resolution iterations, L = fine " + "resolution iterations" + ), + ) + bias_field_correction = traits.Bool( + argstr="-n 1", desc=("Applies bias field correction to moving image") + ) + rigid_body_registration = traits.Bool( + argstr="-r 1", + desc=( + "registers inputs before creating template " + "(useful if no initial template available)" + ), + ) + similarity_metric = traits.Enum( + "PR", + "CC", + "MI", + "MSQ", + argstr="-s %s", + desc=( + "Type of similartiy metric used for registration " + "(CC = cross correlation, MI = mutual information, " + "PR = probability mapping, MSQ = mean square difference)" + ), + ) + transformation_model = traits.Enum( + "GR", + "EL", + "SY", + "S2", + "EX", + "DD", + argstr="-t %s", + usedefault=True, + desc=( + "Type of transofmration model used for registration " + "(EL = elastic transformation model, SY = SyN with time, " + "arbitrary number of time points, S2 = SyN with time " + "optimized for 2 time points, GR = greedy SyN, EX = " + "exponential, DD = diffeomorphic demons style exponential " + "mapping" + ), + ) + use_first_as_target = traits.Bool( + desc=( + "uses first volume as target of " + "all inputs. When not used, an " + "unbiased average image is used " + "to start." + ) + ) + + +class buildtemplateparallelOutputSpec(TraitedSpec): + final_template_file = File(exists=True, desc="final ANTS template") + template_files = OutputMultiPath( + File(exists=True), desc="Templates from different stages of iteration" + ) + subject_outfiles = OutputMultiPath( + File(exists=True), + desc=( + "Outputs for each input image. Includes warp " + "field, inverse warp, Affine, original image " + "(repaired) and warped image (deformed)" + ), + ) + + +class buildtemplateparallel(ANTSCommand): + """Generate a optimal average template + + .. warning:: + + This can take a VERY long time to complete + + Examples + -------- + + >>> from nipype.interfaces.ants.legacy import buildtemplateparallel + >>> tmpl = buildtemplateparallel() + >>> tmpl.inputs.in_files = ['T1.nii', 'structural.nii'] + >>> tmpl.inputs.max_iterations = [30, 90, 20] + >>> tmpl.cmdline + 'buildtemplateparallel.sh -d 3 -i 4 -m 30x90x20 -o antsTMPL_ -c 0 -t GR T1.nii structural.nii' + + """ + + _cmd = "buildtemplateparallel.sh" + input_spec = buildtemplateparallelInputSpec + output_spec = buildtemplateparallelOutputSpec + + def _format_arg(self, opt, spec, val): + if opt == "num_cores": + if self.inputs.parallelization == 2: + return "-j " + str(val) + else: + return "" + if opt == "in_files": + if self.inputs.use_first_as_target: + start = "-z " + else: + start = "" + return start + " ".join(name for name in val) + return super()._format_arg(opt, spec, val) + + def _list_outputs(self): + outputs = self._outputs().get() + outputs["template_files"] = [] + for i in range(len(glob(os.path.realpath("*iteration*")))): + temp = os.path.realpath( + "%s_iteration_%d/%stemplate.nii.gz" + % (self.inputs.transformation_model, i, self.inputs.out_prefix) + ) + os.rename( + temp, + os.path.realpath( + "%s_iteration_%d/%stemplate_i%d.nii.gz" + % (self.inputs.transformation_model, i, self.inputs.out_prefix, i) + ), + ) + file_ = "%s_iteration_%d/%stemplate_i%d.nii.gz" % ( + self.inputs.transformation_model, + i, + self.inputs.out_prefix, + i, + ) + + outputs["template_files"].append(os.path.realpath(file_)) + outputs["final_template_file"] = os.path.realpath( + "%stemplate.nii.gz" % self.inputs.out_prefix + ) + outputs["subject_outfiles"] = [] + for filename in self.inputs.in_files: + _, base, _ = split_filename(filename) + temp = glob(os.path.realpath(f"{self.inputs.out_prefix}{base}*")) + for file_ in temp: + outputs["subject_outfiles"].append(file_) + return outputs diff --git a/nipype/interfaces/ants/registration.py b/nipype/interfaces/ants/registration.py index cb8e363c04..55e9738170 100644 --- a/nipype/interfaces/ants/registration.py +++ b/nipype/interfaces/ants/registration.py @@ -1,11 +1,11 @@ -# -*- coding: utf-8 -*- """The ants module provides basic functions for interfacing with ants - functions. +functions. """ + import os from ...utils.filemanip import ensure_list -from ..base import TraitedSpec, File, Str, traits, InputMultiPath, isdefined +from ..base import TraitedSpec, File, Str, traits, InputMultiPath, isdefined, Tuple from .base import ANTSCommand, ANTSCommandInputSpec, LOCAL_DEFAULT_NUMBER_OF_THREADS @@ -16,7 +16,7 @@ class ANTSInputSpec(ANTSCommandInputSpec): fixed_image = InputMultiPath( File(exists=True), mandatory=True, - desc=("image to which the moving image is " "warped"), + desc=("image to which the moving image is warped"), ) moving_image = InputMultiPath( File(exists=True), @@ -190,10 +190,11 @@ def _transformation_constructor(self): delta_time = self.inputs.delta_time symmetry_type = self.inputs.symmetry_type retval = ["--transformation-model %s" % model] - parameters = [] - for elem in (step_length, time_step, delta_time, symmetry_type): - if elem is not traits.Undefined: - parameters.append("%#.2g" % elem) + parameters = [ + "%#.2g" % elem + for elem in (step_length, time_step, delta_time, symmetry_type) + if elem is not traits.Undefined + ] if len(parameters) > 0: if len(parameters) > 1: parameters = ",".join(parameters) @@ -203,7 +204,7 @@ def _transformation_constructor(self): return "".join(retval) def _regularization_constructor(self): - return "--regularization {0}[{1},{2}]".format( + return "--regularization {}[{},{}]".format( self.inputs.regularization, self.inputs.regularization_gradient_field_sigma, self.inputs.regularization_deformation_field_sigma, @@ -237,7 +238,7 @@ def _format_arg(self, opt, spec, val): return "--use-Histogram-Matching 1" else: return "--use-Histogram-Matching 0" - return super(ANTS, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -418,14 +419,14 @@ class RegistrationInputSpec(ANTSCommandInputSpec): "BSpline", "MultiLabel", "Gaussian", + "GenericLabel", argstr="%s", usedefault=True, ) interpolation_parameters = traits.Either( - traits.Tuple(traits.Int()), # BSpline (order) - traits.Tuple( - traits.Float(), traits.Float() # Gaussian/MultiLabel (sigma, alpha) - ), + Tuple(traits.Int()), # BSpline (order) + Tuple(traits.Float(), traits.Float()), # Gaussian/MultiLabel (sigma, alpha) + Tuple(traits.Str()), # GenericLabel (interpolator) ) write_composite_transform = traits.Bool( @@ -451,7 +452,7 @@ class RegistrationInputSpec(ANTSCommandInputSpec): usedefault=True, # This should be true for explicit completeness desc=( "Initialize linear transforms from the previous stage. By enabling this option, " - "the current linear stage transform is directly intialized from the previous " + "the current linear stage transform is directly initialized from the previous " "stages linear transform; this allows multiple linear stages to be run where " "each stage directly updates the estimated linear transform from the previous " "stage. (e.g. Translation -> Rigid -> Affine). " @@ -489,20 +490,20 @@ class RegistrationInputSpec(ANTSCommandInputSpec): # Exponential, and BSplineExponential. EVEN DEFAULTS! transform_parameters = traits.List( traits.Either( - traits.Tuple(traits.Float()), # Translation, Rigid, Affine, + Tuple(traits.Float()), # Translation, Rigid, Affine, # CompositeAffine, Similarity - traits.Tuple( + Tuple( traits.Float(), # GaussianDisplacementField, SyN traits.Float(), traits.Float(), ), - traits.Tuple( + Tuple( traits.Float(), # BSplineSyn, traits.Int(), # BSplineDisplacementField, traits.Int(), # TimeVaryingBSplineVelocityField traits.Int(), ), - traits.Tuple( + Tuple( traits.Float(), # TimeVaryingVelocityField traits.Int(), traits.Float(), @@ -510,13 +511,13 @@ class RegistrationInputSpec(ANTSCommandInputSpec): traits.Float(), traits.Float(), ), - traits.Tuple( + Tuple( traits.Float(), # Exponential traits.Float(), traits.Float(), traits.Int(), ), - traits.Tuple( + Tuple( traits.Float(), # BSplineExponential traits.Int(), traits.Int(), @@ -526,7 +527,7 @@ class RegistrationInputSpec(ANTSCommandInputSpec): ) ) restrict_deformation = traits.List( - traits.List(traits.Enum(0, 1)), + traits.List(traits.Range(low=0.0, high=1.0)), desc=( "This option allows the user to restrict the optimization of " "the displacement field, translation, rigid or affine transform " @@ -583,20 +584,34 @@ class RegistrationInputSpec(ANTSCommandInputSpec): usedefault=True, desc="The Lower quantile to clip image ranges", ) - - verbose = traits.Bool(argstr="-v", default_value=False, usedefault=True) + random_seed = traits.Int( + argstr="--random-seed %d", + desc="Fixed seed for random number generation", + min_ver="2.3.0", + ) + verbose = traits.Bool( + argstr="-v", default_value=False, usedefault=True, nohash=True + ) class RegistrationOutputSpec(TraitedSpec): forward_transforms = traits.List( File(exists=True), desc="List of output transforms for forward registration" ) + reverse_forward_transforms = traits.List( + File(exists=True), + desc="List of output transforms for forward registration reversed for antsApplyTransform", + ) reverse_transforms = traits.List( File(exists=True), desc="List of output transforms for reverse registration" ) forward_invert_flags = traits.List( traits.Bool(), desc="List of flags corresponding to the forward transforms" ) + reverse_forward_invert_flags = traits.List( + traits.Bool(), + desc="List of flags corresponding to the forward transforms reversed for antsApplyTransform", + ) reverse_invert_flags = traits.List( traits.Bool(), desc="List of flags corresponding to the reverse transforms" ) @@ -625,7 +640,7 @@ class Registration(ANTSCommand): *stages*. For example first an Affine, then a Rigid, and ultimately a non-linear (Syn)-transformation. - antsRegistration can be initialized using one ore more transforms from moving_image + antsRegistration can be initialized using one or more transforms from moving_image to fixed_image with the ``initial_moving_transform``-input. For example, when you already have a warpfield that corrects for geometrical distortions in an EPI (functional) image, that you want to apply before an Affine registration to a structural image. @@ -695,9 +710,9 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ +--use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] --convergence [ 100x50x30, 1e-09, 20 ] \ ---smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 --use-estimate-learning-rate-once 1 \ +--smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] --write-composite-transform 1' >>> reg.run() # doctest: +SKIP @@ -711,9 +726,9 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ +--use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] --convergence [ 100x50x30, 1e-09, 20 ] \ ---smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 --use-estimate-learning-rate-once 1 \ +--smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ --use-histogram-matching 1 --winsorize-image-intensities [ 0.025, 1.0 ] --write-composite-transform 1' >>> reg1.run() # doctest: +SKIP @@ -727,9 +742,9 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ +--use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] --convergence [ 100x50x30, 1e-09, 20 ] \ ---smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 --use-estimate-learning-rate-once 1 \ +--smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 0.975 ] --write-composite-transform 1' Clip extremely low intensity data points using winsorize_lower_quantile. All data points @@ -744,9 +759,9 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ +--use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] --convergence [ 100x50x30, 1e-09, 20 ] \ ---smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 --use-estimate-learning-rate-once 1 \ +--smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ --use-histogram-matching 1 --winsorize-image-intensities [ 0.025, 0.975 ] --write-composite-transform 1' Use float instead of double for computations (saves memory usage) @@ -758,10 +773,10 @@ class Registration(ANTSCommand): --initial-moving-transform [ trans.mat, 1 ] --initialize-transforms-per-stage 0 --interpolation Linear \ --output [ output_, output_warped_image.nii.gz ] --transform Affine[ 2.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] --convergence [ 1500x200, 1e-08, 20 ] \ ---smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-estimate-learning-rate-once 1 --use-histogram-matching 1 \ +--smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-histogram-matching 1 \ --transform SyN[ 0.25, 3.0, 0.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] \ --convergence [ 100x50x30, 1e-09, 20 ] --smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ +--use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ --write-composite-transform 1' Force to use double instead of float for computations (more precision and memory usage). @@ -773,10 +788,10 @@ class Registration(ANTSCommand): --initial-moving-transform [ trans.mat, 1 ] --initialize-transforms-per-stage 0 --interpolation Linear \ --output [ output_, output_warped_image.nii.gz ] --transform Affine[ 2.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] --convergence [ 1500x200, 1e-08, 20 ] \ ---smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-estimate-learning-rate-once 1 --use-histogram-matching 1 \ +--smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-histogram-matching 1 \ --transform SyN[ 0.25, 3.0, 0.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] \ --convergence [ 100x50x30, 1e-09, 20 ] --smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ +--use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ --write-composite-transform 1' 'collapse_output_transforms' can be used to put all transformation in a single 'composite_transform'- @@ -797,6 +812,8 @@ class Registration(ANTSCommand): 'inverse_composite_transform': '...data/output_InverseComposite.h5', 'inverse_warped_image': , 'metric_value': , + 'reverse_forward_invert_flags': [], + 'reverse_forward_transforms': [], 'reverse_invert_flags': [], 'reverse_transforms': [], 'save_state': '...data/trans.mat', @@ -806,10 +823,10 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 1 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --restore-state trans.mat --save-state trans.mat --transform Affine[ 2.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] --convergence [ 1500x200, 1e-08, 20 ] \ ---smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-estimate-learning-rate-once 1 --use-histogram-matching 1 \ +--smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-histogram-matching 1 \ --transform SyN[ 0.25, 3.0, 0.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] \ --convergence [ 100x50x30, 1e-09, 20 ] --smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ +--use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ --write-composite-transform 1' @@ -826,6 +843,9 @@ class Registration(ANTSCommand): 'inverse_composite_transform': , 'inverse_warped_image': , 'metric_value': , + 'reverse_forward_invert_flags': [False, False], + 'reverse_forward_transforms': ['...data/output_1Warp.nii.gz', + '...data/output_0GenericAffine.mat'], 'reverse_invert_flags': [True, False], 'reverse_transforms': ['...data/output_0GenericAffine.mat', \ '...data/output_1InverseWarp.nii.gz'], @@ -837,14 +857,14 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 1 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --restore-state trans.mat --save-state trans.mat --transform Affine[ 2.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] --convergence [ 1500x200, 1e-08, 20 ] \ ---smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-estimate-learning-rate-once 1 --use-histogram-matching 1 \ +--smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-histogram-matching 1 \ --transform SyN[ 0.25, 3.0, 0.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] \ --convergence [ 100x50x30, 1e-09, 20 ] --smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ +--use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ --write-composite-transform 0' One can use multiple similarity metrics in a single registration stage.The Node below first - performs a linear registation using only the Mutual Information ('Mattes')-metric. + performs a linear registration using only the Mutual Information ('Mattes')-metric. In a second stage, it performs a non-linear registration ('Syn') using both a Mutual Information and a local cross-correlation ('CC')-metric. Both metrics are weighted equally ('metric_weight' is .5 for both). The Mutual Information- metric uses 32 bins. @@ -865,10 +885,10 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ +--use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 0.5, 32, None, 0.05 ] \ --metric CC[ fixed1.nii, moving1.nii, 0.5, 4, None, 0.1 ] --convergence [ 100x50x30, 1e-09, 20 ] \ ---smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 --use-estimate-learning-rate-once 1 \ +--smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] --write-composite-transform 1' ANTS Registration can also use multiple modalities to perform the registration. Here it is assumed @@ -886,10 +906,10 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ +--use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 0.5, 32, None, 0.05 ] \ --metric CC[ fixed2.nii, moving2.nii, 0.5, 4, None, 0.1 ] --convergence [ 100x50x30, 1e-09, 20 ] \ ---smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 --use-estimate-learning-rate-once 1 \ +--smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] --write-composite-transform 1' Different methods can be used for the interpolation when applying transformations. @@ -903,9 +923,9 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation BSpline[ 3 ] --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ +--use-histogram-matching 1 --transform SyN[ 0.25, 3.0, 0.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] --convergence [ 100x50x30, 1e-09, 20 ] \ ---smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 --use-estimate-learning-rate-once 1 \ +--smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] --write-composite-transform 1' >>> # Test Interpolation Parameters (MultiLabel/Gaussian) @@ -917,10 +937,10 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Gaussian[ 1.0, 1.0 ] \ --output [ output_, output_warped_image.nii.gz ] --transform Affine[ 2.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] --convergence [ 1500x200, 1e-08, 20 ] \ ---smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-estimate-learning-rate-once 1 --use-histogram-matching 1 \ +--smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-histogram-matching 1 \ --transform SyN[ 0.25, 3.0, 0.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] \ --convergence [ 100x50x30, 1e-09, 20 ] --smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ +--use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ --write-composite-transform 1' BSplineSyN non-linear registration with custom parameters. @@ -934,9 +954,9 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --transform BSplineSyN[ 0.25, 26, 0, 3 ] \ +--use-histogram-matching 1 --transform BSplineSyN[ 0.25, 26, 0, 3 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] --convergence [ 100x50x30, 1e-09, 20 ] \ ---smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 --use-estimate-learning-rate-once 1 \ +--smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] --write-composite-transform 1' Mask the fixed image in the second stage of the registration (but not the first). @@ -949,10 +969,10 @@ class Registration(ANTSCommand): --initialize-transforms-per-stage 0 --interpolation Linear --output [ output_, output_warped_image.nii.gz ] \ --transform Affine[ 2.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] \ --convergence [ 1500x200, 1e-08, 20 ] --smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --masks [ NULL, NULL ] \ +--use-histogram-matching 1 --masks [ NULL, NULL ] \ --transform SyN[ 0.25, 3.0, 0.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] \ --convergence [ 100x50x30, 1e-09, 20 ] --smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --masks [ fixed1.nii, NULL ] \ +--use-histogram-matching 1 --masks [ fixed1.nii, NULL ] \ --winsorize-image-intensities [ 0.0, 1.0 ] --write-composite-transform 1' Here we use both a warpfield and a linear transformation, before registration commences. Note that @@ -968,10 +988,10 @@ class Registration(ANTSCommand): [ func_to_struct.mat, 0 ] [ ants_Warp.nii.gz, 0 ] --initialize-transforms-per-stage 0 --interpolation Linear \ --output [ output_, output_warped_image.nii.gz ] --transform Affine[ 2.0 ] \ --metric Mattes[ fixed1.nii, moving1.nii, 1, 32, Random, 0.05 ] --convergence [ 1500x200, 1e-08, 20 ] \ ---smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-estimate-learning-rate-once 1 --use-histogram-matching 1 \ +--smoothing-sigmas 1.0x0.0vox --shrink-factors 2x1 --use-histogram-matching 1 \ --transform SyN[ 0.25, 3.0, 0.0 ] --metric Mattes[ fixed1.nii, moving1.nii, 1, 32 ] \ --convergence [ 100x50x30, 1e-09, 20 ] --smoothing-sigmas 2.0x1.0x0.0vox --shrink-factors 3x2x1 \ ---use-estimate-learning-rate-once 1 --use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ +--use-histogram-matching 1 --winsorize-image-intensities [ 0.0, 1.0 ] \ --write-composite-transform 1' """ @@ -991,12 +1011,12 @@ class Registration(ANTSCommand): ] def __init__(self, **inputs): - super(Registration, self).__init__(**inputs) + super().__init__(**inputs) self._elapsed_time = None self._metric_value = None def _run_interface(self, runtime, correct_return_codes=(0,)): - runtime = super(Registration, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) # Parse some profiling info output = runtime.stdout or runtime.merged @@ -1054,10 +1074,10 @@ def _format_metric(self, index): # from the non-list inputs. if isinstance(name_input, list): items = list(stage_inputs.items()) - indexes = list(range(0, len(name_input))) + indexes = list(range(len(name_input))) specs = list() for i in indexes: - temp = dict([(k, v[i]) for k, v in items]) + temp = {k: v[i] for k, v in items} if len(self.inputs.fixed_image) == 1: temp["fixed_image"] = self.inputs.fixed_image[0] else: @@ -1106,21 +1126,16 @@ def _format_metric_argument(**kwargs): return retval def _format_transform(self, index): - retval = [] - retval.append("%s[ " % self.inputs.transforms[index]) parameters = ", ".join( [str(element) for element in self.inputs.transform_parameters[index]] ) - retval.append("%s" % parameters) - retval.append(" ]") - return "".join(retval) + return f"{self.inputs.transforms[index]}[ {parameters} ]" def _format_registration(self): retval = [] for ii in range(len(self.inputs.transforms)): retval.append("--transform %s" % (self._format_transform(ii))) - for metric in self._format_metric(ii): - retval.append("--metric %s" % metric) + retval.extend("--metric %s" % metric for metric in self._format_metric(ii)) retval.append("--convergence %s" % self._format_convergence(ii)) if isdefined(self.inputs.sigma_units): retval.append( @@ -1140,10 +1155,9 @@ def _format_registration(self): % self._format_xarray(self.inputs.shrink_factors[ii]) ) if isdefined(self.inputs.use_estimate_learning_rate_once): - retval.append( - "--use-estimate-learning-rate-once %d" - % self.inputs.use_estimate_learning_rate_once[ii] - ) + # this flag was removed because it was never used in the ants codebase + # removed from Ants in commit e1e47994b on 2022-08-09 + pass if isdefined(self.inputs.use_histogram_matching): # use_histogram_matching is either a common flag for all transforms # or a list of transform-specific flags @@ -1174,7 +1188,7 @@ def _format_registration(self): moving_mask = moving_masks[ii if len(moving_masks) > 1 else 0] else: moving_mask = "NULL" - retval.append("--masks [ %s, %s ]" % (fixed_mask, moving_mask)) + retval.append(f"--masks [ {fixed_mask}, {moving_mask} ]") return " ".join(retval) def _get_outputfilenames(self, inverse=False): @@ -1227,7 +1241,7 @@ def _format_winsorize_image_intensities(self): ) ) self._quantilesDone = True - return "--winsorize-image-intensities [ %s, %s ]" % ( + return "--winsorize-image-intensities [ {}, {} ]".format( self.inputs.winsorize_lower_quantile, self.inputs.winsorize_upper_quantile, ) @@ -1254,7 +1268,7 @@ def _get_initial_transform_filenames(self): def _format_arg(self, opt, spec, val): if opt == "fixed_image_mask": if isdefined(self.inputs.moving_image_mask): - return "--masks [ %s, %s ]" % ( + return "--masks [ {}, {} ]".format( self.inputs.fixed_image_mask, self.inputs.moving_image_mask, ) @@ -1280,8 +1294,9 @@ def _format_arg(self, opt, spec, val): "BSpline", "MultiLabel", "Gaussian", + "GenericLabel", ] and isdefined(self.inputs.interpolation_parameters): - return "--interpolation %s[ %s ]" % ( + return "--interpolation {}[ {} ]".format( self.inputs.interpolation, ", ".join( [str(param) for param in self.inputs.interpolation_parameters] @@ -1293,13 +1308,13 @@ def _format_arg(self, opt, spec, val): out_filename = self._get_outputfilenames(inverse=False) inv_out_filename = self._get_outputfilenames(inverse=True) if out_filename and inv_out_filename: - return "--output [ %s, %s, %s ]" % ( + return "--output [ {}, {}, {} ]".format( self.inputs.output_transform_prefix, out_filename, inv_out_filename, ) elif out_filename: - return "--output [ %s, %s ]" % ( + return "--output [ {}, {} ]".format( self.inputs.output_transform_prefix, out_filename, ) @@ -1314,7 +1329,7 @@ def _format_arg(self, opt, spec, val): # This feature was removed from recent versions of antsRegistration due to corrupt outputs. # elif opt == 'collapse_linear_transforms_to_fixed_image_header': # return self._formatCollapseLinearTransformsToFixedImageHeader() - return super(Registration, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _output_filenames(self, prefix, count, transform, inverse=False): self.low_dimensional_transform_map = { @@ -1373,10 +1388,11 @@ def _list_outputs(self): self.inputs.initial_moving_transform + outputs["reverse_transforms"] ) - outputs["reverse_invert_flags"] = ( - [not e for e in invert_initial_moving_transform] - + outputs["reverse_invert_flags"] - ) # Prepend + outputs["reverse_invert_flags"] = [ + not e for e in invert_initial_moving_transform + ] + outputs[ + "reverse_invert_flags" + ] # Prepend transform_count += len(self.inputs.initial_moving_transform) elif isdefined(self.inputs.initial_moving_transform_com): forward_filename, forward_inversemode = self._output_filenames( @@ -1472,6 +1488,10 @@ def _list_outputs(self): outputs["metric_value"] = self._metric_value if self._elapsed_time: outputs["elapsed_time"] = self._elapsed_time + + outputs["reverse_forward_transforms"] = outputs["forward_transforms"][::-1] + outputs["reverse_forward_invert_flags"] = outputs["forward_invert_flags"][::-1] + return outputs @@ -1485,7 +1505,7 @@ class MeasureImageSimilarityInputSpec(ANTSCommandInputSpec): desc="Dimensionality of the fixed/moving image pair", ) fixed_image = File( - exists=True, mandatory=True, desc="Image to which the moving image is warped", + exists=True, mandatory=True, desc="Image to which the moving image is warped" ) moving_image = File( exists=True, @@ -1493,14 +1513,7 @@ class MeasureImageSimilarityInputSpec(ANTSCommandInputSpec): desc="Image to apply transformation to (generally a coregistered functional)", ) metric = traits.Enum( - "CC", - "MI", - "Mattes", - "MeanSquares", - "Demons", - "GC", - argstr="%s", - mandatory=True, + "CC", "MI", "Mattes", "MeanSquares", "Demons", "GC", argstr="%s", mandatory=True ) metric_weight = traits.Float( requires=["metric"], @@ -1597,7 +1610,7 @@ def _mask_constructor(self): ) else: retval = '--masks "{fixed_image_mask}"'.format( - fixed_image_mask=self.inputs.fixed_image_mask, + fixed_image_mask=self.inputs.fixed_image_mask ) return retval @@ -1606,7 +1619,7 @@ def _format_arg(self, opt, spec, val): return self._metric_constructor() elif opt == "fixed_image_mask": return self._mask_constructor() - return super(MeasureImageSimilarity, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def aggregate_outputs(self, runtime=None, needed_outputs=None): outputs = self._outputs() @@ -1692,6 +1705,11 @@ class RegistrationSynQuickInputSpec(ANTSCommandInputSpec): desc="precision type (default = double)", usedefault=True, ) + random_seed = traits.Int( + argstr="-e %d", + desc="fixed random seed", + min_ver="2.3.0", + ) class RegistrationSynQuickOutputSpec(TraitedSpec): @@ -1747,7 +1765,7 @@ def _num_threads_update(self): def _format_arg(self, name, spec, value): if name == "precision_type": return spec.argstr % value[0] - return super(RegistrationSynQuick, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -1843,13 +1861,13 @@ def _format_arg(self, name, spec, value): return "" if name == "out_file" and self.inputs.process == "disassemble": return "" - return super(CompositeTransformUtil, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() if self.inputs.process == "disassemble": outputs["affine_transform"] = os.path.abspath( - "00_{}_AffineTransform.mat".format(self.inputs.output_prefix) + f"00_{self.inputs.output_prefix}_AffineTransform.mat" ) outputs["displacement_field"] = os.path.abspath( "01_{}_DisplacementFieldTransform.nii.gz".format( diff --git a/nipype/interfaces/ants/resampling.py b/nipype/interfaces/ants/resampling.py index a5d6a52c04..883eff1de3 100644 --- a/nipype/interfaces/ants/resampling.py +++ b/nipype/interfaces/ants/resampling.py @@ -1,10 +1,9 @@ -# -*- coding: utf-8 -*- -"""ANTS Apply Transforms interface -""" +"""ANTS Apply Transforms interface""" + import os from .base import ANTSCommand, ANTSCommandInputSpec -from ..base import TraitedSpec, File, traits, isdefined, InputMultiPath +from ..base import TraitedSpec, File, traits, Tuple, isdefined, InputMultiObject from ...utils.filemanip import split_filename @@ -16,15 +15,13 @@ class WarpTimeSeriesImageMultiTransformInputSpec(ANTSCommandInputSpec): argstr="%s", mandatory=True, copyfile=True, - desc=( - "image to apply transformation to (generally a " "coregistered functional)" - ), + desc=("image to apply transformation to (generally a coregistered functional)"), ) out_postfix = traits.Str( "_wtsimt", argstr="%s", usedefault=True, - desc=("Postfix that is prepended to all output " "files (default = _wtsimt)"), + desc=("Postfix that is prepended to all output files (default = _wtsimt)"), ) reference_image = File( argstr="-R %s", @@ -34,7 +31,7 @@ class WarpTimeSeriesImageMultiTransformInputSpec(ANTSCommandInputSpec): tightest_box = traits.Bool( argstr="--tightest-bounding-box", desc=( - "computes tightest bounding box (overrided by " "reference_image if given)" + "computes tightest bounding box (overridden by reference_image if given)" ), xor=["reference_image"], ) @@ -52,7 +49,7 @@ class WarpTimeSeriesImageMultiTransformInputSpec(ANTSCommandInputSpec): use_bspline = traits.Bool( argstr="--use-Bspline", desc="Use 3rd order B-Spline interpolation" ) - transformation_series = InputMultiPath( + transformation_series = InputMultiObject( File(exists=True), argstr="%s", desc="transformation file(s) to be applied", @@ -124,28 +121,24 @@ def _format_arg(self, opt, spec, val): if isdefined(self.inputs.invert_affine): diff_inv = set(self.inputs.invert_affine) - set(affine_invert) if diff_inv: - raise Exceptions( + raise Exception( "Review invert_affine, not all indexes from invert_affine were used, " "check the description for the full definition" ) return " ".join(series) - return super(WarpTimeSeriesImageMultiTransform, self)._format_arg( - opt, spec, val - ) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() _, name, ext = split_filename(os.path.abspath(self.inputs.input_image)) outputs["output_image"] = os.path.join( - os.getcwd(), "".join((name, self.inputs.out_postfix, ext)) + os.getcwd(), f"{name}{self.inputs.out_postfix}{ext}" ) return outputs def _run_interface(self, runtime, correct_return_codes=[0]): - runtime = super(WarpTimeSeriesImageMultiTransform, self)._run_interface( - runtime, correct_return_codes=[0, 1] - ) + runtime = super()._run_interface(runtime, correct_return_codes=[0, 1]) if "100 % complete" not in runtime.stdout: self.raise_exception(runtime) return runtime @@ -158,9 +151,7 @@ class WarpImageMultiTransformInputSpec(ANTSCommandInputSpec): input_image = File( argstr="%s", mandatory=True, - desc=( - "image to apply transformation to (generally a " "coregistered functional)" - ), + desc=("image to apply transformation to (generally a coregistered functional)"), position=2, ) output_image = File( @@ -175,7 +166,7 @@ class WarpImageMultiTransformInputSpec(ANTSCommandInputSpec): "_wimt", usedefault=True, hash_files=False, - desc=("Postfix that is prepended to all output " "files (default = _wimt)"), + desc=("Postfix that is prepended to all output files (default = _wimt)"), xor=["output_image"], ) reference_image = File( @@ -186,7 +177,7 @@ class WarpImageMultiTransformInputSpec(ANTSCommandInputSpec): tightest_box = traits.Bool( argstr="--tightest-bounding-box", desc=( - "computes tightest bounding box (overrided by " "reference_image if given)" + "computes tightest bounding box (overridden by reference_image if given)" ), xor=["reference_image"], ) @@ -204,7 +195,7 @@ class WarpImageMultiTransformInputSpec(ANTSCommandInputSpec): use_bspline = traits.Bool( argstr="--use-BSpline", desc="Use 3rd order B-Spline interpolation" ) - transformation_series = InputMultiPath( + transformation_series = InputMultiObject( File(exists=True), argstr="%s", desc="transformation file(s) to be applied", @@ -262,7 +253,7 @@ class WarpImageMultiTransform(ANTSCommand): def _gen_filename(self, name): if name == "output_image": _, name, ext = split_filename(os.path.abspath(self.inputs.input_image)) - return "".join((name, self.inputs.out_postfix, ext)) + return f"{name}{self.inputs.out_postfix}{ext}" return None def _format_arg(self, opt, spec, val): @@ -283,14 +274,14 @@ def _format_arg(self, opt, spec, val): if isdefined(self.inputs.invert_affine): diff_inv = set(self.inputs.invert_affine) - set(affine_invert) if diff_inv: - raise Exceptions( + raise Exception( "Review invert_affine, not all indexes from invert_affine were used, " "check the description for the full definition" ) return " ".join(series) - return super(WarpImageMultiTransform, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -331,9 +322,7 @@ class ApplyTransformsInputSpec(ANTSCommandInputSpec): input_image = File( argstr="--input %s", mandatory=True, - desc=( - "image to apply transformation to (generally a " "coregistered functional)" - ), + desc=("image to apply transformation to (generally a coregistered functional)"), exists=True, ) output_image = traits.Str( @@ -342,7 +331,7 @@ class ApplyTransformsInputSpec(ANTSCommandInputSpec): out_postfix = traits.Str( "_trans", usedefault=True, - desc=("Postfix that is appended to all output " "files (default = _trans)"), + desc=("Postfix that is appended to all output files (default = _trans)"), ) reference_image = File( argstr="--reference-image %s", @@ -360,24 +349,23 @@ class ApplyTransformsInputSpec(ANTSCommandInputSpec): "MultiLabel", "Gaussian", "BSpline", + "GenericLabel", argstr="%s", usedefault=True, ) interpolation_parameters = traits.Either( - traits.Tuple(traits.Int()), # BSpline (order) - traits.Tuple( - traits.Float(), traits.Float() # Gaussian/MultiLabel (sigma, alpha) - ), + Tuple(traits.Int()), # BSpline (order) + Tuple(traits.Float(), traits.Float()), # Gaussian/MultiLabel (sigma, alpha) + Tuple(traits.Str()), # GenericLabel ) - transforms = traits.Either( - InputMultiPath(File(exists=True)), - "identity", + transforms = InputMultiObject( + traits.Either(File(exists=True), "identity"), argstr="%s", mandatory=True, desc="transform files: will be applied in reverse order. For " "example, the last specified transform will be applied first.", ) - invert_transform_flags = InputMultiPath(traits.Bool()) + invert_transform_flags = InputMultiObject(traits.Bool()) default_value = traits.Float(0.0, argstr="--default-value %g", usedefault=True) print_out_composite_warp_file = traits.Bool( False, @@ -411,7 +399,7 @@ class ApplyTransforms(ANTSCommand): >>> at.cmdline 'antsApplyTransforms --default-value 0 --float 0 --input moving1.nii \ --interpolation Linear --output moving1_trans.nii \ ---reference-image fixed1.nii -t identity' +--reference-image fixed1.nii --transform identity' >>> at = ApplyTransforms() >>> at.inputs.dimension = 3 @@ -421,11 +409,11 @@ class ApplyTransforms(ANTSCommand): >>> at.inputs.interpolation = 'Linear' >>> at.inputs.default_value = 0 >>> at.inputs.transforms = ['ants_Warp.nii.gz', 'trans.mat'] - >>> at.inputs.invert_transform_flags = [False, False] + >>> at.inputs.invert_transform_flags = [False, True] >>> at.cmdline 'antsApplyTransforms --default-value 0 --dimensionality 3 --float 0 --input moving1.nii \ --interpolation Linear --output deformed_moving1.nii --reference-image fixed1.nii \ ---transform [ ants_Warp.nii.gz, 0 ] --transform [ trans.mat, 0 ]' +--transform ants_Warp.nii.gz --transform [ trans.mat, 1 ]' >>> at1 = ApplyTransforms() >>> at1.inputs.dimension = 3 @@ -440,7 +428,23 @@ class ApplyTransforms(ANTSCommand): >>> at1.cmdline 'antsApplyTransforms --default-value 0 --dimensionality 3 --float 0 --input moving1.nii \ --interpolation BSpline[ 5 ] --output deformed_moving1.nii --reference-image fixed1.nii \ ---transform [ ants_Warp.nii.gz, 0 ] --transform [ trans.mat, 0 ]' +--transform ants_Warp.nii.gz --transform trans.mat' + + Identity transforms may be used as part of a chain: + + >>> at2 = ApplyTransforms() + >>> at2.inputs.dimension = 3 + >>> at2.inputs.input_image = 'moving1.nii' + >>> at2.inputs.reference_image = 'fixed1.nii' + >>> at2.inputs.output_image = 'deformed_moving1.nii' + >>> at2.inputs.interpolation = 'BSpline' + >>> at2.inputs.interpolation_parameters = (5,) + >>> at2.inputs.default_value = 0 + >>> at2.inputs.transforms = ['identity', 'ants_Warp.nii.gz', 'trans.mat'] + >>> at2.cmdline + 'antsApplyTransforms --default-value 0 --dimensionality 3 --float 0 --input moving1.nii \ +--interpolation BSpline[ 5 ] --output deformed_moving1.nii --reference-image fixed1.nii \ +--transform identity --transform ants_Warp.nii.gz --transform trans.mat' """ _cmd = "antsApplyTransforms" @@ -458,25 +462,20 @@ def _gen_filename(self, name): def _get_transform_filenames(self): retval = [] - for ii in range(len(self.inputs.transforms)): - if isdefined(self.inputs.invert_transform_flags): - if len(self.inputs.transforms) == len( - self.inputs.invert_transform_flags - ): - invert_code = 1 if self.inputs.invert_transform_flags[ii] else 0 - retval.append( - "--transform [ %s, %d ]" - % (self.inputs.transforms[ii], invert_code) - ) - else: - raise Exception( - ( - "ERROR: The useInverse list must have the same number " - "of entries as the transformsFileName list." - ) - ) + invert_flags = self.inputs.invert_transform_flags + if not isdefined(invert_flags): + invert_flags = [False] * len(self.inputs.transforms) + elif len(self.inputs.transforms) != len(invert_flags): + raise ValueError( + "ERROR: The invert_transform_flags list must have the same number " + "of entries as the transforms list." + ) + + for transform, invert in zip(self.inputs.transforms, invert_flags): + if invert: + retval.append(f"--transform [ {transform}, 1 ]") else: - retval.append("--transform %s" % self.inputs.transforms[ii]) + retval.append(f"--transform {transform}") return " ".join(retval) def _get_output_warped_filename(self): @@ -492,16 +491,15 @@ def _format_arg(self, opt, spec, val): if opt == "output_image": return self._get_output_warped_filename() elif opt == "transforms": - if val == "identity": - return "-t identity" return self._get_transform_filenames() elif opt == "interpolation": if self.inputs.interpolation in [ "BSpline", "MultiLabel", "Gaussian", + "GenericLabel", ] and isdefined(self.inputs.interpolation_parameters): - return "--interpolation %s[ %s ]" % ( + return "--interpolation {}[ {} ]".format( self.inputs.interpolation, ", ".join( [str(param) for param in self.inputs.interpolation_parameters] @@ -509,7 +507,7 @@ def _format_arg(self, opt, spec, val): ) else: return "--interpolation %s" % self.inputs.interpolation - return super(ApplyTransforms, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -606,10 +604,8 @@ def _get_transform_filenames(self): ) else: raise Exception( - ( - "ERROR: The useInverse list must have the same number " - "of entries as the transformsFileName list." - ) + "ERROR: The useInverse list must have the same number " + "of entries as the transformsFileName list." ) else: retval.append("--transform %s" % self.inputs.transforms[ii]) @@ -618,4 +614,4 @@ def _get_transform_filenames(self): def _format_arg(self, opt, spec, val): if opt == "transforms": return self._get_transform_filenames() - return super(ApplyTransformsToPoints, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) diff --git a/nipype/interfaces/ants/segmentation.py b/nipype/interfaces/ants/segmentation.py index faba90dc82..47592d70b5 100644 --- a/nipype/interfaces/ants/segmentation.py +++ b/nipype/interfaces/ants/segmentation.py @@ -1,10 +1,19 @@ -# -*- coding: utf-8 -*- -"""The ants module provides basic functions for interfacing with ants functions. -""" +"""Wrappers for segmentation utilities within ANTs.""" + import os +from glob import glob from ...external.due import BibTeX from ...utils.filemanip import split_filename, copyfile, which, fname_presuffix -from ..base import TraitedSpec, File, traits, InputMultiPath, OutputMultiPath, isdefined +from ..base import ( + TraitedSpec, + File, + traits, + Tuple, + InputMultiPath, + OutputMultiPath, + isdefined, +) +from ..mixins import CopyHeaderInterface from .base import ANTSCommand, ANTSCommandInputSpec @@ -31,7 +40,12 @@ class AtroposInputSpec(ANTSCommandInputSpec): requires=["number_of_tissue_classes"], mandatory=True, ) - prior_probability_images = InputMultiPath(File(exists=True)) + kmeans_init_centers = traits.List(traits.Either(traits.Int, traits.Float), minlen=1) + prior_image = traits.Either( + File(exists=True), + traits.Str, + desc="either a string pattern (e.g., 'prior%02d.nii') or an existing vector-image file.", + ) number_of_tissue_classes = traits.Int(mandatory=True) prior_weighting = traits.Float() prior_probability_threshold = traits.Float(requires=["prior_weighting"]) @@ -65,7 +79,10 @@ class AtroposOutputSpec(TraitedSpec): class Atropos(ANTSCommand): - """A finite mixture modeling (FMM) segmentation approach with possibilities for + """ + A multivariate n-class segmentation algorithm. + + A finite mixture modeling (FMM) segmentation approach with possibilities for specifying prior constraints. These prior constraints include the specification of a prior label image, prior probability images (one for each class), and/or an MRF prior to enforce spatial smoothing of the labels. Similar algorithms include @@ -73,32 +90,70 @@ class Atropos(ANTSCommand): Examples -------- - >>> from nipype.interfaces.ants import Atropos - >>> at = Atropos() - >>> at.inputs.dimension = 3 - >>> at.inputs.intensity_images = 'structural.nii' - >>> at.inputs.mask_image = 'mask.nii' + >>> at = Atropos( + ... dimension=3, intensity_images='structural.nii', mask_image='mask.nii', + ... number_of_tissue_classes=2, likelihood_model='Gaussian', save_posteriors=True, + ... mrf_smoothing_factor=0.2, mrf_radius=[1, 1, 1], icm_use_synchronous_update=True, + ... maximum_number_of_icm_terations=1, n_iterations=5, convergence_threshold=0.000001, + ... posterior_formulation='Socrates', use_mixture_model_proportions=True) + >>> at.inputs.initialization = 'Random' + >>> at.cmdline + 'Atropos --image-dimensionality 3 --icm [1,1] + --initialization Random[2] --intensity-image structural.nii + --likelihood-model Gaussian --mask-image mask.nii --mrf [0.2,1x1x1] --convergence [5,1e-06] + --output [structural_labeled.nii,POSTERIOR_%02d.nii.gz] --posterior-formulation Socrates[1] + --use-random-seed 1' + + >>> at = Atropos( + ... dimension=3, intensity_images='structural.nii', mask_image='mask.nii', + ... number_of_tissue_classes=2, likelihood_model='Gaussian', save_posteriors=True, + ... mrf_smoothing_factor=0.2, mrf_radius=[1, 1, 1], icm_use_synchronous_update=True, + ... maximum_number_of_icm_terations=1, n_iterations=5, convergence_threshold=0.000001, + ... posterior_formulation='Socrates', use_mixture_model_proportions=True) + >>> at.inputs.initialization = 'KMeans' + >>> at.inputs.kmeans_init_centers = [100, 200] + >>> at.cmdline + 'Atropos --image-dimensionality 3 --icm [1,1] + --initialization KMeans[2,100,200] --intensity-image structural.nii + --likelihood-model Gaussian --mask-image mask.nii --mrf [0.2,1x1x1] --convergence [5,1e-06] + --output [structural_labeled.nii,POSTERIOR_%02d.nii.gz] --posterior-formulation Socrates[1] + --use-random-seed 1' + + >>> at = Atropos( + ... dimension=3, intensity_images='structural.nii', mask_image='mask.nii', + ... number_of_tissue_classes=2, likelihood_model='Gaussian', save_posteriors=True, + ... mrf_smoothing_factor=0.2, mrf_radius=[1, 1, 1], icm_use_synchronous_update=True, + ... maximum_number_of_icm_terations=1, n_iterations=5, convergence_threshold=0.000001, + ... posterior_formulation='Socrates', use_mixture_model_proportions=True) >>> at.inputs.initialization = 'PriorProbabilityImages' - >>> at.inputs.prior_probability_images = ['rc1s1.nii', 'rc1s2.nii'] - >>> at.inputs.number_of_tissue_classes = 2 + >>> at.inputs.prior_image = 'BrainSegmentationPrior%02d.nii.gz' >>> at.inputs.prior_weighting = 0.8 >>> at.inputs.prior_probability_threshold = 0.0000001 - >>> at.inputs.likelihood_model = 'Gaussian' - >>> at.inputs.mrf_smoothing_factor = 0.2 - >>> at.inputs.mrf_radius = [1, 1, 1] - >>> at.inputs.icm_use_synchronous_update = True - >>> at.inputs.maximum_number_of_icm_terations = 1 - >>> at.inputs.n_iterations = 5 - >>> at.inputs.convergence_threshold = 0.000001 - >>> at.inputs.posterior_formulation = 'Socrates' - >>> at.inputs.use_mixture_model_proportions = True - >>> at.inputs.save_posteriors = True >>> at.cmdline - 'Atropos --image-dimensionality 3 --icm [1,1] \ ---initialization PriorProbabilityImages[2,priors/priorProbImages%02d.nii,0.8,1e-07] --intensity-image structural.nii \ ---likelihood-model Gaussian --mask-image mask.nii --mrf [0.2,1x1x1] --convergence [5,1e-06] \ ---output [structural_labeled.nii,POSTERIOR_%02d.nii.gz] --posterior-formulation Socrates[1] --use-random-seed 1' + 'Atropos --image-dimensionality 3 --icm [1,1] + --initialization PriorProbabilityImages[2,BrainSegmentationPrior%02d.nii.gz,0.8,1e-07] + --intensity-image structural.nii --likelihood-model Gaussian --mask-image mask.nii + --mrf [0.2,1x1x1] --convergence [5,1e-06] + --output [structural_labeled.nii,POSTERIOR_%02d.nii.gz] + --posterior-formulation Socrates[1] --use-random-seed 1' + + >>> at = Atropos( + ... dimension=3, intensity_images='structural.nii', mask_image='mask.nii', + ... number_of_tissue_classes=2, likelihood_model='Gaussian', save_posteriors=True, + ... mrf_smoothing_factor=0.2, mrf_radius=[1, 1, 1], icm_use_synchronous_update=True, + ... maximum_number_of_icm_terations=1, n_iterations=5, convergence_threshold=0.000001, + ... posterior_formulation='Socrates', use_mixture_model_proportions=True) + >>> at.inputs.initialization = 'PriorLabelImage' + >>> at.inputs.prior_image = 'segmentation0.nii.gz' + >>> at.inputs.number_of_tissue_classes = 2 + >>> at.inputs.prior_weighting = 0.8 + >>> at.cmdline + 'Atropos --image-dimensionality 3 --icm [1,1] + --initialization PriorLabelImage[2,segmentation0.nii.gz,0.8] --intensity-image structural.nii + --likelihood-model Gaussian --mask-image mask.nii --mrf [0.2,1x1x1] --convergence [5,1e-06] + --output [structural_labeled.nii,POSTERIOR_%02d.nii.gz] --posterior-formulation Socrates[1] + --use-random-seed 1' """ @@ -108,20 +163,52 @@ class Atropos(ANTSCommand): def _format_arg(self, opt, spec, val): if opt == "initialization": - retval = "--initialization %s[%d" % ( - val, - self.inputs.number_of_tissue_classes, - ) - if val == "PriorProbabilityImages": - _, _, ext = split_filename(self.inputs.prior_probability_images[0]) - retval += ( - ",priors/priorProbImages%02d" - + ext - + ",%g" % self.inputs.prior_weighting - ) - if isdefined(self.inputs.prior_probability_threshold): - retval += ",%g" % self.inputs.prior_probability_threshold - return retval + "]" + n_classes = self.inputs.number_of_tissue_classes + brackets = ["%d" % n_classes] + if val == "KMeans" and isdefined(self.inputs.kmeans_init_centers): + centers = sorted(set(self.inputs.kmeans_init_centers)) + if len(centers) != n_classes: + raise ValueError( + "KMeans initialization with initial cluster centers requires " + "the number of centers to match number_of_tissue_classes" + ) + brackets += ["%g" % c for c in centers] + + if val in ("PriorProbabilityImages", "PriorLabelImage"): + if not isdefined(self.inputs.prior_image) or not isdefined( + self.inputs.prior_weighting + ): + raise ValueError( + "'%s' initialization requires setting " + "prior_image and prior_weighting" % val + ) + + priors_paths = [self.inputs.prior_image] + if "%02d" in priors_paths[0]: + if val == "PriorLabelImage": + raise ValueError( + "'PriorLabelImage' initialization does not " + "accept patterns for prior_image." + ) + priors_paths = [ + priors_paths[0] % i for i in range(1, n_classes + 1) + ] + + if not all(os.path.exists(p) for p in priors_paths): + raise FileNotFoundError( + "One or more prior images do not exist: " + "%s." % ", ".join(priors_paths) + ) + brackets += [ + self.inputs.prior_image, + "%g" % self.inputs.prior_weighting, + ] + + if val == "PriorProbabilityImages" and isdefined( + self.inputs.prior_probability_threshold + ): + brackets.append("%g" % self.inputs.prior_probability_threshold) + return "--initialization {}[{}]".format(val, ",".join(brackets)) if opt == "mrf_smoothing_factor": retval = "--mrf [%g" % val if isdefined(self.inputs.mrf_radius): @@ -149,30 +236,7 @@ def _format_arg(self, opt, spec, val): if isdefined(self.inputs.save_posteriors): retval += ",%s" % self.inputs.output_posteriors_name_template return retval + "]" - return super(Atropos, self)._format_arg(opt, spec, val) - - def _run_interface(self, runtime, correct_return_codes=[0]): - if self.inputs.initialization == "PriorProbabilityImages": - priors_directory = os.path.join(os.getcwd(), "priors") - if not os.path.exists(priors_directory): - os.makedirs(priors_directory) - _, _, ext = split_filename(self.inputs.prior_probability_images[0]) - for i, f in enumerate(self.inputs.prior_probability_images): - target = os.path.join( - priors_directory, "priorProbImages%02d" % (i + 1) + ext - ) - if not ( - os.path.exists(target) - and os.path.realpath(target) == os.path.abspath(f) - ): - copyfile( - os.path.abspath(f), - os.path.join( - priors_directory, "priorProbImages%02d" % (i + 1) + ext - ), - ) - runtime = super(Atropos, self)._run_interface(runtime) - return runtime + return super()._format_arg(opt, spec, val) def _gen_filename(self, name): if name == "out_classified_image_name": @@ -181,7 +245,6 @@ def _gen_filename(self, name): _, name, ext = split_filename(self.inputs.intensity_images[0]) output = name + "_labeled" + ext return output - return None def _list_outputs(self): outputs = self._outputs().get() @@ -214,7 +277,7 @@ class LaplacianThicknessInputSpec(ANTSCommandInputSpec): desc="gray matter segmentation image", position=2, ) - output_image = File( + output_image = traits.Str( desc="name of output file", argstr="%s", position=3, @@ -346,7 +409,7 @@ class N4BiasFieldCorrectionInputSpec(ANTSCommandInputSpec): This option rescales to the [min,max] range of the original image intensities within the user-specified mask.""", ) - histogram_sharpening = traits.Tuple( + histogram_sharpening = Tuple( (0.15, 0.01, 200), traits.Float, traits.Float, @@ -366,7 +429,7 @@ class N4BiasFieldCorrectionOutputSpec(TraitedSpec): bias_image = File(exists=True, desc="Estimated bias") -class N4BiasFieldCorrection(ANTSCommand): +class N4BiasFieldCorrection(ANTSCommand, CopyHeaderInterface): """ Bias field correction. @@ -395,57 +458,61 @@ class N4BiasFieldCorrection(ANTSCommand): >>> n4.inputs.shrink_factor = 3 >>> n4.inputs.n_iterations = [50,50,30,20] >>> n4.cmdline - 'N4BiasFieldCorrection --bspline-fitting [ 300 ] \ --d 3 --input-image structural.nii \ ---convergence [ 50x50x30x20 ] --output structural_corrected.nii \ ---shrink-factor 3' + 'N4BiasFieldCorrection --bspline-fitting [ 300 ] + -d 3 --input-image structural.nii + --convergence [ 50x50x30x20 ] --output structural_corrected.nii + --shrink-factor 3' >>> n4_2 = copy.deepcopy(n4) >>> n4_2.inputs.convergence_threshold = 1e-6 >>> n4_2.cmdline - 'N4BiasFieldCorrection --bspline-fitting [ 300 ] \ --d 3 --input-image structural.nii \ ---convergence [ 50x50x30x20, 1e-06 ] --output structural_corrected.nii \ ---shrink-factor 3' + 'N4BiasFieldCorrection --bspline-fitting [ 300 ] + -d 3 --input-image structural.nii + --convergence [ 50x50x30x20, 1e-06 ] --output structural_corrected.nii + --shrink-factor 3' >>> n4_3 = copy.deepcopy(n4_2) >>> n4_3.inputs.bspline_order = 5 >>> n4_3.cmdline - 'N4BiasFieldCorrection --bspline-fitting [ 300, 5 ] \ --d 3 --input-image structural.nii \ ---convergence [ 50x50x30x20, 1e-06 ] --output structural_corrected.nii \ ---shrink-factor 3' + 'N4BiasFieldCorrection --bspline-fitting [ 300, 5 ] + -d 3 --input-image structural.nii + --convergence [ 50x50x30x20, 1e-06 ] --output structural_corrected.nii + --shrink-factor 3' >>> n4_4 = N4BiasFieldCorrection() >>> n4_4.inputs.input_image = 'structural.nii' >>> n4_4.inputs.save_bias = True >>> n4_4.inputs.dimension = 3 >>> n4_4.cmdline - 'N4BiasFieldCorrection -d 3 --input-image structural.nii \ ---output [ structural_corrected.nii, structural_bias.nii ]' + 'N4BiasFieldCorrection -d 3 --input-image structural.nii + --output [ structural_corrected.nii, structural_bias.nii ]' >>> n4_5 = N4BiasFieldCorrection() >>> n4_5.inputs.input_image = 'structural.nii' >>> n4_5.inputs.dimension = 3 >>> n4_5.inputs.histogram_sharpening = (0.12, 0.02, 200) >>> n4_5.cmdline - 'N4BiasFieldCorrection -d 3 --histogram-sharpening [0.12,0.02,200] \ ---input-image structural.nii --output structural_corrected.nii' + 'N4BiasFieldCorrection -d 3 --histogram-sharpening [0.12,0.02,200] + --input-image structural.nii --output structural_corrected.nii' """ _cmd = "N4BiasFieldCorrection" input_spec = N4BiasFieldCorrectionInputSpec output_spec = N4BiasFieldCorrectionOutputSpec + _copy_header_map = { + "output_image": ("input_image", False), + "bias_image": ("input_image", True), + } def __init__(self, *args, **kwargs): """Instantiate the N4BiasFieldCorrection interface.""" self._out_bias_file = None - super(N4BiasFieldCorrection, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def _format_arg(self, name, trait_spec, value): if name == "output_image" and self._out_bias_file: - newval = "[ %s, %s ]" % (value, self._out_bias_file) + newval = f"[ {value}, {self._out_bias_file} ]" return trait_spec.argstr % newval if name == "bspline_fitting_distance": @@ -457,7 +524,7 @@ def _format_arg(self, name, trait_spec, value): if name == "n_iterations": if isdefined(self.inputs.convergence_threshold): - newval = "[ %s, %g ]" % ( + newval = "[ {}, {:g} ]".format( self._format_xarray([str(elt) for elt in value]), self.inputs.convergence_threshold, ) @@ -465,7 +532,7 @@ def _format_arg(self, name, trait_spec, value): newval = "[ %s ]" % self._format_xarray([str(elt) for elt in value]) return trait_spec.argstr % newval - return super(N4BiasFieldCorrection, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _parse_inputs(self, skip=None): skip = (skip or []) + ["save_bias", "bias_image"] @@ -477,31 +544,14 @@ def _parse_inputs(self, skip=None): os.path.basename(self.inputs.input_image), suffix="_bias" ) self._out_bias_file = bias_image - return super(N4BiasFieldCorrection, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _list_outputs(self): - outputs = super(N4BiasFieldCorrection, self)._list_outputs() - - # Fix headers - if self.inputs.copy_header: - self._copy_header(outputs["output_image"]) - + outputs = super()._list_outputs() if self._out_bias_file: outputs["bias_image"] = os.path.abspath(self._out_bias_file) - if self.inputs.copy_header: - self._copy_header(outputs["bias_image"]) return outputs - def _copy_header(self, fname): - """Copy header from input image to an output image.""" - import nibabel as nb - - in_img = nb.load(self.inputs.input_image) - out_img = nb.load(fname, mmap=False) - new_img = out_img.__class__(out_img.get_fdata(), in_img.affine, in_img.header) - new_img.set_data_dtype(out_img.get_data_dtype()) - new_img.to_filename(fname) - class CorticalThicknessInputSpec(ANTSCommandInputSpec): dimension = traits.Enum( @@ -657,7 +707,7 @@ class CorticalThicknessInputSpec(ANTSCommandInputSpec): class CorticalThicknessOutputSpec(TraitedSpec): BrainExtractionMask = File(exists=True, desc="brain extraction mask") ExtractedBrainN4 = File(exists=True, desc="extracted brain from N4 image") - BrainSegmentation = File(exists=True, desc="brain segmentaion image") + BrainSegmentation = File(exists=True, desc="brain segmentation image") BrainSegmentationN4 = File(exists=True, desc="N4 corrected image") BrainSegmentationPosteriors = OutputMultiPath( File(exists=True), desc="Posterior probability images" @@ -696,8 +746,9 @@ class CorticalThickness(ANTSCommand): ... 'BrainSegmentationPrior04.nii.gz'] >>> corticalthickness.inputs.t1_registration_template = 'brain_study_template.nii.gz' >>> corticalthickness.cmdline - 'antsCorticalThickness.sh -a T1.nii.gz -m ProbabilityMaskOfStudyTemplate.nii.gz -e study_template.nii.gz -d 3 \ --s nii.gz -o antsCT_ -p nipype_priors/BrainSegmentationPrior%02d.nii.gz -t brain_study_template.nii.gz' + 'antsCorticalThickness.sh -a T1.nii.gz -m ProbabilityMaskOfStudyTemplate.nii.gz + -e study_template.nii.gz -d 3 -s nii.gz -o antsCT_ + -p nipype_priors/BrainSegmentationPrior%02d.nii.gz -t brain_study_template.nii.gz' """ @@ -725,7 +776,7 @@ def _format_arg(self, opt, spec, val): _, _, ext = split_filename(self.inputs.segmentation_priors[0]) retval = "-p nipype_priors/BrainSegmentationPrior%02d" + ext return retval - return super(CorticalThickness, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _run_interface(self, runtime, correct_return_codes=[0]): priors_directory = os.path.join(os.getcwd(), "nipype_priors") @@ -741,7 +792,7 @@ def _run_interface(self, runtime, correct_return_codes=[0]): and os.path.realpath(target) == os.path.abspath(f) ): copyfile(os.path.abspath(f), target) - runtime = super(CorticalThickness, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) return runtime def _list_outputs(self): @@ -762,16 +813,15 @@ def _list_outputs(self): os.getcwd(), self.inputs.out_prefix + "BrainSegmentation0N4." + self.inputs.image_suffix, ) - posteriors = [] - for i in range(len(self.inputs.segmentation_priors)): - posteriors.append( - os.path.join( - os.getcwd(), - self.inputs.out_prefix - + "BrainSegmentationPosteriors%02d." % (i + 1) - + self.inputs.image_suffix, - ) + posteriors = [ + os.path.join( + os.getcwd(), + self.inputs.out_prefix + + "BrainSegmentationPosteriors%02d." % (i + 1) + + self.inputs.image_suffix, ) + for i in range(len(self.inputs.segmentation_priors)) + ] outputs["BrainSegmentationPosteriors"] = posteriors outputs["CorticalThickness"] = os.path.join( os.getcwd(), @@ -937,7 +987,8 @@ class BrainExtraction(ANTSCommand): >>> brainextraction.inputs.brain_template = 'study_template.nii.gz' >>> brainextraction.inputs.brain_probability_mask ='ProbabilityMaskOfStudyTemplate.nii.gz' >>> brainextraction.cmdline - 'antsBrainExtraction.sh -a T1.nii.gz -m ProbabilityMaskOfStudyTemplate.nii.gz -e study_template.nii.gz -d 3 -s nii.gz -o highres001_' + 'antsBrainExtraction.sh -a T1.nii.gz -m ProbabilityMaskOfStudyTemplate.nii.gz + -e study_template.nii.gz -d 3 -s nii.gz -o highres001_' """ @@ -963,13 +1014,13 @@ def _run_interface(self, runtime, correct_return_codes=(0,)): self.inputs.environ.update({"ANTSPATH": ants_path}) runtime.environ.update({"ANTSPATH": ants_path}) - runtime = super(BrainExtraction, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) # Still, double-check if it didn't found N4 - if "we cant find" in runtime.stdout: + if "we can't find" in runtime.stdout: for line in runtime.stdout.split("\n"): - if line.strip().startswith("we cant find"): - tool = line.strip().replace("we cant find the", "").split(" ")[0] + if line.strip().startswith("we can't find"): + tool = line.strip().replace("we can't find the", "").split(" ")[0] break errmsg = ( @@ -1090,155 +1141,6 @@ def _list_outputs(self): return outputs -class JointFusionInputSpec(ANTSCommandInputSpec): - dimension = traits.Enum( - 3, - 2, - 4, - argstr="%d", - position=0, - usedefault=True, - mandatory=True, - desc="image dimension (2, 3, or 4)", - ) - modalities = traits.Int( - argstr="%d", position=1, mandatory=True, desc="Number of modalities or features" - ) - warped_intensity_images = InputMultiPath( - File(exists=True), argstr="-g %s...", mandatory=True, desc="Warped atlas images" - ) - target_image = InputMultiPath( - File(exists=True), argstr="-tg %s...", mandatory=True, desc="Target image(s)" - ) - warped_label_images = InputMultiPath( - File(exists=True), - argstr="-l %s...", - mandatory=True, - desc="Warped atlas segmentations", - ) - method = traits.Str( - "Joint", - argstr="-m %s", - usedefault=True, - desc=( - "Select voting method. Options: Joint (Joint" - "Label Fusion). May be followed by optional" - "parameters in brackets, e.g., -m Joint[0.1,2]" - ), - ) - alpha = traits.Float( - 0.1, - usedefault=True, - requires=["method"], - desc=("Regularization term added to matrix Mx for inverse"), - ) - beta = traits.Int( - 2, - usedefault=True, - requires=["method"], - desc=("Exponent for mapping intensity difference to joint error"), - ) - output_label_image = File( - argstr="%s", - mandatory=True, - position=-1, - name_template="%s", - output_name="output_label_image", - desc="Output fusion label map image", - ) - patch_radius = traits.ListInt( - minlen=3, - maxlen=3, - argstr="-rp %s", - desc=("Patch radius for similarity measures, scalar or vector. Default: 2x2x2"), - ) - search_radius = traits.ListInt( - minlen=3, maxlen=3, argstr="-rs %s", desc="Local search radius. Default: 3x3x3" - ) - exclusion_region = File( - exists=True, - argstr="-x %s", - desc=("Specify an exclusion region for the given label."), - ) - atlas_group_id = traits.ListInt( - argstr="-gp %d...", desc="Assign a group ID for each atlas" - ) - atlas_group_weights = traits.ListInt( - argstr="-gpw %d...", desc=("Assign the voting weights to each atlas group") - ) - - -class JointFusionOutputSpec(TraitedSpec): - output_label_image = File(exists=True) - # TODO: optional outputs - output_posteriors, output_voting_weights - - -class JointFusion(ANTSCommand): - """ - Segmentation fusion tool. - - Examples - -------- - >>> from nipype.interfaces.ants import JointFusion - >>> at = JointFusion() - >>> at.inputs.dimension = 3 - >>> at.inputs.modalities = 1 - >>> at.inputs.method = 'Joint[0.1,2]' - >>> at.inputs.output_label_image ='fusion_labelimage_output.nii' - >>> at.inputs.warped_intensity_images = ['im1.nii', - ... 'im2.nii', - ... 'im3.nii'] - >>> at.inputs.warped_label_images = ['segmentation0.nii.gz', - ... 'segmentation1.nii.gz', - ... 'segmentation1.nii.gz'] - >>> at.inputs.target_image = 'T1.nii' - >>> at.cmdline - 'jointfusion 3 1 -m Joint[0.1,2] -tg T1.nii -g im1.nii -g im2.nii -g im3.nii -l segmentation0.nii.gz \ --l segmentation1.nii.gz -l segmentation1.nii.gz fusion_labelimage_output.nii' - - >>> at.inputs.method = 'Joint' - >>> at.inputs.alpha = 0.5 - >>> at.inputs.beta = 1 - >>> at.inputs.patch_radius = [3,2,1] - >>> at.inputs.search_radius = [1,2,3] - >>> at.cmdline - 'jointfusion 3 1 -m Joint[0.5,1] -rp 3x2x1 -rs 1x2x3 -tg T1.nii -g im1.nii -g im2.nii -g im3.nii \ --l segmentation0.nii.gz -l segmentation1.nii.gz -l segmentation1.nii.gz fusion_labelimage_output.nii' - - """ - - input_spec = JointFusionInputSpec - output_spec = JointFusionOutputSpec - _cmd = "jointfusion" - - def _format_arg(self, opt, spec, val): - if opt == "method": - if "[" in val: - retval = "-m {0}".format(val) - else: - retval = "-m {0}[{1},{2}]".format( - self.inputs.method, self.inputs.alpha, self.inputs.beta - ) - elif opt == "patch_radius": - retval = "-rp {0}".format(self._format_xarray(val)) - elif opt == "search_radius": - retval = "-rs {0}".format(self._format_xarray(val)) - else: - if opt == "warped_intensity_images": - assert len(val) == self.inputs.modalities * len( - self.inputs.warped_label_images - ), "Number of intensity images and label maps must be the same {0}!={1}".format( - len(val), len(self.inputs.warped_label_images) - ) - return super(JointFusion, self)._format_arg(opt, spec, val) - return retval - - def _list_outputs(self): - outputs = self._outputs().get() - outputs["output_label_image"] = os.path.abspath(self.inputs.output_label_image) - return outputs - - class DenoiseImageInputSpec(ANTSCommandInputSpec): dimension = traits.Enum( 2, @@ -1341,16 +1243,16 @@ def _format_arg(self, name, trait_spec, value): if (name == "output_image") and ( self.inputs.save_noise or isdefined(self.inputs.noise_image) ): - newval = "[ %s, %s ]" % ( + newval = "[ {}, {} ]".format( self._filename_from_source("output_image"), self._filename_from_source("noise_image"), ) return trait_spec.argstr % newval - return super(DenoiseImage, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) -class AntsJointFusionInputSpec(ANTSCommandInputSpec): +class JointFusionInputSpec(ANTSCommandInputSpec): dimension = traits.Enum( 3, 2, @@ -1426,7 +1328,8 @@ class AntsJointFusionInputSpec(ANTSCommandInputSpec): usedefault=True, desc=("Constrain solution to non-negative weights."), ) - patch_radius = traits.ListInt( + patch_radius = traits.List( + traits.Int, minlen=3, maxlen=3, argstr="-p %s", @@ -1496,171 +1399,181 @@ class AntsJointFusionInputSpec(ANTSCommandInputSpec): verbose = traits.Bool(False, argstr="-v", desc=("Verbose output.")) -class AntsJointFusionOutputSpec(TraitedSpec): +class JointFusionOutputSpec(TraitedSpec): out_label_fusion = File(exists=True) - out_intensity_fusion_name_format = traits.Str() - out_label_post_prob_name_format = traits.Str() - out_atlas_voting_weight_name_format = traits.Str() + out_intensity_fusion = OutputMultiPath(File(exists=True)) + out_label_post_prob = OutputMultiPath(File(exists=True)) + out_atlas_voting_weight = OutputMultiPath(File(exists=True)) -class AntsJointFusion(ANTSCommand): +class JointFusion(ANTSCommand): """ + An image fusion algorithm. + + Developed by Hongzhi Wang and Paul Yushkevich, and it won segmentation challenges + at MICCAI 2012 and MICCAI 2013. + The original label fusion framework was extended to accommodate intensities by Brian + Avants. + This implementation is based on Paul's original ITK-style implementation + and Brian's ANTsR implementation. + + References include 1) H. Wang, J. W. Suh, S. + Das, J. Pluta, C. Craige, P. Yushkevich, Multi-atlas segmentation with joint + label fusion IEEE Trans. on Pattern Analysis and Machine Intelligence, 35(3), + 611-623, 2013. and 2) H. Wang and P. A. Yushkevich, Multi-atlas segmentation + with joint label fusion and corrective learning--an open source implementation, + Front. Neuroinform., 2013. + Examples -------- - >>> from nipype.interfaces.ants import AntsJointFusion - >>> antsjointfusion = AntsJointFusion() - >>> antsjointfusion.inputs.out_label_fusion = 'ants_fusion_label_output.nii' - >>> antsjointfusion.inputs.atlas_image = [ ['rc1s1.nii','rc1s2.nii'] ] - >>> antsjointfusion.inputs.atlas_segmentation_image = ['segmentation0.nii.gz'] - >>> antsjointfusion.inputs.target_image = ['im1.nii'] - >>> antsjointfusion.cmdline - "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -l segmentation0.nii.gz \ --b 2.0 -o ants_fusion_label_output.nii -s 3x3x3 -t ['im1.nii']" - - >>> antsjointfusion.inputs.target_image = [ ['im1.nii', 'im2.nii'] ] - >>> antsjointfusion.cmdline - "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -l segmentation0.nii.gz \ --b 2.0 -o ants_fusion_label_output.nii -s 3x3x3 -t ['im1.nii', 'im2.nii']" - - >>> antsjointfusion.inputs.atlas_image = [ ['rc1s1.nii','rc1s2.nii'], + >>> from nipype.interfaces.ants import JointFusion + >>> jf = JointFusion() + >>> jf.inputs.out_label_fusion = 'ants_fusion_label_output.nii' + >>> jf.inputs.atlas_image = [ ['rc1s1.nii','rc1s2.nii'] ] + >>> jf.inputs.atlas_segmentation_image = ['segmentation0.nii.gz'] + >>> jf.inputs.target_image = ['im1.nii'] + >>> jf.cmdline + "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -l segmentation0.nii.gz + -b 2.0 -o ants_fusion_label_output.nii -s 3x3x3 -t ['im1.nii']" + + >>> jf.inputs.target_image = [ ['im1.nii', 'im2.nii'] ] + >>> jf.cmdline + "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -l segmentation0.nii.gz + -b 2.0 -o ants_fusion_label_output.nii -s 3x3x3 -t ['im1.nii', 'im2.nii']" + + >>> jf.inputs.atlas_image = [ ['rc1s1.nii','rc1s2.nii'], ... ['rc2s1.nii','rc2s2.nii'] ] - >>> antsjointfusion.inputs.atlas_segmentation_image = ['segmentation0.nii.gz', + >>> jf.inputs.atlas_segmentation_image = ['segmentation0.nii.gz', ... 'segmentation1.nii.gz'] - >>> antsjointfusion.cmdline - "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] \ --l segmentation0.nii.gz -l segmentation1.nii.gz -b 2.0 -o ants_fusion_label_output.nii \ --s 3x3x3 -t ['im1.nii', 'im2.nii']" - - >>> antsjointfusion.inputs.dimension = 3 - >>> antsjointfusion.inputs.alpha = 0.5 - >>> antsjointfusion.inputs.beta = 1.0 - >>> antsjointfusion.inputs.patch_radius = [3,2,1] - >>> antsjointfusion.inputs.search_radius = [3] - >>> antsjointfusion.cmdline - "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] \ --l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -o ants_fusion_label_output.nii \ --p 3x2x1 -s 3 -t ['im1.nii', 'im2.nii']" - - >>> antsjointfusion.inputs.search_radius = ['mask.nii'] - >>> antsjointfusion.inputs.verbose = True - >>> antsjointfusion.inputs.exclusion_image = ['roi01.nii', 'roi02.nii'] - >>> antsjointfusion.inputs.exclusion_image_label = ['1','2'] - >>> antsjointfusion.cmdline - "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] \ --l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -e 1[roi01.nii] -e 2[roi02.nii] \ --o ants_fusion_label_output.nii -p 3x2x1 -s mask.nii -t ['im1.nii', 'im2.nii'] -v" - - >>> antsjointfusion.inputs.out_label_fusion = 'ants_fusion_label_output.nii' - >>> antsjointfusion.inputs.out_intensity_fusion_name_format = 'ants_joint_fusion_intensity_%d.nii.gz' - >>> antsjointfusion.inputs.out_label_post_prob_name_format = 'ants_joint_fusion_posterior_%d.nii.gz' - >>> antsjointfusion.inputs.out_atlas_voting_weight_name_format = 'ants_joint_fusion_voting_weight_%d.nii.gz' - >>> antsjointfusion.cmdline - "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] \ --l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -e 1[roi01.nii] -e 2[roi02.nii] \ --o [ants_fusion_label_output.nii, ants_joint_fusion_intensity_%d.nii.gz, \ -ants_joint_fusion_posterior_%d.nii.gz, ants_joint_fusion_voting_weight_%d.nii.gz] \ --p 3x2x1 -s mask.nii -t ['im1.nii', 'im2.nii'] -v" + >>> jf.cmdline + "antsJointFusion -a 0.1 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] + -l segmentation0.nii.gz -l segmentation1.nii.gz -b 2.0 -o ants_fusion_label_output.nii + -s 3x3x3 -t ['im1.nii', 'im2.nii']" + + >>> jf.inputs.dimension = 3 + >>> jf.inputs.alpha = 0.5 + >>> jf.inputs.beta = 1.0 + >>> jf.inputs.patch_radius = [3,2,1] + >>> jf.inputs.search_radius = [3] + >>> jf.cmdline + "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] + -l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -o ants_fusion_label_output.nii + -p 3x2x1 -s 3 -t ['im1.nii', 'im2.nii']" + + >>> jf.inputs.search_radius = ['mask.nii'] + >>> jf.inputs.verbose = True + >>> jf.inputs.exclusion_image = ['roi01.nii', 'roi02.nii'] + >>> jf.inputs.exclusion_image_label = ['1','2'] + >>> jf.cmdline + "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] + -l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -e 1[roi01.nii] -e 2[roi02.nii] + -o ants_fusion_label_output.nii -p 3x2x1 -s mask.nii -t ['im1.nii', 'im2.nii'] -v" + + >>> jf.inputs.out_label_fusion = 'ants_fusion_label_output.nii' + >>> jf.inputs.out_intensity_fusion_name_format = 'ants_joint_fusion_intensity_%d.nii.gz' + >>> jf.inputs.out_label_post_prob_name_format = 'ants_joint_fusion_posterior_%d.nii.gz' + >>> jf.inputs.out_atlas_voting_weight_name_format = 'ants_joint_fusion_voting_weight_%d.nii.gz' + >>> jf.cmdline + "antsJointFusion -a 0.5 -g ['rc1s1.nii', 'rc1s2.nii'] -g ['rc2s1.nii', 'rc2s2.nii'] + -l segmentation0.nii.gz -l segmentation1.nii.gz -b 1.0 -d 3 -e 1[roi01.nii] -e 2[roi02.nii] + -o [ants_fusion_label_output.nii, ants_joint_fusion_intensity_%d.nii.gz, + ants_joint_fusion_posterior_%d.nii.gz, ants_joint_fusion_voting_weight_%d.nii.gz] + -p 3x2x1 -s mask.nii -t ['im1.nii', 'im2.nii'] -v" """ - input_spec = AntsJointFusionInputSpec - output_spec = AntsJointFusionOutputSpec + input_spec = JointFusionInputSpec + output_spec = JointFusionOutputSpec _cmd = "antsJointFusion" def _format_arg(self, opt, spec, val): if opt == "exclusion_image_label": - retval = [] - for ii in range(len(self.inputs.exclusion_image_label)): - retval.append( - "-e {0}[{1}]".format( - self.inputs.exclusion_image_label[ii], - self.inputs.exclusion_image[ii], - ) + return " ".join( + "-e {}[{}]".format( + self.inputs.exclusion_image_label[ii], + self.inputs.exclusion_image[ii], ) - retval = " ".join(retval) - elif opt == "patch_radius": - retval = "-p {0}".format(self._format_xarray(val)) - elif opt == "search_radius": - retval = "-s {0}".format(self._format_xarray(val)) - elif opt == "out_label_fusion": - if isdefined(self.inputs.out_intensity_fusion_name_format): - if isdefined(self.inputs.out_label_post_prob_name_format): - if isdefined(self.inputs.out_atlas_voting_weight_name_format): - retval = "-o [{0}, {1}, {2}, {3}]".format( - self.inputs.out_label_fusion, - self.inputs.out_intensity_fusion_name_format, - self.inputs.out_label_post_prob_name_format, - self.inputs.out_atlas_voting_weight_name_format, - ) - else: - retval = "-o [{0}, {1}, {2}]".format( - self.inputs.out_label_fusion, - self.inputs.out_intensity_fusion_name_format, - self.inputs.out_label_post_prob_name_format, - ) + for ii in range(len(self.inputs.exclusion_image_label)) + ) + if opt == "patch_radius": + return f"-p {self._format_xarray(val)}" + if opt == "search_radius": + return f"-s {self._format_xarray(val)}" + if opt == "out_label_fusion": + args = [self.inputs.out_label_fusion] + for option in ( + self.inputs.out_intensity_fusion_name_format, + self.inputs.out_label_post_prob_name_format, + self.inputs.out_atlas_voting_weight_name_format, + ): + if isdefined(option): + args.append(option) else: - retval = "-o [{0}, {1}]".format( - self.inputs.out_label_fusion, - self.inputs.out_intensity_fusion_name_format, - ) - else: - retval = "-o {0}".format(self.inputs.out_label_fusion) - elif opt == "out_intensity_fusion_name_format": - retval = "" + break + if len(args) == 1: + return " ".join(("-o", args[0])) + return "-o [{}]".format(", ".join(args)) + if opt == "out_intensity_fusion_name_format": if not isdefined(self.inputs.out_label_fusion): - retval = "-o {0}".format(self.inputs.out_intensity_fusion_name_format) - elif opt == "atlas_image": - atlas_image_cmd = " ".join( + return f"-o {self.inputs.out_intensity_fusion_name_format}" + return "" + if opt == "atlas_image": + return " ".join( [ - "-g [{0}]".format(", ".join("'%s'" % fn for fn in ai)) + "-g [{}]".format(", ".join("'%s'" % fn for fn in ai)) for ai in self.inputs.atlas_image ] ) - retval = atlas_image_cmd - elif opt == "target_image": - target_image_cmd = " ".join( + if opt == "target_image": + return " ".join( [ - "-t [{0}]".format(", ".join("'%s'" % fn for fn in ai)) + "-t [{}]".format(", ".join("'%s'" % fn for fn in ai)) for ai in self.inputs.target_image ] ) - retval = target_image_cmd - elif opt == "atlas_segmentation_image": - assert len(val) == len(self.inputs.atlas_image), ( - "Number of specified " - "segmentations should be identical to the number of atlas image " - "sets {0}!={1}".format(len(val), len(self.inputs.atlas_image)) - ) - - atlas_segmentation_image_cmd = " ".join( - ["-l {0}".format(fn) for fn in self.inputs.atlas_segmentation_image] - ) - retval = atlas_segmentation_image_cmd - else: + if opt == "atlas_segmentation_image": + if len(val) != len(self.inputs.atlas_image): + raise ValueError( + "Number of specified segmentations should be identical to the number " + "of atlas image sets {}!={}".format( + len(val), len(self.inputs.atlas_image) + ) + ) - return super(AntsJointFusion, self)._format_arg(opt, spec, val) - return retval + return " ".join([f"-l {fn}" for fn in self.inputs.atlas_segmentation_image]) + return super(AntsJointFusion, self)._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() if isdefined(self.inputs.out_label_fusion): outputs["out_label_fusion"] = os.path.abspath(self.inputs.out_label_fusion) if isdefined(self.inputs.out_intensity_fusion_name_format): - outputs["out_intensity_fusion_name_format"] = os.path.abspath( - self.inputs.out_intensity_fusion_name_format + outputs["out_intensity_fusion"] = glob( + os.path.abspath( + self.inputs.out_intensity_fusion_name_format.replace("%d", "*") + ) ) if isdefined(self.inputs.out_label_post_prob_name_format): - outputs["out_label_post_prob_name_format"] = os.path.abspath( - self.inputs.out_label_post_prob_name_format + outputs["out_label_post_prob"] = glob( + os.path.abspath( + self.inputs.out_label_post_prob_name_format.replace("%d", "*") + ) ) if isdefined(self.inputs.out_atlas_voting_weight_name_format): - outputs["out_atlas_voting_weight_name_format"] = os.path.abspath( - self.inputs.out_atlas_voting_weight_name_format + outputs["out_atlas_voting_weight"] = glob( + os.path.abspath( + self.inputs.out_atlas_voting_weight_name_format.replace("%d", "*") + ) ) - return outputs +# For backwards compatibility +AntsJointFusion = JointFusion +AntsJointFusionInputSpec = JointFusionInputSpec +AntsJointFusionOutputSpec = JointFusionOutputSpec + + class KellyKapowskiInputSpec(ANTSCommandInputSpec): dimension = traits.Enum( 3, @@ -1797,7 +1710,8 @@ class KellyKapowskiOutputSpec(TraitedSpec): class KellyKapowski(ANTSCommand): - """ Nipype Interface to ANTs' KellyKapowski, also known as DiReCT. + """ + Nipype Interface to ANTs' KellyKapowski, also known as DiReCT. DiReCT is a registration based estimate of cortical thickness. It was published in S. R. Das, B. B. Avants, M. Grossman, and J. C. Gee, Registration based @@ -1812,12 +1726,12 @@ class KellyKapowski(ANTSCommand): >>> kk.inputs.convergence = "[45,0.0,10]" >>> kk.inputs.thickness_prior_estimate = 10 >>> kk.cmdline - 'KellyKapowski --convergence "[45,0.0,10]" \ ---output "[segmentation0_cortical_thickness.nii.gz,segmentation0_warped_white_matter.nii.gz]" \ ---image-dimensionality 3 --gradient-step 0.025000 \ ---maximum-number-of-invert-displacement-field-iterations 20 --number-of-integration-points 10 \ ---segmentation-image "[segmentation0.nii.gz,2,3]" --smoothing-variance 1.000000 \ ---smoothing-velocity-field-parameter 1.500000 --thickness-prior-estimate 10.000000' + 'KellyKapowski --convergence "[45,0.0,10]" + --output "[segmentation0_cortical_thickness.nii.gz,segmentation0_warped_white_matter.nii.gz]" + --image-dimensionality 3 --gradient-step 0.025000 + --maximum-number-of-invert-displacement-field-iterations 20 --number-of-integration-points 10 + --segmentation-image "[segmentation0.nii.gz,2,3]" --smoothing-variance 1.000000 + --smoothing-velocity-field-parameter 1.500000 --thickness-prior-estimate 10.000000' """ @@ -1825,7 +1739,7 @@ class KellyKapowski(ANTSCommand): input_spec = KellyKapowskiInputSpec output_spec = KellyKapowskiOutputSpec - references_ = [ + _references = [ { "entry": BibTeX( """\ @@ -1851,7 +1765,7 @@ def _parse_inputs(self, skip=None): if skip is None: skip = [] skip += ["warped_white_matter", "gray_matter_label", "white_matter_label"] - return super(KellyKapowski, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _gen_filename(self, name): if name == "cortical_thickness": @@ -1868,11 +1782,9 @@ def _gen_filename(self, name): output = name + "_warped_white_matter" + ext return output - return None - def _format_arg(self, opt, spec, val): if opt == "segmentation_image": - newval = "[{0},{1},{2}]".format( + newval = "[{},{},{}]".format( self.inputs.segmentation_image, self.inputs.gray_matter_label, self.inputs.white_matter_label, @@ -1882,7 +1794,7 @@ def _format_arg(self, opt, spec, val): if opt == "cortical_thickness": ct = self._gen_filename("cortical_thickness") wm = self._gen_filename("warped_white_matter") - newval = "[{},{}]".format(ct, wm) + newval = f"[{ct},{wm}]" return spec.argstr % newval - return super(KellyKapowski, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) diff --git a/nipype/interfaces/ants/tests/__init__.py b/nipype/interfaces/ants/tests/__init__.py index 99fb243f19..349937997e 100644 --- a/nipype/interfaces/ants/tests/__init__.py +++ b/nipype/interfaces/ants/tests/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/interfaces/ants/tests/test_auto_AI.py b/nipype/interfaces/ants/tests/test_auto_AI.py new file mode 100644 index 0000000000..bef56b7ee6 --- /dev/null +++ b/nipype/interfaces/ants/tests/test_auto_AI.py @@ -0,0 +1,90 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import AI + + +def test_AI_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + convergence=dict( + argstr="-c [%d,%g,%d]", + usedefault=True, + ), + dimension=dict( + argstr="-d %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + extensions=None, + mandatory=True, + ), + fixed_image_mask=dict( + argstr="-x %s", + extensions=None, + ), + metric=dict( + argstr="-m %s", + mandatory=True, + ), + moving_image=dict( + extensions=None, + mandatory=True, + ), + moving_image_mask=dict( + extensions=None, + requires=["fixed_image_mask"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_transform=dict( + argstr="-o %s", + extensions=None, + usedefault=True, + ), + principal_axes=dict( + argstr="-p %d", + usedefault=True, + xor=["blobs"], + ), + search_factor=dict( + argstr="-s [%g,%g]", + usedefault=True, + ), + search_grid=dict( + argstr="-g %s", + min_ver="2.3.0", + ), + transform=dict( + argstr="-t %s[%g]", + usedefault=True, + ), + verbose=dict( + argstr="-v %d", + usedefault=True, + ), + ) + inputs = AI.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_AI_outputs(): + output_map = dict( + output_transform=dict( + extensions=None, + ), + ) + outputs = AI.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_auto_ANTS.py b/nipype/interfaces/ants/tests/test_auto_ANTS.py index f3e329f957..17f456e0dd 100644 --- a/nipype/interfaces/ants/tests/test_auto_ANTS.py +++ b/nipype/interfaces/ants/tests/test_auto_ANTS.py @@ -4,35 +4,97 @@ def test_ANTS_inputs(): input_map = dict( - affine_gradient_descent_option=dict(argstr="%s",), - args=dict(argstr="%s",), - delta_time=dict(requires=["number_of_time_steps"],), - dimension=dict(argstr="%d", position=1,), - environ=dict(nohash=True, usedefault=True,), - fixed_image=dict(mandatory=True,), - gradient_step_length=dict(requires=["transformation_model"],), - metric=dict(mandatory=True,), - metric_weight=dict(mandatory=True, requires=["metric"], usedefault=True,), - mi_option=dict(argstr="--MI-option %s", sep="x",), - moving_image=dict(argstr="%s", mandatory=True,), - num_threads=dict(nohash=True, usedefault=True,), + affine_gradient_descent_option=dict( + argstr="%s", + ), + args=dict( + argstr="%s", + ), + delta_time=dict( + requires=["number_of_time_steps"], + ), + dimension=dict( + argstr="%d", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + mandatory=True, + ), + gradient_step_length=dict( + requires=["transformation_model"], + ), + metric=dict( + mandatory=True, + ), + metric_weight=dict( + mandatory=True, + requires=["metric"], + usedefault=True, + ), + mi_option=dict( + argstr="--MI-option %s", + sep="x", + ), + moving_image=dict( + argstr="%s", + mandatory=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), number_of_affine_iterations=dict( - argstr="--number-of-affine-iterations %s", sep="x", + argstr="--number-of-affine-iterations %s", + sep="x", + ), + number_of_iterations=dict( + argstr="--number-of-iterations %s", + sep="x", + ), + number_of_time_steps=dict( + requires=["gradient_step_length"], ), - number_of_iterations=dict(argstr="--number-of-iterations %s", sep="x",), - number_of_time_steps=dict(requires=["gradient_step_length"],), output_transform_prefix=dict( - argstr="--output-naming %s", mandatory=True, usedefault=True, - ), - radius=dict(mandatory=True, requires=["metric"],), - regularization=dict(argstr="%s",), - regularization_deformation_field_sigma=dict(requires=["regularization"],), - regularization_gradient_field_sigma=dict(requires=["regularization"],), - smoothing_sigmas=dict(argstr="--gaussian-smoothing-sigmas %s", sep="x",), - subsampling_factors=dict(argstr="--subsampling-factors %s", sep="x",), - symmetry_type=dict(requires=["delta_time"],), - transformation_model=dict(argstr="%s", mandatory=True,), - use_histogram_matching=dict(argstr="%s", usedefault=True,), + argstr="--output-naming %s", + mandatory=True, + usedefault=True, + ), + radius=dict( + mandatory=True, + requires=["metric"], + ), + regularization=dict( + argstr="%s", + ), + regularization_deformation_field_sigma=dict( + requires=["regularization"], + ), + regularization_gradient_field_sigma=dict( + requires=["regularization"], + ), + smoothing_sigmas=dict( + argstr="--gaussian-smoothing-sigmas %s", + sep="x", + ), + subsampling_factors=dict( + argstr="--subsampling-factors %s", + sep="x", + ), + symmetry_type=dict( + requires=["delta_time"], + ), + transformation_model=dict( + argstr="%s", + mandatory=True, + ), + use_histogram_matching=dict( + argstr="%s", + usedefault=True, + ), ) inputs = ANTS.input_spec() @@ -43,11 +105,21 @@ def test_ANTS_inputs(): def test_ANTS_outputs(): output_map = dict( - affine_transform=dict(extensions=None,), - inverse_warp_transform=dict(extensions=None,), - metaheader=dict(extensions=None,), - metaheader_raw=dict(extensions=None,), - warp_transform=dict(extensions=None,), + affine_transform=dict( + extensions=None, + ), + inverse_warp_transform=dict( + extensions=None, + ), + metaheader=dict( + extensions=None, + ), + metaheader_raw=dict( + extensions=None, + ), + warp_transform=dict( + extensions=None, + ), ) outputs = ANTS.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_ANTSCommand.py b/nipype/interfaces/ants/tests/test_auto_ANTSCommand.py index 7a5ff5dec5..8907c4ab91 100644 --- a/nipype/interfaces/ants/tests/test_auto_ANTSCommand.py +++ b/nipype/interfaces/ants/tests/test_auto_ANTSCommand.py @@ -4,9 +4,17 @@ def test_ANTSCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), ) inputs = ANTSCommand.input_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_AffineInitializer.py b/nipype/interfaces/ants/tests/test_auto_AffineInitializer.py index f97fbe3352..24ef0d655e 100644 --- a/nipype/interfaces/ants/tests/test_auto_AffineInitializer.py +++ b/nipype/interfaces/ants/tests/test_auto_AffineInitializer.py @@ -4,17 +4,60 @@ def test_AffineInitializer_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="%s", position=0, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - fixed_image=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - local_search=dict(argstr="%d", position=7, usedefault=True,), - moving_image=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="%s", extensions=None, position=3, usedefault=True,), - principal_axes=dict(argstr="%d", position=6, usedefault=True,), - radian_fraction=dict(argstr="%f", position=5, usedefault=True,), - search_factor=dict(argstr="%f", position=4, usedefault=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%s", + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + local_search=dict( + argstr="%d", + position=7, + usedefault=True, + ), + moving_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + position=3, + usedefault=True, + ), + principal_axes=dict( + argstr="%d", + position=6, + usedefault=True, + ), + radian_fraction=dict( + argstr="%f", + position=5, + usedefault=True, + ), + search_factor=dict( + argstr="%f", + position=4, + usedefault=True, + ), ) inputs = AffineInitializer.input_spec() @@ -24,7 +67,11 @@ def test_AffineInitializer_inputs(): def test_AffineInitializer_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AffineInitializer.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_AntsJointFusion.py b/nipype/interfaces/ants/tests/test_auto_AntsJointFusion.py deleted file mode 100644 index d86f7f84cb..0000000000 --- a/nipype/interfaces/ants/tests/test_auto_AntsJointFusion.py +++ /dev/null @@ -1,59 +0,0 @@ -# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT -from ..segmentation import AntsJointFusion - - -def test_AntsJointFusion_inputs(): - input_map = dict( - alpha=dict(argstr="-a %s", usedefault=True,), - args=dict(argstr="%s",), - atlas_image=dict(argstr="-g %s...", mandatory=True,), - atlas_segmentation_image=dict(argstr="-l %s...", mandatory=True,), - beta=dict(argstr="-b %s", usedefault=True,), - constrain_nonnegative=dict(argstr="-c", usedefault=True,), - dimension=dict(argstr="-d %d",), - environ=dict(nohash=True, usedefault=True,), - exclusion_image=dict(), - exclusion_image_label=dict(argstr="-e %s", requires=["exclusion_image"],), - mask_image=dict(argstr="-x %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), - out_atlas_voting_weight_name_format=dict( - requires=[ - "out_label_fusion", - "out_intensity_fusion_name_format", - "out_label_post_prob_name_format", - ], - ), - out_intensity_fusion_name_format=dict(argstr="",), - out_label_fusion=dict(argstr="%s", extensions=None, hash_files=False,), - out_label_post_prob_name_format=dict( - requires=["out_label_fusion", "out_intensity_fusion_name_format"], - ), - patch_metric=dict(argstr="-m %s",), - patch_radius=dict(argstr="-p %s", maxlen=3, minlen=3,), - retain_atlas_voting_images=dict(argstr="-f", usedefault=True,), - retain_label_posterior_images=dict( - argstr="-r", requires=["atlas_segmentation_image"], usedefault=True, - ), - search_radius=dict(argstr="-s %s", usedefault=True,), - target_image=dict(argstr="-t %s", mandatory=True,), - verbose=dict(argstr="-v",), - ) - inputs = AntsJointFusion.input_spec() - - for key, metadata in list(input_map.items()): - for metakey, value in list(metadata.items()): - assert getattr(inputs.traits()[key], metakey) == value - - -def test_AntsJointFusion_outputs(): - output_map = dict( - out_atlas_voting_weight_name_format=dict(), - out_intensity_fusion_name_format=dict(), - out_label_fusion=dict(extensions=None,), - out_label_post_prob_name_format=dict(), - ) - outputs = AntsJointFusion.output_spec() - - for key, metadata in list(output_map.items()): - for metakey, value in list(metadata.items()): - assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_auto_ApplyTransforms.py b/nipype/interfaces/ants/tests/test_auto_ApplyTransforms.py index 18add39b6c..a18a3b60b4 100644 --- a/nipype/interfaces/ants/tests/test_auto_ApplyTransforms.py +++ b/nipype/interfaces/ants/tests/test_auto_ApplyTransforms.py @@ -4,24 +4,62 @@ def test_ApplyTransforms_inputs(): input_map = dict( - args=dict(argstr="%s",), - default_value=dict(argstr="--default-value %g", usedefault=True,), - dimension=dict(argstr="--dimensionality %d",), - environ=dict(nohash=True, usedefault=True,), - float=dict(argstr="--float %d", usedefault=True,), - input_image=dict(argstr="--input %s", extensions=None, mandatory=True,), - input_image_type=dict(argstr="--input-image-type %d",), - interpolation=dict(argstr="%s", usedefault=True,), + args=dict( + argstr="%s", + ), + default_value=dict( + argstr="--default-value %g", + usedefault=True, + ), + dimension=dict( + argstr="--dimensionality %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + float=dict( + argstr="--float %d", + usedefault=True, + ), + input_image=dict( + argstr="--input %s", + extensions=None, + mandatory=True, + ), + input_image_type=dict( + argstr="--input-image-type %d", + ), + interpolation=dict( + argstr="%s", + usedefault=True, + ), interpolation_parameters=dict(), invert_transform_flags=dict(), - num_threads=dict(nohash=True, usedefault=True,), - out_postfix=dict(usedefault=True,), - output_image=dict(argstr="--output %s", genfile=True, hash_files=False,), - print_out_composite_warp_file=dict(requires=["output_image"],), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_postfix=dict( + usedefault=True, + ), + output_image=dict( + argstr="--output %s", + genfile=True, + hash_files=False, + ), + print_out_composite_warp_file=dict( + requires=["output_image"], + ), reference_image=dict( - argstr="--reference-image %s", extensions=None, mandatory=True, + argstr="--reference-image %s", + extensions=None, + mandatory=True, + ), + transforms=dict( + argstr="%s", + mandatory=True, ), - transforms=dict(argstr="%s", mandatory=True,), ) inputs = ApplyTransforms.input_spec() @@ -31,7 +69,11 @@ def test_ApplyTransforms_inputs(): def test_ApplyTransforms_outputs(): - output_map = dict(output_image=dict(extensions=None,),) + output_map = dict( + output_image=dict( + extensions=None, + ), + ) outputs = ApplyTransforms.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_ApplyTransformsToPoints.py b/nipype/interfaces/ants/tests/test_auto_ApplyTransformsToPoints.py index a0258471b8..472c22c8b2 100644 --- a/nipype/interfaces/ants/tests/test_auto_ApplyTransformsToPoints.py +++ b/nipype/interfaces/ants/tests/test_auto_ApplyTransformsToPoints.py @@ -4,19 +4,36 @@ def test_ApplyTransformsToPoints_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="--dimensionality %d",), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="--input %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="--dimensionality %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="--input %s", + extensions=None, + mandatory=True, + ), invert_transform_flags=dict(), - num_threads=dict(nohash=True, usedefault=True,), + num_threads=dict( + nohash=True, + usedefault=True, + ), output_file=dict( argstr="--output %s", hash_files=False, name_source=["input_file"], name_template="%s_transformed.csv", ), - transforms=dict(argstr="%s", mandatory=True,), + transforms=dict( + argstr="%s", + mandatory=True, + ), ) inputs = ApplyTransformsToPoints.input_spec() @@ -26,7 +43,11 @@ def test_ApplyTransformsToPoints_inputs(): def test_ApplyTransformsToPoints_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = ApplyTransformsToPoints.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_Atropos.py b/nipype/interfaces/ants/tests/test_auto_Atropos.py index 021348bba0..9f02bb5151 100644 --- a/nipype/interfaces/ants/tests/test_auto_Atropos.py +++ b/nipype/interfaces/ants/tests/test_auto_Atropos.py @@ -4,34 +4,85 @@ def test_Atropos_inputs(): input_map = dict( - args=dict(argstr="%s",), - convergence_threshold=dict(requires=["n_iterations"],), - dimension=dict(argstr="--image-dimensionality %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - icm_use_synchronous_update=dict(argstr="%s",), + args=dict( + argstr="%s", + ), + convergence_threshold=dict( + requires=["n_iterations"], + ), + dimension=dict( + argstr="--image-dimensionality %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + icm_use_synchronous_update=dict( + argstr="%s", + ), initialization=dict( - argstr="%s", mandatory=True, requires=["number_of_tissue_classes"], - ), - intensity_images=dict(argstr="--intensity-image %s...", mandatory=True,), - likelihood_model=dict(argstr="--likelihood-model %s",), - mask_image=dict(argstr="--mask-image %s", extensions=None, mandatory=True,), - maximum_number_of_icm_terations=dict(requires=["icm_use_synchronous_update"],), - mrf_radius=dict(requires=["mrf_smoothing_factor"],), - mrf_smoothing_factor=dict(argstr="%s",), - n_iterations=dict(argstr="%s",), - num_threads=dict(nohash=True, usedefault=True,), - number_of_tissue_classes=dict(mandatory=True,), + argstr="%s", + mandatory=True, + requires=["number_of_tissue_classes"], + ), + intensity_images=dict( + argstr="--intensity-image %s...", + mandatory=True, + ), + kmeans_init_centers=dict(), + likelihood_model=dict( + argstr="--likelihood-model %s", + ), + mask_image=dict( + argstr="--mask-image %s", + extensions=None, + mandatory=True, + ), + maximum_number_of_icm_terations=dict( + requires=["icm_use_synchronous_update"], + ), + mrf_radius=dict( + requires=["mrf_smoothing_factor"], + ), + mrf_smoothing_factor=dict( + argstr="%s", + ), + n_iterations=dict( + argstr="%s", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + number_of_tissue_classes=dict( + mandatory=True, + ), out_classified_image_name=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + ), + output_posteriors_name_template=dict( + usedefault=True, + ), + posterior_formulation=dict( + argstr="%s", + ), + prior_image=dict(), + prior_probability_threshold=dict( + requires=["prior_weighting"], ), - output_posteriors_name_template=dict(usedefault=True,), - posterior_formulation=dict(argstr="%s",), - prior_probability_images=dict(), - prior_probability_threshold=dict(requires=["prior_weighting"],), prior_weighting=dict(), save_posteriors=dict(), - use_mixture_model_proportions=dict(requires=["posterior_formulation"],), - use_random_seed=dict(argstr="--use-random-seed %d", usedefault=True,), + use_mixture_model_proportions=dict( + requires=["posterior_formulation"], + ), + use_random_seed=dict( + argstr="--use-random-seed %d", + usedefault=True, + ), ) inputs = Atropos.input_spec() @@ -41,7 +92,12 @@ def test_Atropos_inputs(): def test_Atropos_outputs(): - output_map = dict(classified_image=dict(extensions=None,), posteriors=dict(),) + output_map = dict( + classified_image=dict( + extensions=None, + ), + posteriors=dict(), + ) outputs = Atropos.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_AverageAffineTransform.py b/nipype/interfaces/ants/tests/test_auto_AverageAffineTransform.py index 5d8b191931..3da6956de2 100644 --- a/nipype/interfaces/ants/tests/test_auto_AverageAffineTransform.py +++ b/nipype/interfaces/ants/tests/test_auto_AverageAffineTransform.py @@ -4,14 +4,33 @@ def test_AverageAffineTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="%d", mandatory=True, position=0,), - environ=dict(nohash=True, usedefault=True,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%d", + mandatory=True, + position=0, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), output_affine_transform=dict( - argstr="%s", extensions=None, mandatory=True, position=1, + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + transforms=dict( + argstr="%s", + mandatory=True, + position=3, ), - transforms=dict(argstr="%s", mandatory=True, position=3,), ) inputs = AverageAffineTransform.input_spec() @@ -21,7 +40,11 @@ def test_AverageAffineTransform_inputs(): def test_AverageAffineTransform_outputs(): - output_map = dict(affine_transform=dict(extensions=None,),) + output_map = dict( + affine_transform=dict( + extensions=None, + ), + ) outputs = AverageAffineTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_AverageImages.py b/nipype/interfaces/ants/tests/test_auto_AverageImages.py index 572407efbc..8eb03ea7b4 100644 --- a/nipype/interfaces/ants/tests/test_auto_AverageImages.py +++ b/nipype/interfaces/ants/tests/test_auto_AverageImages.py @@ -4,14 +4,38 @@ def test_AverageImages_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="%d", mandatory=True, position=0,), - environ=dict(nohash=True, usedefault=True,), - images=dict(argstr="%s", mandatory=True, position=3,), - normalize=dict(argstr="%d", mandatory=True, position=2,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%d", + mandatory=True, + position=0, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + images=dict( + argstr="%s", + mandatory=True, + position=3, + ), + normalize=dict( + argstr="%d", + mandatory=True, + position=2, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), output_average_image=dict( - argstr="%s", extensions=None, hash_files=False, position=1, usedefault=True, + argstr="%s", + extensions=None, + hash_files=False, + position=1, + usedefault=True, ), ) inputs = AverageImages.input_spec() @@ -22,7 +46,11 @@ def test_AverageImages_inputs(): def test_AverageImages_outputs(): - output_map = dict(output_average_image=dict(extensions=None,),) + output_map = dict( + output_average_image=dict( + extensions=None, + ), + ) outputs = AverageImages.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_BrainExtraction.py b/nipype/interfaces/ants/tests/test_auto_BrainExtraction.py index 8eb0293313..454a102f2d 100644 --- a/nipype/interfaces/ants/tests/test_auto_BrainExtraction.py +++ b/nipype/interfaces/ants/tests/test_auto_BrainExtraction.py @@ -4,22 +4,61 @@ def test_BrainExtraction_inputs(): input_map = dict( - anatomical_image=dict(argstr="-a %s", extensions=None, mandatory=True,), - args=dict(argstr="%s",), + anatomical_image=dict( + argstr="-a %s", + extensions=None, + mandatory=True, + ), + args=dict( + argstr="%s", + ), brain_probability_mask=dict( - argstr="-m %s", copyfile=False, extensions=None, mandatory=True, - ), - brain_template=dict(argstr="-e %s", extensions=None, mandatory=True,), - debug=dict(argstr="-z 1",), - dimension=dict(argstr="-d %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - extraction_registration_mask=dict(argstr="-f %s", extensions=None,), - image_suffix=dict(argstr="-s %s", usedefault=True,), - keep_temporary_files=dict(argstr="-k %d",), - num_threads=dict(nohash=True, usedefault=True,), - out_prefix=dict(argstr="-o %s", usedefault=True,), - use_floatingpoint_precision=dict(argstr="-q %d",), - use_random_seeding=dict(argstr="-u %d",), + argstr="-m %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + brain_template=dict( + argstr="-e %s", + extensions=None, + mandatory=True, + ), + debug=dict( + argstr="-z 1", + ), + dimension=dict( + argstr="-d %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extraction_registration_mask=dict( + argstr="-f %s", + extensions=None, + ), + image_suffix=dict( + argstr="-s %s", + usedefault=True, + ), + keep_temporary_files=dict( + argstr="-k %d", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr="-o %s", + usedefault=True, + ), + use_floatingpoint_precision=dict( + argstr="-q %d", + ), + use_random_seeding=dict( + argstr="-u %d", + ), ) inputs = BrainExtraction.input_spec() @@ -30,24 +69,60 @@ def test_BrainExtraction_inputs(): def test_BrainExtraction_outputs(): output_map = dict( - BrainExtractionBrain=dict(extensions=None,), - BrainExtractionCSF=dict(extensions=None,), - BrainExtractionGM=dict(extensions=None,), - BrainExtractionInitialAffine=dict(extensions=None,), - BrainExtractionInitialAffineFixed=dict(extensions=None,), - BrainExtractionInitialAffineMoving=dict(extensions=None,), - BrainExtractionLaplacian=dict(extensions=None,), - BrainExtractionMask=dict(extensions=None,), - BrainExtractionPrior0GenericAffine=dict(extensions=None,), - BrainExtractionPrior1InverseWarp=dict(extensions=None,), - BrainExtractionPrior1Warp=dict(extensions=None,), - BrainExtractionPriorWarped=dict(extensions=None,), - BrainExtractionSegmentation=dict(extensions=None,), - BrainExtractionTemplateLaplacian=dict(extensions=None,), - BrainExtractionTmp=dict(extensions=None,), - BrainExtractionWM=dict(extensions=None,), - N4Corrected0=dict(extensions=None,), - N4Truncated0=dict(extensions=None,), + BrainExtractionBrain=dict( + extensions=None, + ), + BrainExtractionCSF=dict( + extensions=None, + ), + BrainExtractionGM=dict( + extensions=None, + ), + BrainExtractionInitialAffine=dict( + extensions=None, + ), + BrainExtractionInitialAffineFixed=dict( + extensions=None, + ), + BrainExtractionInitialAffineMoving=dict( + extensions=None, + ), + BrainExtractionLaplacian=dict( + extensions=None, + ), + BrainExtractionMask=dict( + extensions=None, + ), + BrainExtractionPrior0GenericAffine=dict( + extensions=None, + ), + BrainExtractionPrior1InverseWarp=dict( + extensions=None, + ), + BrainExtractionPrior1Warp=dict( + extensions=None, + ), + BrainExtractionPriorWarped=dict( + extensions=None, + ), + BrainExtractionSegmentation=dict( + extensions=None, + ), + BrainExtractionTemplateLaplacian=dict( + extensions=None, + ), + BrainExtractionTmp=dict( + extensions=None, + ), + BrainExtractionWM=dict( + extensions=None, + ), + N4Corrected0=dict( + extensions=None, + ), + N4Truncated0=dict( + extensions=None, + ), ) outputs = BrainExtraction.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_ComposeMultiTransform.py b/nipype/interfaces/ants/tests/test_auto_ComposeMultiTransform.py index ccc54c6eb8..78afc21df2 100644 --- a/nipype/interfaces/ants/tests/test_auto_ComposeMultiTransform.py +++ b/nipype/interfaces/ants/tests/test_auto_ComposeMultiTransform.py @@ -4,10 +4,22 @@ def test_ComposeMultiTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="%d", position=0, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%d", + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), output_transform=dict( argstr="%s", extensions=None, @@ -16,8 +28,16 @@ def test_ComposeMultiTransform_inputs(): name_template="%s_composed", position=1, ), - reference_image=dict(argstr="%s", extensions=None, position=2,), - transforms=dict(argstr="%s", mandatory=True, position=3,), + reference_image=dict( + argstr="%s", + extensions=None, + position=2, + ), + transforms=dict( + argstr="%s", + mandatory=True, + position=3, + ), ) inputs = ComposeMultiTransform.input_spec() @@ -27,7 +47,11 @@ def test_ComposeMultiTransform_inputs(): def test_ComposeMultiTransform_outputs(): - output_map = dict(output_transform=dict(extensions=None,),) + output_map = dict( + output_transform=dict( + extensions=None, + ), + ) outputs = ComposeMultiTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_CompositeTransformUtil.py b/nipype/interfaces/ants/tests/test_auto_CompositeTransformUtil.py index 125c69f141..54b428db2a 100644 --- a/nipype/interfaces/ants/tests/test_auto_CompositeTransformUtil.py +++ b/nipype/interfaces/ants/tests/test_auto_CompositeTransformUtil.py @@ -4,13 +4,37 @@ def test_CompositeTransformUtil_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s...", mandatory=True, position=3,), - num_threads=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="%s", extensions=None, position=2,), - output_prefix=dict(argstr="%s", position=4, usedefault=True,), - process=dict(argstr="--%s", position=1, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s...", + mandatory=True, + position=3, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + position=2, + ), + output_prefix=dict( + argstr="%s", + position=4, + usedefault=True, + ), + process=dict( + argstr="--%s", + position=1, + usedefault=True, + ), ) inputs = CompositeTransformUtil.input_spec() @@ -21,9 +45,15 @@ def test_CompositeTransformUtil_inputs(): def test_CompositeTransformUtil_outputs(): output_map = dict( - affine_transform=dict(extensions=None,), - displacement_field=dict(extensions=None,), - out_file=dict(extensions=None,), + affine_transform=dict( + extensions=None, + ), + displacement_field=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = CompositeTransformUtil.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_ConvertScalarImageToRGB.py b/nipype/interfaces/ants/tests/test_auto_ConvertScalarImageToRGB.py index eb0a7d48b0..0ffdaef6fc 100644 --- a/nipype/interfaces/ants/tests/test_auto_ConvertScalarImageToRGB.py +++ b/nipype/interfaces/ants/tests/test_auto_ConvertScalarImageToRGB.py @@ -4,19 +4,69 @@ def test_ConvertScalarImageToRGB_inputs(): input_map = dict( - args=dict(argstr="%s",), - colormap=dict(argstr="%s", mandatory=True, position=4,), - custom_color_map_file=dict(argstr="%s", position=5, usedefault=True,), - dimension=dict(argstr="%d", mandatory=True, position=0, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - input_image=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - mask_image=dict(argstr="%s", extensions=None, position=3, usedefault=True,), - maximum_RGB_output=dict(argstr="%d", position=9, usedefault=True,), - maximum_input=dict(argstr="%d", mandatory=True, position=7,), - minimum_RGB_output=dict(argstr="%d", position=8, usedefault=True,), - minimum_input=dict(argstr="%d", mandatory=True, position=6,), - num_threads=dict(nohash=True, usedefault=True,), - output_image=dict(argstr="%s", position=2, usedefault=True,), + args=dict( + argstr="%s", + ), + colormap=dict( + argstr="%s", + mandatory=True, + position=4, + ), + custom_color_map_file=dict( + argstr="%s", + position=5, + usedefault=True, + ), + dimension=dict( + argstr="%d", + mandatory=True, + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + mask_image=dict( + argstr="%s", + position=3, + usedefault=True, + ), + maximum_RGB_output=dict( + argstr="%d", + position=9, + usedefault=True, + ), + maximum_input=dict( + argstr="%d", + mandatory=True, + position=7, + ), + minimum_RGB_output=dict( + argstr="%d", + position=8, + usedefault=True, + ), + minimum_input=dict( + argstr="%d", + mandatory=True, + position=6, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_image=dict( + argstr="%s", + position=2, + usedefault=True, + ), ) inputs = ConvertScalarImageToRGB.input_spec() @@ -26,7 +76,11 @@ def test_ConvertScalarImageToRGB_inputs(): def test_ConvertScalarImageToRGB_outputs(): - output_map = dict(output_image=dict(extensions=None,),) + output_map = dict( + output_image=dict( + extensions=None, + ), + ) outputs = ConvertScalarImageToRGB.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_CorticalThickness.py b/nipype/interfaces/ants/tests/test_auto_CorticalThickness.py index 92a3f04b57..a42551788b 100644 --- a/nipype/interfaces/ants/tests/test_auto_CorticalThickness.py +++ b/nipype/interfaces/ants/tests/test_auto_CorticalThickness.py @@ -4,32 +4,94 @@ def test_CorticalThickness_inputs(): input_map = dict( - anatomical_image=dict(argstr="-a %s", extensions=None, mandatory=True,), - args=dict(argstr="%s",), - b_spline_smoothing=dict(argstr="-v",), + anatomical_image=dict( + argstr="-a %s", + extensions=None, + mandatory=True, + ), + args=dict( + argstr="%s", + ), + b_spline_smoothing=dict( + argstr="-v", + ), brain_probability_mask=dict( - argstr="-m %s", copyfile=False, extensions=None, mandatory=True, - ), - brain_template=dict(argstr="-e %s", extensions=None, mandatory=True,), - cortical_label_image=dict(extensions=None,), - debug=dict(argstr="-z 1",), - dimension=dict(argstr="-d %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - extraction_registration_mask=dict(argstr="-f %s", extensions=None,), - image_suffix=dict(argstr="-s %s", usedefault=True,), - keep_temporary_files=dict(argstr="-k %d",), - label_propagation=dict(argstr="-l %s",), - max_iterations=dict(argstr="-i %d",), - num_threads=dict(nohash=True, usedefault=True,), - out_prefix=dict(argstr="-o %s", usedefault=True,), - posterior_formulation=dict(argstr="-b %s",), - prior_segmentation_weight=dict(argstr="-w %f",), - quick_registration=dict(argstr="-q 1",), - segmentation_iterations=dict(argstr="-n %d",), - segmentation_priors=dict(argstr="-p %s", mandatory=True,), - t1_registration_template=dict(argstr="-t %s", extensions=None, mandatory=True,), - use_floatingpoint_precision=dict(argstr="-j %d",), - use_random_seeding=dict(argstr="-u %d",), + argstr="-m %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + brain_template=dict( + argstr="-e %s", + extensions=None, + mandatory=True, + ), + cortical_label_image=dict( + extensions=None, + ), + debug=dict( + argstr="-z 1", + ), + dimension=dict( + argstr="-d %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extraction_registration_mask=dict( + argstr="-f %s", + extensions=None, + ), + image_suffix=dict( + argstr="-s %s", + usedefault=True, + ), + keep_temporary_files=dict( + argstr="-k %d", + ), + label_propagation=dict( + argstr="-l %s", + ), + max_iterations=dict( + argstr="-i %d", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr="-o %s", + usedefault=True, + ), + posterior_formulation=dict( + argstr="-b %s", + ), + prior_segmentation_weight=dict( + argstr="-w %f", + ), + quick_registration=dict( + argstr="-q 1", + ), + segmentation_iterations=dict( + argstr="-n %d", + ), + segmentation_priors=dict( + argstr="-p %s", + mandatory=True, + ), + t1_registration_template=dict( + argstr="-t %s", + extensions=None, + mandatory=True, + ), + use_floatingpoint_precision=dict( + argstr="-j %d", + ), + use_random_seeding=dict( + argstr="-u %d", + ), ) inputs = CorticalThickness.input_spec() @@ -40,19 +102,43 @@ def test_CorticalThickness_inputs(): def test_CorticalThickness_outputs(): output_map = dict( - BrainExtractionMask=dict(extensions=None,), - BrainSegmentation=dict(extensions=None,), - BrainSegmentationN4=dict(extensions=None,), + BrainExtractionMask=dict( + extensions=None, + ), + BrainSegmentation=dict( + extensions=None, + ), + BrainSegmentationN4=dict( + extensions=None, + ), BrainSegmentationPosteriors=dict(), - BrainVolumes=dict(extensions=None,), - CorticalThickness=dict(extensions=None,), - CorticalThicknessNormedToTemplate=dict(extensions=None,), - ExtractedBrainN4=dict(extensions=None,), - SubjectToTemplate0GenericAffine=dict(extensions=None,), - SubjectToTemplate1Warp=dict(extensions=None,), - SubjectToTemplateLogJacobian=dict(extensions=None,), - TemplateToSubject0Warp=dict(extensions=None,), - TemplateToSubject1GenericAffine=dict(extensions=None,), + BrainVolumes=dict( + extensions=None, + ), + CorticalThickness=dict( + extensions=None, + ), + CorticalThicknessNormedToTemplate=dict( + extensions=None, + ), + ExtractedBrainN4=dict( + extensions=None, + ), + SubjectToTemplate0GenericAffine=dict( + extensions=None, + ), + SubjectToTemplate1Warp=dict( + extensions=None, + ), + SubjectToTemplateLogJacobian=dict( + extensions=None, + ), + TemplateToSubject0Warp=dict( + extensions=None, + ), + TemplateToSubject1GenericAffine=dict( + extensions=None, + ), ) outputs = CorticalThickness.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_CreateJacobianDeterminantImage.py b/nipype/interfaces/ants/tests/test_auto_CreateJacobianDeterminantImage.py index be694c055f..197ec2ad23 100644 --- a/nipype/interfaces/ants/tests/test_auto_CreateJacobianDeterminantImage.py +++ b/nipype/interfaces/ants/tests/test_auto_CreateJacobianDeterminantImage.py @@ -4,16 +4,42 @@ def test_CreateJacobianDeterminantImage_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), deformationField=dict( - argstr="%s", extensions=None, mandatory=True, position=1, - ), - doLogJacobian=dict(argstr="%d", position=3,), - environ=dict(nohash=True, usedefault=True,), - imageDimension=dict(argstr="%d", mandatory=True, position=0,), - num_threads=dict(nohash=True, usedefault=True,), - outputImage=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - useGeometric=dict(argstr="%d", position=4,), + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + doLogJacobian=dict( + argstr="%d", + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + imageDimension=dict( + argstr="%d", + mandatory=True, + position=0, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + outputImage=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + useGeometric=dict( + argstr="%d", + position=4, + ), ) inputs = CreateJacobianDeterminantImage.input_spec() @@ -23,7 +49,11 @@ def test_CreateJacobianDeterminantImage_inputs(): def test_CreateJacobianDeterminantImage_outputs(): - output_map = dict(jacobian_image=dict(extensions=None,),) + output_map = dict( + jacobian_image=dict( + extensions=None, + ), + ) outputs = CreateJacobianDeterminantImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_CreateTiledMosaic.py b/nipype/interfaces/ants/tests/test_auto_CreateTiledMosaic.py index 3bb36c9d01..6516b03ad7 100644 --- a/nipype/interfaces/ants/tests/test_auto_CreateTiledMosaic.py +++ b/nipype/interfaces/ants/tests/test_auto_CreateTiledMosaic.py @@ -4,20 +4,56 @@ def test_CreateTiledMosaic_inputs(): input_map = dict( - alpha_value=dict(argstr="-a %.2f",), - args=dict(argstr="%s",), - direction=dict(argstr="-d %d",), - environ=dict(nohash=True, usedefault=True,), - flip_slice=dict(argstr="-f %s",), - input_image=dict(argstr="-i %s", extensions=None, mandatory=True,), - mask_image=dict(argstr="-x %s", extensions=None,), - num_threads=dict(nohash=True, usedefault=True,), - output_image=dict(argstr="-o %s", usedefault=True,), - pad_or_crop=dict(argstr="-p %s",), - permute_axes=dict(argstr="-g",), - rgb_image=dict(argstr="-r %s", extensions=None, mandatory=True,), - slices=dict(argstr="-s %s",), - tile_geometry=dict(argstr="-t %s",), + alpha_value=dict( + argstr="-a %.2f", + ), + args=dict( + argstr="%s", + ), + direction=dict( + argstr="-d %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip_slice=dict( + argstr="-f %s", + ), + input_image=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + mask_image=dict( + argstr="-x %s", + extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + output_image=dict( + argstr="-o %s", + usedefault=True, + ), + pad_or_crop=dict( + argstr="-p %s", + ), + permute_axes=dict( + argstr="-g", + ), + rgb_image=dict( + argstr="-r %s", + extensions=None, + mandatory=True, + ), + slices=dict( + argstr="-s %s", + ), + tile_geometry=dict( + argstr="-t %s", + ), ) inputs = CreateTiledMosaic.input_spec() @@ -27,7 +63,11 @@ def test_CreateTiledMosaic_inputs(): def test_CreateTiledMosaic_outputs(): - output_map = dict(output_image=dict(extensions=None,),) + output_map = dict( + output_image=dict( + extensions=None, + ), + ) outputs = CreateTiledMosaic.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_DenoiseImage.py b/nipype/interfaces/ants/tests/test_auto_DenoiseImage.py index 244b2ca778..7af4764633 100644 --- a/nipype/interfaces/ants/tests/test_auto_DenoiseImage.py +++ b/nipype/interfaces/ants/tests/test_auto_DenoiseImage.py @@ -4,10 +4,21 @@ def test_DenoiseImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-d %d",), - environ=dict(nohash=True, usedefault=True,), - input_image=dict(argstr="-i %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-d %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), noise_image=dict( extensions=None, hash_files=False, @@ -15,8 +26,14 @@ def test_DenoiseImage_inputs(): name_source=["input_image"], name_template="%s_noise", ), - noise_model=dict(argstr="-n %s", usedefault=True,), - num_threads=dict(nohash=True, usedefault=True,), + noise_model=dict( + argstr="-n %s", + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), output_image=dict( argstr="-o %s", extensions=None, @@ -25,9 +42,18 @@ def test_DenoiseImage_inputs(): name_source=["input_image"], name_template="%s_noise_corrected", ), - save_noise=dict(mandatory=True, usedefault=True, xor=["noise_image"],), - shrink_factor=dict(argstr="-s %s", usedefault=True,), - verbose=dict(argstr="-v",), + save_noise=dict( + mandatory=True, + usedefault=True, + xor=["noise_image"], + ), + shrink_factor=dict( + argstr="-s %s", + usedefault=True, + ), + verbose=dict( + argstr="-v", + ), ) inputs = DenoiseImage.input_spec() @@ -38,7 +64,12 @@ def test_DenoiseImage_inputs(): def test_DenoiseImage_outputs(): output_map = dict( - noise_image=dict(extensions=None,), output_image=dict(extensions=None,), + noise_image=dict( + extensions=None, + ), + output_image=dict( + extensions=None, + ), ) outputs = DenoiseImage.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_GenWarpFields.py b/nipype/interfaces/ants/tests/test_auto_GenWarpFields.py new file mode 100644 index 0000000000..6fde6f5b44 --- /dev/null +++ b/nipype/interfaces/ants/tests/test_auto_GenWarpFields.py @@ -0,0 +1,92 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..legacy import GenWarpFields + + +def test_GenWarpFields_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + bias_field_correction=dict( + argstr="-n 1", + ), + dimension=dict( + argstr="-d %d", + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + force_proceed=dict( + argstr="-f 1", + ), + input_image=dict( + argstr="-i %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + inverse_warp_template_labels=dict( + argstr="-l", + ), + max_iterations=dict( + argstr="-m %s", + sep="x", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr="-o %s", + usedefault=True, + ), + quality_check=dict( + argstr="-q 1", + ), + reference_image=dict( + argstr="-r %s", + copyfile=True, + extensions=None, + mandatory=True, + ), + similarity_metric=dict( + argstr="-s %s", + ), + transformation_model=dict( + argstr="-t %s", + usedefault=True, + ), + ) + inputs = GenWarpFields.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_GenWarpFields_outputs(): + output_map = dict( + affine_transformation=dict( + extensions=None, + ), + input_file=dict( + extensions=None, + ), + inverse_warp_field=dict( + extensions=None, + ), + output_file=dict( + extensions=None, + ), + warp_field=dict( + extensions=None, + ), + ) + outputs = GenWarpFields.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_auto_ImageMath.py b/nipype/interfaces/ants/tests/test_auto_ImageMath.py new file mode 100644 index 0000000000..d720233eb4 --- /dev/null +++ b/nipype/interfaces/ants/tests/test_auto_ImageMath.py @@ -0,0 +1,68 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import ImageMath + + +def test_ImageMath_inputs(): + input_map = dict( + args=dict( + argstr="%s", + position=-1, + ), + copy_header=dict( + usedefault=True, + ), + dimension=dict( + argstr="%d", + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + op1=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + op2=dict( + argstr="%s", + position=-2, + ), + operation=dict( + argstr="%s", + mandatory=True, + position=3, + ), + output_image=dict( + argstr="%s", + extensions=None, + keep_extension=True, + name_source=["op1"], + name_template="%s_maths", + position=2, + ), + ) + inputs = ImageMath.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_ImageMath_outputs(): + output_map = dict( + output_image=dict( + extensions=None, + ), + ) + outputs = ImageMath.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_auto_JointFusion.py b/nipype/interfaces/ants/tests/test_auto_JointFusion.py index 4919b27a2d..98d8d696a1 100644 --- a/nipype/interfaces/ants/tests/test_auto_JointFusion.py +++ b/nipype/interfaces/ants/tests/test_auto_JointFusion.py @@ -4,30 +4,93 @@ def test_JointFusion_inputs(): input_map = dict( - alpha=dict(requires=["method"], usedefault=True,), - args=dict(argstr="%s",), - atlas_group_id=dict(argstr="-gp %d...",), - atlas_group_weights=dict(argstr="-gpw %d...",), - beta=dict(requires=["method"], usedefault=True,), - dimension=dict(argstr="%d", mandatory=True, position=0, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - exclusion_region=dict(argstr="-x %s", extensions=None,), - method=dict(argstr="-m %s", usedefault=True,), - modalities=dict(argstr="%d", mandatory=True, position=1,), - num_threads=dict(nohash=True, usedefault=True,), - output_label_image=dict( + alpha=dict( + argstr="-a %s", + usedefault=True, + ), + args=dict( argstr="%s", + ), + atlas_image=dict( + argstr="-g %s...", + mandatory=True, + ), + atlas_segmentation_image=dict( + argstr="-l %s...", + mandatory=True, + ), + beta=dict( + argstr="-b %s", + usedefault=True, + ), + constrain_nonnegative=dict( + argstr="-c", + usedefault=True, + ), + dimension=dict( + argstr="-d %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclusion_image=dict(), + exclusion_image_label=dict( + argstr="-e %s", + requires=["exclusion_image"], + ), + mask_image=dict( + argstr="-x %s", extensions=None, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_atlas_voting_weight_name_format=dict( + requires=[ + "out_label_fusion", + "out_intensity_fusion_name_format", + "out_label_post_prob_name_format", + ], + ), + out_intensity_fusion_name_format=dict( + argstr="", + ), + out_label_fusion=dict( + argstr="%s", + extensions=None, + hash_files=False, + ), + out_label_post_prob_name_format=dict( + requires=["out_label_fusion", "out_intensity_fusion_name_format"], + ), + patch_metric=dict( + argstr="-m %s", + ), + patch_radius=dict( + argstr="-p %s", + ), + retain_atlas_voting_images=dict( + argstr="-f", + usedefault=True, + ), + retain_label_posterior_images=dict( + argstr="-r", + requires=["atlas_segmentation_image"], + usedefault=True, + ), + search_radius=dict( + argstr="-s %s", + usedefault=True, + ), + target_image=dict( + argstr="-t %s", mandatory=True, - name_template="%s", - output_name="output_label_image", - position=-1, - ), - patch_radius=dict(argstr="-rp %s", maxlen=3, minlen=3,), - search_radius=dict(argstr="-rs %s", maxlen=3, minlen=3,), - target_image=dict(argstr="-tg %s...", mandatory=True,), - warped_intensity_images=dict(argstr="-g %s...", mandatory=True,), - warped_label_images=dict(argstr="-l %s...", mandatory=True,), + ), + verbose=dict( + argstr="-v", + ), ) inputs = JointFusion.input_spec() @@ -37,7 +100,14 @@ def test_JointFusion_inputs(): def test_JointFusion_outputs(): - output_map = dict(output_label_image=dict(extensions=None,),) + output_map = dict( + out_atlas_voting_weight=dict(), + out_intensity_fusion=dict(), + out_label_fusion=dict( + extensions=None, + ), + out_label_post_prob=dict(), + ) outputs = JointFusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_KellyKapowski.py b/nipype/interfaces/ants/tests/test_auto_KellyKapowski.py index 94ce9e9abf..00c1ec53a9 100644 --- a/nipype/interfaces/ants/tests/test_auto_KellyKapowski.py +++ b/nipype/interfaces/ants/tests/test_auto_KellyKapowski.py @@ -4,8 +4,13 @@ def test_KellyKapowski_inputs(): input_map = dict( - args=dict(argstr="%s",), - convergence=dict(argstr='--convergence "%s"', usedefault=True,), + args=dict( + argstr="%s", + ), + convergence=dict( + argstr='--convergence "%s"', + usedefault=True, + ), cortical_thickness=dict( argstr='--output "%s"', extensions=None, @@ -14,35 +19,61 @@ def test_KellyKapowski_inputs(): name_source=["segmentation_image"], name_template="%s_cortical_thickness", ), - dimension=dict(argstr="--image-dimensionality %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - gradient_step=dict(argstr="--gradient-step %f", usedefault=True,), - gray_matter_label=dict(usedefault=True,), + dimension=dict( + argstr="--image-dimensionality %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradient_step=dict( + argstr="--gradient-step %f", + usedefault=True, + ), + gray_matter_label=dict( + usedefault=True, + ), gray_matter_prob_image=dict( - argstr='--gray-matter-probability-image "%s"', extensions=None, + argstr='--gray-matter-probability-image "%s"', + extensions=None, ), max_invert_displacement_field_iters=dict( argstr="--maximum-number-of-invert-displacement-field-iterations %d", usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), + num_threads=dict( + nohash=True, + usedefault=True, + ), number_integration_points=dict( - argstr="--number-of-integration-points %d", usedefault=True, + argstr="--number-of-integration-points %d", + usedefault=True, ), segmentation_image=dict( - argstr='--segmentation-image "%s"', extensions=None, mandatory=True, + argstr='--segmentation-image "%s"', + extensions=None, + mandatory=True, + ), + smoothing_variance=dict( + argstr="--smoothing-variance %f", + usedefault=True, ), - smoothing_variance=dict(argstr="--smoothing-variance %f", usedefault=True,), smoothing_velocity_field=dict( - argstr="--smoothing-velocity-field-parameter %f", usedefault=True, + argstr="--smoothing-velocity-field-parameter %f", + usedefault=True, ), thickness_prior_estimate=dict( - argstr="--thickness-prior-estimate %f", usedefault=True, + argstr="--thickness-prior-estimate %f", + usedefault=True, ), thickness_prior_image=dict( - argstr='--thickness-prior-image "%s"', extensions=None, + argstr='--thickness-prior-image "%s"', + extensions=None, + ), + use_bspline_smoothing=dict( + argstr="--use-bspline-smoothing 1", ), - use_bspline_smoothing=dict(argstr="--use-bspline-smoothing 1",), warped_white_matter=dict( extensions=None, hash_files=False, @@ -50,9 +81,12 @@ def test_KellyKapowski_inputs(): name_source=["segmentation_image"], name_template="%s_warped_white_matter", ), - white_matter_label=dict(usedefault=True,), + white_matter_label=dict( + usedefault=True, + ), white_matter_prob_image=dict( - argstr='--white-matter-probability-image "%s"', extensions=None, + argstr='--white-matter-probability-image "%s"', + extensions=None, ), ) inputs = KellyKapowski.input_spec() @@ -64,8 +98,12 @@ def test_KellyKapowski_inputs(): def test_KellyKapowski_outputs(): output_map = dict( - cortical_thickness=dict(extensions=None,), - warped_white_matter=dict(extensions=None,), + cortical_thickness=dict( + extensions=None, + ), + warped_white_matter=dict( + extensions=None, + ), ) outputs = KellyKapowski.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_LabelGeometry.py b/nipype/interfaces/ants/tests/test_auto_LabelGeometry.py index dfc4e0ff60..306c7aa17e 100644 --- a/nipype/interfaces/ants/tests/test_auto_LabelGeometry.py +++ b/nipype/interfaces/ants/tests/test_auto_LabelGeometry.py @@ -4,14 +4,35 @@ def test_LabelGeometry_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="%d", position=0, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%d", + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), intensity_image=dict( - argstr="%s", extensions=None, mandatory=True, position=2, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=2, + usedefault=True, + ), + label_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - label_image=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - num_threads=dict(nohash=True, usedefault=True,), output_file=dict( argstr="%s", name_source=["label_image"], @@ -27,7 +48,11 @@ def test_LabelGeometry_inputs(): def test_LabelGeometry_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = LabelGeometry.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_LaplacianThickness.py b/nipype/interfaces/ants/tests/test_auto_LaplacianThickness.py index 3b18ca5d0f..f6a8ffde25 100644 --- a/nipype/interfaces/ants/tests/test_auto_LaplacianThickness.py +++ b/nipype/interfaces/ants/tests/test_auto_LaplacianThickness.py @@ -4,29 +4,63 @@ def test_LaplacianThickness_inputs(): input_map = dict( - args=dict(argstr="%s",), - dT=dict(argstr="%s", position=6, requires=["prior_thickness"],), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + dT=dict( + argstr="%s", + position=6, + requires=["prior_thickness"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), input_gm=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=2, + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=2, ), input_wm=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=1, + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, ), - num_threads=dict(nohash=True, usedefault=True,), output_image=dict( argstr="%s", - extensions=None, hash_files=False, keep_extension=True, name_source=["input_wm"], name_template="%s_thickness", position=3, ), - prior_thickness=dict(argstr="%s", position=5, requires=["smooth_param"],), - smooth_param=dict(argstr="%s", position=4,), - sulcus_prior=dict(argstr="%s", position=7, requires=["dT"],), - tolerance=dict(argstr="%s", position=8, requires=["sulcus_prior"],), + prior_thickness=dict( + argstr="%s", + position=5, + requires=["smooth_param"], + ), + smooth_param=dict( + argstr="%s", + position=4, + ), + sulcus_prior=dict( + argstr="%s", + position=7, + requires=["dT"], + ), + tolerance=dict( + argstr="%s", + position=8, + requires=["sulcus_prior"], + ), ) inputs = LaplacianThickness.input_spec() @@ -36,7 +70,11 @@ def test_LaplacianThickness_inputs(): def test_LaplacianThickness_outputs(): - output_map = dict(output_image=dict(extensions=None,),) + output_map = dict( + output_image=dict( + extensions=None, + ), + ) outputs = LaplacianThickness.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py b/nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py index 2d15c49afa..05279d8017 100644 --- a/nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py +++ b/nipype/interfaces/ants/tests/test_auto_MeasureImageSimilarity.py @@ -4,19 +4,57 @@ def test_MeasureImageSimilarity_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="--dimensionality %d", position=1,), - environ=dict(nohash=True, usedefault=True,), - fixed_image=dict(extensions=None, mandatory=True,), - fixed_image_mask=dict(argstr="%s", extensions=None,), - metric=dict(argstr="%s", mandatory=True,), - metric_weight=dict(requires=["metric"], usedefault=True,), - moving_image=dict(extensions=None, mandatory=True,), - moving_image_mask=dict(extensions=None, requires=["fixed_image_mask"],), - num_threads=dict(nohash=True, usedefault=True,), - radius_or_number_of_bins=dict(mandatory=True, requires=["metric"],), - sampling_percentage=dict(mandatory=True, requires=["metric"],), - sampling_strategy=dict(requires=["metric"], usedefault=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="--dimensionality %d", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + extensions=None, + mandatory=True, + ), + fixed_image_mask=dict( + argstr="%s", + extensions=None, + ), + metric=dict( + argstr="%s", + mandatory=True, + ), + metric_weight=dict( + requires=["metric"], + usedefault=True, + ), + moving_image=dict( + extensions=None, + mandatory=True, + ), + moving_image_mask=dict( + extensions=None, + requires=["fixed_image_mask"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + radius_or_number_of_bins=dict( + mandatory=True, + requires=["metric"], + ), + sampling_percentage=dict( + mandatory=True, + requires=["metric"], + ), + sampling_strategy=dict( + requires=["metric"], + usedefault=True, + ), ) inputs = MeasureImageSimilarity.input_spec() @@ -26,7 +64,9 @@ def test_MeasureImageSimilarity_inputs(): def test_MeasureImageSimilarity_outputs(): - output_map = dict(similarity=dict(),) + output_map = dict( + similarity=dict(), + ) outputs = MeasureImageSimilarity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_MultiplyImages.py b/nipype/interfaces/ants/tests/test_auto_MultiplyImages.py index 8a8d0958eb..89f8fa60ae 100644 --- a/nipype/interfaces/ants/tests/test_auto_MultiplyImages.py +++ b/nipype/interfaces/ants/tests/test_auto_MultiplyImages.py @@ -4,15 +4,39 @@ def test_MultiplyImages_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="%d", mandatory=True, position=0,), - environ=dict(nohash=True, usedefault=True,), - first_input=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%d", + mandatory=True, + position=0, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + first_input=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), output_product_image=dict( - argstr="%s", extensions=None, mandatory=True, position=3, + argstr="%s", + extensions=None, + mandatory=True, + position=3, + ), + second_input=dict( + argstr="%s", + mandatory=True, + position=2, ), - second_input=dict(argstr="%s", mandatory=True, position=2,), ) inputs = MultiplyImages.input_spec() @@ -22,7 +46,11 @@ def test_MultiplyImages_inputs(): def test_MultiplyImages_outputs(): - output_map = dict(output_product_image=dict(extensions=None,),) + output_map = dict( + output_product_image=dict( + extensions=None, + ), + ) outputs = MultiplyImages.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_N4BiasFieldCorrection.py b/nipype/interfaces/ants/tests/test_auto_N4BiasFieldCorrection.py index 2426660455..59775df2ea 100644 --- a/nipype/interfaces/ants/tests/test_auto_N4BiasFieldCorrection.py +++ b/nipype/interfaces/ants/tests/test_auto_N4BiasFieldCorrection.py @@ -4,19 +4,53 @@ def test_N4BiasFieldCorrection_inputs(): input_map = dict( - args=dict(argstr="%s",), - bias_image=dict(extensions=None, hash_files=False,), - bspline_fitting_distance=dict(argstr="--bspline-fitting %s",), - bspline_order=dict(requires=["bspline_fitting_distance"],), - convergence_threshold=dict(requires=["n_iterations"],), - copy_header=dict(mandatory=True, usedefault=True,), - dimension=dict(argstr="-d %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - histogram_sharpening=dict(argstr="--histogram-sharpening [%g,%g,%d]",), - input_image=dict(argstr="--input-image %s", extensions=None, mandatory=True,), - mask_image=dict(argstr="--mask-image %s", extensions=None,), - n_iterations=dict(argstr="--convergence %s",), - num_threads=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + bias_image=dict( + extensions=None, + hash_files=False, + ), + bspline_fitting_distance=dict( + argstr="--bspline-fitting %s", + ), + bspline_order=dict( + requires=["bspline_fitting_distance"], + ), + convergence_threshold=dict( + requires=["n_iterations"], + ), + copy_header=dict( + mandatory=True, + usedefault=True, + ), + dimension=dict( + argstr="-d %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + histogram_sharpening=dict( + argstr="--histogram-sharpening [%g,%g,%d]", + ), + input_image=dict( + argstr="--input-image %s", + extensions=None, + mandatory=True, + ), + mask_image=dict( + argstr="--mask-image %s", + extensions=None, + ), + n_iterations=dict( + argstr="--convergence %s", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), output_image=dict( argstr="--output %s", hash_files=False, @@ -24,10 +58,23 @@ def test_N4BiasFieldCorrection_inputs(): name_source=["input_image"], name_template="%s_corrected", ), - rescale_intensities=dict(argstr="-r", min_ver="2.1.0", usedefault=True,), - save_bias=dict(mandatory=True, usedefault=True, xor=["bias_image"],), - shrink_factor=dict(argstr="--shrink-factor %d",), - weight_image=dict(argstr="--weight-image %s", extensions=None,), + rescale_intensities=dict( + argstr="-r", + min_ver="2.1.0", + usedefault=True, + ), + save_bias=dict( + mandatory=True, + usedefault=True, + xor=["bias_image"], + ), + shrink_factor=dict( + argstr="--shrink-factor %d", + ), + weight_image=dict( + argstr="--weight-image %s", + extensions=None, + ), ) inputs = N4BiasFieldCorrection.input_spec() @@ -38,7 +85,12 @@ def test_N4BiasFieldCorrection_inputs(): def test_N4BiasFieldCorrection_outputs(): output_map = dict( - bias_image=dict(extensions=None,), output_image=dict(extensions=None,), + bias_image=dict( + extensions=None, + ), + output_image=dict( + extensions=None, + ), ) outputs = N4BiasFieldCorrection.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_Registration.py b/nipype/interfaces/ants/tests/test_auto_Registration.py index 33921e8638..814948835c 100644 --- a/nipype/interfaces/ants/tests/test_auto_Registration.py +++ b/nipype/interfaces/ants/tests/test_auto_Registration.py @@ -4,81 +4,174 @@ def test_Registration_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), collapse_output_transforms=dict( - argstr="--collapse-output-transforms %d", usedefault=True, + argstr="--collapse-output-transforms %d", + usedefault=True, + ), + convergence_threshold=dict( + requires=["number_of_iterations"], + usedefault=True, ), - convergence_threshold=dict(requires=["number_of_iterations"], usedefault=True,), convergence_window_size=dict( - requires=["convergence_threshold"], usedefault=True, + requires=["convergence_threshold"], + usedefault=True, + ), + dimension=dict( + argstr="--dimensionality %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + mandatory=True, ), - dimension=dict(argstr="--dimensionality %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - fixed_image=dict(mandatory=True,), fixed_image_mask=dict( - argstr="%s", extensions=None, max_ver="2.1.0", xor=["fixed_image_masks"], + argstr="%s", + extensions=None, + max_ver="2.1.0", + xor=["fixed_image_masks"], + ), + fixed_image_masks=dict( + min_ver="2.2.0", + xor=["fixed_image_mask"], + ), + float=dict( + argstr="--float %d", ), - fixed_image_masks=dict(min_ver="2.2.0", xor=["fixed_image_mask"],), - float=dict(argstr="--float %d",), initial_moving_transform=dict( - argstr="%s", xor=["initial_moving_transform_com"], + argstr="%s", + xor=["initial_moving_transform_com"], ), initial_moving_transform_com=dict( - argstr="%s", xor=["initial_moving_transform"], + argstr="%s", + xor=["initial_moving_transform"], ), initialize_transforms_per_stage=dict( - argstr="--initialize-transforms-per-stage %d", usedefault=True, + argstr="--initialize-transforms-per-stage %d", + usedefault=True, + ), + interpolation=dict( + argstr="%s", + usedefault=True, ), - interpolation=dict(argstr="%s", usedefault=True,), interpolation_parameters=dict(), invert_initial_moving_transform=dict( - requires=["initial_moving_transform"], xor=["initial_moving_transform_com"], + requires=["initial_moving_transform"], + xor=["initial_moving_transform_com"], + ), + metric=dict( + mandatory=True, ), - metric=dict(mandatory=True,), metric_item_trait=dict(), metric_stage_trait=dict(), - metric_weight=dict(mandatory=True, requires=["metric"], usedefault=True,), - metric_weight_item_trait=dict(usedefault=True,), + metric_weight=dict( + mandatory=True, + requires=["metric"], + usedefault=True, + ), + metric_weight_item_trait=dict( + usedefault=True, + ), metric_weight_stage_trait=dict(), - moving_image=dict(mandatory=True,), + moving_image=dict( + mandatory=True, + ), moving_image_mask=dict( extensions=None, max_ver="2.1.0", requires=["fixed_image_mask"], xor=["moving_image_masks"], ), - moving_image_masks=dict(min_ver="2.2.0", xor=["moving_image_mask"],), - num_threads=dict(nohash=True, usedefault=True,), + moving_image_masks=dict( + min_ver="2.2.0", + xor=["moving_image_mask"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), number_of_iterations=dict(), output_inverse_warped_image=dict( - hash_files=False, requires=["output_warped_image"], + hash_files=False, + requires=["output_warped_image"], + ), + output_transform_prefix=dict( + argstr="%s", + usedefault=True, + ), + output_warped_image=dict( + hash_files=False, + ), + radius_bins_item_trait=dict( + usedefault=True, ), - output_transform_prefix=dict(argstr="%s", usedefault=True,), - output_warped_image=dict(hash_files=False,), - radius_bins_item_trait=dict(usedefault=True,), radius_bins_stage_trait=dict(), - radius_or_number_of_bins=dict(requires=["metric_weight"], usedefault=True,), - restore_state=dict(argstr="--restore-state %s", extensions=None,), + radius_or_number_of_bins=dict( + requires=["metric_weight"], + usedefault=True, + ), + random_seed=dict( + argstr="--random-seed %d", + min_ver="2.3.0", + ), + restore_state=dict( + argstr="--restore-state %s", + extensions=None, + ), restrict_deformation=dict(), - sampling_percentage=dict(requires=["sampling_strategy"],), + sampling_percentage=dict( + requires=["sampling_strategy"], + ), sampling_percentage_item_trait=dict(), sampling_percentage_stage_trait=dict(), - sampling_strategy=dict(requires=["metric_weight"],), + sampling_strategy=dict( + requires=["metric_weight"], + ), sampling_strategy_item_trait=dict(), sampling_strategy_stage_trait=dict(), - save_state=dict(argstr="--save-state %s", extensions=None,), - shrink_factors=dict(mandatory=True,), - sigma_units=dict(requires=["smoothing_sigmas"],), - smoothing_sigmas=dict(mandatory=True,), + save_state=dict( + argstr="--save-state %s", + extensions=None, + ), + shrink_factors=dict( + mandatory=True, + ), + sigma_units=dict( + requires=["smoothing_sigmas"], + ), + smoothing_sigmas=dict( + mandatory=True, + ), transform_parameters=dict(), - transforms=dict(argstr="%s", mandatory=True,), + transforms=dict( + argstr="%s", + mandatory=True, + ), use_estimate_learning_rate_once=dict(), - use_histogram_matching=dict(usedefault=True,), - verbose=dict(argstr="-v", usedefault=True,), - winsorize_lower_quantile=dict(argstr="%s", usedefault=True,), - winsorize_upper_quantile=dict(argstr="%s", usedefault=True,), + use_histogram_matching=dict( + usedefault=True, + ), + verbose=dict( + argstr="-v", + nohash=True, + usedefault=True, + ), + winsorize_lower_quantile=dict( + argstr="%s", + usedefault=True, + ), + winsorize_upper_quantile=dict( + argstr="%s", + usedefault=True, + ), write_composite_transform=dict( - argstr="--write-composite-transform %d", usedefault=True, + argstr="--write-composite-transform %d", + usedefault=True, ), ) inputs = Registration.input_spec() @@ -90,17 +183,29 @@ def test_Registration_inputs(): def test_Registration_outputs(): output_map = dict( - composite_transform=dict(extensions=None,), + composite_transform=dict( + extensions=None, + ), elapsed_time=dict(), forward_invert_flags=dict(), forward_transforms=dict(), - inverse_composite_transform=dict(extensions=None,), - inverse_warped_image=dict(extensions=None,), + inverse_composite_transform=dict( + extensions=None, + ), + inverse_warped_image=dict( + extensions=None, + ), metric_value=dict(), + reverse_forward_invert_flags=dict(), + reverse_forward_transforms=dict(), reverse_invert_flags=dict(), reverse_transforms=dict(), - save_state=dict(extensions=None,), - warped_image=dict(extensions=None,), + save_state=dict( + extensions=None, + ), + warped_image=dict( + extensions=None, + ), ) outputs = Registration.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_RegistrationSynQuick.py b/nipype/interfaces/ants/tests/test_auto_RegistrationSynQuick.py index 3bc1b8aa06..c799f47299 100644 --- a/nipype/interfaces/ants/tests/test_auto_RegistrationSynQuick.py +++ b/nipype/interfaces/ants/tests/test_auto_RegistrationSynQuick.py @@ -4,18 +4,56 @@ def test_RegistrationSynQuick_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-d %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - fixed_image=dict(argstr="-f %s...", mandatory=True,), - histogram_bins=dict(argstr="-r %d", usedefault=True,), - moving_image=dict(argstr="-m %s...", mandatory=True,), - num_threads=dict(argstr="-n %d", usedefault=True,), - output_prefix=dict(argstr="-o %s", usedefault=True,), - precision_type=dict(argstr="-p %s", usedefault=True,), - spline_distance=dict(argstr="-s %d", usedefault=True,), - transform_type=dict(argstr="-t %s", usedefault=True,), - use_histogram_matching=dict(argstr="-j %d",), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-d %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + argstr="-f %s...", + mandatory=True, + ), + histogram_bins=dict( + argstr="-r %d", + usedefault=True, + ), + moving_image=dict( + argstr="-m %s...", + mandatory=True, + ), + num_threads=dict( + argstr="-n %d", + usedefault=True, + ), + output_prefix=dict( + argstr="-o %s", + usedefault=True, + ), + precision_type=dict( + argstr="-p %s", + usedefault=True, + ), + random_seed=dict( + argstr="-e %d", + min_ver="2.3.0", + ), + spline_distance=dict( + argstr="-s %d", + usedefault=True, + ), + transform_type=dict( + argstr="-t %s", + usedefault=True, + ), + use_histogram_matching=dict( + argstr="-j %d", + ), ) inputs = RegistrationSynQuick.input_spec() @@ -26,11 +64,21 @@ def test_RegistrationSynQuick_inputs(): def test_RegistrationSynQuick_outputs(): output_map = dict( - forward_warp_field=dict(extensions=None,), - inverse_warp_field=dict(extensions=None,), - inverse_warped_image=dict(extensions=None,), - out_matrix=dict(extensions=None,), - warped_image=dict(extensions=None,), + forward_warp_field=dict( + extensions=None, + ), + inverse_warp_field=dict( + extensions=None, + ), + inverse_warped_image=dict( + extensions=None, + ), + out_matrix=dict( + extensions=None, + ), + warped_image=dict( + extensions=None, + ), ) outputs = RegistrationSynQuick.output_spec() diff --git a/nipype/interfaces/ants/tests/test_auto_ResampleImageBySpacing.py b/nipype/interfaces/ants/tests/test_auto_ResampleImageBySpacing.py new file mode 100644 index 0000000000..9bf5c6c6a6 --- /dev/null +++ b/nipype/interfaces/ants/tests/test_auto_ResampleImageBySpacing.py @@ -0,0 +1,74 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import ResampleImageBySpacing + + +def test_ResampleImageBySpacing_inputs(): + input_map = dict( + addvox=dict( + argstr="%d", + position=6, + requires=["apply_smoothing"], + ), + apply_smoothing=dict( + argstr="%d", + position=5, + ), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%d", + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + nn_interp=dict( + argstr="%d", + position=-1, + requires=["addvox"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_spacing=dict( + argstr="%s", + mandatory=True, + position=4, + ), + output_image=dict( + argstr="%s", + extensions=None, + keep_extension=True, + name_source=["input_image"], + name_template="%s_resampled", + position=3, + ), + ) + inputs = ResampleImageBySpacing.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_ResampleImageBySpacing_outputs(): + output_map = dict( + output_image=dict( + extensions=None, + ), + ) + outputs = ResampleImageBySpacing.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_auto_ThresholdImage.py b/nipype/interfaces/ants/tests/test_auto_ThresholdImage.py new file mode 100644 index 0000000000..c17f340b69 --- /dev/null +++ b/nipype/interfaces/ants/tests/test_auto_ThresholdImage.py @@ -0,0 +1,94 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import ThresholdImage + + +def test_ThresholdImage_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + copy_header=dict( + mandatory=True, + usedefault=True, + ), + dimension=dict( + argstr="%d", + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + input_mask=dict( + argstr="%s", + extensions=None, + requires=["num_thresholds"], + ), + inside_value=dict( + argstr="%f", + position=6, + requires=["th_low"], + ), + mode=dict( + argstr="%s", + position=4, + requires=["num_thresholds"], + xor=["th_low", "th_high"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + num_thresholds=dict( + argstr="%d", + position=5, + ), + output_image=dict( + argstr="%s", + extensions=None, + keep_extension=True, + name_source=["input_image"], + name_template="%s_resampled", + position=3, + ), + outside_value=dict( + argstr="%f", + position=7, + requires=["th_low"], + ), + th_high=dict( + argstr="%f", + position=5, + xor=["mode"], + ), + th_low=dict( + argstr="%f", + position=4, + xor=["mode"], + ), + ) + inputs = ThresholdImage.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_ThresholdImage_outputs(): + output_map = dict( + output_image=dict( + extensions=None, + ), + ) + outputs = ThresholdImage.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_auto_WarpImageMultiTransform.py b/nipype/interfaces/ants/tests/test_auto_WarpImageMultiTransform.py index b9acca1442..66f45d0cd7 100644 --- a/nipype/interfaces/ants/tests/test_auto_WarpImageMultiTransform.py +++ b/nipype/interfaces/ants/tests/test_auto_WarpImageMultiTransform.py @@ -4,14 +4,34 @@ def test_WarpImageMultiTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="%d", position=1, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - input_image=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%d", + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), invert_affine=dict(), - num_threads=dict(nohash=True, usedefault=True,), + num_threads=dict( + nohash=True, + usedefault=True, + ), out_postfix=dict( - extensions=None, hash_files=False, usedefault=True, xor=["output_image"], + extensions=None, + hash_files=False, + usedefault=True, + xor=["output_image"], ), output_image=dict( argstr="%s", @@ -21,12 +41,29 @@ def test_WarpImageMultiTransform_inputs(): position=3, xor=["out_postfix"], ), - reference_image=dict(argstr="-R %s", extensions=None, xor=["tightest_box"],), - reslice_by_header=dict(argstr="--reslice-by-header",), - tightest_box=dict(argstr="--tightest-bounding-box", xor=["reference_image"],), - transformation_series=dict(argstr="%s", mandatory=True, position=-1,), - use_bspline=dict(argstr="--use-BSpline",), - use_nearest=dict(argstr="--use-NN",), + reference_image=dict( + argstr="-R %s", + extensions=None, + xor=["tightest_box"], + ), + reslice_by_header=dict( + argstr="--reslice-by-header", + ), + tightest_box=dict( + argstr="--tightest-bounding-box", + xor=["reference_image"], + ), + transformation_series=dict( + argstr="%s", + mandatory=True, + position=-1, + ), + use_bspline=dict( + argstr="--use-BSpline", + ), + use_nearest=dict( + argstr="--use-NN", + ), ) inputs = WarpImageMultiTransform.input_spec() @@ -36,7 +73,11 @@ def test_WarpImageMultiTransform_inputs(): def test_WarpImageMultiTransform_outputs(): - output_map = dict(output_image=dict(extensions=None,),) + output_map = dict( + output_image=dict( + extensions=None, + ), + ) outputs = WarpImageMultiTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_WarpTimeSeriesImageMultiTransform.py b/nipype/interfaces/ants/tests/test_auto_WarpTimeSeriesImageMultiTransform.py index e95d70c9ac..63d8d8365e 100644 --- a/nipype/interfaces/ants/tests/test_auto_WarpTimeSeriesImageMultiTransform.py +++ b/nipype/interfaces/ants/tests/test_auto_WarpTimeSeriesImageMultiTransform.py @@ -4,19 +4,56 @@ def test_WarpTimeSeriesImageMultiTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="%d", position=1, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - input_image=dict(argstr="%s", copyfile=True, extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="%d", + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_image=dict( + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + ), invert_affine=dict(), - num_threads=dict(nohash=True, usedefault=True,), - out_postfix=dict(argstr="%s", usedefault=True,), - reference_image=dict(argstr="-R %s", extensions=None, xor=["tightest_box"],), - reslice_by_header=dict(argstr="--reslice-by-header",), - tightest_box=dict(argstr="--tightest-bounding-box", xor=["reference_image"],), - transformation_series=dict(argstr="%s", copyfile=False, mandatory=True,), - use_bspline=dict(argstr="--use-Bspline",), - use_nearest=dict(argstr="--use-NN",), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_postfix=dict( + argstr="%s", + usedefault=True, + ), + reference_image=dict( + argstr="-R %s", + extensions=None, + xor=["tightest_box"], + ), + reslice_by_header=dict( + argstr="--reslice-by-header", + ), + tightest_box=dict( + argstr="--tightest-bounding-box", + xor=["reference_image"], + ), + transformation_series=dict( + argstr="%s", + copyfile=False, + mandatory=True, + ), + use_bspline=dict( + argstr="--use-Bspline", + ), + use_nearest=dict( + argstr="--use-NN", + ), ) inputs = WarpTimeSeriesImageMultiTransform.input_spec() @@ -26,7 +63,11 @@ def test_WarpTimeSeriesImageMultiTransform_inputs(): def test_WarpTimeSeriesImageMultiTransform_outputs(): - output_map = dict(output_image=dict(extensions=None,),) + output_map = dict( + output_image=dict( + extensions=None, + ), + ) outputs = WarpTimeSeriesImageMultiTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/ants/tests/test_auto_antsIntroduction.py b/nipype/interfaces/ants/tests/test_auto_antsIntroduction.py new file mode 100644 index 0000000000..0318db7624 --- /dev/null +++ b/nipype/interfaces/ants/tests/test_auto_antsIntroduction.py @@ -0,0 +1,92 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..legacy import antsIntroduction + + +def test_antsIntroduction_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + bias_field_correction=dict( + argstr="-n 1", + ), + dimension=dict( + argstr="-d %d", + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + force_proceed=dict( + argstr="-f 1", + ), + input_image=dict( + argstr="-i %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + inverse_warp_template_labels=dict( + argstr="-l", + ), + max_iterations=dict( + argstr="-m %s", + sep="x", + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr="-o %s", + usedefault=True, + ), + quality_check=dict( + argstr="-q 1", + ), + reference_image=dict( + argstr="-r %s", + copyfile=True, + extensions=None, + mandatory=True, + ), + similarity_metric=dict( + argstr="-s %s", + ), + transformation_model=dict( + argstr="-t %s", + usedefault=True, + ), + ) + inputs = antsIntroduction.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_antsIntroduction_outputs(): + output_map = dict( + affine_transformation=dict( + extensions=None, + ), + input_file=dict( + extensions=None, + ), + inverse_warp_field=dict( + extensions=None, + ), + output_file=dict( + extensions=None, + ), + warp_field=dict( + extensions=None, + ), + ) + outputs = antsIntroduction.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_auto_buildtemplateparallel.py b/nipype/interfaces/ants/tests/test_auto_buildtemplateparallel.py new file mode 100644 index 0000000000..2713c6af54 --- /dev/null +++ b/nipype/interfaces/ants/tests/test_auto_buildtemplateparallel.py @@ -0,0 +1,85 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..legacy import buildtemplateparallel + + +def test_buildtemplateparallel_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + bias_field_correction=dict( + argstr="-n 1", + ), + dimension=dict( + argstr="-d %d", + position=1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradient_step_size=dict( + argstr="-g %f", + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-1, + ), + iteration_limit=dict( + argstr="-i %d", + usedefault=True, + ), + max_iterations=dict( + argstr="-m %s", + sep="x", + ), + num_cores=dict( + argstr="-j %d", + requires=["parallelization"], + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + out_prefix=dict( + argstr="-o %s", + usedefault=True, + ), + parallelization=dict( + argstr="-c %d", + usedefault=True, + ), + rigid_body_registration=dict( + argstr="-r 1", + ), + similarity_metric=dict( + argstr="-s %s", + ), + transformation_model=dict( + argstr="-t %s", + usedefault=True, + ), + use_first_as_target=dict(), + ) + inputs = buildtemplateparallel.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_buildtemplateparallel_outputs(): + output_map = dict( + final_template_file=dict( + extensions=None, + ), + subject_outfiles=dict(), + template_files=dict(), + ) + outputs = buildtemplateparallel.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/ants/tests/test_base.py b/nipype/interfaces/ants/tests/test_base.py new file mode 100644 index 0000000000..293aed72e6 --- /dev/null +++ b/nipype/interfaces/ants/tests/test_base.py @@ -0,0 +1,25 @@ +from nipype.interfaces.ants.base import Info + +import pytest + +# fmt: off +ANTS_VERSIONS = [("""\ +ANTs Version: 2.3.3.dev168-g29bdf +Compiled: Jun 9 2020 03:44:55 + +""", "2.3.3"), ("""\ +ANTs Version: v2.3.5.post76-g28dd25c +Compiled: Nov 16 2021 14:57:48 + +""", "2.3.5"), ("""\ +ANTs Version: v2.1.0.post789-g0740f +Compiled: I don't still have this so not going to pretend + +""", "2.2.0"), +] +# fmt: on + + +@pytest.mark.parametrize("raw_info, version", ANTS_VERSIONS) +def test_version_parser(raw_info, version): + assert Info.parse_version(raw_info) == version diff --git a/nipype/interfaces/ants/tests/test_spec_JointFusion.py b/nipype/interfaces/ants/tests/test_spec_JointFusion.py deleted file mode 100644 index a0276afbb0..0000000000 --- a/nipype/interfaces/ants/tests/test_spec_JointFusion.py +++ /dev/null @@ -1,92 +0,0 @@ -# -*- coding: utf-8 -*- -from nipype.testing import example_data -from nipype.interfaces.base import InputMultiPath -from traits.trait_errors import TraitError -from nipype.interfaces.ants import JointFusion -import pytest - - -def test_JointFusion_dimension(): - at = JointFusion() - set_dimension = lambda d: setattr(at.inputs, "dimension", int(d)) - for d in range(2, 5): - set_dimension(d) - assert at.inputs.dimension == int(d) - for d in [0, 1, 6, 7]: - with pytest.raises(TraitError): - set_dimension(d) - - -@pytest.mark.parametrize("m", range(1, 5)) -def test_JointFusion_modalities(m): - at = JointFusion() - setattr(at.inputs, "modalities", int(m)) - assert at.inputs.modalities == int(m) - - -@pytest.mark.parametrize("a, b", [(a, b) for a in range(10) for b in range(10)]) -def test_JointFusion_method(a, b): - at = JointFusion() - set_method = lambda a, b: setattr( - at.inputs, "method", "Joint[%.1f,%d]".format(a, b) - ) - _a = a / 10.0 - set_method(_a, b) - # set directly - assert at.inputs.method == "Joint[%.1f,%d]".format(_a, b) - aprime = _a + 0.1 - bprime = b + 1 - at.inputs.alpha = aprime - at.inputs.beta = bprime - # set with alpha/beta - assert at.inputs.method == "Joint[%.1f,%d]".format(aprime, bprime) - - -@pytest.mark.parametrize( - "attr, x", - [(attr, x) for attr in ["patch_radius", "search_radius"] for x in range(5)], -) -def test_JointFusion_radius(attr, x): - at = JointFusion() - setattr(at.inputs, attr, [x, x + 1, x ** x]) - assert at._format_arg(attr, None, getattr(at.inputs, attr))[ - 4: - ] == "{0}x{1}x{2}".format(x, x + 1, x ** x) - - -def test_JointFusion_cmd(): - at = JointFusion() - at.inputs.dimension = 3 - at.inputs.modalities = 1 - at.inputs.method = "Joint[0.1,2]" - at.inputs.output_label_image = "fusion_labelimage_output.nii" - warped_intensity_images = [example_data("im1.nii"), example_data("im2.nii")] - at.inputs.warped_intensity_images = warped_intensity_images - segmentation_images = [ - example_data("segmentation0.nii.gz"), - example_data("segmentation1.nii.gz"), - ] - at.inputs.warped_label_images = segmentation_images - T1_image = example_data("T1.nii") - at.inputs.target_image = T1_image - at.inputs.patch_radius = [3, 2, 1] - at.inputs.search_radius = [1, 2, 3] - expected_command = ( - "jointfusion 3 1 -m Joint[0.1,2] -rp 3x2x1 -rs 1x2x3" - " -tg %s -g %s -g %s -l %s -l %s" - " fusion_labelimage_output.nii" - ) % ( - T1_image, - warped_intensity_images[0], - warped_intensity_images[1], - segmentation_images[0], - segmentation_images[1], - ) - assert at.cmdline == expected_command - # setting intensity or labels with unequal lengths raises error - with pytest.raises(AssertionError): - at._format_arg( - "warped_intensity_images", - InputMultiPath, - warped_intensity_images + [example_data("im3.nii")], - ) diff --git a/nipype/interfaces/ants/utils.py b/nipype/interfaces/ants/utils.py index 5497535609..57202f5a34 100644 --- a/nipype/interfaces/ants/utils.py +++ b/nipype/interfaces/ants/utils.py @@ -1,11 +1,542 @@ -# -*- coding: utf-8 -*- -"""ANTS Apply Transforms interface -""" +"""ANTs' utilities.""" import os +from warnings import warn +from ..base import traits, Tuple, isdefined, TraitedSpec, File, Str, InputMultiObject +from ..mixins import CopyHeaderInterface +from .base import ANTSCommandInputSpec, ANTSCommand -from ..base import TraitedSpec, File, traits, InputMultiPath -from .base import ANTSCommand, ANTSCommandInputSpec + +class ImageMathInputSpec(ANTSCommandInputSpec): + dimension = traits.Int( + 3, usedefault=True, position=1, argstr="%d", desc="dimension of output image" + ) + output_image = File( + position=2, + argstr="%s", + name_source=["op1"], + name_template="%s_maths", + desc="output image file", + keep_extension=True, + ) + operation = traits.Enum( + # Mathematical Operations + "m", + "vm", + "+", + "v+", + "-", + "v-", + "/", + "^", + "max", + "exp", + "addtozero", + "overadd", + "abs", + "total", + "mean", + "vtotal", + "Decision", + "Neg", + # Spatial Filtering Operations + "Project", + "G", + "MD", + "ME", + "MO", + "MC", + "GD", + "GE", + "GO", + "GC", + "ExtractContours", + # Transform Image Operations + "Translate", + # Tensor Operations + "4DTensorTo3DTensor", + "ExtractVectorComponent", + "TensorColor", + "TensorFA", + "TensorFADenominator", + "TensorFANumerator", + "TensorMeanDiffusion", + "TensorRadialDiffusion", + "TensorAxialDiffusion", + "TensorEigenvalue", + "TensorToVector", + "TensorToVectorComponent", + "TensorMask", + # Unclassified Operators + "Byte", + "CorruptImage", + "D", + "MaurerDistance", + "ExtractSlice", + "FillHoles", + "Convolve", + "Finite", + "FlattenImage", + "GetLargestComponent", + "Grad", + "RescaleImage", + "WindowImage", + "NeighborhoodStats", + "ReplicateDisplacement", + "ReplicateImage", + "LabelStats", + "Laplacian", + "Canny", + "Lipschitz", + "MTR", + "Normalize", + "PadImage", + "SigmoidImage", + "Sharpen", + "UnsharpMask", + "PValueImage", + "ReplaceVoxelValue", + "SetTimeSpacing", + "SetTimeSpacingWarp", + "stack", + "ThresholdAtMean", + "TriPlanarView", + "TruncateImageIntensity", + mandatory=True, + position=3, + argstr="%s", + desc="mathematical operations", + ) + op1 = File( + exists=True, mandatory=True, position=-3, argstr="%s", desc="first operator" + ) + op2 = traits.Either( + File(exists=True), Str, position=-2, argstr="%s", desc="second operator" + ) + + args = Str(position=-1, argstr="%s", desc="Additional parameters to the command") + + copy_header = traits.Bool( + True, + usedefault=True, + desc="copy headers of the original image into the output (corrected) file", + ) + + +class ImageMathOuputSpec(TraitedSpec): + output_image = File(exists=True, desc="output image file") + + +class ImageMath(ANTSCommand, CopyHeaderInterface): + """ + Operations over images. + + Examples + -------- + >>> ImageMath( + ... op1='structural.nii', + ... operation='+', + ... op2='2').cmdline + 'ImageMath 3 structural_maths.nii + structural.nii 2' + + >>> ImageMath( + ... op1='structural.nii', + ... operation='Project', + ... op2='1 2').cmdline + 'ImageMath 3 structural_maths.nii Project structural.nii 1 2' + + >>> ImageMath( + ... op1='structural.nii', + ... operation='G', + ... op2='4').cmdline + 'ImageMath 3 structural_maths.nii G structural.nii 4' + + >>> ImageMath( + ... op1='structural.nii', + ... operation='TruncateImageIntensity', + ... op2='0.005 0.999 256').cmdline + 'ImageMath 3 structural_maths.nii TruncateImageIntensity structural.nii 0.005 0.999 256' + + By default, Nipype copies headers from the first input image (``op1``) + to the output image. + For some operations, as the ``PadImage`` operation, the header cannot be copied from inputs to + outputs, and so ``copy_header`` option is automatically set to ``False``. + + >>> pad = ImageMath( + ... op1='structural.nii', + ... operation='PadImage') + >>> pad.inputs.copy_header + False + + While the operation is set to ``PadImage``, + setting ``copy_header = True`` will have no effect. + + >>> pad.inputs.copy_header = True + >>> pad.inputs.copy_header + False + + For any other operation, ``copy_header`` can be enabled/disabled normally: + + >>> pad.inputs.operation = "ME" + >>> pad.inputs.copy_header = True + >>> pad.inputs.copy_header + True + + """ + + _cmd = "ImageMath" + input_spec = ImageMathInputSpec + output_spec = ImageMathOuputSpec + _copy_header_map = {"output_image": "op1"} + _no_copy_header_operation = ( + "PadImage", + "LabelStats", + "SetTimeSpacing", + "SetTimeSpacingWarp", + "TriPlanarView", + ) + + def __init__(self, **inputs): + super().__init__(**inputs) + if self.inputs.operation in self._no_copy_header_operation: + self.inputs.copy_header = False + + self.inputs.on_trait_change(self._operation_update, "operation") + self.inputs.on_trait_change(self._copyheader_update, "copy_header") + + def _operation_update(self): + if self.inputs.operation in self._no_copy_header_operation: + self.inputs.copy_header = False + + def _copyheader_update(self): + if ( + self.inputs.copy_header + and self.inputs.operation in self._no_copy_header_operation + ): + warn( + f"copy_header cannot be updated to True with {self.inputs.operation} as operation." + ) + self.inputs.copy_header = False + + +class ResampleImageBySpacingInputSpec(ANTSCommandInputSpec): + dimension = traits.Int( + 3, usedefault=True, position=1, argstr="%d", desc="dimension of output image" + ) + input_image = File( + exists=True, mandatory=True, position=2, argstr="%s", desc="input image file" + ) + output_image = File( + position=3, + argstr="%s", + name_source=["input_image"], + name_template="%s_resampled", + desc="output image file", + keep_extension=True, + ) + out_spacing = traits.Either( + traits.List(traits.Float, minlen=2, maxlen=3), + Tuple(traits.Float, traits.Float, traits.Float), + Tuple(traits.Float, traits.Float), + position=4, + argstr="%s", + mandatory=True, + desc="output spacing", + ) + apply_smoothing = traits.Bool( + False, argstr="%d", position=5, desc="smooth before resampling" + ) + addvox = traits.Int( + argstr="%d", + position=6, + requires=["apply_smoothing"], + desc="addvox pads each dimension by addvox", + ) + nn_interp = traits.Bool( + argstr="%d", desc="nn interpolation", position=-1, requires=["addvox"] + ) + + +class ResampleImageBySpacingOutputSpec(TraitedSpec): + output_image = File(exists=True, desc="resampled file") + + +class ResampleImageBySpacing(ANTSCommand): + """ + Resample an image with a given spacing. + + Examples + -------- + >>> res = ResampleImageBySpacing(dimension=3) + >>> res.inputs.input_image = 'structural.nii' + >>> res.inputs.output_image = 'output.nii.gz' + >>> res.inputs.out_spacing = (4, 4, 4) + >>> res.cmdline #doctest: +ELLIPSIS + 'ResampleImageBySpacing 3 structural.nii output.nii.gz 4 4 4' + + >>> res = ResampleImageBySpacing(dimension=3) + >>> res.inputs.input_image = 'structural.nii' + >>> res.inputs.output_image = 'output.nii.gz' + >>> res.inputs.out_spacing = (4, 4, 4) + >>> res.inputs.apply_smoothing = True + >>> res.cmdline #doctest: +ELLIPSIS + 'ResampleImageBySpacing 3 structural.nii output.nii.gz 4 4 4 1' + + >>> res = ResampleImageBySpacing(dimension=3) + >>> res.inputs.input_image = 'structural.nii' + >>> res.inputs.output_image = 'output.nii.gz' + >>> res.inputs.out_spacing = (0.4, 0.4, 0.4) + >>> res.inputs.apply_smoothing = True + >>> res.inputs.addvox = 2 + >>> res.inputs.nn_interp = False + >>> res.cmdline #doctest: +ELLIPSIS + 'ResampleImageBySpacing 3 structural.nii output.nii.gz 0.4 0.4 0.4 1 2 0' + + """ + + _cmd = "ResampleImageBySpacing" + input_spec = ResampleImageBySpacingInputSpec + output_spec = ResampleImageBySpacingOutputSpec + + def _format_arg(self, name, trait_spec, value): + if name == "out_spacing": + if len(value) != self.inputs.dimension: + raise ValueError("out_spacing dimensions should match dimension") + + value = " ".join(["%g" % d for d in value]) + + return super()._format_arg(name, trait_spec, value) + + +class ThresholdImageInputSpec(ANTSCommandInputSpec): + dimension = traits.Int( + 3, usedefault=True, position=1, argstr="%d", desc="dimension of output image" + ) + input_image = File( + exists=True, mandatory=True, position=2, argstr="%s", desc="input image file" + ) + output_image = File( + position=3, + argstr="%s", + name_source=["input_image"], + name_template="%s_resampled", + desc="output image file", + keep_extension=True, + ) + + mode = traits.Enum( + "Otsu", + "Kmeans", + argstr="%s", + position=4, + requires=["num_thresholds"], + xor=["th_low", "th_high"], + desc="whether to run Otsu / Kmeans thresholding", + ) + num_thresholds = traits.Int(position=5, argstr="%d", desc="number of thresholds") + input_mask = File( + exists=True, + requires=["num_thresholds"], + argstr="%s", + desc="input mask for Otsu, Kmeans", + ) + + th_low = traits.Float(position=4, argstr="%f", xor=["mode"], desc="lower threshold") + th_high = traits.Float( + position=5, argstr="%f", xor=["mode"], desc="upper threshold" + ) + inside_value = traits.Float( + 1, position=6, argstr="%f", requires=["th_low"], desc="inside value" + ) + outside_value = traits.Float( + 0, position=7, argstr="%f", requires=["th_low"], desc="outside value" + ) + copy_header = traits.Bool( + True, + mandatory=True, + usedefault=True, + desc="copy headers of the original image into the output (corrected) file", + ) + + +class ThresholdImageOutputSpec(TraitedSpec): + output_image = File(exists=True, desc="resampled file") + + +class ThresholdImage(ANTSCommand, CopyHeaderInterface): + """ + Apply thresholds on images. + + Examples + -------- + >>> thres = ThresholdImage(dimension=3) + >>> thres.inputs.input_image = 'structural.nii' + >>> thres.inputs.output_image = 'output.nii.gz' + >>> thres.inputs.th_low = 0.5 + >>> thres.inputs.th_high = 1.0 + >>> thres.inputs.inside_value = 1.0 + >>> thres.inputs.outside_value = 0.0 + >>> thres.cmdline #doctest: +ELLIPSIS + 'ThresholdImage 3 structural.nii output.nii.gz 0.500000 1.000000 1.000000 0.000000' + + >>> thres = ThresholdImage(dimension=3) + >>> thres.inputs.input_image = 'structural.nii' + >>> thres.inputs.output_image = 'output.nii.gz' + >>> thres.inputs.mode = 'Kmeans' + >>> thres.inputs.num_thresholds = 4 + >>> thres.cmdline #doctest: +ELLIPSIS + 'ThresholdImage 3 structural.nii output.nii.gz Kmeans 4' + + """ + + _cmd = "ThresholdImage" + input_spec = ThresholdImageInputSpec + output_spec = ThresholdImageOutputSpec + _copy_header_map = {"output_image": "input_image"} + + +class AIInputSpec(ANTSCommandInputSpec): + dimension = traits.Enum( + 3, 2, usedefault=True, argstr="-d %d", desc="dimension of output image" + ) + verbose = traits.Bool( + False, usedefault=True, argstr="-v %d", desc="enable verbosity" + ) + + fixed_image = File( + exists=True, + mandatory=True, + desc="Image to which the moving_image should be transformed", + ) + moving_image = File( + exists=True, + mandatory=True, + desc="Image that will be transformed to fixed_image", + ) + + fixed_image_mask = File(exists=True, argstr="-x %s", desc="fixed mage mask") + moving_image_mask = File( + exists=True, requires=["fixed_image_mask"], desc="moving mage mask" + ) + + metric_trait = ( + traits.Enum("Mattes", "GC", "MI"), + traits.Int(32), + traits.Enum("Regular", "Random", "None"), + traits.Range(value=0.2, low=0.0, high=1.0), + ) + metric = Tuple( + *metric_trait, argstr="-m %s", mandatory=True, desc="the metric(s) to use." + ) + + transform = Tuple( + traits.Enum("Affine", "Rigid", "Similarity"), + traits.Range(value=0.1, low=0.0, exclude_low=True), + argstr="-t %s[%g]", + usedefault=True, + desc="Several transform options are available", + ) + + principal_axes = traits.Bool( + False, + usedefault=True, + argstr="-p %d", + xor=["blobs"], + desc="align using principal axes", + ) + search_factor = Tuple( + traits.Float(20), + traits.Range(value=0.12, low=0.0, high=1.0), + usedefault=True, + argstr="-s [%g,%g]", + desc="search factor", + ) + + search_grid = traits.Either( + Tuple(traits.Float, Tuple(traits.Float, traits.Float, traits.Float)), + Tuple(traits.Float, traits.Tuple(traits.Float, traits.Float)), + argstr="-g %s", + desc="Translation search grid in mm", + min_ver="2.3.0", + ) + + convergence = Tuple( + traits.Range(low=1, high=10000, value=10), + traits.Float(1e-6), + traits.Range(low=1, high=100, value=10), + usedefault=True, + argstr="-c [%d,%g,%d]", + desc="convergence", + ) + + output_transform = File( + "initialization.mat", usedefault=True, argstr="-o %s", desc="output file name" + ) + + +class AIOuputSpec(TraitedSpec): + output_transform = File(exists=True, desc="output file name") + + +class AI(ANTSCommand): + """ + Calculate the optimal linear transform parameters for aligning two images. + + Examples + -------- + >>> AI( + ... fixed_image='structural.nii', + ... moving_image='epi.nii', + ... metric=('Mattes', 32, 'Regular', 1), + ... ).cmdline + 'antsAI -c [10,1e-06,10] -d 3 -m Mattes[structural.nii,epi.nii,32,Regular,1] + -o initialization.mat -p 0 -s [20,0.12] -t Affine[0.1] -v 0' + + >>> AI(fixed_image='structural.nii', + ... moving_image='epi.nii', + ... metric=('Mattes', 32, 'Regular', 1), + ... search_grid=(12, (1, 1, 1)), + ... ).cmdline + 'antsAI -c [10,1e-06,10] -d 3 -m Mattes[structural.nii,epi.nii,32,Regular,1] + -o initialization.mat -p 0 -s [20,0.12] -g [12.0,1x1x1] -t Affine[0.1] -v 0' + + """ + + _cmd = "antsAI" + input_spec = AIInputSpec + output_spec = AIOuputSpec + + def _run_interface(self, runtime, correct_return_codes=(0,)): + runtime = super()._run_interface(runtime, correct_return_codes) + + self._output = { + "output_transform": os.path.join( + runtime.cwd, os.path.basename(self.inputs.output_transform) + ) + } + return runtime + + def _format_arg(self, opt, spec, val): + if opt == "metric": + val = "%s[{fixed_image},{moving_image},%d,%s,%g]" % val + val = val.format( + fixed_image=self.inputs.fixed_image, + moving_image=self.inputs.moving_image, + ) + return spec.argstr % val + + if opt == "search_grid": + fmtval = "[{},{}]".format(val[0], "x".join("%g" % v for v in val[1])) + return spec.argstr % fmtval + + if opt == "fixed_image_mask": + if isdefined(self.inputs.moving_image_mask): + return spec.argstr % (f"[{val},{self.inputs.moving_image_mask}]") + + return super()._format_arg(opt, spec, val) + + def _list_outputs(self): + return self._output class AverageAffineTransformInputSpec(ANTSCommandInputSpec): @@ -18,7 +549,7 @@ class AverageAffineTransformInputSpec(ANTSCommandInputSpec): position=1, desc="Outputfname.txt: the name of the resulting transform.", ) - transforms = InputMultiPath( + transforms = InputMultiObject( File(exists=True), argstr="%s", mandatory=True, @@ -42,6 +573,7 @@ class AverageAffineTransform(ANTSCommand): >>> avg.inputs.output_affine_transform = 'MYtemplatewarp.mat' >>> avg.cmdline 'AverageAffineTransform 3 MYtemplatewarp.mat trans.mat func_to_struct.mat' + """ _cmd = "AverageAffineTransform" @@ -49,7 +581,7 @@ class AverageAffineTransform(ANTSCommand): output_spec = AverageAffineTransformOutputSpec def _format_arg(self, opt, spec, val): - return super(AverageAffineTransform, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -78,7 +610,7 @@ class AverageImagesInputSpec(ANTSCommandInputSpec): desc="Normalize: if true, the 2nd image is divided by its mean. " "This will select the largest image to average into.", ) - images = InputMultiPath( + images = InputMultiObject( File(exists=True), argstr="%s", mandatory=True, @@ -110,7 +642,7 @@ class AverageImages(ANTSCommand): output_spec = AverageImagesOutputSpec def _format_arg(self, opt, spec, val): - return super(AverageImages, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -166,7 +698,7 @@ class MultiplyImages(ANTSCommand): output_spec = MultiplyImagesOutputSpec def _format_arg(self, opt, spec, val): - return super(MultiplyImages, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -218,7 +750,7 @@ class CreateJacobianDeterminantImage(ANTSCommand): output_spec = CreateJacobianDeterminantImageOutputSpec def _format_arg(self, opt, spec, val): - return super(CreateJacobianDeterminantImage, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -319,7 +851,7 @@ class ComposeMultiTransformInputSpec(ANTSCommandInputSpec): position=2, desc="Reference image (only necessary when output is warpfield)", ) - transforms = InputMultiPath( + transforms = InputMultiObject( File(exists=True), argstr="%s", mandatory=True, @@ -343,7 +875,8 @@ class ComposeMultiTransform(ANTSCommand): >>> compose_transform.inputs.dimension = 3 >>> compose_transform.inputs.transforms = ['struct_to_template.mat', 'func_to_struct.mat'] >>> compose_transform.cmdline - 'ComposeMultiTransform 3 struct_to_template_composed.mat struct_to_template.mat func_to_struct.mat' + 'ComposeMultiTransform 3 struct_to_template_composed.mat + struct_to_template.mat func_to_struct.mat' """ @@ -369,7 +902,7 @@ class LabelGeometryInputSpec(ANTSCommandInputSpec): mandatory=True, usedefault=True, position=2, - desc="Intensity image to extract values from. " "This is an optional input", + desc="Intensity image to extract values from. This is an optional input", ) output_file = traits.Str( name_source=["label_image"], diff --git a/nipype/interfaces/ants/visualization.py b/nipype/interfaces/ants/visualization.py index a443a76651..cdfa3529a7 100644 --- a/nipype/interfaces/ants/visualization.py +++ b/nipype/interfaces/ants/visualization.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- -"""The ants visualisation module provides basic functions based on ITK. -""" +"""The ants visualisation module provides basic functions based on ITK.""" import os @@ -28,8 +26,14 @@ class ConvertScalarImageToRGBInputSpec(ANTSCommandInputSpec): output_image = traits.Str( "rgb.nii.gz", argstr="%s", usedefault=True, desc="rgb output image", position=2 ) - mask_image = File( - "none", argstr="%s", exists=True, desc="mask image", position=3, usedefault=True + mask_image = traits.Either( + "none", + traits.File(exists=True), + argstr="%s", + desc="mask image", + position=3, + default="none", + usedefault=True, ) colormap = traits.Enum( "grey", @@ -92,7 +96,7 @@ class ConvertScalarImageToRGB(ANTSCommand): output_spec = ConvertScalarImageToRGBOutputSpec def _format_arg(self, opt, spec, val): - return super(ConvertScalarImageToRGB, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() diff --git a/nipype/interfaces/base/__init__.py b/nipype/interfaces/base/__init__.py index 7c70f9768d..2af425d284 100644 --- a/nipype/interfaces/base/__init__.py +++ b/nipype/interfaces/base/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -8,7 +7,8 @@ This module defines the API of all nipype interfaces. """ -from traits.trait_handlers import TraitDictObject, TraitListObject +from traits.trait_dict_object import TraitDictObject +from traits.trait_list_object import TraitListObject from traits.trait_errors import TraitError from .core import ( @@ -46,6 +46,7 @@ InputMultiObject, OutputMultiPath, InputMultiPath, + Tuple, ) from .support import Bunch, InterfaceResult, NipypeInterfaceError diff --git a/nipype/interfaces/base/core.py b/nipype/interfaces/base/core.py index 82da393a84..8fadd9cc2d 100644 --- a/nipype/interfaces/base/core.py +++ b/nipype/interfaces/base/core.py @@ -1,37 +1,38 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Nipype interfaces core ...................... - Defines the ``Interface`` API and the body of the most basic interfaces. The I/O specifications corresponding to these base interfaces are found in the ``specs`` module. """ -from copy import deepcopy -from datetime import datetime as dt import os -import platform import subprocess as sp import shlex -import sys import simplejson as json -from dateutil.parser import parse as parseutc from traits.trait_errors import TraitError -from ... import config, logging, LooseVersion +from looseversion import LooseVersion + +from ... import config, logging from ...utils.provenance import write_provenance -from ...utils.misc import str2bool, rgetcwd -from ...utils.filemanip import split_filename, which, get_dependencies +from ...utils.misc import str2bool +from ...utils.filemanip import ( + canonicalize_env, + get_dependencies, + indirectory, + split_filename, + which, +) from ...utils.subprocess import run_command from ...external.due import due -from .traits_extension import traits, isdefined +from .traits_extension import traits, isdefined, Undefined from .specs import ( BaseInterfaceInputSpec, CommandLineInputSpec, @@ -39,7 +40,12 @@ MpiCommandLineInputSpec, get_filecopy_info, ) -from .support import Bunch, InterfaceResult, NipypeInterfaceError, format_help +from .support import ( + RuntimeContext, + InterfaceResult, + NipypeInterfaceError, + format_help, +) iflogger = logging.getLogger("nipype.interface") @@ -55,7 +61,7 @@ __docformat__ = "restructuredtext" -class Interface(object): +class Interface: """This is an abstract definition for Interface objects. It provides no functionality. It defines the necessary attributes @@ -63,8 +69,15 @@ class Interface(object): """ - input_spec = None # A traited input specification - output_spec = None # A traited output specification + input_spec = None + """ + The specification of the input, defined by a :py:class:`~traits.has_traits.HasTraits` class. + """ + output_spec = None + """ + The specification of the output, defined by a :py:class:`~traits.has_traits.HasTraits` class. + """ + _can_resume = False # See property below _always_run = False # See property below @@ -87,12 +100,12 @@ def version(self): @classmethod def _outputs(cls): - """ Initializes outputs""" + """Initializes outputs""" raise NotImplementedError @classmethod def help(cls, returnhelp=False): - """ Prints class help """ + """Prints class help""" allhelp = format_help(cls) if returnhelp: return allhelp @@ -112,7 +125,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): raise NotImplementedError def _list_outputs(self): - """ List expected outputs""" + """List expected outputs""" raise NotImplementedError @classmethod @@ -161,7 +174,7 @@ class BaseInterface(Interface): _version = None _additional_metadata = [] _redirect_x = False - references_ = [] + _references = [] resource_monitor = True # Enabled for this interface IFF enabled in the config _etelemetry_version_data = None @@ -175,12 +188,21 @@ def __init__( from ... import check_latest_version if BaseInterface._etelemetry_version_data is None: - BaseInterface._etelemetry_version_data = check_latest_version() + BaseInterface._etelemetry_version_data = check_latest_version() or "n/a" if not self.input_spec: raise Exception("No input_spec in class: %s" % self.__class__.__name__) - self.inputs = self.input_spec(**inputs) + # Create input spec, disable any defaults that are unavailable due to + # version, and then apply the inputs that were passed. + self.inputs = self.input_spec() + unavailable_traits = self._check_version_requirements( + self.inputs, permissive=True + ) + if unavailable_traits: + self.inputs.trait_set(**{k: Undefined for k in unavailable_traits}) + self.inputs.trait_set(**inputs) + self.ignore_exception = ignore_exception if resource_monitor is not None: @@ -193,8 +215,7 @@ def __init__( setattr(self.inputs, name, value) def _outputs(self): - """ Returns a bunch containing output fields for the class - """ + """Returns a bunch containing output fields for the class""" outputs = None if self.output_spec: outputs = self.output_spec() @@ -202,8 +223,7 @@ def _outputs(self): return outputs def _check_requires(self, spec, name, value): - """ check if required inputs are satisfied - """ + """check if required inputs are satisfied""" if spec.requires: values = [ not isdefined(getattr(self.inputs, field)) for field in spec.requires @@ -228,8 +248,7 @@ def _check_requires(self, spec, name, value): raise ValueError(msg) def _check_xor(self, spec, name, value): - """ check if mutually exclusive inputs are satisfied - """ + """check if mutually exclusive inputs are satisfied""" if spec.xor: values = [isdefined(getattr(self.inputs, field)) for field in spec.xor] if not any(values) and not isdefined(value): @@ -245,8 +264,7 @@ def _check_xor(self, spec, name, value): raise ValueError(msg) def _check_mandatory_inputs(self): - """ Raises an exception if a mandatory input is Undefined - """ + """Raises an exception if a mandatory input is Undefined""" for name, spec in list(self.inputs.traits(mandatory=True).items()): value = getattr(self.inputs, name) self._check_xor(spec, name, value) @@ -264,8 +282,12 @@ def _check_mandatory_inputs(self): ): self._check_requires(spec, name, getattr(self.inputs, name)) - def _check_version_requirements(self, trait_object, raise_exception=True): - """ Raises an exception on version mismatch + def _check_version_requirements(self, trait_object, permissive=False): + """Raises an exception on version mismatch + + Set the ``permissive`` attribute to True to suppress warnings and exceptions. + This is currently only used in __init__ to silently identify unavailable + traits. """ unavailable_traits = [] # check minimum version @@ -276,11 +298,23 @@ def _check_version_requirements(self, trait_object, raise_exception=True): version = LooseVersion(str(self.version)) for name in names: min_ver = LooseVersion(str(trait_object.traits()[name].min_ver)) - if min_ver > version: + try: + too_old = min_ver > version + except TypeError as err: + msg = ( + f"Nipype cannot validate the package version {version!r} for " + f"{self.__class__.__name__}. Trait {name} requires version >={min_ver}." + ) + if not permissive: + iflogger.warning(f"{msg}. Please verify validity.") + if config.getboolean("execution", "stop_on_unknown_version"): + raise ValueError(msg) from err + continue + if too_old: unavailable_traits.append(name) if not isdefined(getattr(trait_object, name)): continue - if raise_exception: + if not permissive: raise Exception( "Trait %s (%s) (version %s < required %s)" % (name, self.__class__.__name__, version, min_ver) @@ -293,11 +327,23 @@ def _check_version_requirements(self, trait_object, raise_exception=True): version = LooseVersion(str(self.version)) for name in names: max_ver = LooseVersion(str(trait_object.traits()[name].max_ver)) - if max_ver < version: + try: + too_new = max_ver < version + except TypeError as err: + msg = ( + f"Nipype cannot validate the package version {version!r} for " + f"{self.__class__.__name__}. Trait {name} requires version <={max_ver}." + ) + if not permissive: + iflogger.warning(f"{msg}. Please verify validity.") + if config.getboolean("execution", "stop_on_unknown_version"): + raise ValueError(msg) from err + continue + if too_new: unavailable_traits.append(name) if not isdefined(getattr(trait_object, name)): continue - if raise_exception: + if not permissive: raise Exception( "Trait %s (%s) (version %s > required %s)" % (name, self.__class__.__name__, version, max_ver) @@ -305,14 +351,12 @@ def _check_version_requirements(self, trait_object, raise_exception=True): return unavailable_traits def _run_interface(self, runtime): - """ Core function that executes interface - """ + """Core function that executes interface""" raise NotImplementedError def _duecredit_cite(self): - """ Add the interface references to the duecredit citations - """ - for r in self.references_: + """Add the interface references to the duecredit citations""" + for r in self._references: r["path"] = self.__module__ due.cite(**r) @@ -334,137 +378,50 @@ def run(self, cwd=None, ignore_exception=None, **inputs): if successful, results """ - from ...utils.profiler import ResourceMonitor - - # if ignore_exception is not provided, taking self.ignore_exception - if ignore_exception is None: - ignore_exception = self.ignore_exception - - # Tear-up: get current and prev directories - syscwd = rgetcwd(error=False) # Recover when wd does not exist - if cwd is None: - cwd = syscwd - - os.chdir(cwd) # Change to the interface wd + rtc = RuntimeContext( + resource_monitor=config.resource_monitor and self.resource_monitor, + ignore_exception=( + ignore_exception + if ignore_exception is not None + else self.ignore_exception + ), + ) - enable_rm = config.resource_monitor and self.resource_monitor - self.inputs.trait_set(**inputs) + with indirectory(cwd or os.getcwd()): + self.inputs.trait_set(**inputs) self._check_mandatory_inputs() self._check_version_requirements(self.inputs) - interface = self.__class__ - self._duecredit_cite() - - # initialize provenance tracking - store_provenance = str2bool( - config.get("execution", "write_provenance", "false") - ) - env = deepcopy(dict(os.environ)) - if self._redirect_x: - env["DISPLAY"] = config.get_display() - - runtime = Bunch( - cwd=cwd, - prevcwd=syscwd, - returncode=None, - duration=None, - environ=env, - startTime=dt.isoformat(dt.utcnow()), - endTime=None, - platform=platform.platform(), - hostname=platform.node(), - version=self.version, - ) - runtime_attrs = set(runtime.dictcopy()) - - mon_sp = None - if enable_rm: - mon_freq = float(config.get("execution", "resource_monitor_frequency", 1)) - proc_pid = os.getpid() - iflogger.debug( - "Creating a ResourceMonitor on a %s interface, PID=%d.", - self.__class__.__name__, - proc_pid, - ) - mon_sp = ResourceMonitor(proc_pid, freq=mon_freq) - mon_sp.start() - # Grab inputs now, as they should not change during execution - inputs = self.inputs.get_traitsfree() - outputs = None - - try: + with rtc(self, cwd=cwd, redirect_x=self._redirect_x) as runtime: + # Grab inputs now, as they should not change during execution + inputs = self.inputs.get_traitsfree() + outputs = None + # Run interface runtime = self._pre_run_hook(runtime) runtime = self._run_interface(runtime) runtime = self._post_run_hook(runtime) + # Collect outputs outputs = self.aggregate_outputs(runtime) - except Exception as e: - import traceback - - # Retrieve the maximum info fast - runtime.traceback = traceback.format_exc() - # Gather up the exception arguments and append nipype info. - exc_args = e.args if getattr(e, "args") else tuple() - exc_args += ( - "An exception of type %s occurred while running interface %s." - % (type(e).__name__, self.__class__.__name__), - ) - if config.get("logging", "interface_level", "info").lower() == "debug": - exc_args += ("Inputs: %s" % str(self.inputs),) - - runtime.traceback_args = ("\n".join(["%s" % arg for arg in exc_args]),) - - if not ignore_exception: - raise - finally: - if runtime is None or runtime_attrs - set(runtime.dictcopy()): - raise RuntimeError( - "{} interface failed to return valid " - "runtime object".format(interface.__class__.__name__) - ) - # This needs to be done always - runtime.endTime = dt.isoformat(dt.utcnow()) - timediff = parseutc(runtime.endTime) - parseutc(runtime.startTime) - runtime.duration = ( - timediff.days * 86400 + timediff.seconds + timediff.microseconds / 1e6 - ) - results = InterfaceResult( - interface, runtime, inputs=inputs, outputs=outputs, provenance=None - ) - # Add provenance (if required) - if store_provenance: - # Provenance will only throw a warning if something went wrong - results.provenance = write_provenance(results) - - # Make sure runtime profiler is shut down - if enable_rm: - import numpy as np - - mon_sp.stop() - - runtime.mem_peak_gb = None - runtime.cpu_percent = None + results = InterfaceResult( + self.__class__, + rtc.runtime, + inputs=inputs, + outputs=outputs, + provenance=None, + ) - # Read .prof file in and set runtime values - vals = np.loadtxt(mon_sp.fname, delimiter=",") - if vals.size: - vals = np.atleast_2d(vals) - runtime.mem_peak_gb = vals[:, 2].max() / 1024 - runtime.cpu_percent = vals[:, 1].max() + # Add provenance (if required) + if str2bool(config.get("execution", "write_provenance", "false")): + # Provenance will only throw a warning if something went wrong + results.provenance = write_provenance(results) - runtime.prof_dict = { - "time": vals[:, 0].tolist(), - "cpus": vals[:, 1].tolist(), - "rss_GiB": (vals[:, 2] / 1024).tolist(), - "vms_GiB": (vals[:, 3] / 1024).tolist(), - } - os.chdir(syscwd) + self._duecredit_cite() return results def _list_outputs(self): - """ List the expected outputs - """ + """List the expected outputs""" if self.output_spec: raise NotImplementedError else: @@ -529,7 +486,7 @@ def load_inputs_from_json(self, json_file, overwrite=True): if not overwrite: def_inputs = list(self.inputs.get_traitsfree().keys()) - new_inputs = list(set(list(inputs_dict.keys())) - set(def_inputs)) + new_inputs = set(inputs_dict) - set(def_inputs) for key in new_inputs: if hasattr(self.inputs, key): setattr(self.inputs, key, inputs_dict[key]) @@ -567,7 +524,7 @@ def _post_run_hook(self, runtime): class SimpleInterface(BaseInterface): - """ An interface pattern that allows outputs to be set in a dictionary + """An interface pattern that allows outputs to be set in a dictionary called ``_results`` that is automatically interpreted by ``_list_outputs()`` to find the outputs. @@ -607,7 +564,7 @@ class SimpleInterface(BaseInterface): """ def __init__(self, from_file=None, resource_monitor=None, **inputs): - super(SimpleInterface, self).__init__( + super().__init__( from_file=from_file, resource_monitor=resource_monitor, **inputs ) self._results = {} @@ -653,6 +610,7 @@ class must be instantiated with a command argument _cmd = None _version = None _terminal_output = "stream" + _write_cmdline = False @classmethod def set_default_terminal_output(cls, output_type): @@ -669,8 +627,10 @@ def set_default_terminal_output(cls, output_type): else: raise AttributeError("Invalid terminal output_type: %s" % output_type) - def __init__(self, command=None, terminal_output=None, **inputs): - super(CommandLine, self).__init__(**inputs) + def __init__( + self, command=None, terminal_output=None, write_cmdline=False, **inputs + ): + super().__init__(**inputs) self._environ = None # Set command. Input argument takes precedence self._cmd = command or getattr(self, "_cmd", None) @@ -684,6 +644,8 @@ def __init__(self, command=None, terminal_output=None, **inputs): if terminal_output is not None: self.terminal_output = terminal_output + self._write_cmdline = write_cmdline + @property def cmd(self): """sets base command, immutable""" @@ -696,7 +658,7 @@ def cmd(self): @property def cmdline(self): - """ `command` plus any arguments (args) + """`command` plus any arguments (args) validates arguments and generates command line""" self._check_mandatory_inputs() allargs = [self._cmd_prefix + self.cmd] + self._parse_inputs() @@ -715,6 +677,14 @@ def terminal_output(self, value): ) self._terminal_output = value + @property + def write_cmdline(self): + return self._write_cmdline + + @write_cmdline.setter + def write_cmdline(self, value): + self._write_cmdline = value is True + def raise_exception(self, runtime): raise RuntimeError( ( @@ -739,9 +709,9 @@ def version_from_command(self, flag="-v", cmd=None): out_environ = self._get_environ() env.update(out_environ) proc = sp.Popen( - " ".join((cmd, flag)), + f"{cmd} {flag}", shell=True, - env=env, + env=canonicalize_env(env), stdout=sp.PIPE, stderr=sp.PIPE, ) @@ -762,20 +732,28 @@ def _run_interface(self, runtime, correct_return_codes=(0,)): adds stdout, stderr, merged, cmdline, dependencies, command_path """ - out_environ = self._get_environ() # Initialize runtime Bunch + + try: + runtime.cmdline = self.cmdline + except Exception as exc: + raise RuntimeError( + "Error raised when interpolating the command line" + ) from exc + runtime.stdout = None runtime.stderr = None runtime.cmdline = self.cmdline runtime.environ.update(out_environ) + runtime.success_codes = correct_return_codes # which $cmd executable_name = shlex.split(self._cmd_prefix + self.cmd)[0] cmd_path = which(executable_name, env=runtime.environ) if cmd_path is None: - raise IOError( + raise OSError( 'No command "%s" found on host %s. Please check that the ' "corresponding package is installed." % (executable_name, runtime.hostname) @@ -787,10 +765,11 @@ def _run_interface(self, runtime, correct_return_codes=(0,)): if self._ldd else "" ) - runtime = run_command(runtime, output=self.terminal_output) - if runtime.returncode is None or runtime.returncode not in correct_return_codes: - self.raise_exception(runtime) - + runtime = run_command( + runtime, + output=self.terminal_output, + write_cmdline=self.write_cmdline, + ) return runtime def _format_arg(self, name, trait_spec, value): @@ -955,7 +934,14 @@ def _parse_inputs(self, skip=None): if not isdefined(value): continue - arg = self._format_arg(name, spec, value) + + try: + arg = self._format_arg(name, spec, value) + except Exception as exc: + raise ValueError( + f"Error formatting command line argument '{name}' with value '{value}'" + ) from exc + if arg is None: continue pos = spec.position @@ -1004,13 +990,13 @@ class MpiCommandLine(CommandLine): @property def cmdline(self): - """Adds 'mpiexec' to begining of command""" + """Adds 'mpiexec' to beginning of command""" result = [] if self.inputs.use_mpi: result.append("mpiexec") if self.inputs.n_procs: result.append("-n %d" % self.inputs.n_procs) - result.append(super(MpiCommandLine, self).cmdline) + result.append(super().cmdline) return " ".join(result) @@ -1049,7 +1035,7 @@ def _format_arg(self, name, spec, value): value = os.path.abspath(self._outputs_filenames[name]) else: return "" - return super(SEMLikeCommandLine, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class LibraryBaseInterface(BaseInterface): @@ -1057,17 +1043,18 @@ class LibraryBaseInterface(BaseInterface): imports = () def __init__(self, check_import=True, *args, **kwargs): - super(LibraryBaseInterface, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if check_import: - import pkgutil + import importlib.util - failed_imports = [] - for pkg in (self._pkg,) + tuple(self.imports): - if pkgutil.find_loader(pkg) is None: - failed_imports.append(pkg) + failed_imports = [ + pkg + for pkg in (self._pkg,) + tuple(self.imports) + if importlib.util.find_spec(pkg) is None + ] if failed_imports: iflogger.warning( - "Unable to import %s; %s interface may fail to " "run", + "Unable to import %s; %s interface may fail to run", failed_imports, self.__class__.__name__, ) @@ -1081,10 +1068,10 @@ def version(self): self._version = importlib.import_module(self._pkg).__version__ except (ImportError, AttributeError): pass - return super(LibraryBaseInterface, self).version + return super().version -class PackageInfo(object): +class PackageInfo: _version = None version_cmd = None version_file = None @@ -1099,13 +1086,13 @@ def version(klass): resource_monitor=False, terminal_output="allatonce", ).run() - except IOError: + except OSError: return None raw_info = clout.runtime.stdout elif klass.version_file is not None: try: - with open(klass.version_file, "rt") as fobj: + with open(klass.version_file) as fobj: raw_info = fobj.read() except OSError: return None diff --git a/nipype/interfaces/base/specs.py b/nipype/interfaces/base/specs.py index b42a73f501..defbca7f43 100644 --- a/nipype/interfaces/base/specs.py +++ b/nipype/interfaces/base/specs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -16,7 +15,8 @@ from packaging.version import Version from traits.trait_errors import TraitError -from traits.trait_handlers import TraitDictObject, TraitListObject +from traits.trait_dict_object import TraitDictObject +from traits.trait_list_object import TraitListObject from ...utils.filemanip import md5, hash_infile, hash_timestamp from .traits_extension import ( traits, @@ -58,12 +58,12 @@ class BaseTraitedSpec(traits.HasTraits): package_version = nipype_version def __init__(self, **kwargs): - """ Initialize handlers and inputs""" + """Initialize handlers and inputs""" # NOTE: In python 2.6, object.__init__ no longer accepts input # arguments. HasTraits does not define an __init__ and # therefore these args were being ignored. # super(TraitedSpec, self).__init__(*args, **kwargs) - super(BaseTraitedSpec, self).__init__(**kwargs) + super().__init__(**kwargs) traits.push_exception_handler(reraise_exceptions=True) undefined_traits = {} for trait in self.copyable_trait_names(): @@ -74,16 +74,15 @@ def __init__(self, **kwargs): self.trait_set(**kwargs) def items(self): - """ Name, trait generator for user modifiable traits - """ + """Name, trait generator for user modifiable traits""" for name in sorted(self.copyable_trait_names()): yield name, self.traits()[name] def __repr__(self): - """ Return a well-formatted representation of the traits """ + """Return a well-formatted representation of the traits""" outstr = [] for name, value in sorted(self.trait_get().items()): - outstr.append("%s = %s" % (name, value)) + outstr.append(f"{name} = {value}") return "\n{}\n".format("\n".join(outstr)) def _generate_handlers(self): @@ -100,8 +99,7 @@ def _generate_handlers(self): self.on_trait_change(self._deprecated_warn, elem) def _xor_warn(self, obj, name, old, new): - """ Generates warnings for xor traits - """ + """Generates warnings for xor traits""" if isdefined(new): trait_spec = self.traits()[name] # for each xor, set to default_value @@ -117,14 +115,13 @@ def _xor_warn(self, obj, name, old, new): 'Input "%s" is mutually exclusive with input "%s", ' "which is already set" ) % (name, trait_name) - raise IOError(msg) + raise OSError(msg) def _deprecated_warn(self, obj, name, old, new): - """Checks if a user assigns a value to a deprecated trait - """ + """Checks if a user assigns a value to a deprecated trait""" if isdefined(new): trait_spec = self.traits()[name] - msg1 = "Input %s in interface %s is deprecated." % ( + msg1 = "Input {} in interface {} is deprecated.".format( name, self.__class__.__name__.split("InputSpec")[0], ) @@ -140,12 +137,12 @@ def _deprecated_warn(self, obj, name, old, new): msg3 = "It has been replaced by %s." % trait_spec.new_name else: msg3 = "" - msg = " ".join((msg1, msg2, msg3)) + msg = f"{msg1} {msg2} {msg3}" if Version(str(trait_spec.deprecated)) < self.package_version: raise TraitError(msg) else: if trait_spec.new_name: - msg += "Unsetting old value %s; setting new value %s." % ( + msg += "Unsetting old value {}; setting new value {}.".format( name, trait_spec.new_name, ) @@ -153,36 +150,35 @@ def _deprecated_warn(self, obj, name, old, new): if trait_spec.new_name: self.trait_set( trait_change_notify=False, - **{"%s" % name: Undefined, "%s" % trait_spec.new_name: new} + **{"%s" % name: Undefined, "%s" % trait_spec.new_name: new}, ) def trait_get(self, **kwargs): - """ Returns traited class as a dict + """Returns traited class as a dict Augments the trait get function to return a dictionary without notification handles """ - out = super(BaseTraitedSpec, self).trait_get(**kwargs) + out = super().trait_get(**kwargs) out = self._clean_container(out, Undefined) return out get = trait_get def get_traitsfree(self, **kwargs): - """ Returns traited class as a dict + """Returns traited class as a dict Augments the trait get function to return a dictionary without any traits. The dictionary does not contain any attributes that were Undefined """ - out = super(BaseTraitedSpec, self).trait_get(**kwargs) + out = super().trait_get(**kwargs) out = self._clean_container(out, skipundefined=True) return out def _clean_container(self, objekt, undefinedval=None, skipundefined=False): - """Convert a traited obejct into a pure python representation. - """ - if isinstance(objekt, TraitDictObject) or isinstance(objekt, dict): + """Convert a traited object into a pure python representation.""" + if isinstance(objekt, (TraitDictObject, dict)): out = {} for key, val in list(objekt.items()): if isdefined(val): @@ -190,11 +186,7 @@ def _clean_container(self, objekt, undefinedval=None, skipundefined=False): else: if not skipundefined: out[key] = undefinedval - elif ( - isinstance(objekt, TraitListObject) - or isinstance(objekt, list) - or isinstance(objekt, tuple) - ): + elif isinstance(objekt, (TraitListObject, list, tuple)): out = [] for val in objekt: if isdefined(val): @@ -352,7 +344,7 @@ def __getstate__(self): [4] """ - state = super(BaseTraitedSpec, self).__getstate__() + state = super().__getstate__() for key in self.__all__: _trait_spec = self.trait(key) if _trait_spec.is_trait_type(OutputMultiObject): @@ -361,7 +353,7 @@ def __getstate__(self): class TraitedSpec(BaseTraitedSpec): - """ Create a subclass with strict traits. + """Create a subclass with strict traits. This is used in 90% of the cases. """ @@ -374,7 +366,7 @@ class BaseInterfaceInputSpec(TraitedSpec): class DynamicTraitedSpec(BaseTraitedSpec): - """ A subclass to handle dynamic traits + """A subclass to handle dynamic traits This class is a workaround for add_traits and clone_traits not functioning well together. @@ -392,7 +384,7 @@ def __deepcopy__(self, memo): dup_dict = deepcopy(self.trait_get(), memo) # access all keys for key in self.copyable_trait_names(): - if key in self.__dict__.keys(): + if key in self.__dict__: _ = getattr(self, key) # clone once dup = self.clone_traits(memo=memo) diff --git a/nipype/interfaces/base/support.py b/nipype/interfaces/base/support.py index 80835604a0..45aeed5917 100644 --- a/nipype/interfaces/base/support.py +++ b/nipype/interfaces/base/support.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -8,12 +7,17 @@ """ import os +from contextlib import AbstractContextManager from copy import deepcopy from textwrap import wrap import re +from datetime import datetime as dt +from dateutil.parser import parse as parseutc +import platform -from ... import logging -from ...utils.misc import is_container +from ... import logging, config +from ...utils.datetime import utcnow +from ...utils.misc import is_container, rgetcwd from ...utils.filemanip import md5, hash_infile iflogger = logging.getLogger("nipype.interface") @@ -21,6 +25,103 @@ HELP_LINEWIDTH = 70 +class RuntimeContext(AbstractContextManager): + """A context manager to run NiPype interfaces.""" + + __slots__ = ("_ignore_exc", "_resmon", "_runtime") + + def __init__(self, resource_monitor=False, ignore_exception=False): + """Initialize the context manager object.""" + self._ignore_exc = ignore_exception + _proc_pid = os.getpid() + if resource_monitor: + from ...utils.profiler import ResourceMonitor + else: + from ...utils.profiler import ResourceMonitorMock as ResourceMonitor + + self._resmon = ResourceMonitor( + _proc_pid, + freq=float(config.get("execution", "resource_monitor_frequency", 1)), + ) + + def __call__(self, interface, cwd=None, redirect_x=False): + """Generate a new runtime object.""" + # Tear-up: get current and prev directories + _syscwd = rgetcwd(error=False) # Recover when wd does not exist + if cwd is None: + cwd = _syscwd + + self._runtime = Bunch( + cwd=str(cwd), + duration=None, + endTime=None, + environ=deepcopy(dict(os.environ)), + hostname=platform.node(), + interface=interface.__class__.__name__, + platform=platform.platform(), + prevcwd=str(_syscwd), + redirect_x=redirect_x, + resmon=self._resmon.fname or "off", + returncode=None, + startTime=None, + version=interface.version, + ) + return self + + def __enter__(self): + """Tear-up the execution of an interface.""" + if self._runtime.redirect_x: + self._runtime.environ["DISPLAY"] = config.get_display() + + self._runtime.startTime = dt.isoformat(utcnow()) + self._resmon.start() + # TODO: Perhaps clean-up path and ensure it exists? + os.chdir(self._runtime.cwd) + return self._runtime + + def __exit__(self, exc_type, exc_value, exc_tb): + """Tear-down interface execution.""" + self._runtime.endTime = dt.isoformat(utcnow()) + timediff = parseutc(self._runtime.endTime) - parseutc(self._runtime.startTime) + self._runtime.duration = ( + timediff.days * 86400 + timediff.seconds + timediff.microseconds / 1e6 + ) + # Collect monitored data + for k, v in self._resmon.stop().items(): + setattr(self._runtime, k, v) + + os.chdir(self._runtime.prevcwd) + + if exc_type is not None or exc_value is not None or exc_tb is not None: + import traceback + + # Retrieve the maximum info fast + self._runtime.traceback = "".join( + traceback.format_exception(exc_type, exc_value, exc_tb) + ) + # Gather up the exception arguments and append nipype info. + exc_args = exc_value.args or () + exc_args += ( + f"An exception of type {exc_type.__name__} occurred while " + f"running interface {self._runtime.interface}.", + ) + self._runtime.traceback_args = ("\n".join([f"{arg}" for arg in exc_args]),) + + if self._ignore_exc: + return True + + if hasattr(self._runtime, "cmdline"): + retcode = self._runtime.returncode + if retcode not in self._runtime.success_codes: + self._runtime.traceback = ( + f"RuntimeError: subprocess exited with code {retcode}." + ) + + @property + def runtime(self): + return self._runtime + + class NipypeInterfaceError(Exception): """Custom error for interfaces""" @@ -28,10 +129,10 @@ def __init__(self, value): self.value = value def __str__(self): - return "{}".format(self.value) + return f"{self.value}" -class Bunch(object): +class Bunch: """ Dictionary-like class that provides attribute-style access to its items. @@ -75,13 +176,11 @@ def iteritems(self): return list(self.items()) def get(self, *args): - """Support dictionary get() functionality - """ + """Support dictionary get() functionality""" return self.__dict__.get(*args) def set(self, **kwargs): - """Support dictionary get() functionality - """ + """Support dictionary get() functionality""" return self.__dict__.update(**kwargs) def dictcopy(self): @@ -104,11 +203,11 @@ def __repr__(self): if isinstance(v, dict): pairs = [] for key, value in sorted(v.items()): - pairs.append("'%s': %s" % (key, value)) + pairs.append(f"'{key}': {value}") v = "{" + ", ".join(pairs) + "}" - outstr.append("%s=%s" % (k, v)) + outstr.append(f"{k}={v}") else: - outstr.append("%s=%r" % (k, v)) + outstr.append(f"{k}={v!r}") first = False outstr.append(")") return "".join(outstr) @@ -190,7 +289,7 @@ def _hash_bunch_dict(adict, key): return [(afile, hash_infile(afile)) for afile in stuff] -class InterfaceResult(object): +class InterfaceResult: """Object that contains the results of running a particular Interface. Attributes @@ -324,7 +423,7 @@ def _outputs_help(cls): def _refs_help(cls): """Prints interface references.""" - references = getattr(cls, "references_", None) + references = getattr(cls, "_references", None) if not references: return [] @@ -349,7 +448,7 @@ def get_trait_desc(inputs, name, spec): default = "" if spec.usedefault: default = ", nipype default value: %s" % str(spec.default_value()[1]) - line = "(%s%s)" % (type_info, default) + line = f"({type_info}{default})" manhelpstr = wrap( line, @@ -369,7 +468,7 @@ def get_trait_desc(inputs, name, spec): pos = spec.position if pos is not None: manhelpstr += wrap( - "argument: ``%s``, position: %s" % (argstr, pos), + f"argument: ``{argstr}``, position: {pos}", HELP_LINEWIDTH, initial_indent="\t\t", subsequent_indent="\t\t", diff --git a/nipype/interfaces/base/tests/__init__.py b/nipype/interfaces/base/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/base/tests/__init__.py +++ b/nipype/interfaces/base/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/base/tests/test_auto_CommandLine.py b/nipype/interfaces/base/tests/test_auto_CommandLine.py index b003543a3e..b03e4adfca 100644 --- a/nipype/interfaces/base/tests/test_auto_CommandLine.py +++ b/nipype/interfaces/base/tests/test_auto_CommandLine.py @@ -4,7 +4,13 @@ def test_CommandLine_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = CommandLine.input_spec() diff --git a/nipype/interfaces/base/tests/test_auto_MpiCommandLine.py b/nipype/interfaces/base/tests/test_auto_MpiCommandLine.py index 7ab181458f..908943c754 100644 --- a/nipype/interfaces/base/tests/test_auto_MpiCommandLine.py +++ b/nipype/interfaces/base/tests/test_auto_MpiCommandLine.py @@ -4,10 +4,17 @@ def test_MpiCommandLine_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), n_procs=dict(), - use_mpi=dict(usedefault=True,), + use_mpi=dict( + usedefault=True, + ), ) inputs = MpiCommandLine.input_spec() diff --git a/nipype/interfaces/base/tests/test_auto_SEMLikeCommandLine.py b/nipype/interfaces/base/tests/test_auto_SEMLikeCommandLine.py index e17eed4db1..1197b2479c 100644 --- a/nipype/interfaces/base/tests/test_auto_SEMLikeCommandLine.py +++ b/nipype/interfaces/base/tests/test_auto_SEMLikeCommandLine.py @@ -4,7 +4,13 @@ def test_SEMLikeCommandLine_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = SEMLikeCommandLine.input_spec() diff --git a/nipype/interfaces/base/tests/test_auto_StdOutCommandLine.py b/nipype/interfaces/base/tests/test_auto_StdOutCommandLine.py index bc0771ac78..39b80d487b 100644 --- a/nipype/interfaces/base/tests/test_auto_StdOutCommandLine.py +++ b/nipype/interfaces/base/tests/test_auto_StdOutCommandLine.py @@ -4,9 +4,19 @@ def test_StdOutCommandLine_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), ) inputs = StdOutCommandLine.input_spec() diff --git a/nipype/interfaces/base/tests/test_core.py b/nipype/interfaces/base/tests/test_core.py index d7e2620c9b..d86142ff3b 100644 --- a/nipype/interfaces/base/tests/test_core.py +++ b/nipype/interfaces/base/tests/test_core.py @@ -1,10 +1,11 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os import simplejson as json +import logging import pytest +from unittest import mock from .... import config from ....testing import example_data @@ -115,7 +116,7 @@ class DerivedInterface(nib.BaseInterface): input_spec = InputSpec def __init__(self, **inputs): - super(DerivedInterface, self).__init__(**inputs) + super().__init__(**inputs) inputs_dict = {"input1": 12, "input3": True, "input4": "some string"} bif = DerivedInterface(**inputs_dict) @@ -155,7 +156,7 @@ def __init__(self, **inputs): assert {} == check_dict(data_dict, tsthash2.inputs.get_traitsfree()) _, hashvalue = tsthash.inputs.get_hashval(hash_method="timestamp") - assert "8562a5623562a871115eb14822ee8d02" == hashvalue + assert hashvalue == "e35bf07fea8049cc02de9235f85e8903" class MinVerInputSpec(nib.TraitedSpec): @@ -235,6 +236,83 @@ class DerivedInterface1(nib.BaseInterface): obj._check_version_requirements(obj.inputs) +def test_input_version_missing(caplog): + class DerivedInterface(nib.BaseInterface): + class input_spec(nib.TraitedSpec): + foo = nib.traits.Int(min_ver="0.9") + bar = nib.traits.Int(max_ver="0.9") + + _version = "misparsed-garbage" + + obj = DerivedInterface() + obj.inputs.foo = 1 + obj.inputs.bar = 1 + with caplog.at_level(logging.WARNING, logger="nipype.interface"): + obj._check_version_requirements(obj.inputs) + assert len(caplog.records) == 2 + + +def test_input_version_missing_error(caplog): + from nipype import config + + class DerivedInterface(nib.BaseInterface): + class input_spec(nib.TraitedSpec): + foo = nib.traits.Int(min_ver="0.9") + bar = nib.traits.Int(max_ver="0.9") + + _version = "misparsed-garbage" + + obj1 = DerivedInterface(foo=1) + obj2 = DerivedInterface(bar=1) + with caplog.at_level(logging.WARNING, logger="nipype.interface"): + with mock.patch.object(config, "getboolean", return_value=True): + with pytest.raises(ValueError): + obj1._check_version_requirements(obj1.inputs) + with pytest.raises(ValueError): + obj2._check_version_requirements(obj2.inputs) + assert len(caplog.records) == 2 + + +def test_unavailable_input(): + class WithInput(nib.BaseInterface): + class input_spec(nib.TraitedSpec): + foo = nib.traits.Int(3, usedefault=True, max_ver="0.5") + + _version = "0.4" + + def _run_interface(self, runtime): + return runtime + + class WithoutInput(WithInput): + _version = "0.6" + + has = WithInput() + hasnot = WithoutInput() + trying_anyway = WithoutInput(foo=3) + assert has.inputs.foo == 3 + assert not nib.isdefined(hasnot.inputs.foo) + assert trying_anyway.inputs.foo == 3 + + has.run() + hasnot.run() + with pytest.raises(Exception): + trying_anyway.run() + + # Still settable + has.inputs.foo = 4 + hasnot.inputs.foo = 4 + trying_anyway.inputs.foo = 4 + assert has.inputs.foo == 4 + assert hasnot.inputs.foo == 4 + assert trying_anyway.inputs.foo == 4 + + has.run() + with pytest.raises(Exception): + hasnot.run() + with pytest.raises(Exception): + trying_anyway.run() + + def test_output_version(): class InputSpec(nib.TraitedSpec): foo = nib.traits.Int(desc="a random int") @@ -456,17 +534,18 @@ def test_global_CommandLine_output(tmpdir): ci = BET() assert ci.terminal_output == "stream" # default case - nib.CommandLine.set_default_terminal_output("allatonce") - ci = nib.CommandLine(command="ls -l") - assert ci.terminal_output == "allatonce" + with mock.patch.object(nib.CommandLine, "_terminal_output"): + nib.CommandLine.set_default_terminal_output("allatonce") + ci = nib.CommandLine(command="ls -l") + assert ci.terminal_output == "allatonce" - nib.CommandLine.set_default_terminal_output("file") - ci = nib.CommandLine(command="ls -l") - assert ci.terminal_output == "file" + nib.CommandLine.set_default_terminal_output("file") + ci = nib.CommandLine(command="ls -l") + assert ci.terminal_output == "file" - # Check default affects derived interfaces - ci = BET() - assert ci.terminal_output == "file" + # Check default affects derived interfaces + ci = BET() + assert ci.terminal_output == "file" def test_CommandLine_prefix(tmpdir): @@ -491,13 +570,13 @@ class OOPCLI(nib.CommandLine): ci.run() class OOPShell(nib.CommandLine): - _cmd_prefix = "bash {}/".format(oop) + _cmd_prefix = f"bash {oop}/" ci = OOPShell(command=script_name) ci.run() class OOPBadShell(nib.CommandLine): - _cmd_prefix = "shell_dne {}/".format(oop) + _cmd_prefix = f"shell_dne {oop}/" ci = OOPBadShell(command=script_name) with pytest.raises(IOError): diff --git a/nipype/interfaces/base/tests/test_resource_monitor.py b/nipype/interfaces/base/tests/test_resource_monitor.py index 47a515f64c..802e8e6ec9 100644 --- a/nipype/interfaces/base/tests/test_resource_monitor.py +++ b/nipype/interfaces/base/tests/test_resource_monitor.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -79,7 +78,7 @@ def test_cmdline_profiling(tmpdir, mem_gb, n_procs, use_resource_monitor): @pytest.mark.skipif( - True, reason="test disabled temporarily, until funcion profiling works" + True, reason="test disabled temporarily, until function profiling works" ) @pytest.mark.parametrize("mem_gb,n_procs", [(0.5, 3), (2.2, 8), (0.8, 4), (1.5, 1)]) def test_function_profiling(tmpdir, mem_gb, n_procs, use_resource_monitor): diff --git a/nipype/interfaces/base/tests/test_specs.py b/nipype/interfaces/base/tests/test_specs.py index d94f97ed1b..44a9c014c4 100644 --- a/nipype/interfaces/base/tests/test_specs.py +++ b/nipype/interfaces/base/tests/test_specs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -183,7 +182,7 @@ class DeprecationSpec3(nib.TraitedSpec): except nib.TraitError: not_raised = False assert not_raised - assert len(w) == 1, "deprecated warning 1 %s" % [w1.message for w1 in w] + assert len(w) == 1, f"deprecated warning 1 {[str(w1) for w1 in w]}" with warnings.catch_warnings(record=True) as w: warnings.filterwarnings("always", "", UserWarning) @@ -201,7 +200,7 @@ class DeprecationSpec3(nib.TraitedSpec): assert not_raised assert spec_instance.foo == Undefined assert spec_instance.bar == 1 - assert len(w) == 1, "deprecated warning 2 %s" % [w1.message for w1 in w] + assert len(w) == 1, f"deprecated warning 2 {[str(w1) for w1 in w]}" def test_namesource(setup_file): diff --git a/nipype/interfaces/base/tests/test_support.py b/nipype/interfaces/base/tests/test_support.py index 878794b04f..406e6e9358 100644 --- a/nipype/interfaces/base/tests/test_support.py +++ b/nipype/interfaces/base/tests/test_support.py @@ -1,10 +1,9 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os import pytest -from pkg_resources import resource_filename as pkgrf +import acres from ....utils.filemanip import md5 from ... import base as nib @@ -36,21 +35,20 @@ def test_bunch_methods(): assert b.get("a") == 3 assert b.get("badkey", "otherthing") == "otherthing" assert b != newb - assert type(dict()) == type(newb) + assert type(newb) is dict assert newb["a"] == 3 def test_bunch_hash(): # NOTE: Since the path to the json file is included in the Bunch, # the hash will be unique to each machine. - json_pth = pkgrf("nipype", os.path.join("testing", "data", "realign_json.json")) + json_pth = acres.Loader('nipype.testing').cached('data', 'realign_json.json') - b = nib.Bunch(infile=json_pth, otherthing="blue", yat=True) + b = nib.Bunch(infile=str(json_pth), otherthing="blue", yat=True) newbdict, bhash = b._get_bunch_hash() assert bhash == "d1f46750044c3de102efc847720fc35f" # Make sure the hash stored in the json file for `infile` is correct. jshash = md5() - with open(json_pth, "r") as fp: - jshash.update(fp.read().encode("utf-8")) + jshash.update(json_pth.read_bytes()) assert newbdict["infile"][0][1] == jshash.hexdigest() assert newbdict["yat"] is True diff --git a/nipype/interfaces/base/tests/test_traits_extension.py b/nipype/interfaces/base/tests/test_traits_extension.py index ec0574ad9c..91682f459e 100644 --- a/nipype/interfaces/base/tests/test_traits_extension.py +++ b/nipype/interfaces/base/tests/test_traits_extension.py @@ -7,7 +7,7 @@ class _test_spec(nib.TraitedSpec): a = nib.File() - b = nib.traits.Tuple(nib.File(), nib.File()) + b = nib.Tuple(nib.File(), nib.File()) c = nib.traits.List(nib.File()) d = nib.traits.Either(nib.File(), nib.traits.Float()) e = nib.OutputMultiObject(nib.File()) @@ -15,10 +15,10 @@ class _test_spec(nib.TraitedSpec): f = nib.traits.Dict(nib.Str, nib.File()) g = nib.traits.Either(nib.File, nib.Str) h = nib.Str - i = nib.traits.Either(nib.File, nib.traits.Tuple(nib.File, nib.traits.Int)) + i = nib.traits.Either(nib.File, nib.Tuple(nib.File, nib.traits.Int)) j = nib.traits.Either( nib.File, - nib.traits.Tuple(nib.File, nib.traits.Int), + nib.Tuple(nib.File, nib.traits.Int), nib.traits.Dict(nib.Str, nib.File()), ) k = nib.DictStrStr diff --git a/nipype/interfaces/base/traits_extension.py b/nipype/interfaces/base/traits_extension.py index cbfe24e676..49ba234ba8 100644 --- a/nipype/interfaces/base/traits_extension.py +++ b/nipype/interfaces/base/traits_extension.py @@ -19,13 +19,14 @@ (usually by Robert Kern). """ -from collections import Sequence +from collections.abc import Sequence # perform all external trait imports here from traits import __version__ as traits_version import traits.api as traits from traits.api import TraitType, Unicode from traits.trait_base import _Undefined + try: # Moved in traits 6.0 from traits.trait_type import NoDefaultSpecified @@ -49,7 +50,7 @@ "nifti2": (".nii", ".nii.gz"), "nrrd": (".nrrd", ".nhdr"), } -IMG_ZIP_FMT = set([".nii.gz", "tar.gz", ".gii.gz", ".mgz", ".mgh.gz", "img.gz"]) +IMG_ZIP_FMT = {".nii.gz", "tar.gz", ".gii.gz", ".mgz", ".mgh.gz", "img.gz"} """ The functions that pop-up the Traits GUIs, edit_traits and @@ -57,7 +58,7 @@ Undefined deep and down in traits/ui/wx/list_editor.py it checks for the len() of the elements of the list. The _Undefined class in traits does not define the __len__ method and would error. I tried defining -our own Undefined and even sublassing Undefined, but both of those +our own Undefined and even subclassing Undefined, but both of those failed with a TraitError in our initializer when we assign the Undefined to the inputs because of an incompatible type: @@ -120,7 +121,7 @@ def __init__(self, value=Undefined, exists=False, resolve=False, **metadata): """Create a BasePath trait.""" self.exists = exists self.resolve = resolve - super(BasePath, self).__init__(value, **metadata) + super().__init__(value, **metadata) def validate(self, objekt, name, value, return_pathlike=False): """Validate a value change.""" @@ -297,7 +298,7 @@ def __init__( resolve=False, allow_compressed=True, extensions=None, - **metadata + **metadata, ): """Create a File trait.""" if extensions is not None: @@ -308,28 +309,23 @@ def __init__( extensions = list(set(extensions) - IMG_ZIP_FMT) self._exts = sorted( - set( - [ - ".%s" % ext if not ext.startswith(".") else ext - for ext in extensions - ] - ) + {f".{ext}" if not ext.startswith(".") else ext for ext in extensions} ) - super(File, self).__init__( + super().__init__( value=value, exists=exists, resolve=resolve, extensions=self._exts, - **metadata + **metadata, ) def validate(self, objekt, name, value, return_pathlike=False): """Validate a value change.""" - value = super(File, self).validate(objekt, name, value, return_pathlike=True) + value = super().validate(objekt, name, value, return_pathlike=True) if self._exts: fname = value.name - if not any((fname.endswith(e) for e in self._exts)): + if not any(fname.endswith(e) for e in self._exts): self.error(objekt, name, str(value)) if not return_pathlike: @@ -347,7 +343,7 @@ def __init__( exists=False, resolve=False, types=None, - **metadata + **metadata, ): """Create an ImageFile trait.""" extensions = None @@ -365,15 +361,23 @@ def __init__( ) extensions = [ext for t in types for ext in IMG_FORMATS[t]] - super(ImageFile, self).__init__( + super().__init__( value=value, exists=exists, extensions=extensions, resolve=resolve, - **metadata + **metadata, ) +class Tuple(traits.BaseTuple): + def validate(self, objekt, name, value): + if isinstance(value, list): + value = tuple(value) + + return super().validate(objekt, name, value) + + def isdefined(objekt): return not isinstance(objekt, _Undefined) @@ -401,11 +405,9 @@ def has_metadata(trait, metadata, value=None, recursive=True): class MultiObject(traits.List): - """ Abstract class - shared functionality of input and output MultiObject - """ + """Abstract class - shared functionality of input and output MultiObject""" def validate(self, objekt, name, value): - # want to treat range and other sequences (except str) as list if not isinstance(value, (str, bytes)) and isinstance(value, Sequence): value = list(value) @@ -422,7 +424,7 @@ def validate(self, objekt, name, value): and not isinstance(value[0], list) ): newvalue = [value] - value = super(MultiObject, self).validate(objekt, name, newvalue) + value = super().validate(objekt, name, newvalue) if value: return value @@ -431,7 +433,7 @@ def validate(self, objekt, name, value): class OutputMultiObject(MultiObject): - """ Implements a user friendly traits that accepts one or more + """Implements a user friendly traits that accepts one or more paths to files or directories. This is the output version which return a single string whenever possible (when it was set to a single value or a list of length 1). Default value of this trait @@ -477,7 +479,7 @@ def set(self, objekt, name, value): class InputMultiObject(MultiObject): - """ Implements a user friendly traits that accepts one or more + """Implements a user friendly traits that accepts one or more paths to files or directories. This is the input version which always returns a list. Default value of this trait is _Undefined. It does not accept empty lists. @@ -561,12 +563,10 @@ def _recurse_on_path_traits(func, thistrait, value, cwd): k: _recurse_on_path_traits(func, innertrait, v, cwd) for k, v in value.items() } - elif isinstance(value, tuple) and thistrait.is_trait_type(traits.Tuple): + elif isinstance(value, tuple) and thistrait.is_trait_type(traits.BaseTuple): value = tuple( - [ - _recurse_on_path_traits(func, subtrait, v, cwd) - for subtrait, v in zip(thistrait.handler.types, value) - ] + _recurse_on_path_traits(func, subtrait, v, cwd) + for subtrait, v in zip(thistrait.handler.types, value) ) elif thistrait.is_trait_type(traits.TraitCompound): is_str = [ diff --git a/nipype/interfaces/brainsuite/__init__.py b/nipype/interfaces/brainsuite/__init__.py index 45bcf5fc65..5fb27d6ae1 100644 --- a/nipype/interfaces/brainsuite/__init__.py +++ b/nipype/interfaces/brainsuite/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .brainsuite import ( Bse, Bfc, diff --git a/nipype/interfaces/brainsuite/brainsuite.py b/nipype/interfaces/brainsuite/brainsuite.py index 84177a16ad..cf7161c030 100644 --- a/nipype/interfaces/brainsuite/brainsuite.py +++ b/nipype/interfaces/brainsuite/brainsuite.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """This script provides interfaces for BrainSuite command line tools. Please see brainsuite.org for more information. @@ -19,7 +18,6 @@ class BseInputSpec(CommandLineInputSpec): - inputMRIFile = File(mandatory=True, argstr="-i %s", desc="input MRI volume") outputMRIVolume = File( desc="output brain-masked MRI volume. If unspecified, output file name will be auto generated.", @@ -270,7 +268,7 @@ def _format_arg(self, name, spec, value): }[value] ) - return super(Bfc, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): return l_outputs(self) @@ -778,12 +776,12 @@ def _format_arg(self, name, spec, value): return ( spec.argstr % { - "greater_than": "".join(("-gt %f" % threshold)), - "less_than": "".join(("-lt %f" % threshold)), - "equal_to": "".join(("-eq %f" % threshold)), + "greater_than": "".join("-gt %f" % threshold), + "less_than": "".join("-lt %f" % threshold), + "equal_to": "".join("-eq %f" % threshold), }[value] ) - return super(Dfs, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_filename(self, name): inputs = self.inputs.get() @@ -1207,7 +1205,7 @@ def _format_arg(self, name, spec, value): return spec.argstr % os.path.expanduser(value) if name == "dataSinkDelay": return spec.argstr % "" - return super(SVReg, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class BDPInputSpec(CommandLineInputSpec): @@ -1492,7 +1490,7 @@ class BDPInputSpec(CommandLineInputSpec): ) ignoreFieldmapFOV = traits.Bool( argstr="--ignore-fieldmap-fov", - desc="Supresses the error generated by an insufficient field of view of the " + desc="Suppresses the error generated by an insufficient field of view of the " "input fieldmap and continues with the processing. It is useful only when " "used with fieldmap-based distortion correction. See " "fieldmap-correction for a detailed explanation. ", @@ -1677,7 +1675,7 @@ class BDPInputSpec(CommandLineInputSpec): desc="Enables estimation of diffusion tensors and/or ODFs (and statistics if " "applicable) in the native diffusion coordinate in addition to the " "default T1-coordinate. All native diffusion coordinate files are saved " - 'in a seperate folder named "diffusion_coord_outputs". In case statistics ' + 'in a separate folder named "diffusion_coord_outputs". In case statistics ' "computation is required, it will also transform/save all label/mask " "files required to diffusion coordinate (see generateStats for " "details). ", @@ -1757,7 +1755,7 @@ def _format_arg(self, name, spec, value): return spec.argstr % (value[0], value[1]) if name == "dataSinkDelay": return spec.argstr % "" - return super(BDP, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class ThicknessPVCInputSpec(CommandLineInputSpec): @@ -1803,7 +1801,7 @@ def getFileName(inputName, suffix): dotRegex = regex.compile("[^.]+") # extract between last slash and first period inputNoExtension = dotRegex.findall(fullInput)[0] - return os.path.abspath("".join((inputNoExtension, suffix))) + return os.path.abspath(f"{inputNoExtension}{suffix}") def l_outputs(self): diff --git a/nipype/interfaces/brainsuite/tests/__init__.py b/nipype/interfaces/brainsuite/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/brainsuite/tests/__init__.py +++ b/nipype/interfaces/brainsuite/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/brainsuite/tests/test_auto_BDP.py b/nipype/interfaces/brainsuite/tests/test_auto_BDP.py index 94f95c5c2a..0da29c372d 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_BDP.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_BDP.py @@ -10,7 +10,9 @@ def test_BDP_inputs(): position=-1, xor=["bMatrixFile"], ), - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), bMatrixFile=dict( argstr="--bmat %s", extensions=None, @@ -18,7 +20,9 @@ def test_BDP_inputs(): position=-1, xor=["BVecBValPair"], ), - bValRatioThreshold=dict(argstr="--bval-ratio-threshold %f",), + bValRatioThreshold=dict( + argstr="--bval-ratio-threshold %f", + ), bfcFile=dict( argstr="%s", extensions=None, @@ -27,68 +31,152 @@ def test_BDP_inputs(): xor=["noStructuralRegistration"], ), customDiffusionLabel=dict( - argstr="--custom-diffusion-label %s", extensions=None, - ), - customLabelXML=dict(argstr="--custom-label-xml %s", extensions=None,), - customT1Label=dict(argstr="--custom-t1-label %s", extensions=None,), - dataSinkDelay=dict(argstr="%s",), - dcorrRegMeasure=dict(argstr="--dcorr-reg-method %s",), - dcorrWeight=dict(argstr="--dcorr-regularization-wt %f",), - dwiMask=dict(argstr="--dwi-mask %s", extensions=None,), - echoSpacing=dict(argstr="--echo-spacing=%f",), - environ=dict(nohash=True, usedefault=True,), - estimateODF_3DShore=dict(argstr="--3dshore --diffusion_time_ms %f",), - estimateODF_FRACT=dict(argstr="--FRACT",), - estimateODF_FRT=dict(argstr="--FRT",), - estimateTensors=dict(argstr="--tensors",), + argstr="--custom-diffusion-label %s", + extensions=None, + ), + customLabelXML=dict( + argstr="--custom-label-xml %s", + extensions=None, + ), + customT1Label=dict( + argstr="--custom-t1-label %s", + extensions=None, + ), + dataSinkDelay=dict( + argstr="%s", + ), + dcorrRegMeasure=dict( + argstr="--dcorr-reg-method %s", + ), + dcorrWeight=dict( + argstr="--dcorr-regularization-wt %f", + ), + dwiMask=dict( + argstr="--dwi-mask %s", + extensions=None, + ), + echoSpacing=dict( + argstr="--echo-spacing=%f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + estimateODF_3DShore=dict( + argstr="--3dshore --diffusion_time_ms %f", + ), + estimateODF_FRACT=dict( + argstr="--FRACT", + ), + estimateODF_FRT=dict( + argstr="--FRT", + ), + estimateTensors=dict( + argstr="--tensors", + ), fieldmapCorrection=dict( argstr="--fieldmap-correction %s", extensions=None, requires=["echoSpacing"], ), fieldmapCorrectionMethod=dict( - argstr="--fieldmap-correction-method %s", xor=["skipIntensityCorr"], - ), - fieldmapSmooth=dict(argstr="--fieldmap-smooth3=%f",), - flagConfigFile=dict(argstr="--flag-conf-file %s", extensions=None,), - forcePartialROIStats=dict(argstr="--force-partial-roi-stats",), - generateStats=dict(argstr="--generate-stats",), - ignoreFieldmapFOV=dict(argstr="--ignore-fieldmap-fov",), - ignoreMemory=dict(argstr="--ignore-memory",), + argstr="--fieldmap-correction-method %s", + xor=["skipIntensityCorr"], + ), + fieldmapSmooth=dict( + argstr="--fieldmap-smooth3=%f", + ), + flagConfigFile=dict( + argstr="--flag-conf-file %s", + extensions=None, + ), + forcePartialROIStats=dict( + argstr="--force-partial-roi-stats", + ), + generateStats=dict( + argstr="--generate-stats", + ), + ignoreFieldmapFOV=dict( + argstr="--ignore-fieldmap-fov", + ), + ignoreMemory=dict( + argstr="--ignore-memory", + ), inputDiffusionData=dict( - argstr="--nii %s", extensions=None, mandatory=True, position=-2, + argstr="--nii %s", + extensions=None, + mandatory=True, + position=-2, + ), + lowMemory=dict( + argstr="--low-memory", ), - lowMemory=dict(argstr="--low-memory",), noStructuralRegistration=dict( argstr="--no-structural-registration", mandatory=True, position=0, xor=["bfcFile"], ), - odfLambta=dict(argstr="--odf-lambda ",), - onlyStats=dict(argstr="--generate-only-stats",), - outPrefix=dict(argstr="--output-fileprefix %s",), - outputDiffusionCoordinates=dict(argstr="--output-diffusion-coordinate",), - outputSubdir=dict(argstr="--output-subdir %s",), - phaseEncodingDirection=dict(argstr="--dir=%s",), - rigidRegMeasure=dict(argstr="--rigid-reg-measure %s",), - skipDistortionCorr=dict(argstr="--no-distortion-correction",), + odfLambta=dict( + argstr="--odf-lambda ", + ), + onlyStats=dict( + argstr="--generate-only-stats", + ), + outPrefix=dict( + argstr="--output-fileprefix %s", + ), + outputDiffusionCoordinates=dict( + argstr="--output-diffusion-coordinate", + ), + outputSubdir=dict( + argstr="--output-subdir %s", + ), + phaseEncodingDirection=dict( + argstr="--dir=%s", + ), + rigidRegMeasure=dict( + argstr="--rigid-reg-measure %s", + ), + skipDistortionCorr=dict( + argstr="--no-distortion-correction", + ), skipIntensityCorr=dict( - argstr="--no-intensity-correction", xor=["fieldmapCorrectionMethod"], + argstr="--no-intensity-correction", + xor=["fieldmapCorrectionMethod"], + ), + skipNonuniformityCorr=dict( + argstr="--no-nonuniformity-correction", + ), + t1Mask=dict( + argstr="--t1-mask %s", + extensions=None, + ), + threads=dict( + argstr="--threads=%d", + ), + transformDataOnly=dict( + argstr="--transform-data-only", ), - skipNonuniformityCorr=dict(argstr="--no-nonuniformity-correction",), - t1Mask=dict(argstr="--t1-mask %s", extensions=None,), - threads=dict(argstr="--threads=%d",), - transformDataOnly=dict(argstr="--transform-data-only",), transformDiffusionSurface=dict( - argstr="--transform-diffusion-surface %s", extensions=None, + argstr="--transform-diffusion-surface %s", + extensions=None, ), transformDiffusionVolume=dict( - argstr="--transform-diffusion-volume %s", extensions=None, + argstr="--transform-diffusion-volume %s", + extensions=None, + ), + transformInterpolation=dict( + argstr="--transform-interpolation %s", + ), + transformT1Surface=dict( + argstr="--transform-t1-surface %s", + extensions=None, + ), + transformT1Volume=dict( + argstr="--transform-t1-volume %s", + extensions=None, ), - transformInterpolation=dict(argstr="--transform-interpolation %s",), - transformT1Surface=dict(argstr="--transform-t1-surface %s", extensions=None,), - transformT1Volume=dict(argstr="--transform-t1-volume %s", extensions=None,), ) inputs = BDP.input_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Bfc.py b/nipype/interfaces/brainsuite/tests/test_auto_Bfc.py index 5e2588fd74..dbb1f3d839 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Bfc.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Bfc.py @@ -4,35 +4,96 @@ def test_Bfc_inputs(): input_map = dict( - args=dict(argstr="%s",), - biasEstimateConvergenceThreshold=dict(argstr="--beps %f",), - biasEstimateSpacing=dict(argstr="-s %d",), - biasFieldEstimatesOutputPrefix=dict(argstr="--biasprefix %s",), - biasRange=dict(argstr="%s",), - controlPointSpacing=dict(argstr="-c %d",), - convergenceThreshold=dict(argstr="--eps %f",), - correctWholeVolume=dict(argstr="--extrapolate",), - correctedImagesOutputPrefix=dict(argstr="--prefix %s",), - correctionScheduleFile=dict(argstr="--schedule %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - histogramRadius=dict(argstr="-r %d",), - histogramType=dict(argstr="%s",), - inputMRIFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - inputMaskFile=dict(argstr="-m %s", extensions=None, hash_files=False,), - intermediate_file_type=dict(argstr="%s",), - iterativeMode=dict(argstr="--iterate",), - maxBias=dict(argstr="-U %f", usedefault=True,), - minBias=dict(argstr="-L %f", usedefault=True,), - outputBiasField=dict(argstr="--bias %s", extensions=None, hash_files=False,), + args=dict( + argstr="%s", + ), + biasEstimateConvergenceThreshold=dict( + argstr="--beps %f", + ), + biasEstimateSpacing=dict( + argstr="-s %d", + ), + biasFieldEstimatesOutputPrefix=dict( + argstr="--biasprefix %s", + ), + biasRange=dict( + argstr="%s", + ), + controlPointSpacing=dict( + argstr="-c %d", + ), + convergenceThreshold=dict( + argstr="--eps %f", + ), + correctWholeVolume=dict( + argstr="--extrapolate", + ), + correctedImagesOutputPrefix=dict( + argstr="--prefix %s", + ), + correctionScheduleFile=dict( + argstr="--schedule %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + histogramRadius=dict( + argstr="-r %d", + ), + histogramType=dict( + argstr="%s", + ), + inputMRIFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + inputMaskFile=dict( + argstr="-m %s", + extensions=None, + hash_files=False, + ), + intermediate_file_type=dict( + argstr="%s", + ), + iterativeMode=dict( + argstr="--iterate", + ), + maxBias=dict( + argstr="-U %f", + usedefault=True, + ), + minBias=dict( + argstr="-L %f", + usedefault=True, + ), + outputBiasField=dict( + argstr="--bias %s", + extensions=None, + hash_files=False, + ), outputMRIVolume=dict( - argstr="-o %s", extensions=None, genfile=True, hash_files=False, + argstr="-o %s", + extensions=None, + genfile=True, + hash_files=False, ), outputMaskedBiasField=dict( - argstr="--maskedbias %s", extensions=None, hash_files=False, + argstr="--maskedbias %s", + extensions=None, + hash_files=False, + ), + splineLambda=dict( + argstr="-w %f", + ), + timer=dict( + argstr="--timer", + ), + verbosityLevel=dict( + argstr="-v %d", ), - splineLambda=dict(argstr="-w %f",), - timer=dict(argstr="--timer",), - verbosityLevel=dict(argstr="-v %d",), ) inputs = Bfc.input_spec() @@ -43,10 +104,18 @@ def test_Bfc_inputs(): def test_Bfc_outputs(): output_map = dict( - correctionScheduleFile=dict(extensions=None,), - outputBiasField=dict(extensions=None,), - outputMRIVolume=dict(extensions=None,), - outputMaskedBiasField=dict(extensions=None,), + correctionScheduleFile=dict( + extensions=None, + ), + outputBiasField=dict( + extensions=None, + ), + outputMRIVolume=dict( + extensions=None, + ), + outputMaskedBiasField=dict( + extensions=None, + ), ) outputs = Bfc.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Bse.py b/nipype/interfaces/brainsuite/tests/test_auto_Bse.py index a980010ef0..748defcc00 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Bse.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Bse.py @@ -4,32 +4,84 @@ def test_Bse_inputs(): input_map = dict( - args=dict(argstr="%s",), - diffusionConstant=dict(argstr="-d %f", usedefault=True,), - diffusionIterations=dict(argstr="-n %d", usedefault=True,), - dilateFinalMask=dict(argstr="-p", usedefault=True,), - edgeDetectionConstant=dict(argstr="-s %f", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - inputMRIFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - noRotate=dict(argstr="--norotate",), - outputCortexFile=dict(argstr="--cortex %s", extensions=None, hash_files=False,), + args=dict( + argstr="%s", + ), + diffusionConstant=dict( + argstr="-d %f", + usedefault=True, + ), + diffusionIterations=dict( + argstr="-n %d", + usedefault=True, + ), + dilateFinalMask=dict( + argstr="-p", + usedefault=True, + ), + edgeDetectionConstant=dict( + argstr="-s %f", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMRIFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + noRotate=dict( + argstr="--norotate", + ), + outputCortexFile=dict( + argstr="--cortex %s", + extensions=None, + hash_files=False, + ), outputDetailedBrainMask=dict( - argstr="--hires %s", extensions=None, hash_files=False, + argstr="--hires %s", + extensions=None, + hash_files=False, ), outputDiffusionFilter=dict( - argstr="--adf %s", extensions=None, hash_files=False, + argstr="--adf %s", + extensions=None, + hash_files=False, + ), + outputEdgeMap=dict( + argstr="--edge %s", + extensions=None, + hash_files=False, ), - outputEdgeMap=dict(argstr="--edge %s", extensions=None, hash_files=False,), outputMRIVolume=dict( - argstr="-o %s", extensions=None, genfile=True, hash_files=False, + argstr="-o %s", + extensions=None, + genfile=True, + hash_files=False, ), outputMaskFile=dict( - argstr="--mask %s", extensions=None, genfile=True, hash_files=False, + argstr="--mask %s", + extensions=None, + genfile=True, + hash_files=False, + ), + radius=dict( + argstr="-r %f", + usedefault=True, + ), + timer=dict( + argstr="--timer", + ), + trim=dict( + argstr="--trim", + usedefault=True, + ), + verbosityLevel=dict( + argstr="-v %f", + usedefault=True, ), - radius=dict(argstr="-r %f", usedefault=True,), - timer=dict(argstr="--timer",), - trim=dict(argstr="--trim", usedefault=True,), - verbosityLevel=dict(argstr="-v %f", usedefault=True,), ) inputs = Bse.input_spec() @@ -40,12 +92,24 @@ def test_Bse_inputs(): def test_Bse_outputs(): output_map = dict( - outputCortexFile=dict(extensions=None,), - outputDetailedBrainMask=dict(extensions=None,), - outputDiffusionFilter=dict(extensions=None,), - outputEdgeMap=dict(extensions=None,), - outputMRIVolume=dict(extensions=None,), - outputMaskFile=dict(extensions=None,), + outputCortexFile=dict( + extensions=None, + ), + outputDetailedBrainMask=dict( + extensions=None, + ), + outputDiffusionFilter=dict( + extensions=None, + ), + outputEdgeMap=dict( + extensions=None, + ), + outputMRIVolume=dict( + extensions=None, + ), + outputMaskFile=dict( + extensions=None, + ), ) outputs = Bse.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Cerebro.py b/nipype/interfaces/brainsuite/tests/test_auto_Cerebro.py index e2ff64c071..a924d7ce0f 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Cerebro.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Cerebro.py @@ -4,31 +4,80 @@ def test_Cerebro_inputs(): input_map = dict( - args=dict(argstr="%s",), - costFunction=dict(argstr="-c %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + costFunction=dict( + argstr="-c %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputAtlasLabelFile=dict( - argstr="--atlaslabels %s", extensions=None, mandatory=True, + argstr="--atlaslabels %s", + extensions=None, + mandatory=True, + ), + inputAtlasMRIFile=dict( + argstr="--atlas %s", + extensions=None, + mandatory=True, + ), + inputBrainMaskFile=dict( + argstr="-m %s", + extensions=None, + ), + inputMRIFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + keepTempFiles=dict( + argstr="--keep", + ), + linearConvergence=dict( + argstr="--linconv %f", ), - inputAtlasMRIFile=dict(argstr="--atlas %s", extensions=None, mandatory=True,), - inputBrainMaskFile=dict(argstr="-m %s", extensions=None,), - inputMRIFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - keepTempFiles=dict(argstr="--keep",), - linearConvergence=dict(argstr="--linconv %f",), outputAffineTransformFile=dict( - argstr="--air %s", extensions=None, genfile=True, + argstr="--air %s", + extensions=None, + genfile=True, + ), + outputCerebrumMaskFile=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + outputLabelVolumeFile=dict( + argstr="-l %s", + extensions=None, + genfile=True, ), - outputCerebrumMaskFile=dict(argstr="-o %s", extensions=None, genfile=True,), - outputLabelVolumeFile=dict(argstr="-l %s", extensions=None, genfile=True,), outputWarpTransformFile=dict( - argstr="--warp %s", extensions=None, genfile=True, - ), - tempDirectory=dict(argstr="--tempdir %s",), - tempDirectoryBase=dict(argstr="--tempdirbase %s",), - useCentroids=dict(argstr="--centroids",), - verbosity=dict(argstr="-v %d",), - warpConvergence=dict(argstr="--warpconv %f",), - warpLabel=dict(argstr="--warplevel %d",), + argstr="--warp %s", + extensions=None, + genfile=True, + ), + tempDirectory=dict( + argstr="--tempdir %s", + ), + tempDirectoryBase=dict( + argstr="--tempdirbase %s", + ), + useCentroids=dict( + argstr="--centroids", + ), + verbosity=dict( + argstr="-v %d", + ), + warpConvergence=dict( + argstr="--warpconv %f", + ), + warpLabel=dict( + argstr="--warplevel %d", + ), ) inputs = Cerebro.input_spec() @@ -39,10 +88,18 @@ def test_Cerebro_inputs(): def test_Cerebro_outputs(): output_map = dict( - outputAffineTransformFile=dict(extensions=None,), - outputCerebrumMaskFile=dict(extensions=None,), - outputLabelVolumeFile=dict(extensions=None,), - outputWarpTransformFile=dict(extensions=None,), + outputAffineTransformFile=dict( + extensions=None, + ), + outputCerebrumMaskFile=dict( + extensions=None, + ), + outputLabelVolumeFile=dict( + extensions=None, + ), + outputWarpTransformFile=dict( + extensions=None, + ), ) outputs = Cerebro.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Cortex.py b/nipype/interfaces/brainsuite/tests/test_auto_Cortex.py index 75015d79ab..30287edf90 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Cortex.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Cortex.py @@ -4,17 +4,49 @@ def test_Cortex_inputs(): input_map = dict( - args=dict(argstr="%s",), - computeGCBoundary=dict(argstr="-g",), - computeWGBoundary=dict(argstr="-w", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - includeAllSubcorticalAreas=dict(argstr="-a", usedefault=True,), - inputHemisphereLabelFile=dict(argstr="-h %s", extensions=None, mandatory=True,), - inputTissueFractionFile=dict(argstr="-f %s", extensions=None, mandatory=True,), - outputCerebrumMask=dict(argstr="-o %s", extensions=None, genfile=True,), - timer=dict(argstr="--timer",), - tissueFractionThreshold=dict(argstr="-p %f", usedefault=True,), - verbosity=dict(argstr="-v %d",), + args=dict( + argstr="%s", + ), + computeGCBoundary=dict( + argstr="-g", + ), + computeWGBoundary=dict( + argstr="-w", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + includeAllSubcorticalAreas=dict( + argstr="-a", + usedefault=True, + ), + inputHemisphereLabelFile=dict( + argstr="-h %s", + extensions=None, + mandatory=True, + ), + inputTissueFractionFile=dict( + argstr="-f %s", + extensions=None, + mandatory=True, + ), + outputCerebrumMask=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + timer=dict( + argstr="--timer", + ), + tissueFractionThreshold=dict( + argstr="-p %f", + usedefault=True, + ), + verbosity=dict( + argstr="-v %d", + ), ) inputs = Cortex.input_spec() @@ -24,7 +56,11 @@ def test_Cortex_inputs(): def test_Cortex_outputs(): - output_map = dict(outputCerebrumMask=dict(extensions=None,),) + output_map = dict( + outputCerebrumMask=dict( + extensions=None, + ), + ) outputs = Cortex.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Dewisp.py b/nipype/interfaces/brainsuite/tests/test_auto_Dewisp.py index ed3b4c32f6..4d986e22f3 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Dewisp.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Dewisp.py @@ -4,14 +4,35 @@ def test_Dewisp_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMaskFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - maximumIterations=dict(argstr="-n %d",), - outputMaskFile=dict(argstr="-o %s", extensions=None, genfile=True,), - sizeThreshold=dict(argstr="-t %d",), - timer=dict(argstr="--timer",), - verbosity=dict(argstr="-v %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMaskFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + maximumIterations=dict( + argstr="-n %d", + ), + outputMaskFile=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + sizeThreshold=dict( + argstr="-t %d", + ), + timer=dict( + argstr="--timer", + ), + verbosity=dict( + argstr="-v %d", + ), ) inputs = Dewisp.input_spec() @@ -21,7 +42,11 @@ def test_Dewisp_inputs(): def test_Dewisp_outputs(): - output_map = dict(outputMaskFile=dict(extensions=None,),) + output_map = dict( + outputMaskFile=dict( + extensions=None, + ), + ) outputs = Dewisp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Dfs.py b/nipype/interfaces/brainsuite/tests/test_auto_Dfs.py index 00a35e8c82..3122791cf5 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Dfs.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Dfs.py @@ -4,30 +4,70 @@ def test_Dfs_inputs(): input_map = dict( - args=dict(argstr="%s",), - curvatureWeighting=dict(argstr="-w %f", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - inputShadingVolume=dict(argstr="-c %s", extensions=None,), - inputVolumeFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - noNormalsFlag=dict(argstr="--nonormals",), + args=dict( + argstr="%s", + ), + curvatureWeighting=dict( + argstr="-w %f", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputShadingVolume=dict( + argstr="-c %s", + extensions=None, + ), + inputVolumeFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + noNormalsFlag=dict( + argstr="--nonormals", + ), nonZeroTessellation=dict( - argstr="-nz", xor=("nonZeroTessellation", "specialTessellation"), + argstr="-nz", + xor=("nonZeroTessellation", "specialTessellation"), + ), + outputSurfaceFile=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + postSmoothFlag=dict( + argstr="--postsmooth", + ), + scalingPercentile=dict( + argstr="-f %f", + ), + smoothingConstant=dict( + argstr="-a %f", + usedefault=True, + ), + smoothingIterations=dict( + argstr="-n %d", + usedefault=True, ), - outputSurfaceFile=dict(argstr="-o %s", extensions=None, genfile=True,), - postSmoothFlag=dict(argstr="--postsmooth",), - scalingPercentile=dict(argstr="-f %f",), - smoothingConstant=dict(argstr="-a %f", usedefault=True,), - smoothingIterations=dict(argstr="-n %d", usedefault=True,), specialTessellation=dict( argstr="%s", position=-1, requires=["tessellationThreshold"], xor=("nonZeroTessellation", "specialTessellation"), ), - tessellationThreshold=dict(argstr="%f",), - timer=dict(argstr="--timer",), - verbosity=dict(argstr="-v %d",), - zeroPadFlag=dict(argstr="-z",), + tessellationThreshold=dict( + argstr="%f", + ), + timer=dict( + argstr="--timer", + ), + verbosity=dict( + argstr="-v %d", + ), + zeroPadFlag=dict( + argstr="-z", + ), ) inputs = Dfs.input_spec() @@ -37,7 +77,11 @@ def test_Dfs_inputs(): def test_Dfs_outputs(): - output_map = dict(outputSurfaceFile=dict(extensions=None,),) + output_map = dict( + outputSurfaceFile=dict( + extensions=None, + ), + ) outputs = Dfs.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py b/nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py index 761d049672..0696f11992 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Hemisplit.py @@ -4,17 +4,53 @@ def test_Hemisplit_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputHemisphereLabelFile=dict(argstr="-l %s", extensions=None, mandatory=True,), - inputSurfaceFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - outputLeftHemisphere=dict(argstr="--left %s", extensions=None, genfile=True,), - outputLeftPialHemisphere=dict(argstr="-pl %s", extensions=None, genfile=True,), - outputRightHemisphere=dict(argstr="--right %s", extensions=None, genfile=True,), - outputRightPialHemisphere=dict(argstr="-pr %s", extensions=None, genfile=True,), - pialSurfaceFile=dict(argstr="-p %s", extensions=None,), - timer=dict(argstr="--timer",), - verbosity=dict(argstr="-v %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputHemisphereLabelFile=dict( + argstr="-l %s", + extensions=None, + mandatory=True, + ), + inputSurfaceFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + outputLeftHemisphere=dict( + argstr="--left %s", + extensions=None, + genfile=True, + ), + outputLeftPialHemisphere=dict( + argstr="-pl %s", + extensions=None, + genfile=True, + ), + outputRightHemisphere=dict( + argstr="--right %s", + extensions=None, + genfile=True, + ), + outputRightPialHemisphere=dict( + argstr="-pr %s", + extensions=None, + genfile=True, + ), + pialSurfaceFile=dict( + argstr="-p %s", + extensions=None, + ), + timer=dict( + argstr="--timer", + ), + verbosity=dict( + argstr="-v %d", + ), ) inputs = Hemisplit.input_spec() @@ -25,10 +61,18 @@ def test_Hemisplit_inputs(): def test_Hemisplit_outputs(): output_map = dict( - outputLeftHemisphere=dict(extensions=None,), - outputLeftPialHemisphere=dict(extensions=None,), - outputRightHemisphere=dict(extensions=None,), - outputRightPialHemisphere=dict(extensions=None,), + outputLeftHemisphere=dict( + extensions=None, + ), + outputLeftPialHemisphere=dict( + extensions=None, + ), + outputRightHemisphere=dict( + extensions=None, + ), + outputRightPialHemisphere=dict( + extensions=None, + ), ) outputs = Hemisplit.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Pialmesh.py b/nipype/interfaces/brainsuite/tests/test_auto_Pialmesh.py index 9da07862f8..f5ba0725df 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Pialmesh.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Pialmesh.py @@ -4,25 +4,80 @@ def test_Pialmesh_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - exportPrefix=dict(argstr="--prefix %s",), - inputMaskFile=dict(argstr="-m %s", extensions=None, mandatory=True,), - inputSurfaceFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - inputTissueFractionFile=dict(argstr="-f %s", extensions=None, mandatory=True,), - laplacianSmoothing=dict(argstr="--smooth %f", usedefault=True,), - maxThickness=dict(argstr="--max %f", usedefault=True,), - normalSmoother=dict(argstr="--nc %f", usedefault=True,), - numIterations=dict(argstr="-n %d", usedefault=True,), - outputInterval=dict(argstr="--interval %d", usedefault=True,), - outputSurfaceFile=dict(argstr="-o %s", extensions=None, genfile=True,), - recomputeNormals=dict(argstr="--norm",), - searchRadius=dict(argstr="-r %f", usedefault=True,), - stepSize=dict(argstr="-s %f", usedefault=True,), - tangentSmoother=dict(argstr="--tc %f",), - timer=dict(argstr="--timer",), - tissueThreshold=dict(argstr="-t %f", usedefault=True,), - verbosity=dict(argstr="-v %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + exportPrefix=dict( + argstr="--prefix %s", + ), + inputMaskFile=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + ), + inputSurfaceFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + inputTissueFractionFile=dict( + argstr="-f %s", + extensions=None, + mandatory=True, + ), + laplacianSmoothing=dict( + argstr="--smooth %f", + usedefault=True, + ), + maxThickness=dict( + argstr="--max %f", + usedefault=True, + ), + normalSmoother=dict( + argstr="--nc %f", + usedefault=True, + ), + numIterations=dict( + argstr="-n %d", + usedefault=True, + ), + outputInterval=dict( + argstr="--interval %d", + usedefault=True, + ), + outputSurfaceFile=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + recomputeNormals=dict( + argstr="--norm", + ), + searchRadius=dict( + argstr="-r %f", + usedefault=True, + ), + stepSize=dict( + argstr="-s %f", + usedefault=True, + ), + tangentSmoother=dict( + argstr="--tc %f", + ), + timer=dict( + argstr="--timer", + ), + tissueThreshold=dict( + argstr="-t %f", + usedefault=True, + ), + verbosity=dict( + argstr="-v %d", + ), ) inputs = Pialmesh.input_spec() @@ -32,7 +87,11 @@ def test_Pialmesh_inputs(): def test_Pialmesh_outputs(): - output_map = dict(outputSurfaceFile=dict(extensions=None,),) + output_map = dict( + outputSurfaceFile=dict( + extensions=None, + ), + ) outputs = Pialmesh.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Pvc.py b/nipype/interfaces/brainsuite/tests/test_auto_Pvc.py index fa1c8bc8b7..a6f52a26a7 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Pvc.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Pvc.py @@ -4,16 +4,44 @@ def test_Pvc_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMRIFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - inputMaskFile=dict(argstr="-m %s", extensions=None,), - outputLabelFile=dict(argstr="-o %s", extensions=None, genfile=True,), - outputTissueFractionFile=dict(argstr="-f %s", extensions=None, genfile=True,), - spatialPrior=dict(argstr="-l %f",), - threeClassFlag=dict(argstr="-3",), - timer=dict(argstr="--timer",), - verbosity=dict(argstr="-v %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMRIFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + inputMaskFile=dict( + argstr="-m %s", + extensions=None, + ), + outputLabelFile=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + outputTissueFractionFile=dict( + argstr="-f %s", + extensions=None, + genfile=True, + ), + spatialPrior=dict( + argstr="-l %f", + ), + threeClassFlag=dict( + argstr="-3", + ), + timer=dict( + argstr="--timer", + ), + verbosity=dict( + argstr="-v %d", + ), ) inputs = Pvc.input_spec() @@ -24,8 +52,12 @@ def test_Pvc_inputs(): def test_Pvc_outputs(): output_map = dict( - outputLabelFile=dict(extensions=None,), - outputTissueFractionFile=dict(extensions=None,), + outputLabelFile=dict( + extensions=None, + ), + outputTissueFractionFile=dict( + extensions=None, + ), ) outputs = Pvc.output_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_SVReg.py b/nipype/interfaces/brainsuite/tests/test_auto_SVReg.py index 2c19934e7c..4c29c2bfda 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_SVReg.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_SVReg.py @@ -4,33 +4,82 @@ def test_SVReg_inputs(): input_map = dict( - args=dict(argstr="%s",), - atlasFilePrefix=dict(argstr="'%s'", position=1,), - curveMatchingInstructions=dict(argstr="'-cur %s'",), - dataSinkDelay=dict(argstr="%s",), - displayModuleName=dict(argstr="'-m'",), - displayTimestamps=dict(argstr="'-t'",), - environ=dict(nohash=True, usedefault=True,), - iterations=dict(argstr="'-H %d'",), - keepIntermediates=dict(argstr="'-k'",), - pialSurfaceMaskDilation=dict(argstr="'-D %d'",), - refineOutputs=dict(argstr="'-r'",), - shortMessages=dict(argstr="'-gui'",), - skipToIntensityReg=dict(argstr="'-p'",), - skipToVolumeReg=dict(argstr="'-s'",), - skipVolumetricProcessing=dict(argstr="'-S'",), - subjectFilePrefix=dict(argstr="'%s'", mandatory=True, position=0,), - useCerebrumMask=dict(argstr="'-C'",), - useManualMaskFile=dict(argstr="'-cbm'",), - useMultiThreading=dict(argstr="'-P'",), - useSingleThreading=dict(argstr="'-U'",), + args=dict( + argstr="%s", + ), + atlasFilePrefix=dict( + argstr="'%s'", + position=1, + ), + curveMatchingInstructions=dict( + argstr="'-cur %s'", + ), + dataSinkDelay=dict( + argstr="%s", + ), + displayModuleName=dict( + argstr="'-m'", + ), + displayTimestamps=dict( + argstr="'-t'", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + iterations=dict( + argstr="'-H %d'", + ), + keepIntermediates=dict( + argstr="'-k'", + ), + pialSurfaceMaskDilation=dict( + argstr="'-D %d'", + ), + refineOutputs=dict( + argstr="'-r'", + ), + shortMessages=dict( + argstr="'-gui'", + ), + skipToIntensityReg=dict( + argstr="'-p'", + ), + skipToVolumeReg=dict( + argstr="'-s'", + ), + skipVolumetricProcessing=dict( + argstr="'-S'", + ), + subjectFilePrefix=dict( + argstr="'%s'", + mandatory=True, + position=0, + ), + useCerebrumMask=dict( + argstr="'-C'", + ), + useManualMaskFile=dict( + argstr="'-cbm'", + ), + useMultiThreading=dict( + argstr="'-P'", + ), + useSingleThreading=dict( + argstr="'-U'", + ), verbosity0=dict( - argstr="'-v0'", xor=("verbosity0", "verbosity1", "verbosity2"), + argstr="'-v0'", + xor=("verbosity0", "verbosity1", "verbosity2"), ), verbosity1=dict( - argstr="'-v1'", xor=("verbosity0", "verbosity1", "verbosity2"), + argstr="'-v1'", + xor=("verbosity0", "verbosity1", "verbosity2"), + ), + verbosity2=dict( + argstr="'v2'", + xor=("verbosity0", "verbosity1", "verbosity2"), ), - verbosity2=dict(argstr="'v2'", xor=("verbosity0", "verbosity1", "verbosity2"),), ) inputs = SVReg.input_spec() diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Scrubmask.py b/nipype/interfaces/brainsuite/tests/test_auto_Scrubmask.py index b356b0335e..97094db018 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Scrubmask.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Scrubmask.py @@ -4,15 +4,40 @@ def test_Scrubmask_inputs(): input_map = dict( - args=dict(argstr="%s",), - backgroundFillThreshold=dict(argstr="-b %d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - foregroundTrimThreshold=dict(argstr="-f %d", usedefault=True,), - inputMaskFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - numberIterations=dict(argstr="-n %d",), - outputMaskFile=dict(argstr="-o %s", extensions=None, genfile=True,), - timer=dict(argstr="--timer",), - verbosity=dict(argstr="-v %d",), + args=dict( + argstr="%s", + ), + backgroundFillThreshold=dict( + argstr="-b %d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + foregroundTrimThreshold=dict( + argstr="-f %d", + usedefault=True, + ), + inputMaskFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + numberIterations=dict( + argstr="-n %d", + ), + outputMaskFile=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + timer=dict( + argstr="--timer", + ), + verbosity=dict( + argstr="-v %d", + ), ) inputs = Scrubmask.input_spec() @@ -22,7 +47,11 @@ def test_Scrubmask_inputs(): def test_Scrubmask_outputs(): - output_map = dict(outputMaskFile=dict(extensions=None,),) + output_map = dict( + outputMaskFile=dict( + extensions=None, + ), + ) outputs = Scrubmask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Skullfinder.py b/nipype/interfaces/brainsuite/tests/test_auto_Skullfinder.py index 06480f30e8..3120f00184 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Skullfinder.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Skullfinder.py @@ -4,21 +4,58 @@ def test_Skullfinder_inputs(): input_map = dict( - args=dict(argstr="%s",), - bgLabelValue=dict(argstr="--bglabel %d",), - brainLabelValue=dict(argstr="--brainlabel %d",), - environ=dict(nohash=True, usedefault=True,), - inputMRIFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - inputMaskFile=dict(argstr="-m %s", extensions=None, mandatory=True,), - lowerThreshold=dict(argstr="-l %d",), - outputLabelFile=dict(argstr="-o %s", extensions=None, genfile=True,), - performFinalOpening=dict(argstr="--finalOpening",), - scalpLabelValue=dict(argstr="--scalplabel %d",), - skullLabelValue=dict(argstr="--skulllabel %d",), - spaceLabelValue=dict(argstr="--spacelabel %d",), - surfaceFilePrefix=dict(argstr="-s %s",), - upperThreshold=dict(argstr="-u %d",), - verbosity=dict(argstr="-v %d",), + args=dict( + argstr="%s", + ), + bgLabelValue=dict( + argstr="--bglabel %d", + ), + brainLabelValue=dict( + argstr="--brainlabel %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMRIFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + inputMaskFile=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + ), + lowerThreshold=dict( + argstr="-l %d", + ), + outputLabelFile=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + performFinalOpening=dict( + argstr="--finalOpening", + ), + scalpLabelValue=dict( + argstr="--scalplabel %d", + ), + skullLabelValue=dict( + argstr="--skulllabel %d", + ), + spaceLabelValue=dict( + argstr="--spacelabel %d", + ), + surfaceFilePrefix=dict( + argstr="-s %s", + ), + upperThreshold=dict( + argstr="-u %d", + ), + verbosity=dict( + argstr="-v %d", + ), ) inputs = Skullfinder.input_spec() @@ -28,7 +65,11 @@ def test_Skullfinder_inputs(): def test_Skullfinder_outputs(): - output_map = dict(outputLabelFile=dict(extensions=None,),) + output_map = dict( + outputLabelFile=dict( + extensions=None, + ), + ) outputs = Skullfinder.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_Tca.py b/nipype/interfaces/brainsuite/tests/test_auto_Tca.py index 66cb70ac8f..eaba6a1d5f 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_Tca.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_Tca.py @@ -4,15 +4,40 @@ def test_Tca_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - foregroundDelta=dict(argstr="--delta %d", usedefault=True,), - inputMaskFile=dict(argstr="-i %s", extensions=None, mandatory=True,), - maxCorrectionSize=dict(argstr="-n %d",), - minCorrectionSize=dict(argstr="-m %d", usedefault=True,), - outputMaskFile=dict(argstr="-o %s", extensions=None, genfile=True,), - timer=dict(argstr="--timer",), - verbosity=dict(argstr="-v %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + foregroundDelta=dict( + argstr="--delta %d", + usedefault=True, + ), + inputMaskFile=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + maxCorrectionSize=dict( + argstr="-n %d", + ), + minCorrectionSize=dict( + argstr="-m %d", + usedefault=True, + ), + outputMaskFile=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + timer=dict( + argstr="--timer", + ), + verbosity=dict( + argstr="-v %d", + ), ) inputs = Tca.input_spec() @@ -22,7 +47,11 @@ def test_Tca_inputs(): def test_Tca_outputs(): - output_map = dict(outputMaskFile=dict(extensions=None,),) + output_map = dict( + outputMaskFile=dict( + extensions=None, + ), + ) outputs = Tca.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/brainsuite/tests/test_auto_ThicknessPVC.py b/nipype/interfaces/brainsuite/tests/test_auto_ThicknessPVC.py index c0265e7e6c..8b043c63c7 100644 --- a/nipype/interfaces/brainsuite/tests/test_auto_ThicknessPVC.py +++ b/nipype/interfaces/brainsuite/tests/test_auto_ThicknessPVC.py @@ -4,9 +4,17 @@ def test_ThicknessPVC_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - subjectFilePrefix=dict(argstr="%s", mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + subjectFilePrefix=dict( + argstr="%s", + mandatory=True, + ), ) inputs = ThicknessPVC.input_spec() diff --git a/nipype/interfaces/bru2nii.py b/nipype/interfaces/bru2nii.py index 7ed9c77651..b07f6a58d3 100644 --- a/nipype/interfaces/bru2nii.py +++ b/nipype/interfaces/bru2nii.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- -"""The bru2nii module provides basic functions for dicom conversion -""" +"""The bru2nii module provides basic functions for dicom conversion""" import os from .base import ( @@ -24,7 +22,7 @@ class Bru2InputSpec(CommandLineInputSpec): ) force_conversion = traits.Bool( argstr="-f", - desc="Force conversion of localizers images (multiple slice " "orientations).", + desc="Force conversion of localizers images (multiple slice orientations).", ) compress = traits.Bool(argstr="-z", desc='gz compress images (".nii.gz").') append_protocol_name = traits.Bool( diff --git a/nipype/interfaces/c3.py b/nipype/interfaces/c3.py index c91c02569c..3871120d2c 100644 --- a/nipype/interfaces/c3.py +++ b/nipype/interfaces/c3.py @@ -1,5 +1,5 @@ -# -*- coding: utf-8 -*- """Convert3D is a command-line tool for converting 3D images between common file formats.""" + import os from glob import glob @@ -84,7 +84,7 @@ class C3dInputSpec(CommandLineInputSpec): desc=( "Write all images on the convert3d stack as multiple files." " Supports both list of output files or a pattern for the output" - " filenames (using %d substituion)." + " filenames (using %d substitution)." ), ) pix_type = traits.Enum( @@ -156,7 +156,7 @@ class C3dInputSpec(CommandLineInputSpec): is_4d = traits.Bool( False, usedefault=True, - desc=("Changes command to support 4D file operations (default is" " false)."), + desc=("Changes command to support 4D file operations (default is false)."), ) @@ -197,7 +197,7 @@ class C3d(CommandLine): _cmd = "c3d" def __init__(self, **inputs): - super(C3d, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._is_4d, "is_4d") if self.inputs.is_4d: self._is_4d() @@ -211,7 +211,7 @@ def _run_interface(self, runtime): # Convert3d does not want to override file, by default # so we define a new output file self._gen_outfile() - runtime = super(C3d, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) self._cmd = cmd return runtime @@ -219,13 +219,13 @@ def _gen_outfile(self): # if many infiles, raise exception if (len(self.inputs.in_file) > 1) or ("*" in self.inputs.in_file[0]): raise AttributeError( - "Multiple in_files found - specify either" " `out_file` or `out_files`." + "Multiple in_files found - specify either `out_file` or `out_files`." ) _, fn, ext = split_filename(self.inputs.in_file[0]) self.inputs.out_file = fn + "_generated" + ext # if generated file will overwrite, raise error if os.path.exists(os.path.abspath(self.inputs.out_file)): - raise IOError("File already found - to overwrite, use `out_file`.") + raise OSError("File already found - to overwrite, use `out_file`.") iflogger.info("Generating `out_file`.") def _list_outputs(self): diff --git a/nipype/interfaces/camino/__init__.py b/nipype/interfaces/camino/__init__.py index e90cc6f375..67e973df66 100644 --- a/nipype/interfaces/camino/__init__.py +++ b/nipype/interfaces/camino/__init__.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Camino top level namespace -""" +"""Camino top level namespace""" from .connectivity import Conmat from .convert import ( diff --git a/nipype/interfaces/camino/calib.py b/nipype/interfaces/camino/calib.py index 0c44b4abea..6345e01cdb 100644 --- a/nipype/interfaces/camino/calib.py +++ b/nipype/interfaces/camino/calib.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import os from ...utils.filemanip import split_filename @@ -45,7 +43,7 @@ class SFPICOCalibDataInputSpec(StdOutCommandLineInputSpec): minlen=2, maxlen=2, units="NA", - desc=("Minimum and maximum FA for the single tensor " "synthetic data."), + desc=("Minimum and maximum FA for the single tensor synthetic data."), ) onedtfastep = traits.Float( argstr="-onedtfastep %f", @@ -82,7 +80,7 @@ class SFPICOCalibDataInputSpec(StdOutCommandLineInputSpec): minlen=2, maxlen=2, units="NA", - desc=("Minimum and maximum crossing angles " "between the two fibres."), + desc=("Minimum and maximum crossing angles between the two fibres."), ) twodtanglestep = traits.Float( argstr="-twodtanglestep %f", diff --git a/nipype/interfaces/camino/connectivity.py b/nipype/interfaces/camino/connectivity.py index 2b7d0ff337..3421afced2 100644 --- a/nipype/interfaces/camino/connectivity.py +++ b/nipype/interfaces/camino/connectivity.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os from ...utils.filemanip import split_filename @@ -133,7 +132,7 @@ class Conmat(CommandLine): Such fibers will add to the diagonal elements of the matrix. To remove these entries, run procstreamlines with -endpointfile before running conmat. - If the seed point is inside a labled region, it counts as one end of the + If the seed point is inside a labeled region, it counts as one end of the connection. So :: ----[SEED inside A]---------B diff --git a/nipype/interfaces/camino/convert.py b/nipype/interfaces/camino/convert.py index a5b4b70fb3..4dfd65375e 100644 --- a/nipype/interfaces/camino/convert.py +++ b/nipype/interfaces/camino/convert.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import os import glob @@ -446,10 +444,10 @@ class ProcStreamlines(StdOutCommandLine): def _format_arg(self, name, spec, value): if name == "outputroot": return spec.argstr % self._get_actual_outputroot(value) - return super(ProcStreamlines, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def __init__(self, *args, **kwargs): - super(ProcStreamlines, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.outputroot_files = [] def _run_interface(self, runtime): @@ -459,13 +457,13 @@ def _run_interface(self, runtime): base, filename, ext = split_filename(actual_outputroot) if not os.path.exists(base): os.makedirs(base) - new_runtime = super(ProcStreamlines, self)._run_interface(runtime) + new_runtime = super()._run_interface(runtime) self.outputroot_files = glob.glob( os.path.join(os.getcwd(), actual_outputroot + "*") ) return new_runtime else: - new_runtime = super(ProcStreamlines, self)._run_interface(runtime) + new_runtime = super()._run_interface(runtime) return new_runtime def _get_actual_outputroot(self, outputroot): @@ -718,7 +716,7 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): exists=True, argstr="%s", position=2, - desc=("Camino scheme file (b values / vectors, " "see camino.fsl2scheme)"), + desc=("Camino scheme file (b values / vectors, see camino.fsl2scheme)"), ) readheader = File( @@ -737,9 +735,7 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): exists=True, argstr="-printimagedims %s", position=3, - desc=( - "Prints image data and voxel dimensions as " "Camino arguments and exits." - ), + desc=("Prints image data and voxel dimensions as Camino arguments and exits."), ) # How do we implement both file and enum (for the program) in one argument? @@ -764,14 +760,14 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): exists=True, argstr="-printintelbyteorder %s", position=3, - desc=("Prints 1 if the header is little-endian, " "0 otherwise."), + desc=("Prints 1 if the header is little-endian, 0 otherwise."), ) printbigendian = File( exists=True, argstr="-printbigendian %s", position=3, - desc=("Prints 1 if the header is big-endian, 0 " "otherwise."), + desc=("Prints 1 if the header is big-endian, 0 otherwise."), ) initfromheader = File( @@ -780,7 +776,7 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): position=3, desc=( "Reads header information from file and " - "intializes a new header with the values read " + "initializes a new header with the values read " "from the file. You may replace any " "combination of fields in the new header by " "specifying subsequent options." @@ -822,7 +818,7 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): argstr="-picoseed %s", minlen=3, maxlen=3, - desc=("Voxel specifying the seed (for PICo maps), " "default [0 0 0]."), + desc=("Voxel specifying the seed (for PICo maps), default [0 0 0]."), units="mm", ) @@ -868,7 +864,7 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): argstr="-gl %s", minlen=2, maxlen=2, - desc=("Minimum and maximum greylevels. Stored as " "shorts in the header."), + desc=("Minimum and maximum greylevels. Stored as shorts in the header."), units="NA", ) @@ -885,7 +881,7 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): scaleinter = traits.Float( argstr="-scaleinter %d", units="NA", - desc=("Constant to add to the image intensities. " "Used by SPM and MRIcro."), + desc=("Constant to add to the image intensities. Used by SPM and MRIcro."), ) description = traits.String( @@ -899,7 +895,7 @@ class AnalyzeHeaderInputSpec(StdOutCommandLineInputSpec): intelbyteorder = traits.Bool( argstr="-intelbyteorder", - desc=("Write header in intel byte order " "(little-endian)."), + desc=("Write header in intel byte order (little-endian)."), ) networkbyteorder = traits.Bool( diff --git a/nipype/interfaces/camino/dti.py b/nipype/interfaces/camino/dti.py index 6d210c1b0b..ba2131b8ac 100644 --- a/nipype/interfaces/camino/dti.py +++ b/nipype/interfaces/camino/dti.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import os from ...utils.filemanip import split_filename @@ -621,7 +619,7 @@ class PicoPDFsInputSpec(StdOutCommandLineInputSpec): units="NA", desc="The maximum number of PDs in a voxel (default 3) for PD data." "This option determines the size of the input and output voxels." - "This means that the data file may be large enough to accomodate three or more PDs," + "This means that the data file may be large enough to accommodate three or more PDs," "but does not mean that any of the voxels are classified as containing three or more PDs.", ) @@ -740,7 +738,7 @@ class TrackInputSpec(CommandLineInputSpec): stepsize = traits.Float( argstr="-stepsize %f", requires=["tracker"], - desc=("Step size for EULER and RK4 tracking. " "The default is 1mm."), + desc=("Step size for EULER and RK4 tracking. The default is 1mm."), ) inputdatatype = traits.Enum( @@ -938,7 +936,7 @@ class TrackDT(Track): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "dt" - return super(TrackDT, self).__init__(command, **inputs) + return super().__init__(command, **inputs) class TrackPICoInputSpec(TrackInputSpec): @@ -975,7 +973,7 @@ class TrackPICo(Track): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "pico" - return super(TrackPICo, self).__init__(command, **inputs) + return super().__init__(command, **inputs) class TrackBedpostxDeterInputSpec(TrackInputSpec): @@ -1025,7 +1023,7 @@ class TrackBedpostxDeter(Track): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "bedpostx_dyad" - return super(TrackBedpostxDeter, self).__init__(command, **inputs) + return super().__init__(command, **inputs) class TrackBedpostxProbaInputSpec(TrackInputSpec): @@ -1086,7 +1084,7 @@ class TrackBedpostxProba(Track): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "bedpostx" - return super(TrackBedpostxProba, self).__init__(command, **inputs) + return super().__init__(command, **inputs) class TrackBayesDiracInputSpec(TrackInputSpec): @@ -1094,7 +1092,7 @@ class TrackBayesDiracInputSpec(TrackInputSpec): argstr="-schemefile %s", mandatory=True, exists=True, - desc=("The scheme file corresponding to the data being " "processed."), + desc=("The scheme file corresponding to the data being processed."), ) iterations = traits.Int( @@ -1187,7 +1185,7 @@ class TrackBayesDirac(Track): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "bayesdirac" - return super(TrackBayesDirac, self).__init__(command, **inputs) + return super().__init__(command, **inputs) class TrackBallStick(Track): @@ -1206,7 +1204,7 @@ class TrackBallStick(Track): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "ballstick" - return super(TrackBallStick, self).__init__(command, **inputs) + return super().__init__(command, **inputs) class TrackBootstrapInputSpec(TrackInputSpec): @@ -1251,7 +1249,7 @@ class TrackBootstrapInputSpec(TrackInputSpec): class TrackBootstrap(Track): """ - Performs bootstrap streamline tractography using mulitple scans of the same subject + Performs bootstrap streamline tractography using multiple scans of the same subject Example ------- @@ -1268,7 +1266,7 @@ class TrackBootstrap(Track): input_spec = TrackBootstrapInputSpec def __init__(self, command=None, **inputs): - return super(TrackBootstrap, self).__init__(command, **inputs) + return super().__init__(command, **inputs) class ComputeMeanDiffusivityInputSpec(CommandLineInputSpec): diff --git a/nipype/interfaces/camino/odf.py b/nipype/interfaces/camino/odf.py index 0cd8b0c49c..90d72f114a 100644 --- a/nipype/interfaces/camino/odf.py +++ b/nipype/interfaces/camino/odf.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import os from ...utils.filemanip import split_filename @@ -152,9 +150,7 @@ class LinReconInputSpec(StdOutCommandLineInputSpec): ) log = traits.Bool( argstr="-log", - desc=( - "Transform the log measurements rather than the " "measurements themselves" - ), + desc=("Transform the log measurements rather than the measurements themselves"), ) bgmask = File(exists=True, argstr="-bgmask %s", desc="background mask") @@ -170,7 +166,7 @@ class LinRecon(StdOutCommandLine): Reads a linear transformation from the matrix file assuming the imaging scheme specified in the scheme file. Performs the linear transformation on the data in every voxel and outputs the result to - the standard output. The ouput in every voxel is actually: :: + the standard output. The output in every voxel is actually: :: [exit code, ln(S(0)), p1, ..., pR] diff --git a/nipype/interfaces/camino/tests/__init__.py b/nipype/interfaces/camino/tests/__init__.py index 99fb243f19..349937997e 100644 --- a/nipype/interfaces/camino/tests/__init__.py +++ b/nipype/interfaces/camino/tests/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py b/nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py index 419330da13..9b6110d30d 100644 --- a/nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py +++ b/nipype/interfaces/camino/tests/test_auto_AnalyzeHeader.py @@ -4,32 +4,109 @@ def test_AnalyzeHeader_inputs(): input_map = dict( - args=dict(argstr="%s",), - centre=dict(argstr="-centre %s", units="mm",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - datatype=dict(argstr="-datatype %s", mandatory=True,), - description=dict(argstr="-description %s",), - environ=dict(nohash=True, usedefault=True,), - greylevels=dict(argstr="-gl %s", units="NA",), - in_file=dict(argstr="< %s", extensions=None, mandatory=True, position=1,), - initfromheader=dict(argstr="-initfromheader %s", extensions=None, position=3,), - intelbyteorder=dict(argstr="-intelbyteorder",), - networkbyteorder=dict(argstr="-networkbyteorder",), - nimages=dict(argstr="-nimages %d", units="NA",), - offset=dict(argstr="-offset %d", units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - picoseed=dict(argstr="-picoseed %s", units="mm",), - printbigendian=dict(argstr="-printbigendian %s", extensions=None, position=3,), - printimagedims=dict(argstr="-printimagedims %s", extensions=None, position=3,), + args=dict( + argstr="%s", + ), + centre=dict( + argstr="-centre %s", + units="mm", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + datatype=dict( + argstr="-datatype %s", + mandatory=True, + ), + description=dict( + argstr="-description %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + greylevels=dict( + argstr="-gl %s", + units="NA", + ), + in_file=dict( + argstr="< %s", + extensions=None, + mandatory=True, + position=1, + ), + initfromheader=dict( + argstr="-initfromheader %s", + extensions=None, + position=3, + ), + intelbyteorder=dict( + argstr="-intelbyteorder", + ), + networkbyteorder=dict( + argstr="-networkbyteorder", + ), + nimages=dict( + argstr="-nimages %d", + units="NA", + ), + offset=dict( + argstr="-offset %d", + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + picoseed=dict( + argstr="-picoseed %s", + units="mm", + ), + printbigendian=dict( + argstr="-printbigendian %s", + extensions=None, + position=3, + ), + printimagedims=dict( + argstr="-printimagedims %s", + extensions=None, + position=3, + ), printintelbyteorder=dict( - argstr="-printintelbyteorder %s", extensions=None, position=3, - ), - printprogargs=dict(argstr="-printprogargs %s", extensions=None, position=3,), - readheader=dict(argstr="-readheader %s", extensions=None, position=3,), - scaleinter=dict(argstr="-scaleinter %d", units="NA",), - scaleslope=dict(argstr="-scaleslope %d", units="NA",), - scheme_file=dict(argstr="%s", extensions=None, position=2,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-printintelbyteorder %s", + extensions=None, + position=3, + ), + printprogargs=dict( + argstr="-printprogargs %s", + extensions=None, + position=3, + ), + readheader=dict( + argstr="-readheader %s", + extensions=None, + position=3, + ), + scaleinter=dict( + argstr="-scaleinter %d", + units="NA", + ), + scaleslope=dict( + argstr="-scaleslope %d", + units="NA", + ), + scheme_file=dict( + argstr="%s", + extensions=None, + position=2, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = AnalyzeHeader.input_spec() @@ -39,7 +116,11 @@ def test_AnalyzeHeader_inputs(): def test_AnalyzeHeader_outputs(): - output_map = dict(header=dict(extensions=None,),) + output_map = dict( + header=dict( + extensions=None, + ), + ) outputs = AnalyzeHeader.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ComputeEigensystem.py b/nipype/interfaces/camino/tests/test_auto_ComputeEigensystem.py index 70e1603a33..6181cf7541 100644 --- a/nipype/interfaces/camino/tests/test_auto_ComputeEigensystem.py +++ b/nipype/interfaces/camino/tests/test_auto_ComputeEigensystem.py @@ -4,14 +4,39 @@ def test_ComputeEigensystem_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="< %s", extensions=None, mandatory=True, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s", usedefault=True,), - inputmodel=dict(argstr="-inputmodel %s",), - maxcomponents=dict(argstr="-maxcomponents %d",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - outputdatatype=dict(argstr="-outputdatatype %s", usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="< %s", + extensions=None, + mandatory=True, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + usedefault=True, + ), + inputmodel=dict( + argstr="-inputmodel %s", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + outputdatatype=dict( + argstr="-outputdatatype %s", + usedefault=True, + ), ) inputs = ComputeEigensystem.input_spec() @@ -21,7 +46,11 @@ def test_ComputeEigensystem_inputs(): def test_ComputeEigensystem_outputs(): - output_map = dict(eigen=dict(extensions=None,),) + output_map = dict( + eigen=dict( + extensions=None, + ), + ) outputs = ComputeEigensystem.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ComputeFractionalAnisotropy.py b/nipype/interfaces/camino/tests/test_auto_ComputeFractionalAnisotropy.py index cecdcd6dd9..0a13ac4f64 100644 --- a/nipype/interfaces/camino/tests/test_auto_ComputeFractionalAnisotropy.py +++ b/nipype/interfaces/camino/tests/test_auto_ComputeFractionalAnisotropy.py @@ -4,14 +4,39 @@ def test_ComputeFractionalAnisotropy_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="< %s", extensions=None, mandatory=True, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - outputdatatype=dict(argstr="-outputdatatype %s",), - scheme_file=dict(argstr="%s", extensions=None, position=2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="< %s", + extensions=None, + mandatory=True, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + outputdatatype=dict( + argstr="-outputdatatype %s", + ), + scheme_file=dict( + argstr="%s", + extensions=None, + position=2, + ), ) inputs = ComputeFractionalAnisotropy.input_spec() @@ -21,7 +46,11 @@ def test_ComputeFractionalAnisotropy_inputs(): def test_ComputeFractionalAnisotropy_outputs(): - output_map = dict(fa=dict(extensions=None,),) + output_map = dict( + fa=dict( + extensions=None, + ), + ) outputs = ComputeFractionalAnisotropy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ComputeMeanDiffusivity.py b/nipype/interfaces/camino/tests/test_auto_ComputeMeanDiffusivity.py index 692d900494..822bd0306e 100644 --- a/nipype/interfaces/camino/tests/test_auto_ComputeMeanDiffusivity.py +++ b/nipype/interfaces/camino/tests/test_auto_ComputeMeanDiffusivity.py @@ -4,14 +4,39 @@ def test_ComputeMeanDiffusivity_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="< %s", extensions=None, mandatory=True, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - outputdatatype=dict(argstr="-outputdatatype %s",), - scheme_file=dict(argstr="%s", extensions=None, position=2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="< %s", + extensions=None, + mandatory=True, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + outputdatatype=dict( + argstr="-outputdatatype %s", + ), + scheme_file=dict( + argstr="%s", + extensions=None, + position=2, + ), ) inputs = ComputeMeanDiffusivity.input_spec() @@ -21,7 +46,11 @@ def test_ComputeMeanDiffusivity_inputs(): def test_ComputeMeanDiffusivity_outputs(): - output_map = dict(md=dict(extensions=None,),) + output_map = dict( + md=dict( + extensions=None, + ), + ) outputs = ComputeMeanDiffusivity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ComputeTensorTrace.py b/nipype/interfaces/camino/tests/test_auto_ComputeTensorTrace.py index 3a7469378e..8a912685ae 100644 --- a/nipype/interfaces/camino/tests/test_auto_ComputeTensorTrace.py +++ b/nipype/interfaces/camino/tests/test_auto_ComputeTensorTrace.py @@ -4,14 +4,39 @@ def test_ComputeTensorTrace_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="< %s", extensions=None, mandatory=True, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - outputdatatype=dict(argstr="-outputdatatype %s",), - scheme_file=dict(argstr="%s", extensions=None, position=2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="< %s", + extensions=None, + mandatory=True, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + outputdatatype=dict( + argstr="-outputdatatype %s", + ), + scheme_file=dict( + argstr="%s", + extensions=None, + position=2, + ), ) inputs = ComputeTensorTrace.input_spec() @@ -21,7 +46,11 @@ def test_ComputeTensorTrace_inputs(): def test_ComputeTensorTrace_outputs(): - output_map = dict(trace=dict(extensions=None,),) + output_map = dict( + trace=dict( + extensions=None, + ), + ) outputs = ComputeTensorTrace.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_Conmat.py b/nipype/interfaces/camino/tests/test_auto_Conmat.py index 65c84dc64c..a9ea16865d 100644 --- a/nipype/interfaces/camino/tests/test_auto_Conmat.py +++ b/nipype/interfaces/camino/tests/test_auto_Conmat.py @@ -4,16 +4,42 @@ def test_Conmat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-inputfile %s", extensions=None, mandatory=True,), - output_root=dict(argstr="-outputroot %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + mandatory=True, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + genfile=True, + ), scalar_file=dict( - argstr="-scalarfile %s", extensions=None, requires=["tract_stat"], + argstr="-scalarfile %s", + extensions=None, + requires=["tract_stat"], + ), + target_file=dict( + argstr="-targetfile %s", + extensions=None, + mandatory=True, + ), + targetname_file=dict( + argstr="-targetnamefile %s", + extensions=None, + ), + tract_prop=dict( + argstr="-tractstat %s", + units="NA", + xor=["tract_stat"], ), - target_file=dict(argstr="-targetfile %s", extensions=None, mandatory=True,), - targetname_file=dict(argstr="-targetnamefile %s", extensions=None,), - tract_prop=dict(argstr="-tractstat %s", units="NA", xor=["tract_stat"],), tract_stat=dict( argstr="-tractstat %s", requires=["scalar_file"], @@ -30,7 +56,12 @@ def test_Conmat_inputs(): def test_Conmat_outputs(): output_map = dict( - conmat_sc=dict(extensions=None,), conmat_ts=dict(extensions=None,), + conmat_sc=dict( + extensions=None, + ), + conmat_ts=dict( + extensions=None, + ), ) outputs = Conmat.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_DT2NIfTI.py b/nipype/interfaces/camino/tests/test_auto_DT2NIfTI.py index fce7560dd2..b88fe01ba9 100644 --- a/nipype/interfaces/camino/tests/test_auto_DT2NIfTI.py +++ b/nipype/interfaces/camino/tests/test_auto_DT2NIfTI.py @@ -4,16 +4,30 @@ def test_DT2NIfTI_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), header_file=dict( - argstr="-header %s", extensions=None, mandatory=True, position=3, + argstr="-header %s", + extensions=None, + mandatory=True, + position=3, ), in_file=dict( - argstr="-inputfile %s", extensions=None, mandatory=True, position=1, + argstr="-inputfile %s", + extensions=None, + mandatory=True, + position=1, ), output_root=dict( - argstr="-outputroot %s", extensions=None, genfile=True, position=2, + argstr="-outputroot %s", + extensions=None, + genfile=True, + position=2, ), ) inputs = DT2NIfTI.input_spec() @@ -25,9 +39,15 @@ def test_DT2NIfTI_inputs(): def test_DT2NIfTI_outputs(): output_map = dict( - dt=dict(extensions=None,), - exitcode=dict(extensions=None,), - lns0=dict(extensions=None,), + dt=dict( + extensions=None, + ), + exitcode=dict( + extensions=None, + ), + lns0=dict( + extensions=None, + ), ) outputs = DT2NIfTI.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_DTIFit.py b/nipype/interfaces/camino/tests/test_auto_DTIFit.py index 467e2d54ea..757f870fe3 100644 --- a/nipype/interfaces/camino/tests/test_auto_DTIFit.py +++ b/nipype/interfaces/camino/tests/test_auto_DTIFit.py @@ -4,13 +4,39 @@ def test_DTIFit_inputs(): input_map = dict( - args=dict(argstr="%s",), - bgmask=dict(argstr="-bgmask %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - non_linear=dict(argstr="-nonlinear", position=3,), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - scheme_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + bgmask=dict( + argstr="-bgmask %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + non_linear=dict( + argstr="-nonlinear", + position=3, + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + scheme_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), ) inputs = DTIFit.input_spec() @@ -20,7 +46,11 @@ def test_DTIFit_inputs(): def test_DTIFit_outputs(): - output_map = dict(tensor_fitted=dict(extensions=None,),) + output_map = dict( + tensor_fitted=dict( + extensions=None, + ), + ) outputs = DTIFit.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_DTLUTGen.py b/nipype/interfaces/camino/tests/test_auto_DTLUTGen.py index 674d38a37b..0ee1ffea8f 100644 --- a/nipype/interfaces/camino/tests/test_auto_DTLUTGen.py +++ b/nipype/interfaces/camino/tests/test_auto_DTLUTGen.py @@ -4,22 +4,64 @@ def test_DTLUTGen_inputs(): input_map = dict( - acg=dict(argstr="-acg",), - args=dict(argstr="%s",), - bingham=dict(argstr="-bingham",), - environ=dict(nohash=True, usedefault=True,), - frange=dict(argstr="-frange %s", position=1, units="NA",), - inversion=dict(argstr="-inversion %d", units="NA",), - lrange=dict(argstr="-lrange %s", position=1, units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - samples=dict(argstr="-samples %d", units="NA",), + acg=dict( + argstr="-acg", + ), + args=dict( + argstr="%s", + ), + bingham=dict( + argstr="-bingham", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + frange=dict( + argstr="-frange %s", + position=1, + units="NA", + ), + inversion=dict( + argstr="-inversion %d", + units="NA", + ), + lrange=dict( + argstr="-lrange %s", + position=1, + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + samples=dict( + argstr="-samples %d", + units="NA", + ), scheme_file=dict( - argstr="-schemefile %s", extensions=None, mandatory=True, position=2, + argstr="-schemefile %s", + extensions=None, + mandatory=True, + position=2, + ), + snr=dict( + argstr="-snr %f", + units="NA", + ), + step=dict( + argstr="-step %f", + units="NA", + ), + trace=dict( + argstr="-trace %G", + units="NA", + ), + watson=dict( + argstr="-watson", ), - snr=dict(argstr="-snr %f", units="NA",), - step=dict(argstr="-step %f", units="NA",), - trace=dict(argstr="-trace %G", units="NA",), - watson=dict(argstr="-watson",), ) inputs = DTLUTGen.input_spec() @@ -29,7 +71,11 @@ def test_DTLUTGen_inputs(): def test_DTLUTGen_outputs(): - output_map = dict(dtLUT=dict(extensions=None,),) + output_map = dict( + dtLUT=dict( + extensions=None, + ), + ) outputs = DTLUTGen.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_DTMetric.py b/nipype/interfaces/camino/tests/test_auto_DTMetric.py index fd62a3d329..11e971b28b 100644 --- a/nipype/interfaces/camino/tests/test_auto_DTMetric.py +++ b/nipype/interfaces/camino/tests/test_auto_DTMetric.py @@ -4,14 +4,39 @@ def test_DTMetric_inputs(): input_map = dict( - args=dict(argstr="%s",), - data_header=dict(argstr="-header %s", extensions=None,), - eigen_data=dict(argstr="-inputfile %s", extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - inputdatatype=dict(argstr="-inputdatatype %s", usedefault=True,), - metric=dict(argstr="-stat %s", mandatory=True,), - outputdatatype=dict(argstr="-outputdatatype %s", usedefault=True,), - outputfile=dict(argstr="-outputfile %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + data_header=dict( + argstr="-header %s", + extensions=None, + ), + eigen_data=dict( + argstr="-inputfile %s", + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + usedefault=True, + ), + metric=dict( + argstr="-stat %s", + mandatory=True, + ), + outputdatatype=dict( + argstr="-outputdatatype %s", + usedefault=True, + ), + outputfile=dict( + argstr="-outputfile %s", + extensions=None, + genfile=True, + ), ) inputs = DTMetric.input_spec() @@ -21,7 +46,11 @@ def test_DTMetric_inputs(): def test_DTMetric_outputs(): - output_map = dict(metric_stats=dict(extensions=None,),) + output_map = dict( + metric_stats=dict( + extensions=None, + ), + ) outputs = DTMetric.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py b/nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py index 00b11eb751..376fa1bf3e 100644 --- a/nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py +++ b/nipype/interfaces/camino/tests/test_auto_FSL2Scheme.py @@ -4,23 +4,58 @@ def test_FSL2Scheme_inputs(): input_map = dict( - args=dict(argstr="%s",), - bscale=dict(argstr="-bscale %d", units="NA",), + args=dict( + argstr="%s", + ), + bscale=dict( + argstr="-bscale %d", + units="NA", + ), bval_file=dict( - argstr="-bvalfile %s", extensions=None, mandatory=True, position=2, + argstr="-bvalfile %s", + extensions=None, + mandatory=True, + position=2, ), bvec_file=dict( - argstr="-bvecfile %s", extensions=None, mandatory=True, position=1, - ), - diffusiontime=dict(argstr="-diffusiontime %f", units="NA",), - environ=dict(nohash=True, usedefault=True,), - flipx=dict(argstr="-flipx",), - flipy=dict(argstr="-flipy",), - flipz=dict(argstr="-flipz",), - interleave=dict(argstr="-interleave",), - numscans=dict(argstr="-numscans %d", units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - usegradmod=dict(argstr="-usegradmod",), + argstr="-bvecfile %s", + extensions=None, + mandatory=True, + position=1, + ), + diffusiontime=dict( + argstr="-diffusiontime %f", + units="NA", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flipx=dict( + argstr="-flipx", + ), + flipy=dict( + argstr="-flipy", + ), + flipz=dict( + argstr="-flipz", + ), + interleave=dict( + argstr="-interleave", + ), + numscans=dict( + argstr="-numscans %d", + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + usegradmod=dict( + argstr="-usegradmod", + ), ) inputs = FSL2Scheme.input_spec() @@ -30,7 +65,11 @@ def test_FSL2Scheme_inputs(): def test_FSL2Scheme_outputs(): - output_map = dict(scheme=dict(extensions=None,),) + output_map = dict( + scheme=dict( + extensions=None, + ), + ) outputs = FSL2Scheme.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_Image2Voxel.py b/nipype/interfaces/camino/tests/test_auto_Image2Voxel.py index 47379c7f54..ae49936d02 100644 --- a/nipype/interfaces/camino/tests/test_auto_Image2Voxel.py +++ b/nipype/interfaces/camino/tests/test_auto_Image2Voxel.py @@ -4,13 +4,30 @@ def test_Image2Voxel_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="-4dimage %s", extensions=None, mandatory=True, position=1, + argstr="-4dimage %s", + extensions=None, + mandatory=True, + position=1, + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + out_type=dict( + argstr="-outputdatatype %s", + position=2, + usedefault=True, ), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - out_type=dict(argstr="-outputdatatype %s", position=2, usedefault=True,), ) inputs = Image2Voxel.input_spec() @@ -20,7 +37,11 @@ def test_Image2Voxel_inputs(): def test_Image2Voxel_outputs(): - output_map = dict(voxel_order=dict(extensions=None,),) + output_map = dict( + voxel_order=dict( + extensions=None, + ), + ) outputs = Image2Voxel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ImageStats.py b/nipype/interfaces/camino/tests/test_auto_ImageStats.py index 9d817f4ca9..4bc6aa941b 100644 --- a/nipype/interfaces/camino/tests/test_auto_ImageStats.py +++ b/nipype/interfaces/camino/tests/test_auto_ImageStats.py @@ -4,12 +4,32 @@ def test_ImageStats_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="-images %s", mandatory=True, position=-1,), - out_type=dict(argstr="-outputdatatype %s", usedefault=True,), - output_root=dict(argstr="-outputroot %s", extensions=None, mandatory=True,), - stat=dict(argstr="-stat %s", mandatory=True, units="NA",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="-images %s", + mandatory=True, + position=-1, + ), + out_type=dict( + argstr="-outputdatatype %s", + usedefault=True, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + mandatory=True, + ), + stat=dict( + argstr="-stat %s", + mandatory=True, + units="NA", + ), ) inputs = ImageStats.input_spec() @@ -19,7 +39,11 @@ def test_ImageStats_inputs(): def test_ImageStats_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ImageStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_LinRecon.py b/nipype/interfaces/camino/tests/test_auto_LinRecon.py index a8a7731b70..1ed5bbbe6b 100644 --- a/nipype/interfaces/camino/tests/test_auto_LinRecon.py +++ b/nipype/interfaces/camino/tests/test_auto_LinRecon.py @@ -4,15 +4,47 @@ def test_LinRecon_inputs(): input_map = dict( - args=dict(argstr="%s",), - bgmask=dict(argstr="-bgmask %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - log=dict(argstr="-log",), - normalize=dict(argstr="-normalize",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - qball_mat=dict(argstr="%s", extensions=None, mandatory=True, position=3,), - scheme_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + bgmask=dict( + argstr="-bgmask %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + log=dict( + argstr="-log", + ), + normalize=dict( + argstr="-normalize", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + qball_mat=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=3, + ), + scheme_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), ) inputs = LinRecon.input_spec() @@ -22,7 +54,11 @@ def test_LinRecon_inputs(): def test_LinRecon_outputs(): - output_map = dict(recon_data=dict(extensions=None,),) + output_map = dict( + recon_data=dict( + extensions=None, + ), + ) outputs = LinRecon.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_MESD.py b/nipype/interfaces/camino/tests/test_auto_MESD.py index dd91241d0a..189dd2e2d4 100644 --- a/nipype/interfaces/camino/tests/test_auto_MESD.py +++ b/nipype/interfaces/camino/tests/test_auto_MESD.py @@ -4,19 +4,56 @@ def test_MESD_inputs(): input_map = dict( - args=dict(argstr="%s",), - bgmask=dict(argstr="-bgmask %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - fastmesd=dict(argstr="-fastmesd", requires=["mepointset"],), + args=dict( + argstr="%s", + ), + bgmask=dict( + argstr="-bgmask %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fastmesd=dict( + argstr="-fastmesd", + requires=["mepointset"], + ), in_file=dict( - argstr="-inputfile %s", extensions=None, mandatory=True, position=1, - ), - inputdatatype=dict(argstr="-inputdatatype %s",), - inverter=dict(argstr="-filter %s", mandatory=True, position=2,), - inverter_param=dict(argstr="%f", mandatory=True, position=3, units="NA",), - mepointset=dict(argstr="-mepointset %d", units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - scheme_file=dict(argstr="-schemefile %s", extensions=None, mandatory=True,), + argstr="-inputfile %s", + extensions=None, + mandatory=True, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inverter=dict( + argstr="-filter %s", + mandatory=True, + position=2, + ), + inverter_param=dict( + argstr="%f", + mandatory=True, + position=3, + units="NA", + ), + mepointset=dict( + argstr="-mepointset %d", + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + scheme_file=dict( + argstr="-schemefile %s", + extensions=None, + mandatory=True, + ), ) inputs = MESD.input_spec() @@ -26,7 +63,11 @@ def test_MESD_inputs(): def test_MESD_outputs(): - output_map = dict(mesd_data=dict(extensions=None,),) + output_map = dict( + mesd_data=dict( + extensions=None, + ), + ) outputs = MESD.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ModelFit.py b/nipype/interfaces/camino/tests/test_auto_ModelFit.py index ca5ba4a9d6..82bd1a8400 100644 --- a/nipype/interfaces/camino/tests/test_auto_ModelFit.py +++ b/nipype/interfaces/camino/tests/test_auto_ModelFit.py @@ -4,24 +4,74 @@ def test_ModelFit_inputs(): input_map = dict( - args=dict(argstr="%s",), - bgmask=dict(argstr="-bgmask %s", extensions=None,), - bgthresh=dict(argstr="-bgthresh %G",), - cfthresh=dict(argstr="-csfthresh %G",), - environ=dict(nohash=True, usedefault=True,), - fixedbvalue=dict(argstr="-fixedbvalue %s",), - fixedmodq=dict(argstr="-fixedmod %s",), - in_file=dict(argstr="-inputfile %s", extensions=None, mandatory=True,), - inputdatatype=dict(argstr="-inputdatatype %s",), - model=dict(argstr="-model %s", mandatory=True,), - noisemap=dict(argstr="-noisemap %s", extensions=None,), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - outlier=dict(argstr="-outliermap %s", extensions=None,), - outputfile=dict(argstr="-outputfile %s", extensions=None,), - residualmap=dict(argstr="-residualmap %s", extensions=None,), - scheme_file=dict(argstr="-schemefile %s", extensions=None, mandatory=True,), - sigma=dict(argstr="-sigma %G",), - tau=dict(argstr="-tau %G",), + args=dict( + argstr="%s", + ), + bgmask=dict( + argstr="-bgmask %s", + extensions=None, + ), + bgthresh=dict( + argstr="-bgthresh %G", + ), + cfthresh=dict( + argstr="-csfthresh %G", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedbvalue=dict( + argstr="-fixedbvalue %s", + ), + fixedmodq=dict( + argstr="-fixedmod %s", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + mandatory=True, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + model=dict( + argstr="-model %s", + mandatory=True, + ), + noisemap=dict( + argstr="-noisemap %s", + extensions=None, + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + outlier=dict( + argstr="-outliermap %s", + extensions=None, + ), + outputfile=dict( + argstr="-outputfile %s", + extensions=None, + ), + residualmap=dict( + argstr="-residualmap %s", + extensions=None, + ), + scheme_file=dict( + argstr="-schemefile %s", + extensions=None, + mandatory=True, + ), + sigma=dict( + argstr="-sigma %G", + ), + tau=dict( + argstr="-tau %G", + ), ) inputs = ModelFit.input_spec() @@ -31,7 +81,11 @@ def test_ModelFit_inputs(): def test_ModelFit_outputs(): - output_map = dict(fitted_data=dict(extensions=None,),) + output_map = dict( + fitted_data=dict( + extensions=None, + ), + ) outputs = ModelFit.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_NIfTIDT2Camino.py b/nipype/interfaces/camino/tests/test_auto_NIfTIDT2Camino.py index 951e4bdc0e..82b4276a0f 100644 --- a/nipype/interfaces/camino/tests/test_auto_NIfTIDT2Camino.py +++ b/nipype/interfaces/camino/tests/test_auto_NIfTIDT2Camino.py @@ -4,18 +4,46 @@ def test_NIfTIDT2Camino_inputs(): input_map = dict( - args=dict(argstr="%s",), - bgmask=dict(argstr="-bgmask %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + bgmask=dict( + argstr="-bgmask %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="-inputfile %s", extensions=None, mandatory=True, position=1, - ), - lns0_file=dict(argstr="-lns0 %s", extensions=None,), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - s0_file=dict(argstr="-s0 %s", extensions=None,), - scaleinter=dict(argstr="-scaleinter %s",), - scaleslope=dict(argstr="-scaleslope %s",), - uppertriangular=dict(argstr="-uppertriangular %s",), + argstr="-inputfile %s", + extensions=None, + mandatory=True, + position=1, + ), + lns0_file=dict( + argstr="-lns0 %s", + extensions=None, + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + s0_file=dict( + argstr="-s0 %s", + extensions=None, + ), + scaleinter=dict( + argstr="-scaleinter %s", + ), + scaleslope=dict( + argstr="-scaleslope %s", + ), + uppertriangular=dict( + argstr="-uppertriangular %s", + ), ) inputs = NIfTIDT2Camino.input_spec() @@ -25,7 +53,11 @@ def test_NIfTIDT2Camino_inputs(): def test_NIfTIDT2Camino_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = NIfTIDT2Camino.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_PicoPDFs.py b/nipype/interfaces/camino/tests/test_auto_PicoPDFs.py index 5a321dddba..09f3a93cac 100644 --- a/nipype/interfaces/camino/tests/test_auto_PicoPDFs.py +++ b/nipype/interfaces/camino/tests/test_auto_PicoPDFs.py @@ -4,16 +4,50 @@ def test_PicoPDFs_inputs(): input_map = dict( - args=dict(argstr="%s",), - directmap=dict(argstr="-directmap",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="< %s", extensions=None, mandatory=True, position=1,), - inputmodel=dict(argstr="-inputmodel %s", position=2, usedefault=True,), - luts=dict(argstr="-luts %s", mandatory=True,), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - pdf=dict(argstr="-pdf %s", position=4, usedefault=True,), + args=dict( + argstr="%s", + ), + directmap=dict( + argstr="-directmap", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="< %s", + extensions=None, + mandatory=True, + position=1, + ), + inputmodel=dict( + argstr="-inputmodel %s", + position=2, + usedefault=True, + ), + luts=dict( + argstr="-luts %s", + mandatory=True, + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + pdf=dict( + argstr="-pdf %s", + position=4, + usedefault=True, + ), ) inputs = PicoPDFs.input_spec() @@ -23,7 +57,11 @@ def test_PicoPDFs_inputs(): def test_PicoPDFs_outputs(): - output_map = dict(pdfs=dict(extensions=None,),) + output_map = dict( + pdfs=dict( + extensions=None, + ), + ) outputs = PicoPDFs.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py b/nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py index 7ccd071c99..b1b9fda588 100644 --- a/nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py +++ b/nipype/interfaces/camino/tests/test_auto_ProcStreamlines.py @@ -4,44 +4,138 @@ def test_ProcStreamlines_inputs(): input_map = dict( - allowmultitargets=dict(argstr="-allowmultitargets",), - args=dict(argstr="%s",), - datadims=dict(argstr="-datadims %s", units="voxels",), - directional=dict(argstr="-directional %s", units="NA",), - discardloops=dict(argstr="-discardloops",), - endpointfile=dict(argstr="-endpointfile %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - exclusionfile=dict(argstr="-exclusionfile %s", extensions=None,), - gzip=dict(argstr="-gzip",), + allowmultitargets=dict( + argstr="-allowmultitargets", + ), + args=dict( + argstr="%s", + ), + datadims=dict( + argstr="-datadims %s", + units="voxels", + ), + directional=dict( + argstr="-directional %s", + units="NA", + ), + discardloops=dict( + argstr="-discardloops", + ), + endpointfile=dict( + argstr="-endpointfile %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + exclusionfile=dict( + argstr="-exclusionfile %s", + extensions=None, + ), + gzip=dict( + argstr="-gzip", + ), in_file=dict( - argstr="-inputfile %s", extensions=None, mandatory=True, position=1, - ), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - iterations=dict(argstr="-iterations %d", units="NA",), - maxtractlength=dict(argstr="-maxtractlength %d", units="mm",), - maxtractpoints=dict(argstr="-maxtractpoints %d", units="NA",), - mintractlength=dict(argstr="-mintractlength %d", units="mm",), - mintractpoints=dict(argstr="-mintractpoints %d", units="NA",), - noresample=dict(argstr="-noresample",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - outputacm=dict(argstr="-outputacm", requires=["outputroot", "seedfile"],), + argstr="-inputfile %s", + extensions=None, + mandatory=True, + position=1, + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + iterations=dict( + argstr="-iterations %d", + units="NA", + ), + maxtractlength=dict( + argstr="-maxtractlength %d", + units="mm", + ), + maxtractpoints=dict( + argstr="-maxtractpoints %d", + units="NA", + ), + mintractlength=dict( + argstr="-mintractlength %d", + units="mm", + ), + mintractpoints=dict( + argstr="-mintractpoints %d", + units="NA", + ), + noresample=dict( + argstr="-noresample", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + outputacm=dict( + argstr="-outputacm", + requires=["outputroot", "seedfile"], + ), outputcbs=dict( - argstr="-outputcbs", requires=["outputroot", "targetfile", "seedfile"], - ), - outputcp=dict(argstr="-outputcp", requires=["outputroot", "seedfile"],), - outputroot=dict(argstr="-outputroot %s", extensions=None,), - outputsc=dict(argstr="-outputsc", requires=["outputroot", "seedfile"],), - outputtracts=dict(argstr="-outputtracts",), - regionindex=dict(argstr="-regionindex %d", units="mm",), - resamplestepsize=dict(argstr="-resamplestepsize %d", units="NA",), - seedfile=dict(argstr="-seedfile %s", extensions=None,), - seedpointmm=dict(argstr="-seedpointmm %s", units="mm",), - seedpointvox=dict(argstr="-seedpointvox %s", units="voxels",), - targetfile=dict(argstr="-targetfile %s", extensions=None,), - truncateinexclusion=dict(argstr="-truncateinexclusion",), - truncateloops=dict(argstr="-truncateloops",), - voxeldims=dict(argstr="-voxeldims %s", units="mm",), - waypointfile=dict(argstr="-waypointfile %s", extensions=None,), + argstr="-outputcbs", + requires=["outputroot", "targetfile", "seedfile"], + ), + outputcp=dict( + argstr="-outputcp", + requires=["outputroot", "seedfile"], + ), + outputroot=dict( + argstr="-outputroot %s", + extensions=None, + ), + outputsc=dict( + argstr="-outputsc", + requires=["outputroot", "seedfile"], + ), + outputtracts=dict( + argstr="-outputtracts", + ), + regionindex=dict( + argstr="-regionindex %d", + units="mm", + ), + resamplestepsize=dict( + argstr="-resamplestepsize %d", + units="NA", + ), + seedfile=dict( + argstr="-seedfile %s", + extensions=None, + ), + seedpointmm=dict( + argstr="-seedpointmm %s", + units="mm", + ), + seedpointvox=dict( + argstr="-seedpointvox %s", + units="voxels", + ), + targetfile=dict( + argstr="-targetfile %s", + extensions=None, + ), + truncateinexclusion=dict( + argstr="-truncateinexclusion", + ), + truncateloops=dict( + argstr="-truncateloops", + ), + voxeldims=dict( + argstr="-voxeldims %s", + units="mm", + ), + waypointfile=dict( + argstr="-waypointfile %s", + extensions=None, + ), ) inputs = ProcStreamlines.input_spec() @@ -51,7 +145,12 @@ def test_ProcStreamlines_inputs(): def test_ProcStreamlines_outputs(): - output_map = dict(outputroot_files=dict(), proc=dict(extensions=None,),) + output_map = dict( + outputroot_files=dict(), + proc=dict( + extensions=None, + ), + ) outputs = ProcStreamlines.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_QBallMX.py b/nipype/interfaces/camino/tests/test_auto_QBallMX.py index 180e5c6f83..30fda3a483 100644 --- a/nipype/interfaces/camino/tests/test_auto_QBallMX.py +++ b/nipype/interfaces/camino/tests/test_auto_QBallMX.py @@ -4,15 +4,44 @@ def test_QBallMX_inputs(): input_map = dict( - args=dict(argstr="%s",), - basistype=dict(argstr="-basistype %s", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - order=dict(argstr="-order %d", units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - rbfpointset=dict(argstr="-rbfpointset %d", units="NA",), - rbfsigma=dict(argstr="-rbfsigma %f", units="NA",), - scheme_file=dict(argstr="-schemefile %s", extensions=None, mandatory=True,), - smoothingsigma=dict(argstr="-smoothingsigma %f", units="NA",), + args=dict( + argstr="%s", + ), + basistype=dict( + argstr="-basistype %s", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + order=dict( + argstr="-order %d", + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + rbfpointset=dict( + argstr="-rbfpointset %d", + units="NA", + ), + rbfsigma=dict( + argstr="-rbfsigma %f", + units="NA", + ), + scheme_file=dict( + argstr="-schemefile %s", + extensions=None, + mandatory=True, + ), + smoothingsigma=dict( + argstr="-smoothingsigma %f", + units="NA", + ), ) inputs = QBallMX.input_spec() @@ -22,7 +51,11 @@ def test_QBallMX_inputs(): def test_QBallMX_outputs(): - output_map = dict(qmat=dict(extensions=None,),) + output_map = dict( + qmat=dict( + extensions=None, + ), + ) outputs = QBallMX.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_SFLUTGen.py b/nipype/interfaces/camino/tests/test_auto_SFLUTGen.py index 96dd1c2e5e..fc58b2f2e9 100644 --- a/nipype/interfaces/camino/tests/test_auto_SFLUTGen.py +++ b/nipype/interfaces/camino/tests/test_auto_SFLUTGen.py @@ -4,17 +4,52 @@ def test_SFLUTGen_inputs(): input_map = dict( - args=dict(argstr="%s",), - binincsize=dict(argstr="-binincsize %d", units="NA",), - directmap=dict(argstr="-directmap",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-inputfile %s", extensions=None, mandatory=True,), - info_file=dict(argstr="-infofile %s", extensions=None, mandatory=True,), - minvectsperbin=dict(argstr="-minvectsperbin %d", units="NA",), - order=dict(argstr="-order %d", units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - outputstem=dict(argstr="-outputstem %s", usedefault=True,), - pdf=dict(argstr="-pdf %s", usedefault=True,), + args=dict( + argstr="%s", + ), + binincsize=dict( + argstr="-binincsize %d", + units="NA", + ), + directmap=dict( + argstr="-directmap", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + mandatory=True, + ), + info_file=dict( + argstr="-infofile %s", + extensions=None, + mandatory=True, + ), + minvectsperbin=dict( + argstr="-minvectsperbin %d", + units="NA", + ), + order=dict( + argstr="-order %d", + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + outputstem=dict( + argstr="-outputstem %s", + usedefault=True, + ), + pdf=dict( + argstr="-pdf %s", + usedefault=True, + ), ) inputs = SFLUTGen.input_spec() @@ -25,7 +60,12 @@ def test_SFLUTGen_inputs(): def test_SFLUTGen_outputs(): output_map = dict( - lut_one_fibre=dict(extensions=None,), lut_two_fibres=dict(extensions=None,), + lut_one_fibre=dict( + extensions=None, + ), + lut_two_fibres=dict( + extensions=None, + ), ) outputs = SFLUTGen.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_SFPICOCalibData.py b/nipype/interfaces/camino/tests/test_auto_SFPICOCalibData.py index b6a032e66d..5c20399cbc 100644 --- a/nipype/interfaces/camino/tests/test_auto_SFPICOCalibData.py +++ b/nipype/interfaces/camino/tests/test_auto_SFPICOCalibData.py @@ -4,8 +4,13 @@ def test_SFPICOCalibData_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), info_file=dict( argstr="-infooutputfile %s", extensions=None, @@ -13,19 +18,61 @@ def test_SFPICOCalibData_inputs(): hash_files=False, mandatory=True, ), - onedtfarange=dict(argstr="-onedtfarange %s", units="NA",), - onedtfastep=dict(argstr="-onedtfastep %f", units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - scheme_file=dict(argstr="-schemefile %s", extensions=None, mandatory=True,), - seed=dict(argstr="-seed %f", units="NA",), - snr=dict(argstr="-snr %f", units="NA",), - trace=dict(argstr="-trace %f", units="NA",), - twodtanglerange=dict(argstr="-twodtanglerange %s", units="NA",), - twodtanglestep=dict(argstr="-twodtanglestep %f", units="NA",), - twodtfarange=dict(argstr="-twodtfarange %s", units="NA",), - twodtfastep=dict(argstr="-twodtfastep %f", units="NA",), - twodtmixmax=dict(argstr="-twodtmixmax %f", units="NA",), - twodtmixstep=dict(argstr="-twodtmixstep %f", units="NA",), + onedtfarange=dict( + argstr="-onedtfarange %s", + units="NA", + ), + onedtfastep=dict( + argstr="-onedtfastep %f", + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + scheme_file=dict( + argstr="-schemefile %s", + extensions=None, + mandatory=True, + ), + seed=dict( + argstr="-seed %f", + units="NA", + ), + snr=dict( + argstr="-snr %f", + units="NA", + ), + trace=dict( + argstr="-trace %f", + units="NA", + ), + twodtanglerange=dict( + argstr="-twodtanglerange %s", + units="NA", + ), + twodtanglestep=dict( + argstr="-twodtanglestep %f", + units="NA", + ), + twodtfarange=dict( + argstr="-twodtfarange %s", + units="NA", + ), + twodtfastep=dict( + argstr="-twodtfastep %f", + units="NA", + ), + twodtmixmax=dict( + argstr="-twodtmixmax %f", + units="NA", + ), + twodtmixstep=dict( + argstr="-twodtmixstep %f", + units="NA", + ), ) inputs = SFPICOCalibData.input_spec() @@ -36,7 +83,12 @@ def test_SFPICOCalibData_inputs(): def test_SFPICOCalibData_outputs(): output_map = dict( - PICOCalib=dict(extensions=None,), calib_info=dict(extensions=None,), + PICOCalib=dict( + extensions=None, + ), + calib_info=dict( + extensions=None, + ), ) outputs = SFPICOCalibData.output_spec() diff --git a/nipype/interfaces/camino/tests/test_auto_SFPeaks.py b/nipype/interfaces/camino/tests/test_auto_SFPeaks.py index 8012e56d5d..775a9061e6 100644 --- a/nipype/interfaces/camino/tests/test_auto_SFPeaks.py +++ b/nipype/interfaces/camino/tests/test_auto_SFPeaks.py @@ -4,22 +4,71 @@ def test_SFPeaks_inputs(): input_map = dict( - args=dict(argstr="%s",), - density=dict(argstr="-density %d", units="NA",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-inputfile %s", extensions=None, mandatory=True,), - inputmodel=dict(argstr="-inputmodel %s", mandatory=True,), - mepointset=dict(argstr="-mepointset %d", units="NA",), - noconsistencycheck=dict(argstr="-noconsistencycheck",), - numpds=dict(argstr="-numpds %d", units="NA",), - order=dict(argstr="-order %d", units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - pdthresh=dict(argstr="-pdthresh %f", units="NA",), - pointset=dict(argstr="-pointset %d", units="NA",), - rbfpointset=dict(argstr="-rbfpointset %d", units="NA",), - scheme_file=dict(argstr="%s", extensions=None,), - searchradius=dict(argstr="-searchradius %f", units="NA",), - stdsfrommean=dict(argstr="-stdsfrommean %f", units="NA",), + args=dict( + argstr="%s", + ), + density=dict( + argstr="-density %d", + units="NA", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + mandatory=True, + ), + inputmodel=dict( + argstr="-inputmodel %s", + mandatory=True, + ), + mepointset=dict( + argstr="-mepointset %d", + units="NA", + ), + noconsistencycheck=dict( + argstr="-noconsistencycheck", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), + order=dict( + argstr="-order %d", + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + pdthresh=dict( + argstr="-pdthresh %f", + units="NA", + ), + pointset=dict( + argstr="-pointset %d", + units="NA", + ), + rbfpointset=dict( + argstr="-rbfpointset %d", + units="NA", + ), + scheme_file=dict( + argstr="%s", + extensions=None, + ), + searchradius=dict( + argstr="-searchradius %f", + units="NA", + ), + stdsfrommean=dict( + argstr="-stdsfrommean %f", + units="NA", + ), ) inputs = SFPeaks.input_spec() @@ -29,7 +78,11 @@ def test_SFPeaks_inputs(): def test_SFPeaks_outputs(): - output_map = dict(peaks=dict(extensions=None,),) + output_map = dict( + peaks=dict( + extensions=None, + ), + ) outputs = SFPeaks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_Shredder.py b/nipype/interfaces/camino/tests/test_auto_Shredder.py index c7e82afbad..bf0f9dc9dc 100644 --- a/nipype/interfaces/camino/tests/test_auto_Shredder.py +++ b/nipype/interfaces/camino/tests/test_auto_Shredder.py @@ -4,13 +4,40 @@ def test_Shredder_inputs(): input_map = dict( - args=dict(argstr="%s",), - chunksize=dict(argstr="%d", position=2, units="NA",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="< %s", extensions=None, mandatory=True, position=-2,), - offset=dict(argstr="%d", position=1, units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - space=dict(argstr="%d", position=3, units="NA",), + args=dict( + argstr="%s", + ), + chunksize=dict( + argstr="%d", + position=2, + units="NA", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="< %s", + extensions=None, + mandatory=True, + position=-2, + ), + offset=dict( + argstr="%d", + position=1, + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + space=dict( + argstr="%d", + position=3, + units="NA", + ), ) inputs = Shredder.input_spec() @@ -20,7 +47,11 @@ def test_Shredder_inputs(): def test_Shredder_outputs(): - output_map = dict(shredded=dict(extensions=None,),) + output_map = dict( + shredded=dict( + extensions=None, + ), + ) outputs = Shredder.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_Track.py b/nipype/interfaces/camino/tests/test_auto_Track.py index 99f42e95c7..697b2d5275 100644 --- a/nipype/interfaces/camino/tests/test_auto_Track.py +++ b/nipype/interfaces/camino/tests/test_auto_Track.py @@ -4,30 +4,91 @@ def test_Track_inputs(): input_map = dict( - anisfile=dict(argstr="-anisfile %s", extensions=None,), - anisthresh=dict(argstr="-anisthresh %f",), - args=dict(argstr="%s",), - curveinterval=dict(argstr="-curveinterval %f", requires=["curvethresh"],), - curvethresh=dict(argstr="-curvethresh %f",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - environ=dict(nohash=True, usedefault=True,), - gzip=dict(argstr="-gzip",), - in_file=dict(argstr="-inputfile %s", extensions=None, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolator=dict(argstr="-interpolator %s",), - ipthresh=dict(argstr="-ipthresh %f",), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), + anisfile=dict( + argstr="-anisfile %s", + extensions=None, + ), + anisthresh=dict( + argstr="-anisthresh %f", + ), + args=dict( + argstr="%s", + ), + curveinterval=dict( + argstr="-curveinterval %f", + requires=["curvethresh"], + ), + curvethresh=dict( + argstr="-curvethresh %f", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict( + argstr="-gzip", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolator=dict( + argstr="-interpolator %s", + ), + ipthresh=dict( + argstr="-ipthresh %f", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), out_file=dict( - argstr="-outputfile %s", extensions=None, genfile=True, position=-1, - ), - output_root=dict(argstr="-outputroot %s", extensions=None, position=-1,), - outputtracts=dict(argstr="-outputtracts %s",), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=2,), - stepsize=dict(argstr="-stepsize %f", requires=["tracker"],), - tracker=dict(argstr="-tracker %s", usedefault=True,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-outputfile %s", + extensions=None, + genfile=True, + position=-1, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + position=-1, + ), + outputtracts=dict( + argstr="-outputtracts %s", + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=2, + ), + stepsize=dict( + argstr="-stepsize %f", + requires=["tracker"], + ), + tracker=dict( + argstr="-tracker %s", + usedefault=True, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = Track.input_spec() @@ -37,7 +98,11 @@ def test_Track_inputs(): def test_Track_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = Track.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBallStick.py b/nipype/interfaces/camino/tests/test_auto_TrackBallStick.py index ff13fbe241..a117d5d782 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBallStick.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBallStick.py @@ -4,30 +4,91 @@ def test_TrackBallStick_inputs(): input_map = dict( - anisfile=dict(argstr="-anisfile %s", extensions=None,), - anisthresh=dict(argstr="-anisthresh %f",), - args=dict(argstr="%s",), - curveinterval=dict(argstr="-curveinterval %f", requires=["curvethresh"],), - curvethresh=dict(argstr="-curvethresh %f",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - environ=dict(nohash=True, usedefault=True,), - gzip=dict(argstr="-gzip",), - in_file=dict(argstr="-inputfile %s", extensions=None, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolator=dict(argstr="-interpolator %s",), - ipthresh=dict(argstr="-ipthresh %f",), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), + anisfile=dict( + argstr="-anisfile %s", + extensions=None, + ), + anisthresh=dict( + argstr="-anisthresh %f", + ), + args=dict( + argstr="%s", + ), + curveinterval=dict( + argstr="-curveinterval %f", + requires=["curvethresh"], + ), + curvethresh=dict( + argstr="-curvethresh %f", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict( + argstr="-gzip", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolator=dict( + argstr="-interpolator %s", + ), + ipthresh=dict( + argstr="-ipthresh %f", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), out_file=dict( - argstr="-outputfile %s", extensions=None, genfile=True, position=-1, - ), - output_root=dict(argstr="-outputroot %s", extensions=None, position=-1,), - outputtracts=dict(argstr="-outputtracts %s",), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=2,), - stepsize=dict(argstr="-stepsize %f", requires=["tracker"],), - tracker=dict(argstr="-tracker %s", usedefault=True,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-outputfile %s", + extensions=None, + genfile=True, + position=-1, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + position=-1, + ), + outputtracts=dict( + argstr="-outputtracts %s", + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=2, + ), + stepsize=dict( + argstr="-stepsize %f", + requires=["tracker"], + ), + tracker=dict( + argstr="-tracker %s", + usedefault=True, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = TrackBallStick.input_spec() @@ -37,7 +98,11 @@ def test_TrackBallStick_inputs(): def test_TrackBallStick_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = TrackBallStick.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBayesDirac.py b/nipype/interfaces/camino/tests/test_auto_TrackBayesDirac.py index 7f174486d5..56ca8ece97 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBayesDirac.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBayesDirac.py @@ -4,39 +4,122 @@ def test_TrackBayesDirac_inputs(): input_map = dict( - anisfile=dict(argstr="-anisfile %s", extensions=None,), - anisthresh=dict(argstr="-anisthresh %f",), - args=dict(argstr="%s",), - curveinterval=dict(argstr="-curveinterval %f", requires=["curvethresh"],), - curvepriorg=dict(argstr="-curvepriorg %G",), - curvepriork=dict(argstr="-curvepriork %G",), - curvethresh=dict(argstr="-curvethresh %f",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - datamodel=dict(argstr="-datamodel %s",), - environ=dict(nohash=True, usedefault=True,), - extpriordatatype=dict(argstr="-extpriordatatype %s",), - extpriorfile=dict(argstr="-extpriorfile %s", extensions=None,), - gzip=dict(argstr="-gzip",), - in_file=dict(argstr="-inputfile %s", extensions=None, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolator=dict(argstr="-interpolator %s",), - ipthresh=dict(argstr="-ipthresh %f",), - iterations=dict(argstr="-iterations %d", units="NA",), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), + anisfile=dict( + argstr="-anisfile %s", + extensions=None, + ), + anisthresh=dict( + argstr="-anisthresh %f", + ), + args=dict( + argstr="%s", + ), + curveinterval=dict( + argstr="-curveinterval %f", + requires=["curvethresh"], + ), + curvepriorg=dict( + argstr="-curvepriorg %G", + ), + curvepriork=dict( + argstr="-curvepriork %G", + ), + curvethresh=dict( + argstr="-curvethresh %f", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + datamodel=dict( + argstr="-datamodel %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extpriordatatype=dict( + argstr="-extpriordatatype %s", + ), + extpriorfile=dict( + argstr="-extpriorfile %s", + extensions=None, + ), + gzip=dict( + argstr="-gzip", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolator=dict( + argstr="-interpolator %s", + ), + ipthresh=dict( + argstr="-ipthresh %f", + ), + iterations=dict( + argstr="-iterations %d", + units="NA", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), out_file=dict( - argstr="-outputfile %s", extensions=None, genfile=True, position=-1, - ), - output_root=dict(argstr="-outputroot %s", extensions=None, position=-1,), - outputtracts=dict(argstr="-outputtracts %s",), - pdf=dict(argstr="-pdf %s",), - pointset=dict(argstr="-pointset %s",), - scheme_file=dict(argstr="-schemefile %s", extensions=None, mandatory=True,), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=2,), - stepsize=dict(argstr="-stepsize %f", requires=["tracker"],), - tracker=dict(argstr="-tracker %s", usedefault=True,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-outputfile %s", + extensions=None, + genfile=True, + position=-1, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + position=-1, + ), + outputtracts=dict( + argstr="-outputtracts %s", + ), + pdf=dict( + argstr="-pdf %s", + ), + pointset=dict( + argstr="-pointset %s", + ), + scheme_file=dict( + argstr="-schemefile %s", + extensions=None, + mandatory=True, + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=2, + ), + stepsize=dict( + argstr="-stepsize %f", + requires=["tracker"], + ), + tracker=dict( + argstr="-tracker %s", + usedefault=True, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = TrackBayesDirac.input_spec() @@ -46,7 +129,11 @@ def test_TrackBayesDirac_inputs(): def test_TrackBayesDirac_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = TrackBayesDirac.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBedpostxDeter.py b/nipype/interfaces/camino/tests/test_auto_TrackBedpostxDeter.py index 91489a1d84..dbd8f89478 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBedpostxDeter.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBedpostxDeter.py @@ -4,32 +4,99 @@ def test_TrackBedpostxDeter_inputs(): input_map = dict( - anisfile=dict(argstr="-anisfile %s", extensions=None,), - anisthresh=dict(argstr="-anisthresh %f",), - args=dict(argstr="%s",), - bedpostxdir=dict(argstr="-bedpostxdir %s", mandatory=True,), - curveinterval=dict(argstr="-curveinterval %f", requires=["curvethresh"],), - curvethresh=dict(argstr="-curvethresh %f",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - environ=dict(nohash=True, usedefault=True,), - gzip=dict(argstr="-gzip",), - in_file=dict(argstr="-inputfile %s", extensions=None, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolator=dict(argstr="-interpolator %s",), - ipthresh=dict(argstr="-ipthresh %f",), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - min_vol_frac=dict(argstr="-bedpostxminf %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), + anisfile=dict( + argstr="-anisfile %s", + extensions=None, + ), + anisthresh=dict( + argstr="-anisthresh %f", + ), + args=dict( + argstr="%s", + ), + bedpostxdir=dict( + argstr="-bedpostxdir %s", + mandatory=True, + ), + curveinterval=dict( + argstr="-curveinterval %f", + requires=["curvethresh"], + ), + curvethresh=dict( + argstr="-curvethresh %f", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict( + argstr="-gzip", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolator=dict( + argstr="-interpolator %s", + ), + ipthresh=dict( + argstr="-ipthresh %f", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + min_vol_frac=dict( + argstr="-bedpostxminf %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), out_file=dict( - argstr="-outputfile %s", extensions=None, genfile=True, position=-1, - ), - output_root=dict(argstr="-outputroot %s", extensions=None, position=-1,), - outputtracts=dict(argstr="-outputtracts %s",), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=2,), - stepsize=dict(argstr="-stepsize %f", requires=["tracker"],), - tracker=dict(argstr="-tracker %s", usedefault=True,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-outputfile %s", + extensions=None, + genfile=True, + position=-1, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + position=-1, + ), + outputtracts=dict( + argstr="-outputtracts %s", + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=2, + ), + stepsize=dict( + argstr="-stepsize %f", + requires=["tracker"], + ), + tracker=dict( + argstr="-tracker %s", + usedefault=True, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = TrackBedpostxDeter.input_spec() @@ -39,7 +106,11 @@ def test_TrackBedpostxDeter_inputs(): def test_TrackBedpostxDeter_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = TrackBedpostxDeter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBedpostxProba.py b/nipype/interfaces/camino/tests/test_auto_TrackBedpostxProba.py index 92f02879da..7d1baa0e43 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBedpostxProba.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBedpostxProba.py @@ -4,33 +4,103 @@ def test_TrackBedpostxProba_inputs(): input_map = dict( - anisfile=dict(argstr="-anisfile %s", extensions=None,), - anisthresh=dict(argstr="-anisthresh %f",), - args=dict(argstr="%s",), - bedpostxdir=dict(argstr="-bedpostxdir %s", mandatory=True,), - curveinterval=dict(argstr="-curveinterval %f", requires=["curvethresh"],), - curvethresh=dict(argstr="-curvethresh %f",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - environ=dict(nohash=True, usedefault=True,), - gzip=dict(argstr="-gzip",), - in_file=dict(argstr="-inputfile %s", extensions=None, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolator=dict(argstr="-interpolator %s",), - ipthresh=dict(argstr="-ipthresh %f",), - iterations=dict(argstr="-iterations %d", units="NA",), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - min_vol_frac=dict(argstr="-bedpostxminf %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), + anisfile=dict( + argstr="-anisfile %s", + extensions=None, + ), + anisthresh=dict( + argstr="-anisthresh %f", + ), + args=dict( + argstr="%s", + ), + bedpostxdir=dict( + argstr="-bedpostxdir %s", + mandatory=True, + ), + curveinterval=dict( + argstr="-curveinterval %f", + requires=["curvethresh"], + ), + curvethresh=dict( + argstr="-curvethresh %f", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict( + argstr="-gzip", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolator=dict( + argstr="-interpolator %s", + ), + ipthresh=dict( + argstr="-ipthresh %f", + ), + iterations=dict( + argstr="-iterations %d", + units="NA", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + min_vol_frac=dict( + argstr="-bedpostxminf %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), out_file=dict( - argstr="-outputfile %s", extensions=None, genfile=True, position=-1, - ), - output_root=dict(argstr="-outputroot %s", extensions=None, position=-1,), - outputtracts=dict(argstr="-outputtracts %s",), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=2,), - stepsize=dict(argstr="-stepsize %f", requires=["tracker"],), - tracker=dict(argstr="-tracker %s", usedefault=True,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-outputfile %s", + extensions=None, + genfile=True, + position=-1, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + position=-1, + ), + outputtracts=dict( + argstr="-outputtracts %s", + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=2, + ), + stepsize=dict( + argstr="-stepsize %f", + requires=["tracker"], + ), + tracker=dict( + argstr="-tracker %s", + usedefault=True, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = TrackBedpostxProba.input_spec() @@ -40,7 +110,11 @@ def test_TrackBedpostxProba_inputs(): def test_TrackBedpostxProba_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = TrackBedpostxProba.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackBootstrap.py b/nipype/interfaces/camino/tests/test_auto_TrackBootstrap.py index 8cd35bab8a..75cd2e3d11 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackBootstrap.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackBootstrap.py @@ -4,35 +4,111 @@ def test_TrackBootstrap_inputs(): input_map = dict( - anisfile=dict(argstr="-anisfile %s", extensions=None,), - anisthresh=dict(argstr="-anisthresh %f",), - args=dict(argstr="%s",), - bgmask=dict(argstr="-bgmask %s", extensions=None,), - bsdatafiles=dict(argstr="-bsdatafile %s", mandatory=True,), - curveinterval=dict(argstr="-curveinterval %f", requires=["curvethresh"],), - curvethresh=dict(argstr="-curvethresh %f",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - environ=dict(nohash=True, usedefault=True,), - gzip=dict(argstr="-gzip",), - in_file=dict(argstr="-inputfile %s", extensions=None, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolator=dict(argstr="-interpolator %s",), - inversion=dict(argstr="-inversion %s",), - ipthresh=dict(argstr="-ipthresh %f",), - iterations=dict(argstr="-iterations %d", units="NA",), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), + anisfile=dict( + argstr="-anisfile %s", + extensions=None, + ), + anisthresh=dict( + argstr="-anisthresh %f", + ), + args=dict( + argstr="%s", + ), + bgmask=dict( + argstr="-bgmask %s", + extensions=None, + ), + bsdatafiles=dict( + argstr="-bsdatafile %s", + mandatory=True, + ), + curveinterval=dict( + argstr="-curveinterval %f", + requires=["curvethresh"], + ), + curvethresh=dict( + argstr="-curvethresh %f", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict( + argstr="-gzip", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolator=dict( + argstr="-interpolator %s", + ), + inversion=dict( + argstr="-inversion %s", + ), + ipthresh=dict( + argstr="-ipthresh %f", + ), + iterations=dict( + argstr="-iterations %d", + units="NA", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), out_file=dict( - argstr="-outputfile %s", extensions=None, genfile=True, position=-1, - ), - output_root=dict(argstr="-outputroot %s", extensions=None, position=-1,), - outputtracts=dict(argstr="-outputtracts %s",), - scheme_file=dict(argstr="-schemefile %s", extensions=None, mandatory=True,), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=2,), - stepsize=dict(argstr="-stepsize %f", requires=["tracker"],), - tracker=dict(argstr="-tracker %s", usedefault=True,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-outputfile %s", + extensions=None, + genfile=True, + position=-1, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + position=-1, + ), + outputtracts=dict( + argstr="-outputtracts %s", + ), + scheme_file=dict( + argstr="-schemefile %s", + extensions=None, + mandatory=True, + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=2, + ), + stepsize=dict( + argstr="-stepsize %f", + requires=["tracker"], + ), + tracker=dict( + argstr="-tracker %s", + usedefault=True, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = TrackBootstrap.input_spec() @@ -42,7 +118,11 @@ def test_TrackBootstrap_inputs(): def test_TrackBootstrap_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = TrackBootstrap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackDT.py b/nipype/interfaces/camino/tests/test_auto_TrackDT.py index 736dc5fc5f..c60ba7b5f5 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackDT.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackDT.py @@ -4,30 +4,91 @@ def test_TrackDT_inputs(): input_map = dict( - anisfile=dict(argstr="-anisfile %s", extensions=None,), - anisthresh=dict(argstr="-anisthresh %f",), - args=dict(argstr="%s",), - curveinterval=dict(argstr="-curveinterval %f", requires=["curvethresh"],), - curvethresh=dict(argstr="-curvethresh %f",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - environ=dict(nohash=True, usedefault=True,), - gzip=dict(argstr="-gzip",), - in_file=dict(argstr="-inputfile %s", extensions=None, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolator=dict(argstr="-interpolator %s",), - ipthresh=dict(argstr="-ipthresh %f",), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), + anisfile=dict( + argstr="-anisfile %s", + extensions=None, + ), + anisthresh=dict( + argstr="-anisthresh %f", + ), + args=dict( + argstr="%s", + ), + curveinterval=dict( + argstr="-curveinterval %f", + requires=["curvethresh"], + ), + curvethresh=dict( + argstr="-curvethresh %f", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict( + argstr="-gzip", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolator=dict( + argstr="-interpolator %s", + ), + ipthresh=dict( + argstr="-ipthresh %f", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), out_file=dict( - argstr="-outputfile %s", extensions=None, genfile=True, position=-1, - ), - output_root=dict(argstr="-outputroot %s", extensions=None, position=-1,), - outputtracts=dict(argstr="-outputtracts %s",), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=2,), - stepsize=dict(argstr="-stepsize %f", requires=["tracker"],), - tracker=dict(argstr="-tracker %s", usedefault=True,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-outputfile %s", + extensions=None, + genfile=True, + position=-1, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + position=-1, + ), + outputtracts=dict( + argstr="-outputtracts %s", + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=2, + ), + stepsize=dict( + argstr="-stepsize %f", + requires=["tracker"], + ), + tracker=dict( + argstr="-tracker %s", + usedefault=True, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = TrackDT.input_spec() @@ -37,7 +98,11 @@ def test_TrackDT_inputs(): def test_TrackDT_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = TrackDT.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TrackPICo.py b/nipype/interfaces/camino/tests/test_auto_TrackPICo.py index 37d4a95179..1d3647e151 100644 --- a/nipype/interfaces/camino/tests/test_auto_TrackPICo.py +++ b/nipype/interfaces/camino/tests/test_auto_TrackPICo.py @@ -4,32 +4,98 @@ def test_TrackPICo_inputs(): input_map = dict( - anisfile=dict(argstr="-anisfile %s", extensions=None,), - anisthresh=dict(argstr="-anisthresh %f",), - args=dict(argstr="%s",), - curveinterval=dict(argstr="-curveinterval %f", requires=["curvethresh"],), - curvethresh=dict(argstr="-curvethresh %f",), - data_dims=dict(argstr="-datadims %s", units="voxels",), - environ=dict(nohash=True, usedefault=True,), - gzip=dict(argstr="-gzip",), - in_file=dict(argstr="-inputfile %s", extensions=None, position=1,), - inputdatatype=dict(argstr="-inputdatatype %s",), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolator=dict(argstr="-interpolator %s",), - ipthresh=dict(argstr="-ipthresh %f",), - iterations=dict(argstr="-iterations %d", units="NA",), - maxcomponents=dict(argstr="-maxcomponents %d", units="NA",), - numpds=dict(argstr="-numpds %d", units="NA",), + anisfile=dict( + argstr="-anisfile %s", + extensions=None, + ), + anisthresh=dict( + argstr="-anisthresh %f", + ), + args=dict( + argstr="%s", + ), + curveinterval=dict( + argstr="-curveinterval %f", + requires=["curvethresh"], + ), + curvethresh=dict( + argstr="-curvethresh %f", + ), + data_dims=dict( + argstr="-datadims %s", + units="voxels", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gzip=dict( + argstr="-gzip", + ), + in_file=dict( + argstr="-inputfile %s", + extensions=None, + position=1, + ), + inputdatatype=dict( + argstr="-inputdatatype %s", + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolator=dict( + argstr="-interpolator %s", + ), + ipthresh=dict( + argstr="-ipthresh %f", + ), + iterations=dict( + argstr="-iterations %d", + units="NA", + ), + maxcomponents=dict( + argstr="-maxcomponents %d", + units="NA", + ), + numpds=dict( + argstr="-numpds %d", + units="NA", + ), out_file=dict( - argstr="-outputfile %s", extensions=None, genfile=True, position=-1, - ), - output_root=dict(argstr="-outputroot %s", extensions=None, position=-1,), - outputtracts=dict(argstr="-outputtracts %s",), - pdf=dict(argstr="-pdf %s",), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=2,), - stepsize=dict(argstr="-stepsize %f", requires=["tracker"],), - tracker=dict(argstr="-tracker %s", usedefault=True,), - voxel_dims=dict(argstr="-voxeldims %s", units="mm",), + argstr="-outputfile %s", + extensions=None, + genfile=True, + position=-1, + ), + output_root=dict( + argstr="-outputroot %s", + extensions=None, + position=-1, + ), + outputtracts=dict( + argstr="-outputtracts %s", + ), + pdf=dict( + argstr="-pdf %s", + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=2, + ), + stepsize=dict( + argstr="-stepsize %f", + requires=["tracker"], + ), + tracker=dict( + argstr="-tracker %s", + usedefault=True, + ), + voxel_dims=dict( + argstr="-voxeldims %s", + units="mm", + ), ) inputs = TrackPICo.input_spec() @@ -39,7 +105,11 @@ def test_TrackPICo_inputs(): def test_TrackPICo_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = TrackPICo.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_TractShredder.py b/nipype/interfaces/camino/tests/test_auto_TractShredder.py index b8a95c9569..07678c5d64 100644 --- a/nipype/interfaces/camino/tests/test_auto_TractShredder.py +++ b/nipype/interfaces/camino/tests/test_auto_TractShredder.py @@ -4,13 +4,40 @@ def test_TractShredder_inputs(): input_map = dict( - args=dict(argstr="%s",), - bunchsize=dict(argstr="%d", position=2, units="NA",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="< %s", extensions=None, mandatory=True, position=-2,), - offset=dict(argstr="%d", position=1, units="NA",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - space=dict(argstr="%d", position=3, units="NA",), + args=dict( + argstr="%s", + ), + bunchsize=dict( + argstr="%d", + position=2, + units="NA", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="< %s", + extensions=None, + mandatory=True, + position=-2, + ), + offset=dict( + argstr="%d", + position=1, + units="NA", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + space=dict( + argstr="%d", + position=3, + units="NA", + ), ) inputs = TractShredder.input_spec() @@ -20,7 +47,11 @@ def test_TractShredder_inputs(): def test_TractShredder_outputs(): - output_map = dict(shredded=dict(extensions=None,),) + output_map = dict( + shredded=dict( + extensions=None, + ), + ) outputs = TractShredder.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/tests/test_auto_VtkStreamlines.py b/nipype/interfaces/camino/tests/test_auto_VtkStreamlines.py index cee10a70db..194f233cc1 100644 --- a/nipype/interfaces/camino/tests/test_auto_VtkStreamlines.py +++ b/nipype/interfaces/camino/tests/test_auto_VtkStreamlines.py @@ -4,18 +4,58 @@ def test_VtkStreamlines_inputs(): input_map = dict( - args=dict(argstr="%s",), - colourorient=dict(argstr="-colourorient",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr=" < %s", extensions=None, mandatory=True, position=-2,), - inputmodel=dict(argstr="-inputmodel %s", usedefault=True,), - interpolate=dict(argstr="-interpolate",), - interpolatescalars=dict(argstr="-interpolatescalars",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), - scalar_file=dict(argstr="-scalarfile %s", extensions=None, position=3,), - seed_file=dict(argstr="-seedfile %s", extensions=None, position=1,), - target_file=dict(argstr="-targetfile %s", extensions=None, position=2,), - voxeldims=dict(argstr="-voxeldims %s", position=4, units="mm",), + args=dict( + argstr="%s", + ), + colourorient=dict( + argstr="-colourorient", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr=" < %s", + extensions=None, + mandatory=True, + position=-2, + ), + inputmodel=dict( + argstr="-inputmodel %s", + usedefault=True, + ), + interpolate=dict( + argstr="-interpolate", + ), + interpolatescalars=dict( + argstr="-interpolatescalars", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), + scalar_file=dict( + argstr="-scalarfile %s", + extensions=None, + position=3, + ), + seed_file=dict( + argstr="-seedfile %s", + extensions=None, + position=1, + ), + target_file=dict( + argstr="-targetfile %s", + extensions=None, + position=2, + ), + voxeldims=dict( + argstr="-voxeldims %s", + position=4, + units="mm", + ), ) inputs = VtkStreamlines.input_spec() @@ -25,7 +65,11 @@ def test_VtkStreamlines_inputs(): def test_VtkStreamlines_outputs(): - output_map = dict(vtk=dict(extensions=None,),) + output_map = dict( + vtk=dict( + extensions=None, + ), + ) outputs = VtkStreamlines.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino/utils.py b/nipype/interfaces/camino/utils.py index 201e4e05d0..93bd4fe5d4 100644 --- a/nipype/interfaces/camino/utils.py +++ b/nipype/interfaces/camino/utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os from ..base import ( @@ -47,7 +46,7 @@ class ImageStatsInputSpec(CommandLineInputSpec): "double", argstr="-outputdatatype %s", usedefault=True, - desc=('A Camino data type string, default is "float". ' "Type must be signed."), + desc=('A Camino data type string, default is "float". Type must be signed.'), ) output_root = File( argstr="-outputroot %s", diff --git a/nipype/interfaces/camino2trackvis/__init__.py b/nipype/interfaces/camino2trackvis/__init__.py index b132a20f0c..ce31d60610 100644 --- a/nipype/interfaces/camino2trackvis/__init__.py +++ b/nipype/interfaces/camino2trackvis/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Camino-Trackvis allows interoperability between Camino and TrackVis.""" diff --git a/nipype/interfaces/camino2trackvis/convert.py b/nipype/interfaces/camino2trackvis/convert.py index 63d7a385da..8d1db28b95 100644 --- a/nipype/interfaces/camino2trackvis/convert.py +++ b/nipype/interfaces/camino2trackvis/convert.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Provides interfaces to various commands provided by Camino-Trackvis.""" import os @@ -81,7 +80,7 @@ class Camino2TrackvisOutputSpec(TraitedSpec): class Camino2Trackvis(CommandLine): - """ Wraps camino_to_trackvis from Camino-Trackvis + """Wraps camino_to_trackvis from Camino-Trackvis Convert files from camino .Bfloat format to trackvis .trk format. @@ -120,7 +119,7 @@ def _gen_outfilename(self): class Trackvis2CaminoInputSpec(CommandLineInputSpec): - """ Wraps trackvis_to_camino from Camino-Trackvis + """Wraps trackvis_to_camino from Camino-Trackvis Convert files from camino .Bfloat format to trackvis .trk format. diff --git a/nipype/interfaces/camino2trackvis/tests/__init__.py b/nipype/interfaces/camino2trackvis/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/camino2trackvis/tests/__init__.py +++ b/nipype/interfaces/camino2trackvis/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/camino2trackvis/tests/test_auto_Camino2Trackvis.py b/nipype/interfaces/camino2trackvis/tests/test_auto_Camino2Trackvis.py index 3cd618eb10..fb076c1107 100644 --- a/nipype/interfaces/camino2trackvis/tests/test_auto_Camino2Trackvis.py +++ b/nipype/interfaces/camino2trackvis/tests/test_auto_Camino2Trackvis.py @@ -4,16 +4,52 @@ def test_Camino2Trackvis_inputs(): input_map = dict( - args=dict(argstr="%s",), - data_dims=dict(argstr="-d %s", mandatory=True, position=4, sep=",",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=1,), - min_length=dict(argstr="-l %d", position=3, units="mm",), - nifti_file=dict(argstr="--nifti %s", extensions=None, position=7,), - out_file=dict(argstr="-o %s", extensions=None, genfile=True, position=2,), - voxel_dims=dict(argstr="-x %s", mandatory=True, position=5, sep=",",), + args=dict( + argstr="%s", + ), + data_dims=dict( + argstr="-d %s", + mandatory=True, + position=4, + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=1, + ), + min_length=dict( + argstr="-l %d", + position=3, + units="mm", + ), + nifti_file=dict( + argstr="--nifti %s", + extensions=None, + position=7, + ), + out_file=dict( + argstr="-o %s", + extensions=None, + genfile=True, + position=2, + ), + voxel_dims=dict( + argstr="-x %s", + mandatory=True, + position=5, + sep=",", + ), voxel_order=dict( - argstr="--voxel-order %s", extensions=None, mandatory=True, position=6, + argstr="--voxel-order %s", + extensions=None, + mandatory=True, + position=6, ), ) inputs = Camino2Trackvis.input_spec() @@ -24,7 +60,11 @@ def test_Camino2Trackvis_inputs(): def test_Camino2Trackvis_outputs(): - output_map = dict(trackvis=dict(extensions=None,),) + output_map = dict( + trackvis=dict( + extensions=None, + ), + ) outputs = Camino2Trackvis.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/camino2trackvis/tests/test_auto_Trackvis2Camino.py b/nipype/interfaces/camino2trackvis/tests/test_auto_Trackvis2Camino.py index b2869c08e3..ec7ed22d0c 100644 --- a/nipype/interfaces/camino2trackvis/tests/test_auto_Trackvis2Camino.py +++ b/nipype/interfaces/camino2trackvis/tests/test_auto_Trackvis2Camino.py @@ -4,11 +4,30 @@ def test_Trackvis2Camino_inputs(): input_map = dict( - append_file=dict(argstr="-a %s", extensions=None, position=2,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=1,), - out_file=dict(argstr="-o %s", extensions=None, genfile=True, position=2,), + append_file=dict( + argstr="-a %s", + extensions=None, + position=2, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=1, + ), + out_file=dict( + argstr="-o %s", + extensions=None, + genfile=True, + position=2, + ), ) inputs = Trackvis2Camino.input_spec() @@ -18,7 +37,11 @@ def test_Trackvis2Camino_inputs(): def test_Trackvis2Camino_outputs(): - output_map = dict(camino=dict(extensions=None,),) + output_map = dict( + camino=dict( + extensions=None, + ), + ) outputs = Trackvis2Camino.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/cat12/__init__.py b/nipype/interfaces/cat12/__init__.py new file mode 100644 index 0000000000..40059b23e1 --- /dev/null +++ b/nipype/interfaces/cat12/__init__.py @@ -0,0 +1,5 @@ +from .preprocess import CAT12Segment, CAT12SANLMDenoising +from .surface import ( + ExtractAdditionalSurfaceParameters, + ExtractROIBasedSurfaceMeasures, +) diff --git a/nipype/interfaces/cat12/base.py b/nipype/interfaces/cat12/base.py new file mode 100644 index 0000000000..03091f1fb9 --- /dev/null +++ b/nipype/interfaces/cat12/base.py @@ -0,0 +1,15 @@ +class Cell: + def __init__(self, arg): + self.arg = arg + + def to_string(self): + if isinstance(self.arg, list): + v = "\n".join([f"'{el}'" for el in self.arg]) + else: + v = self.arg + return v + + +class NestedCell(Cell): + def __str__(self): + return "{{%s}}" % self.to_string() diff --git a/nipype/interfaces/cat12/preprocess.py b/nipype/interfaces/cat12/preprocess.py new file mode 100644 index 0000000000..0153c556fd --- /dev/null +++ b/nipype/interfaces/cat12/preprocess.py @@ -0,0 +1,746 @@ +import os +from pathlib import Path + +from nipype.interfaces.base import ( + InputMultiPath, + TraitedSpec, + traits, + Tuple, + isdefined, + File, + Str, +) +from nipype.interfaces.cat12.base import Cell + +from nipype.interfaces.spm import SPMCommand +from nipype.interfaces.spm.base import ( + SPMCommandInputSpec, + ImageFileSPM, + scans_for_fnames, + scans_for_fname, +) +from nipype.utils.filemanip import split_filename, fname_presuffix + + +class CAT12SegmentInputSpec(SPMCommandInputSpec): + in_files = InputMultiPath( + ImageFileSPM(exists=True), + field="data", + desc="file to segment", + mandatory=True, + copyfile=False, + ) + + _help_tpm = ( + "Tissue Probability Map. Select the tissue probability image that includes 6 tissue probability " + "classes for (1) grey matter, (2) white matter, (3) cerebrospinal fluid, (4) bone, (5) non-brain " + "soft tissue, and (6) the background. CAT uses the TPM only for the initial SPM segmentation." + ) + tpm = InputMultiPath( + ImageFileSPM(exists=True), + field="tpm", + desc=_help_tpm, + mandatory=False, + copyfile=False, + ) + + _help_shoots_tpm = ( + "Shooting Template %d. The Shooting template must be in multi-volume nifti format and should contain GM," + " WM, and background segmentations and have to be saved with at least 16 bit. " + ) + + shooting_tpm = ImageFileSPM( + exists=True, + field="extopts.registration.shooting.shootingtpm", + desc=_help_shoots_tpm % 0, + mandatory=False, + copyfile=False, + ) + + shooting_tpm_template_1 = ImageFileSPM( + exists=True, desc=_help_shoots_tpm % 1, mandatory=False, copyfile=False + ) + shooting_tpm_template_2 = ImageFileSPM( + exists=True, desc=_help_shoots_tpm % 2, mandatory=False, copyfile=False + ) + shooting_tpm_template_3 = ImageFileSPM( + exists=True, desc=_help_shoots_tpm % 3, mandatory=False, copyfile=False + ) + shooting_tpm_template_4 = ImageFileSPM( + exists=True, desc=_help_shoots_tpm % 4, mandatory=False, copyfile=False + ) + + n_jobs = traits.Int( + 1, usedefault=True, mandatory=True, field="nproc", desc="Number of threads" + ) + + _help_affine_reg = ( + "Affine Regularization. The procedure is a local optimisation, so it needs reasonable initial " + "starting estimates. Images should be placed in approximate alignment using the Display " + "function of SPM before beginning. A Mutual Information affine registration with the tissue " + "probability maps (D" + "Agostino et al, 2004) is used to achieve approximate alignment." + ) + affine_regularization = Str( + default_value="mni", field="opts.affreg", usedefault=True, desc=_help_affine_reg + ) + + _help_bias_acc = ( + "Strength of the SPM inhomogeneity (bias) correction that simultaneously controls the SPM " + "biasreg, biasfwhm, samp (resolution), and tol (iteration) parameter." + ) + power_spm_inhomogeneity_correction = traits.Float( + default_value=0.5, field="opts.biasacc", usedefault=True, desc=_help_bias_acc + ) + # Extended options for CAT12 preprocessing + _help_app = ( + "Affine registration and SPM preprocessing can fail in some subjects with deviating anatomy (e.g. " + "other species/neonates) or in images with strong signal inhomogeneities, or untypical intensities " + "(e.g. synthetic images). An initial bias correction can help to reduce such problems (see details " + 'below). Recommended are the "default" and "full" option.' + ) + affine_preprocessing = traits.Int( + 1070, field="extopts.APP", desc=_help_app, usedefault=True + ) + + _help_initial_seg = ( + "In rare cases the Unified Segmentation can fail in highly abnormal brains, where e.g. the " + "cerebrospinal fluid of superlarge ventricles (hydrocephalus) were classified as white " + "matter. However, if the affine registration is correct, the AMAP segmentation with an " + "prior-independent k-means initialization can be used to replace the SPM brain tissue " + "classification. Moreover, if the default Dartel and Shooting registrations will fail then " + 'rhe "Optimized Shooting - superlarge ventricles" option for "Spatial registration" is ! ' + "required Values: \nnone: 0;\nlight: 1;\nfull: 2;\ndefault: 1070." + ) + initial_segmentation = traits.Int( + 0, field="extopts.spm_kamap", desc=_help_initial_seg, usedefault=True + ) + + _help_las = ( + "Additionally to WM-inhomogeneities, GM intensity can vary across different regions such as the motor" + " cortex, the basal ganglia, or the occipital lobe. These changes have an anatomical background " + "(e.g. iron content, myelinization), but are dependent on the MR-protocol and often lead to " + "underestimation of GM at higher intensities and overestimation of CSF at lower intensities. " + "Therefore, a local intensity transformation of all tissue classes is used to reduce these effects in" + " the image. This local adaptive segmentation (LAS) is applied before the final AMAP segmentation." + "Possible Values: \nSPM Unified Segmentation: 0 \nk-means AMAP: 2" + ) + local_adaptive_seg = traits.Float( + 0.5, field="extopts.LASstr", usedefault=True, desc=_help_las + ) + + _help_gcutstr = ( + "Method of initial skull-stripping before AMAP segmentation. The SPM approach works quite stable " + "for the majority of data. However, in some rare cases parts of GM (i.e. in frontal lobe) might " + "be cut. If this happens the GCUT approach is a good alternative. GCUT is a graph-cut/region-" + "growing approach starting from the WM area. APRG (adaptive probability region-growing) is a new" + " method that refines the probability maps of the SPM approach by region-growing techniques of " + "the gcut approach with a final surface-based optimization strategy. This is currently the method" + " with the most accurate and reliable results. If you use already skull-stripped data you can " + "turn off skull-stripping although this is automatically detected in most cases. Please note that " + "the choice of the skull-stripping method will also influence the estimation of TIV, because the" + " methods mainly differ in the handling of the outer CSF around the cortical surface. " + "\nPossible Values:\n - none (already skull-stripped): -1;\n - SPM approach: 0; " + "\n - GCUT approach: 0.50; \n - APRG approach: 2" + ) + skull_strip = traits.Float( + 2, field="extopts.gcutstr", desc=_help_gcutstr, usedefault=True + ) + + _help_wmhc = ( + "WARNING: Please note that the detection of WM hyperintensies is still under development and does " + "not have the same accuracy as approaches that additionally consider FLAIR images (e.g. Lesion " + "Segmentation Toolbox)! In aging or (neurodegenerative) diseases WM intensity can be reduced " + "locally in T1 or increased in T2/PD images. These so-called WM hyperintensies (WMHs) can lead to " + "preprocessing errors. Large GM areas next to the ventricle can cause normalization problems. " + "Therefore, a temporary correction for normalization is useful if WMHs are expected. CAT allows " + "different ways to handle WMHs: " + "\n0) No Correction (handled as GM). \n1) Temporary (internal) correction as WM for spatial " + "normalization and estimation of cortical thickness. \n2) Permanent correction to WM. " + ) + wm_hyper_intensity_correction = traits.Int( + 1, field="extopts.WMHC", desc=_help_wmhc, usedefault=True + ) + + _help_vox = ( + "The (isotropic) voxel sizes of any spatially normalised written images. A non-finite value will be " + "replaced by the average voxel size of the tissue probability maps used by the segmentation." + ) + voxel_size = traits.Float(1.5, field="extopts.vox", desc=_help_vox, usedefault=True) + + _help_resampling = ( + "Internal resampling for preprocessing.\n The default fixed image resolution offers a good " + "trade-off between optimal quality and preprocessing time and memory demands. Standard " + "structural data with a voxel resolution around 1mm or even data with high in-plane resolution" + " and large slice thickness (e.g. 0.5x0.5x1.5 mm) will benefit from this setting. If you have" + ' higher native resolutions the highres option "Fixed 0.8 mm" will sometimes offer slightly' + " better preprocessing quality with an increase of preprocessing time and memory demands. In" + " case of even higher resolutions and high signal-to-noise ratio (e.g. for 7 T data) the " + '"Best native" option will process the data on the highest native resolution. A resolution' + " of 0.4x0.7x1.0 mm will be interpolated to 0.4x0.4x0.4 mm. A tolerance range of 0.1 mm is " + "used to avoid interpolation artifacts, i.e. a resolution of 0.95x1.01x1.08 mm will not be " + 'interpolated in case of the "Fixed 1.0 mm"! This "optimal" option prefers an isotropic voxel ' + "size with at least 1.1 mm that is controlled by the median voxel size and a volume term that " + "penalizes highly anisotropic voxels." + "Values:\nOptimal: [1.0 0.1]\nFixed 1.0 mm: [1.0 0.1];\nFixed 0.8 mm:[0.8 0.1]" + "\nBest native: [0.5 0.1]" + ) + internal_resampling_process = Tuple( + traits.Float(1), + traits.Float(0.1), + minlen=2, + maxlen=2, + usedefault=True, + field="extopts.restypes.optimal", + desc="help_resampling", + ) + _errors_help = ( + "Error handling.\nTry to catch preprocessing errors and continue with the next data set or ignore " + "all warnings (e.g., bad intensities) and use an experimental pipeline which is still in " + "development. In case of errors, CAT continues with the next subject if this option is enabled. If " + "the experimental option with backup functions is selected and warnings occur, CAT will try to use" + " backup routines and skip some processing steps which require good T1 contrasts (e.g., LAS). If " + "you want to avoid processing of critical data and ensure that only the main pipeline is used then" + ' select the option "Ignore errors (continue with the next subject)". It is strongly recommended ' + "to check for preprocessing problems, especially with non-T1 contrasts. " + "\nValues:\nnone: 0,\ndefault: 1,\ndetails: 2." + ) + ignore_errors = traits.Int( + 1, field="extopts.ignoreErrors", desc=_errors_help, usedefault=True + ) + + # Writing options + _help_surf = ( + "Surface and thickness estimation. \nUse projection-based thickness (PBT) (Dahnke et al. 2012) to" + " estimate cortical thickness and to create the central cortical surface for left and right " + "hemisphere. Surface reconstruction includes topology correction (Yotter et al. 2011), spherical " + "inflation (Yotter et al.) and spherical registration. Additionally you can also estimate surface " + "parameters such as gyrification, cortical complexity or sulcal depth that can be subsequently " + "analyzed at each vertex of the surface. Please note, that surface reconstruction and spherical " + "registration additionally requires about 20-60 min of computation time. A fast (1-3 min) surface " + "pipeline is available for visual preview (e.g., to check preprocessing quality) in the " + "cross-sectional, but not in the longitudinal pipeline. Only the initial surfaces are created with " + "a lower resolution and without topology correction, spherical mapping and surface registration. " + "Please note that the files with the estimated surface thickness can therefore not be used for " + 'further analysis! For distinction, these files contain "preview" in their filename and they' + " are not available as batch dependencies objects. " + ) + surface_and_thickness_estimation = traits.Int( + 1, field="surface", desc=_help_surf, usedefault=True + ) + surface_measures = traits.Int( + 1, + field="output.surf_measures", + usedefault=True, + desc="Extract surface measures", + ) + + # Templates + neuromorphometrics = traits.Bool( + True, + field="output.ROImenu.atlases.neuromorphometrics", + usedefault=True, + desc="Extract brain measures for Neuromorphometrics template", + ) + lpba40 = traits.Bool( + True, + field="output.ROImenu.atlases.lpba40", + usedefault=True, + desc="Extract brain measures for LPBA40 template", + ) + cobra = traits.Bool( + True, + field="output.ROImenu.atlases.hammers", + usedefault=True, + desc="Extract brain measures for COBRA template", + ) + hammers = traits.Bool( + True, + field="output.ROImenu.atlases.cobra", + usedefault=True, + desc="Extract brain measures for Hammers template", + ) + own_atlas = InputMultiPath( + ImageFileSPM(exists=True), + field="output.ROImenu.atlases.ownatlas", + desc="Extract brain measures for a given template", + mandatory=False, + copyfile=False, + ) + + # Grey matter + gm_output_native = traits.Bool( + False, + field="output.GM.native", + usedefault=True, + desc="Save modulated grey matter images.", + ) + gm_output_modulated = traits.Bool( + True, + field="output.GM.mod", + usedefault=True, + desc="Save native grey matter images.", + ) + gm_output_dartel = traits.Bool( + False, + field="output.GM.dartel", + usedefault=True, + desc="Save dartel grey matter images.", + ) + + # White matter + _wm_desc = "Options to save white matter images." + wm_output_native = traits.Bool( + False, + field="output.WM.native", + usedefault=True, + desc="Save dartel white matter images.", + ) + wm_output_modulated = traits.Bool( + True, + field="output.WM.mod", + usedefault=True, + desc="Save dartel white matter images.", + ) + wm_output_dartel = traits.Bool( + False, + field="output.WM.dartel", + usedefault=True, + desc="Save dartel white matter images.", + ) + + # CSF matter + _csf_desc = "Options to save CSF images." + csf_output_native = traits.Bool( + False, + field="output.CSF.native", + usedefault=True, + desc="Save dartel CSF images.", + ) + csf_output_modulated = traits.Bool( + True, field="output.CSF.mod", usedefault=True, desc="Save dartel CSF images." + ) + csf_output_dartel = traits.Bool( + False, + field="output.CSF.dartel", + usedefault=True, + desc="Save dartel CSF images.", + ) + + # Labels + _help_label_desc = ( + "This is the option to save a labeled version of your segmentations in the %s space for fast visual " + "comparison. Labels are saved as Partial Volume Estimation (PVE) values with different mix " + "classes for GM-WM (2.5) and GM-CSF (1.5). BG=0, CSF=1, GM=2, WM=3, WMH=4 (if WMHC=3), " + "SL=1.5 (if SLC)" + ) + label_native = traits.Bool( + False, + field="output.label.native", + usedefault=True, + desc=_help_label_desc % "native", + ) + label_warped = traits.Bool( + True, + field="output.label.warped", + usedefault=True, + desc=_help_label_desc % "warped", + ) + label_dartel = traits.Bool( + False, + field="output.label.dartel", + usedefault=True, + desc=_help_label_desc % "dartel", + ) + output_labelnative = traits.Bool( + False, + field="output.labelnative", + usedefault=True, + desc=_help_label_desc % "native", + ) + + # Bias + save_bias_corrected = traits.Bool( + True, + field="output.bias.warped", + usedefault=True, + desc="Save bias corrected image", + ) + + # las + _las_desc = ( + "This is the option to save a bias, noise, and local intensity corrected version of the original T1" + " image in the %s space. MR images are usually corrupted by a smooth, spatially varying artifact that modulates the" + " intensity of the image (bias). These artifacts, although not usually a problem for visual " + "inspection, can impede automated processing of the images. The bias corrected version should have " + "more uniform intensities within the different types of tissues and can be saved in native space " + "and/or normalised. Noise is corrected by an adaptive non-local mean (NLM) filter (Manjon 2008, " + "Medical Image Analysis 12)." + ) + las_native = traits.Bool( + False, field="output.las.native", usedefault=True, desc=_las_desc % "native" + ) + las_warped = traits.Bool( + True, field="output.las.warped", usedefault=True, desc=_las_desc % "warped" + ) + las_dartel = traits.Bool( + False, field="output.las.dartel", usedefault=True, desc=_las_desc % "dartel" + ) + + # Jacobian Warped + _help_jacobian = ( + "This is the option to save the Jacobian determinant, which expresses local volume changes. This" + " image can be used in a pure deformation based morphometry (DBM) design. Please note that the" + " affine part of the deformation field is ignored. Thus, there is no need for any additional" + " correction for different brain sizes using ICV." + ) + jacobianwarped = traits.Bool( + True, field="output.jacobianwarped", usedefault=True, desc=_help_jacobian + ) + + # Deformation Fields + _help_warp = ( + "Deformation fields can be saved to disk, and used by the Deformations Utility and/or applied to " + "coregistered data from other modalities (e.g. fMRI). For spatially normalising images to MNI space," + " you will need the forward deformation, whereas for spatially normalising (eg) GIFTI surface files," + " you" + "ll need the inverse. It is also possible to transform data in MNI space on to the individual" + " subject, which also requires the inverse transform. Deformations are saved as .nii files, which" + " contain three volumes to encode the x, y and z coordinates." + "\nValues: No:[0 0];\nImage->Template (forward): [1 0];\nTemplate->Image (inverse): [0 1]; " + "\ninverse + forward: [1 1]" + ) + warps = Tuple( + traits.Int(1), + traits.Int(0), + minlen=2, + maxlen=2, + field="output.warps", + usedefault=True, + desc=_help_warp, + ) + + +class CAT12SegmentOutputSpec(TraitedSpec): + ########################################## + # Label XML files + ########################################## + label_files = traits.List( + File(exists=True), desc="Files with the measures extracted for OI ands ROIs" + ) + + label_rois = File(exists=True, desc="Files with thickness values of ROIs.") + label_roi = File(exists=True, desc="Files with thickness values of ROI.") + + ########################################## + # MRI .nii files + ########################################## + + mri_images = traits.List(File(exists=True), desc="Different segmented images.") + + # Grey Matter + gm_modulated_image = File(exists=True, desc="Grey matter modulated image.") + gm_dartel_image = File(exists=True, desc="Grey matter dartel image.") + gm_native_image = File(exists=True, desc="Grey matter native space.") + + # White Matter + wm_modulated_image = File(exists=True, desc="White matter modulated image.") + wm_dartel_image = File(exists=True, desc="White matter dartel image.") + wm_native_image = File(exists=True, desc="White matter in native space.") + + # CSF + csf_modulated_image = File(exists=True, desc="CSF modulated image.") + csf_dartel_image = File(exists=True, desc="CSF dartel image.") + csf_native_image = File(exists=True, desc="CSF in native space.") + + bias_corrected_image = File(exists=True, desc="Bias corrected image") + ########################################## + # Surface files + ########################################## + + surface_files = traits.List(File(exists=True), desc="Surface files") + + # Right hemisphere + rh_central_surface = File(exists=True, desc="Central right hemisphere files") + rh_sphere_surface = File(exists=True, desc="Sphere right hemisphere files") + + # Left hemisphere + lh_central_surface = File(exists=True, desc="Central left hemisphere files") + lh_sphere_surface = File(exists=True, desc="Sphere left hemisphere files") + + # Report files + report_files = traits.List(File(exists=True), desc="Report files.") + report = File(exists=True, desc="Report file.") + + +class CAT12Segment(SPMCommand): + """ + CAT12: Segmentation + + This toolbox is an extension to the default segmentation in SPM12, but uses a completely different segmentation + approach. + The segmentation approach is based on an Adaptive Maximum A Posterior (MAP) technique without the need for a priori + information about tissue probabilities. That is, the Tissue Probability Maps (TPM) are not used constantly in the + sense of the classical Unified Segmentation approach (Ashburner et. al. 2005), but just for spatial normalization. + The following AMAP estimation is adaptive in the sense that local variations of the parameters (i.e., means and + variance) are modeled as slowly varying spatial functions (Rajapakse et al. 1997). This not only accounts for + intensity inhomogeneities but also for other local variations of intensity. + Additionally, the segmentation approach uses a Partial Volume Estimation (PVE) with a simplified mixed model of at + most two tissue types (Tohka et al. 2004). We start with an initial segmentation into three pure classes: gray + matter (GM), white matter (WM), and cerebrospinal fluid (CSF) based on the above described AMAP estimation. The + initial segmentation is followed by a PVE of two additional mixed classes: GM-WM and GM-CSF. This results in an + estimation of the amount (or fraction) of each pure tissue type present in every voxel (as single voxels - given by + Another important extension to the SPM12 segmentation is the integration of the Dartel or Geodesic Shooting + registration into the toolbox by an already existing Dartel/Shooting template in MNI space. This template was + derived from 555 healthy control subjects of the IXI-database (http://www.brain-development.org) and provides the + several Dartel or Shooting iterations. Thus, for the majority of studies the creation of sample-specific templates + is not necessary anymore and is mainly recommended for children data.'}; + + http://www.neuro.uni-jena.de/cat12/CAT12-Manual.pdf#page=15 + + Examples + -------- + >>> path_mr = 'structural.nii' + >>> cat = CAT12Segment(in_files=path_mr) + >>> cat.run() # doctest: +SKIP + """ + + input_spec = CAT12SegmentInputSpec + output_spec = CAT12SegmentOutputSpec + + def __init__(self, **inputs): + _local_version = SPMCommand().version + if _local_version and "12." in _local_version: + self._jobtype = "tools" + self._jobname = "cat.estwrite" + + SPMCommand.__init__(self, **inputs) + + def _format_arg(self, opt, spec, val): + """Convert input to appropriate format for spm""" + if opt == "in_files": + if isinstance(val, list): + return scans_for_fnames(val) + else: + return scans_for_fname(val) + elif opt in ["tpm", "shooting_tpm"]: + return Cell2Str(val) + + return super()._format_arg(opt, spec, val) + + def _list_outputs(self): + outputs = self._outputs().get() + f = self.inputs.in_files[0] + pth, base, ext = split_filename(f) + + outputs["mri_images"] = [ + str(mri) for mri in Path(pth).glob("mri/*") if mri.is_file() + ] + + for tidx, tissue in enumerate(["gm", "wm", "csf"]): + for image, prefix in [("modulated", "mw"), ("dartel", "r"), ("native", "")]: + outtype = f"{tissue}_output_{image}" + if isdefined(getattr(self.inputs, outtype)) and getattr( + self.inputs, outtype + ): + outfield = f"{tissue}_{image}_image" + prefix = os.path.join("mri", f"{prefix}p{tidx + 1}") + if image != "dartel": + outputs[outfield] = fname_presuffix(f, prefix=prefix) + else: + outputs[outfield] = fname_presuffix( + f, prefix=prefix, suffix="_rigid" + ) + + if self.inputs.save_bias_corrected: + outputs["bias_corrected_image"] = fname_presuffix( + f, prefix=os.path.join("mri", "wmi") + ) + + outputs["surface_files"] = [ + str(surf) for surf in Path(pth).glob("surf/*") if surf.is_file() + ] + + for hemisphere in ["rh", "lh"]: + for suffix in ["central", "sphere"]: + outfield = f"{hemisphere}_{suffix}_surface" + outputs[outfield] = fname_presuffix( + f, + prefix=os.path.join("surf", f"{hemisphere}.{suffix}."), + suffix=".gii", + use_ext=False, + ) + + outputs["report_files"] = outputs["report_files"] = [ + str(report) for report in Path(pth).glob("report/*") if report.is_file() + ] + + outputs["report"] = fname_presuffix( + f, prefix=os.path.join("report", "cat_"), suffix=".xml", use_ext=False + ) + + outputs["label_files"] = [ + str(label) for label in Path(pth).glob("label/*") if label.is_file() + ] + + outputs["label_rois"] = fname_presuffix( + f, prefix=os.path.join("label", "catROIs_"), suffix=".xml", use_ext=False + ) + outputs["label_roi"] = fname_presuffix( + f, prefix=os.path.join("label", "catROI_"), suffix=".xml", use_ext=False + ) + + return outputs + + +class CAT12SANLMDenoisingInputSpec(SPMCommandInputSpec): + in_files = InputMultiPath( + ImageFileSPM(exists=True), + field="data", + desc="Images for filtering.", + mandatory=True, + copyfile=False, + ) + + spm_type = traits.Enum( + "float32", + "uint16", + "uint8", + "same", + field="spm_type", + usedefault=True, + desc="Data type of the output images. 'same' matches the input image type.", + ) + + intlim = traits.Int( + field="intlim", + default_value=100, + usedefault=True, + desc="intensity limitation (default = 100)", + ) + + filename_prefix = traits.Str( + field="prefix", + default_value="sanlm_", + usedefault=True, + desc="Filename prefix. Specify the string to be prepended to the filenames of the filtered image file(s).", + ) + + filename_suffix = traits.Str( + field="suffix", + default_value="", + usedefault=True, + desc="Filename suffix. Specify the string to be appended to the filenames of the filtered image file(s).", + ) + + addnoise = traits.Float( + default_value=0.5, + usedefault=True, + field="addnoise", + desc="""Strength of additional noise in noise-free regions. + Add minimal amount of noise in regions without any noise to avoid image segmentation problems. + This parameter defines the strength of additional noise as percentage of the average signal intensity.""", + ) + + rician = traits.Bool( + True, + field="rician", + usedefault=True, + desc="""Rician noise + MRIs can have Gaussian or Rician distributed noise with uniform or nonuniform variance across the image. + If SNR is high enough (>3) noise can be well approximated by Gaussian noise in the foreground. However, for + SENSE reconstruction or DTI data a Rician distribution is expected. Please note that the Rician noise estimation + is sensitive for large signals in the neighbourhood and can lead to artefacts, e.g. cortex can be affected by + very high values in the scalp or in blood vessels.""", + ) + + replace_nan_and_inf = traits.Bool( + True, + field="replaceNANandINF", + usedefault=True, + desc="Replace NAN by 0, -INF by the minimum and INF by the maximum of the image.", + ) + + noisecorr_strength = traits.Enum( + "-Inf", + 2, + 4, + field="nlmfilter.optimized.NCstr", + usedefault=True, + desc="""Strength of Noise Corrections + Strength of the (sub-resolution) spatial adaptive non local means (SANLM) noise correction. Please note + that the filter strength is automatically estimated. Change this parameter only for specific conditions. The + "light" option applies half of the filter strength of the adaptive "medium" cases, whereas the "strong" + option uses the full filter strength, force sub-resolution filtering and applies an additional iteration. + Sub-resolution filtering is only used in case of high image resolution below 0.8 mm or in case of the + "strong" option. light = 2, medium = -Inf, strong = 4""", + ) + + +class CAT12SANLMDenoisingOutputSpec(TraitedSpec): + out_file = File(desc="out file") + + +class CAT12SANLMDenoising(SPMCommand): + """ + Spatially adaptive non-local means (SANLM) denoising filter + + This function applies an spatial adaptive (sub-resolution) non-local means denoising filter + to the data. This filter will remove noise while preserving edges. The filter strength is + automatically estimated based on the standard deviation of the noise. + + This filter is internally used in the segmentation procedure anyway. Thus, it is not + necessary (and not recommended) to apply the filter before segmentation. + ______________________________________________________________________ + Christian Gaser, Robert Dahnke + Structural Brain Mapping Group (http://www.neuro.uni-jena.de) + Departments of Neurology and Psychiatry + Jena University Hospital + ______________________________________________________________________ + + Examples + -------- + >>> from nipype.interfaces import cat12 + >>> c = cat12.CAT12SANLMDenoising() + >>> c.inputs.in_files = 'anatomical.nii' + >>> c.run() # doctest: +SKIP + """ + + input_spec = CAT12SANLMDenoisingInputSpec + output_spec = CAT12SANLMDenoisingOutputSpec + + def __init__(self, **inputs): + _local_version = SPMCommand().version + if _local_version and "12." in _local_version: + self._jobtype = "tools" + self._jobname = "cat.tools.sanlm" + + SPMCommand.__init__(self, **inputs) + + def _format_arg(self, opt, spec, val): + """Convert input to appropriate format for spm""" + if opt == "in_files": + if isinstance(val, list): + return scans_for_fnames(val) + else: + return scans_for_fname(val) + if opt == "spm_type": + type_map = {"same": 0, "uint8": 2, "uint16": 512, "float32": 16} + val = type_map[val] + return super()._format_arg(opt, spec, val) + + def _list_outputs(self): + outputs = self._outputs().get() + outputs["out_file"] = fname_presuffix( + self.inputs.in_files[0], + newpath=os.getcwd(), + prefix=self.inputs.filename_prefix, + suffix=self.inputs.filename_suffix, + ) + return outputs + + +class Cell2Str(Cell): + def __str__(self): + """Convert input to appropriate format for cat12""" + return "{'%s'}" % self.to_string() diff --git a/nipype/interfaces/cat12/surface.py b/nipype/interfaces/cat12/surface.py new file mode 100644 index 0000000000..4186bb899e --- /dev/null +++ b/nipype/interfaces/cat12/surface.py @@ -0,0 +1,274 @@ +import os +from pathlib import Path + +from nipype.interfaces.base import File, InputMultiPath, TraitedSpec, traits, isdefined +from nipype.interfaces.cat12.base import NestedCell, Cell +from nipype.interfaces.spm import SPMCommand +from nipype.interfaces.spm.base import SPMCommandInputSpec +from nipype.utils.filemanip import split_filename + + +class ExtractAdditionalSurfaceParametersInputSpec(SPMCommandInputSpec): + left_central_surfaces = InputMultiPath( + File(exists=True), + field="data_surf", + desc="Left and central surfaces files", + mandatory=True, + copyfile=False, + ) + surface_files = InputMultiPath( + File(exists=True), desc="All surface files", mandatory=False, copyfile=False + ) + + gyrification = traits.Bool( + True, + field="GI", + usedefault=True, + desc="Extract gyrification index (GI) based on absolute mean curvature. The" + " method is described in Luders et al. Neuroimage, 29:1224-1230, 2006", + ) + gmv = traits.Bool(True, field="gmv", usedefault=True, desc="Extract volume") + area = traits.Bool(True, field="area", usedefault=True, desc="Extract area surface") + depth = traits.Bool( + False, + field="SD", + usedefault=True, + desc="Extract sulcus depth based on euclidean distance between the central " + "surface anf its convex hull.", + ) + fractal_dimension = traits.Bool( + False, + field="FD", + usedefault=True, + desc="Extract cortical complexity (fractal dimension) which is " + "described in Yotter ar al. Neuroimage, 56(3): 961-973, 2011", + ) + + +class ExtractAdditionalSurfaceParametersOutputSpec(TraitedSpec): + lh_extracted_files = traits.List( + File(exists=True), desc="Files of left Hemisphere extracted measures" + ) + rh_extracted_files = traits.List( + File(exists=True), desc="Files of right Hemisphere extracted measures" + ) + + lh_gyrification = traits.List( + File(exists=True), desc="Gyrification of left Hemisphere" + ) + rh_gyrification = traits.List( + File(exists=True), desc="Gyrification of right Hemisphere" + ) + + lh_gmv = traits.List( + File(exists=True), desc="Grey matter volume of left Hemisphere" + ) + rh_gmv = traits.List( + File(exists=True), desc="Grey matter volume of right Hemisphere" + ) + + lh_area = traits.List(File(exists=True), desc="Area of left Hemisphere") + rh_area = traits.List(File(exists=True), desc="Area of right Hemisphere") + + lh_depth = traits.List(File(exists=True), desc="Depth of left Hemisphere") + rh_depth = traits.List(File(exists=True), desc="Depth of right Hemisphere") + + lh_fractaldimension = traits.List( + File(exists=True), desc="Fractal Dimension of left Hemisphere" + ) + rh_fractaldimension = traits.List( + File(exists=True), desc="Fractal Dimension of right Hemisphere" + ) + + +class ExtractAdditionalSurfaceParameters(SPMCommand): + """ + Additional surface parameters can be extracted that can be used for statistical analysis, such as: + + * Central surfaces + * Surface area + * Surface GM volume + * Gyrification Index + * Sulcus depth + * Toro's gyrification index + * Shaer's local gyrification index + * Laplacian gyrification indices + * Addicional surfaces + * Measure normalization + * Lazy processing + + http://www.neuro.uni-jena.de/cat12/CAT12-Manual.pdf#page=53 + + Examples + -------- + >>> # Set the left surface files, both will be processed + >>> lh_path_central = 'lh.central.structural.gii' + >>> # Put here all surface files generated by CAT12 Segment, this is only required if the this approach is putted in + >>> surf_files = ['lh.sphere.reg.structural.gii', 'rh.sphere.reg.structural.gii', 'lh.sphere.structural.gii', 'rh.sphere.structural.gii', 'rh.central.structural.gii', 'lh.pbt.structural', 'rh.pbt.structural'] + >>> extract_additional_measures = ExtractAdditionalSurfaceParameters(left_central_surfaces=lh_path_central, surface_files=surf_files) + >>> extract_additional_measures.run() # doctest: +SKIP + + """ + + input_spec = ExtractAdditionalSurfaceParametersInputSpec + output_spec = ExtractAdditionalSurfaceParametersOutputSpec + + def __init__(self, **inputs): + _local_version = SPMCommand().version + if _local_version and "12." in _local_version: + self._jobtype = "tools" + self._jobname = "cat.stools.surfextract" + + super().__init__(**inputs) + + def _list_outputs(self): + outputs = self._outputs().get() + + names_outputs = [ + (self.inputs.gyrification, "gyrification"), + (self.inputs.gmv, "gmv"), + (self.inputs.area, "area"), + (self.inputs.depth, "depth"), + (self.inputs.fractal_dimension, "fractaldimension"), + ] + + for filename in self.inputs.left_central_surfaces: + pth, base, ext = split_filename(filename) + # The first part of the filename is rh.central or lh.central + original_filename = base.split(".", 2)[-1] + for extracted_parameter, parameter_name in names_outputs: + if extracted_parameter: + for hemisphere in ["rh", "lh"]: + all_files_hemisphere = hemisphere + "_extracted_files" + name_hemisphere = hemisphere + "_" + parameter_name + if not isdefined(outputs[name_hemisphere]): + outputs[name_hemisphere] = [] + if not isdefined(outputs[all_files_hemisphere]): + outputs[all_files_hemisphere] = [] + generated_filename = ( + f"{hemisphere}.{parameter_name}.{original_filename}" + ) + outputs[name_hemisphere].append( + os.path.join(pth, generated_filename) + ) + + # Add all hemisphere files into one list, this is important because only the left hemisphere + # files are used as input in the Surface ROI Tools, for instance. + outputs[all_files_hemisphere].append( + os.path.join(pth, generated_filename) + ) + + return outputs + + def _format_arg(self, opt, spec, val): + if opt == "left_central_surfaces": + return Cell2Str(val) + return super()._format_arg(opt, spec, val) + + +class ExtractROIBasedSurfaceMeasuresInputSpec(SPMCommandInputSpec): + # Only these files are given as input, yet the right hemisphere (rh) files should also be on the processing + # directory. + + surface_files = InputMultiPath( + File(exists=True), + desc="Surface data files. This variable should be a list with all", + mandatory=False, + copyfile=False, + ) + lh_roi_atlas = InputMultiPath( + File(exists=True), + field="rdata", + desc="(Left) ROI Atlas. These are the ROI's ", + mandatory=True, + copyfile=False, + ) + + rh_roi_atlas = InputMultiPath( + File(exists=True), + desc="(Right) ROI Atlas. These are the ROI's ", + mandatory=False, + copyfile=False, + ) + + lh_surface_measure = InputMultiPath( + File(exists=True), + field="cdata", + desc="(Left) Surface data files. ", + mandatory=True, + copyfile=False, + ) + rh_surface_measure = InputMultiPath( + File(exists=True), + desc="(Right) Surface data files.", + mandatory=False, + copyfile=False, + ) + + +class ExtractROIBasedSurfaceMeasuresOutputSpec(TraitedSpec): + label_files = traits.List( + File(exists=True), desc="Files with the measures extracted for ROIs." + ) + + +class ExtractROIBasedSurfaceMeasures(SPMCommand): + """ + Extract ROI-based surface values + While ROI-based values for VBM (volume) data are automatically saved in the ``label`` folder as XML file it is + necessary to additionally extract these values for surface data (except for thickness which is automatically + extracted during segmentation). This has to be done after preprocessing the data and creating cortical surfaces. + + You can extract ROI-based values for cortical thickness but also for any other surface parameter that was extracted + using the Extract Additional Surface Parameters such as volume, area, depth, gyrification and fractal dimension. + + + http://www.neuro.uni-jena.de/cat12/CAT12-Manual.pdf#page=53 + + Examples + -------- + >>> # Template surface files + >>> lh_atlas = 'lh.aparc_a2009s.freesurfer.annot' + >>> rh_atlas = 'rh.aparc_a2009s.freesurfer.annot' + >>> surf_files = ['lh.sphere.reg.structural.gii', 'rh.sphere.reg.structural.gii', 'lh.sphere.structural.gii', 'rh.sphere.structural.gii', 'lh.central.structural.gii', 'rh.central.structural.gii', 'lh.pbt.structural', 'rh.pbt.structural'] + >>> lh_measure = 'lh.area.structural' + >>> extract_additional_measures = ExtractROIBasedSurfaceMeasures(surface_files=surf_files, lh_surface_measure=lh_measure, lh_roi_atlas=lh_atlas, rh_roi_atlas=rh_atlas) + >>> extract_additional_measures.run() # doctest: +SKIP + + + """ + + input_spec = ExtractROIBasedSurfaceMeasuresInputSpec + output_spec = ExtractROIBasedSurfaceMeasuresOutputSpec + + def __init__(self, **inputs): + _local_version = SPMCommand().version + if _local_version and "12." in _local_version: + self._jobtype = "tools" + self._jobname = "cat.stools.surf2roi" + + SPMCommand.__init__(self, **inputs) + + def _format_arg(self, opt, spec, val): + if opt == "lh_surface_measure": + return NestedCell(val) + elif opt == "lh_roi_atlas": + return Cell2Str(val) + + return super()._format_arg(opt, spec, val) + + def _list_outputs(self): + outputs = self._outputs().get() + + pth, base, ext = split_filename(self.inputs.lh_surface_measure[0]) + + outputs["label_files"] = [ + str(label) for label in Path(pth).glob("label/*") if label.is_file() + ] + return outputs + + +class Cell2Str(Cell): + def __str__(self): + """Convert input to appropriate format for cat12""" + return "{%s}" % self.to_string() diff --git a/nipype/interfaces/cat12/tests/__init__.py b/nipype/interfaces/cat12/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/interfaces/cat12/tests/test_auto_CAT12SANLMDenoising.py b/nipype/interfaces/cat12/tests/test_auto_CAT12SANLMDenoising.py new file mode 100644 index 0000000000..43c0d5e4ea --- /dev/null +++ b/nipype/interfaces/cat12/tests/test_auto_CAT12SANLMDenoising.py @@ -0,0 +1,72 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..preprocess import CAT12SANLMDenoising + + +def test_CAT12SANLMDenoising_inputs(): + input_map = dict( + addnoise=dict( + field="addnoise", + usedefault=True, + ), + filename_prefix=dict( + field="prefix", + usedefault=True, + ), + filename_suffix=dict( + field="suffix", + usedefault=True, + ), + in_files=dict( + copyfile=False, + field="data", + mandatory=True, + ), + intlim=dict( + field="intlim", + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict( + usedefault=True, + ), + noisecorr_strength=dict( + field="nlmfilter.optimized.NCstr", + usedefault=True, + ), + paths=dict(), + replace_nan_and_inf=dict( + field="replaceNANandINF", + usedefault=True, + ), + rician=dict( + field="rician", + usedefault=True, + ), + spm_type=dict( + field="spm_type", + usedefault=True, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + ) + inputs = CAT12SANLMDenoising.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_CAT12SANLMDenoising_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = CAT12SANLMDenoising.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/cat12/tests/test_auto_CAT12Segment.py b/nipype/interfaces/cat12/tests/test_auto_CAT12Segment.py new file mode 100644 index 0000000000..979b3afa6b --- /dev/null +++ b/nipype/interfaces/cat12/tests/test_auto_CAT12Segment.py @@ -0,0 +1,277 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..preprocess import CAT12Segment + + +def test_CAT12Segment_inputs(): + input_map = dict( + affine_preprocessing=dict( + field="extopts.APP", + usedefault=True, + ), + affine_regularization=dict( + field="opts.affreg", + usedefault=True, + ), + cobra=dict( + field="output.ROImenu.atlases.hammers", + usedefault=True, + ), + csf_output_dartel=dict( + field="output.CSF.dartel", + usedefault=True, + ), + csf_output_modulated=dict( + field="output.CSF.mod", + usedefault=True, + ), + csf_output_native=dict( + field="output.CSF.native", + usedefault=True, + ), + gm_output_dartel=dict( + field="output.GM.dartel", + usedefault=True, + ), + gm_output_modulated=dict( + field="output.GM.mod", + usedefault=True, + ), + gm_output_native=dict( + field="output.GM.native", + usedefault=True, + ), + hammers=dict( + field="output.ROImenu.atlases.cobra", + usedefault=True, + ), + ignore_errors=dict( + field="extopts.ignoreErrors", + usedefault=True, + ), + in_files=dict( + copyfile=False, + field="data", + mandatory=True, + ), + initial_segmentation=dict( + field="extopts.spm_kamap", + usedefault=True, + ), + internal_resampling_process=dict( + field="extopts.restypes.optimal", + maxlen=2, + minlen=2, + usedefault=True, + ), + jacobianwarped=dict( + field="output.jacobianwarped", + usedefault=True, + ), + label_dartel=dict( + field="output.label.dartel", + usedefault=True, + ), + label_native=dict( + field="output.label.native", + usedefault=True, + ), + label_warped=dict( + field="output.label.warped", + usedefault=True, + ), + las_dartel=dict( + field="output.las.dartel", + usedefault=True, + ), + las_native=dict( + field="output.las.native", + usedefault=True, + ), + las_warped=dict( + field="output.las.warped", + usedefault=True, + ), + local_adaptive_seg=dict( + field="extopts.LASstr", + usedefault=True, + ), + lpba40=dict( + field="output.ROImenu.atlases.lpba40", + usedefault=True, + ), + matlab_cmd=dict(), + mfile=dict( + usedefault=True, + ), + n_jobs=dict( + field="nproc", + mandatory=True, + usedefault=True, + ), + neuromorphometrics=dict( + field="output.ROImenu.atlases.neuromorphometrics", + usedefault=True, + ), + output_labelnative=dict( + field="output.labelnative", + usedefault=True, + ), + own_atlas=dict( + copyfile=False, + field="output.ROImenu.atlases.ownatlas", + mandatory=False, + ), + paths=dict(), + power_spm_inhomogeneity_correction=dict( + field="opts.biasacc", + usedefault=True, + ), + save_bias_corrected=dict( + field="output.bias.warped", + usedefault=True, + ), + shooting_tpm=dict( + copyfile=False, + extensions=[".hdr", ".img", ".img.gz", ".nii"], + field="extopts.registration.shooting.shootingtpm", + mandatory=False, + ), + shooting_tpm_template_1=dict( + copyfile=False, + extensions=[".hdr", ".img", ".img.gz", ".nii"], + mandatory=False, + ), + shooting_tpm_template_2=dict( + copyfile=False, + extensions=[".hdr", ".img", ".img.gz", ".nii"], + mandatory=False, + ), + shooting_tpm_template_3=dict( + copyfile=False, + extensions=[".hdr", ".img", ".img.gz", ".nii"], + mandatory=False, + ), + shooting_tpm_template_4=dict( + copyfile=False, + extensions=[".hdr", ".img", ".img.gz", ".nii"], + mandatory=False, + ), + skull_strip=dict( + field="extopts.gcutstr", + usedefault=True, + ), + surface_and_thickness_estimation=dict( + field="surface", + usedefault=True, + ), + surface_measures=dict( + field="output.surf_measures", + usedefault=True, + ), + tpm=dict( + copyfile=False, + field="tpm", + mandatory=False, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + voxel_size=dict( + field="extopts.vox", + usedefault=True, + ), + warps=dict( + field="output.warps", + maxlen=2, + minlen=2, + usedefault=True, + ), + wm_hyper_intensity_correction=dict( + field="extopts.WMHC", + usedefault=True, + ), + wm_output_dartel=dict( + field="output.WM.dartel", + usedefault=True, + ), + wm_output_modulated=dict( + field="output.WM.mod", + usedefault=True, + ), + wm_output_native=dict( + field="output.WM.native", + usedefault=True, + ), + ) + inputs = CAT12Segment.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_CAT12Segment_outputs(): + output_map = dict( + bias_corrected_image=dict( + extensions=None, + ), + csf_dartel_image=dict( + extensions=None, + ), + csf_modulated_image=dict( + extensions=None, + ), + csf_native_image=dict( + extensions=None, + ), + gm_dartel_image=dict( + extensions=None, + ), + gm_modulated_image=dict( + extensions=None, + ), + gm_native_image=dict( + extensions=None, + ), + label_files=dict(), + label_roi=dict( + extensions=None, + ), + label_rois=dict( + extensions=None, + ), + lh_central_surface=dict( + extensions=None, + ), + lh_sphere_surface=dict( + extensions=None, + ), + mri_images=dict(), + report=dict( + extensions=None, + ), + report_files=dict(), + rh_central_surface=dict( + extensions=None, + ), + rh_sphere_surface=dict( + extensions=None, + ), + surface_files=dict(), + wm_dartel_image=dict( + extensions=None, + ), + wm_modulated_image=dict( + extensions=None, + ), + wm_native_image=dict( + extensions=None, + ), + ) + outputs = CAT12Segment.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/cat12/tests/test_auto_ExtractAdditionalSurfaceParameters.py b/nipype/interfaces/cat12/tests/test_auto_ExtractAdditionalSurfaceParameters.py new file mode 100644 index 0000000000..cde7f2057e --- /dev/null +++ b/nipype/interfaces/cat12/tests/test_auto_ExtractAdditionalSurfaceParameters.py @@ -0,0 +1,73 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..surface import ExtractAdditionalSurfaceParameters + + +def test_ExtractAdditionalSurfaceParameters_inputs(): + input_map = dict( + area=dict( + field="area", + usedefault=True, + ), + depth=dict( + field="SD", + usedefault=True, + ), + fractal_dimension=dict( + field="FD", + usedefault=True, + ), + gmv=dict( + field="gmv", + usedefault=True, + ), + gyrification=dict( + field="GI", + usedefault=True, + ), + left_central_surfaces=dict( + copyfile=False, + field="data_surf", + mandatory=True, + ), + matlab_cmd=dict(), + mfile=dict( + usedefault=True, + ), + paths=dict(), + surface_files=dict( + copyfile=False, + mandatory=False, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + ) + inputs = ExtractAdditionalSurfaceParameters.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_ExtractAdditionalSurfaceParameters_outputs(): + output_map = dict( + lh_area=dict(), + lh_depth=dict(), + lh_extracted_files=dict(), + lh_fractaldimension=dict(), + lh_gmv=dict(), + lh_gyrification=dict(), + rh_area=dict(), + rh_depth=dict(), + rh_extracted_files=dict(), + rh_fractaldimension=dict(), + rh_gmv=dict(), + rh_gyrification=dict(), + ) + outputs = ExtractAdditionalSurfaceParameters.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/cat12/tests/test_auto_ExtractROIBasedSurfaceMeasures.py b/nipype/interfaces/cat12/tests/test_auto_ExtractROIBasedSurfaceMeasures.py new file mode 100644 index 0000000000..ffc18324aa --- /dev/null +++ b/nipype/interfaces/cat12/tests/test_auto_ExtractROIBasedSurfaceMeasures.py @@ -0,0 +1,55 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..surface import ExtractROIBasedSurfaceMeasures + + +def test_ExtractROIBasedSurfaceMeasures_inputs(): + input_map = dict( + lh_roi_atlas=dict( + copyfile=False, + field="rdata", + mandatory=True, + ), + lh_surface_measure=dict( + copyfile=False, + field="cdata", + mandatory=True, + ), + matlab_cmd=dict(), + mfile=dict( + usedefault=True, + ), + paths=dict(), + rh_roi_atlas=dict( + copyfile=False, + mandatory=False, + ), + rh_surface_measure=dict( + copyfile=False, + mandatory=False, + ), + surface_files=dict( + copyfile=False, + mandatory=False, + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + ) + inputs = ExtractROIBasedSurfaceMeasures.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_ExtractROIBasedSurfaceMeasures_outputs(): + output_map = dict( + label_files=dict(), + ) + outputs = ExtractROIBasedSurfaceMeasures.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/cmtk/__init__.py b/nipype/interfaces/cmtk/__init__.py index fc45bc986e..d71ac76e2c 100644 --- a/nipype/interfaces/cmtk/__init__.py +++ b/nipype/interfaces/cmtk/__init__.py @@ -1,5 +1,5 @@ -# -*- coding: utf-8 -*- """CMP implements a full processing pipeline for creating connectomes with dMRI data.""" + from .cmtk import ROIGen, CreateMatrix, CreateNodes from .nx import NetworkXMetrics, AverageNetworks from .parcellation import Parcellate diff --git a/nipype/interfaces/cmtk/base.py b/nipype/interfaces/cmtk/base.py index 17d3070504..c4c997288b 100644 --- a/nipype/interfaces/cmtk/base.py +++ b/nipype/interfaces/cmtk/base.py @@ -1,7 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -""" Base interface for cmtk """ +"""Base interface for cmtk""" from ..base import LibraryBaseInterface from ...utils.misc import package_check diff --git a/nipype/interfaces/cmtk/cmtk.py b/nipype/interfaces/cmtk/cmtk.py index 6587dcc291..50902d5d1c 100644 --- a/nipype/interfaces/cmtk/cmtk.py +++ b/nipype/interfaces/cmtk/cmtk.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import pickle @@ -73,12 +72,12 @@ def length(xyz, along=False): def get_rois_crossed(pointsmm, roiData, voxelSize): n_points = len(pointsmm) rois_crossed = [] - for j in range(0, n_points): + for j in range(n_points): # store point x = int(pointsmm[j, 0] / float(voxelSize[0])) y = int(pointsmm[j, 1] / float(voxelSize[1])) z = int(pointsmm[j, 2] / float(voxelSize[2])) - if not roiData[x, y, z] == 0: + if roiData[x, y, z] != 0: rois_crossed.append(roiData[x, y, z]) rois_crossed = list( dict.fromkeys(rois_crossed).keys() @@ -92,15 +91,14 @@ def get_connectivity_matrix(n_rois, list_of_roi_crossed_lists): for idx_i, roi_i in enumerate(rois_crossed): for idx_j, roi_j in enumerate(rois_crossed): if idx_i > idx_j: - if not roi_i == roi_j: + if roi_i != roi_j: connectivity_matrix[roi_i - 1, roi_j - 1] += 1 connectivity_matrix = connectivity_matrix + connectivity_matrix.T return connectivity_matrix def create_allpoints_cmat(streamlines, roiData, voxelSize, n_rois): - """ Create the intersection arrays for each fiber - """ + """Create the intersection arrays for each fiber""" n_fib = len(streamlines) pc = -1 # Computation for each fiber @@ -133,7 +131,7 @@ def create_allpoints_cmat(streamlines, roiData, voxelSize, n_rois): def create_endpoints_array(fib, voxelSize): - """ Create the endpoints arrays for each fiber. + """Create the endpoints arrays for each fiber. Parameters ---------- @@ -191,7 +189,7 @@ def cmat( endpoint_name, intersections=False, ): - """ Create the connection matrix for each resolution using fibers and ROIs. """ + """Create the connection matrix for each resolution using fibers and ROIs.""" import scipy.io as sio stats = {} @@ -227,7 +225,8 @@ def cmat( # Add node information from specified parcellation scheme path, name, ext = split_filename(resolution_network_file) if ext == ".pck": - gp = nx.read_gpickle(resolution_network_file) + with open(resolution_network_file, 'rb') as f: + gp = pickle.load(f) elif ext == ".graphml": gp = nx.read_graphml(resolution_network_file) else: @@ -249,7 +248,7 @@ def cmat( axis=1, ) ) - G.nodes[int(u)]["dn_position"] = tuple([xyz[0], xyz[2], -xyz[1]]) + G.nodes[int(u)]["dn_position"] = (xyz[0], xyz[2], -xyz[1]) if intersections: iflogger.info("Filtering tractography from intersections") @@ -264,7 +263,7 @@ def cmat( ) intersection_matrix = np.matrix(intersection_matrix) I = G.copy() - H = nx.from_numpy_matrix(np.matrix(intersection_matrix)) + H = nx.from_numpy_array(np.matrix(intersection_matrix)) H = nx.relabel_nodes(H, lambda x: x + 1) # relabel nodes so they start at 1 I.add_weighted_edges_from( ((u, v, d["weight"]) for u, v, d in H.edges(data=True)) @@ -272,7 +271,6 @@ def cmat( dis = 0 for i in range(endpoints.shape[0]): - # ROI start => ROI end try: startROI = int( @@ -283,7 +281,7 @@ def cmat( ) except IndexError: iflogger.error( - "AN INDEXERROR EXCEPTION OCCURED FOR FIBER %s. " + "AN INDEXERROR EXCEPTION OCCURRED FOR FIBER %s. " "PLEASE CHECK ENDPOINT GENERATION", i, ) @@ -330,9 +328,11 @@ def cmat( else: final_fibers_indices = final_fibers_idx - for idx in final_fibers_indices: + finalfiberlength.extend( # compute length of fiber - finalfiberlength.append(length(fib[idx][0])) + length(fib[idx][0]) + for idx in final_fibers_indices + ) # convert to array final_fiberlength_array = np.array(finalfiberlength) @@ -371,7 +371,7 @@ def cmat( di["fiber_length_mean"] = 0 di["fiber_length_median"] = 0 di["fiber_length_std"] = 0 - if not u == v: # Fix for self loop problem + if u != v: # Fix for self loop problem G.add_edge(u, v, **di) if "fiblist" in d: numfib.add_edge(u, v, weight=di["number_of_fibers"]) @@ -380,25 +380,27 @@ def cmat( fibdev.add_edge(u, v, weight=di["fiber_length_std"]) iflogger.info("Writing network as %s", matrix_name) - nx.write_gpickle(G, op.abspath(matrix_name)) + with open(op.abspath(matrix_name), 'wb') as f: + pickle.dump(G, f, pickle.HIGHEST_PROTOCOL) - numfib_mlab = nx.to_numpy_matrix(numfib, dtype=int) + numfib_mlab = nx.to_numpy_array(numfib, dtype=int) numfib_dict = {"number_of_fibers": numfib_mlab} - fibmean_mlab = nx.to_numpy_matrix(fibmean, dtype=np.float64) + fibmean_mlab = nx.to_numpy_array(fibmean, dtype=np.float64) fibmean_dict = {"mean_fiber_length": fibmean_mlab} - fibmedian_mlab = nx.to_numpy_matrix(fibmedian, dtype=np.float64) + fibmedian_mlab = nx.to_numpy_array(fibmedian, dtype=np.float64) fibmedian_dict = {"median_fiber_length": fibmedian_mlab} - fibdev_mlab = nx.to_numpy_matrix(fibdev, dtype=np.float64) + fibdev_mlab = nx.to_numpy_array(fibdev, dtype=np.float64) fibdev_dict = {"fiber_length_std": fibdev_mlab} if intersections: path, name, ext = split_filename(matrix_name) intersection_matrix_name = op.abspath(name + "_intersections") + ext iflogger.info("Writing intersection network as %s", intersection_matrix_name) - nx.write_gpickle(I, intersection_matrix_name) + with open(intersection_matrix_name, 'wb') as f: + pickle.dump(I, f, pickle.HIGHEST_PROTOCOL) path, name, ext = split_filename(matrix_mat_name) - if not ext == ".mat": + if ext != ".mat": ext = ".mat" matrix_mat_name = matrix_mat_name + ext @@ -461,11 +463,9 @@ def cmat( def save_fibers(oldhdr, oldfib, fname, indices): - """ Stores a new trackvis file fname using only given indices """ + """Stores a new trackvis file fname using only given indices""" hdrnew = oldhdr.copy() - outstreams = [] - for i in indices: - outstreams.append(oldfib[i]) + outstreams = [oldfib[i] for i in indices] n_fib_out = len(outstreams) hdrnew["n_count"] = n_fib_out iflogger.info("Writing final non-orphan fibers as %s", fname) @@ -608,7 +608,7 @@ def _run_interface(self, runtime): matrix_mat_file = op.abspath(self.inputs.out_matrix_mat_file) path, name, ext = split_filename(matrix_mat_file) - if not ext == ".mat": + if ext != ".mat": ext = ".mat" matrix_mat_file = matrix_mat_file + ext @@ -673,7 +673,7 @@ def _list_outputs(self): matrix_mat_file = op.abspath(self.inputs.out_matrix_mat_file) path, name, ext = split_filename(matrix_mat_file) - if not ext == ".mat": + if ext != ".mat": ext = ".mat" matrix_mat_file = matrix_mat_file + ext @@ -894,7 +894,7 @@ def _run_interface(self, runtime): iflogger.info("Number of labels in LUT: %s", numLUTLabels) LUTlabelDict = {} """ Create dictionary for input LUT table""" - for labels in range(0, numLUTLabels): + for labels in range(numLUTLabels): LUTlabelDict[LUTlabelsRGBA[labels][0]] = [ LUTlabelsRGBA[labels][1], LUTlabelsRGBA[labels][2], @@ -1070,8 +1070,9 @@ def create_nodes(roi_file, resolution_network_file, out_filename): np.where(np.flipud(roiData) == int(d["dn_correspondence_id"])), axis=1 ) ) - G.nodes[int(u)]["dn_position"] = tuple([xyz[0], xyz[2], -xyz[1]]) - nx.write_gpickle(G, out_filename) + G.nodes[int(u)]["dn_position"] = (xyz[0], xyz[2], -xyz[1]) + with open(out_filename, 'wb') as f: + pickle.dump(G, f, pickle.HIGHEST_PROTOCOL) return out_filename diff --git a/nipype/interfaces/cmtk/convert.py b/nipype/interfaces/cmtk/convert.py index a0f956b6f9..0c38fd3342 100644 --- a/nipype/interfaces/cmtk/convert.py +++ b/nipype/interfaces/cmtk/convert.py @@ -1,10 +1,7 @@ -# -*- coding: utf-8 -*- - import os import os.path as op import datetime import string -import networkx as nx from ...utils.filemanip import split_filename from ..base import ( @@ -15,7 +12,14 @@ InputMultiPath, isdefined, ) -from .base import CFFBaseInterface, have_cfflib +from .base import CFFBaseInterface + + +def _read_pickle(fname): + import pickle + + with open(fname, 'rb') as f: + return pickle.load(f) class CFFConverterInputSpec(BaseInterfaceInputSpec): @@ -127,7 +131,7 @@ def _run_interface(self, runtime): for ntwk in self.inputs.graphml_networks: # There must be a better way to deal with the unique name problem # (i.e. tracks and networks can't use the same name, and previously we were pulling them both from the input files) - ntwk_name = "Network {cnt}".format(cnt=count) + ntwk_name = f"Network {count}" a.add_connectome_network_from_graphml(ntwk_name, ntwk) count += 1 @@ -135,7 +139,7 @@ def _run_interface(self, runtime): unpickled = [] for ntwk in self.inputs.gpickled_networks: _, ntwk_name, _ = split_filename(ntwk) - unpickled = nx.read_gpickle(ntwk) + unpickled = _read_pickle(ntwk) cnet = cf.CNetwork(name=ntwk_name) cnet.set_with_nxgraph(unpickled) a.add_connectome_network(cnet) @@ -189,17 +193,17 @@ def _run_interface(self, runtime): for data in self.inputs.data_files: _, data_name, _ = split_filename(data) cda = cf.CData(name=data_name, src=data, fileformat="NumPy") - if not string.find(data_name, "lengths") == -1: + if 'lengths' in data_name: cda.dtype = "FinalFiberLengthArray" - if not string.find(data_name, "endpoints") == -1: + if 'endpoints' in data_name: cda.dtype = "FiberEndpoints" - if not string.find(data_name, "labels") == -1: + if 'labels' in data_name: cda.dtype = "FinalFiberLabels" a.add_connectome_data(cda) a.print_summary() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".cff": + if ext != '.cff': ext = ".cff" cf.save_to_cff(a, op.abspath(name + ext)) @@ -208,7 +212,7 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self._outputs().get() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".cff": + if ext != '.cff': ext = ".cff" outputs["connectome_file"] = op.abspath(name + ext) return outputs @@ -234,7 +238,7 @@ class MergeCNetworksOutputSpec(TraitedSpec): class MergeCNetworks(CFFBaseInterface): - """ Merges networks from multiple CFF files into one new CFF file. + """Merges networks from multiple CFF files into one new CFF file. Example ------- @@ -276,7 +280,7 @@ def _run_interface(self, runtime): metadata.set_email("My Email") _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".cff": + if ext != '.cff': ext = ".cff" cf.save_to_cff(newcon, op.abspath(name + ext)) @@ -285,7 +289,7 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self._outputs().get() _, name, ext = split_filename(self.inputs.out_file) - if not ext == ".cff": + if ext != '.cff': ext = ".cff" outputs["connectome_file"] = op.abspath(name + ext) return outputs diff --git a/nipype/interfaces/cmtk/nbs.py b/nipype/interfaces/cmtk/nbs.py index 4e1db9ffb7..b63144cb50 100644 --- a/nipype/interfaces/cmtk/nbs.py +++ b/nipype/interfaces/cmtk/nbs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -6,6 +5,7 @@ import numpy as np import networkx as nx +import pickle from ... import logging from ..base import ( @@ -18,28 +18,30 @@ OutputMultiPath, isdefined, ) -from .base import have_cv iflogger = logging.getLogger("nipype.interface") +def _read_pickle(fname): + with open(fname, 'rb') as f: + return pickle.load(f) + + def ntwks_to_matrices(in_files, edge_key): - first = nx.read_gpickle(in_files[0]) + first = _read_pickle(in_files[0]) files = len(in_files) nodes = len(first.nodes()) matrix = np.zeros((nodes, nodes, files)) for idx, name in enumerate(in_files): - graph = nx.read_gpickle(name) + graph = _read_pickle(name) for u, v, d in graph.edges(data=True): try: graph[u][v]["weight"] = d[ edge_key ] # Setting the edge requested edge value as weight value except: - raise KeyError( - "the graph edges do not have {} attribute".format(edge_key) - ) - matrix[:, :, idx] = nx.to_numpy_matrix(graph) # Retrieve the matrix + raise KeyError(f"the graph edges do not have {edge_key} attribute") + matrix[:, :, idx] = nx.to_numpy_array(graph) # Retrieve the matrix return matrix @@ -149,8 +151,8 @@ def _run_interface(self, runtime): pADJ[x, y] = PVAL[idx] # Create networkx graphs from the adjacency matrix - nbsgraph = nx.from_numpy_matrix(ADJ) - nbs_pval_graph = nx.from_numpy_matrix(pADJ) + nbsgraph = nx.from_numpy_array(ADJ) + nbs_pval_graph = nx.from_numpy_array(pADJ) # Relabel nodes because they should not start at zero for our convention nbsgraph = nx.relabel_nodes(nbsgraph, lambda x: x + 1) @@ -161,7 +163,7 @@ def _run_interface(self, runtime): else: node_ntwk_name = self.inputs.in_group1[0] - node_network = nx.read_gpickle(node_ntwk_name) + node_network = _read_pickle(node_ntwk_name) iflogger.info( "Populating node dictionaries with attributes from %s", node_ntwk_name ) @@ -172,12 +174,14 @@ def _run_interface(self, runtime): path = op.abspath("NBS_Result_" + details) iflogger.info(path) - nx.write_gpickle(nbsgraph, path) + with open(path, 'wb') as f: + pickle.dump(nbsgraph, f, pickle.HIGHEST_PROTOCOL) iflogger.info("Saving output NBS edge network as %s", path) pval_path = op.abspath("NBS_P_vals_" + details) iflogger.info(pval_path) - nx.write_gpickle(nbs_pval_graph, pval_path) + with open(pval_path, 'wb') as f: + pickle.dump(nbs_pval_graph, f, pickle.HIGHEST_PROTOCOL) iflogger.info("Saving output p-value network as %s", pval_path) return runtime diff --git a/nipype/interfaces/cmtk/nx.py b/nipype/interfaces/cmtk/nx.py index 3886fe8844..ad72582f3d 100644 --- a/nipype/interfaces/cmtk/nx.py +++ b/nipype/interfaces/cmtk/nx.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os.path as op @@ -19,16 +18,20 @@ OutputMultiPath, isdefined, ) -from .base import have_cmp iflogger = logging.getLogger("nipype.interface") +def _read_pickle(fname): + with open(fname, 'rb') as f: + return pickle.load(f) + + def read_unknown_ntwk(ntwk): if not isinstance(ntwk, nx.classes.graph.Graph): _, _, ext = split_filename(ntwk) if ext == ".pck": - ntwk = nx.read_gpickle(ntwk) + ntwk = _read_pickle(ntwk) elif ext == ".graphml": ntwk = nx.read_graphml(ntwk) return ntwk @@ -120,8 +123,8 @@ def average_networks(in_files, ntwk_res_file, group_id): ntwk = remove_all_edges(ntwk_res_file) counting_ntwk = ntwk.copy() # Sums all the relevant variables - for index, subject in enumerate(in_files): - tmp = nx.read_gpickle(subject) + for subject in in_files: + tmp = _read_pickle(subject) iflogger.info("File %s has %i edges", subject, tmp.number_of_edges()) edges = list(tmp.edges()) for edge in edges: @@ -162,8 +165,8 @@ def average_networks(in_files, ntwk_res_file, group_id): for edge in edges: data = ntwk.edge[edge[0]][edge[1]] if ntwk.edge[edge[0]][edge[1]]["count"] >= count_to_keep_edge: - for key in list(data.keys()): - if not key == "count": + for key in data: + if key != "count": data[key] = data[key] / len(in_files) ntwk.edge[edge[0]][edge[1]] = data avg_ntwk.add_edge(edge[0], edge[1], **data) @@ -179,8 +182,8 @@ def average_networks(in_files, ntwk_res_file, group_id): avg_edges = avg_ntwk.edges() for edge in avg_edges: data = avg_ntwk.edge[edge[0]][edge[1]] - for key in list(data.keys()): - if not key == "count": + for key in data: + if key != "count": edge_dict[key] = np.zeros( (avg_ntwk.number_of_nodes(), avg_ntwk.number_of_nodes()) ) @@ -200,7 +203,8 @@ def average_networks(in_files, ntwk_res_file, group_id): # Writes the networks and returns the name network_name = group_id + "_average.pck" - nx.write_gpickle(avg_ntwk, op.abspath(network_name)) + with open(op.abspath(network_name), 'wb') as f: + pickle.dump(avg_ntwk, f, pickle.HIGHEST_PROTOCOL) iflogger.info("Saving average network as %s", op.abspath(network_name)) avg_ntwk = fix_keys_for_gexf(avg_ntwk) network_name = group_id + "_average.gexf" @@ -289,15 +293,9 @@ def compute_singlevalued_measures(ntwk, weighted=True, calculate_cliques=False): iflogger.info("Computing single valued measures:") measures = {} iflogger.info("...Computing degree assortativity (pearson number) ...") - try: - measures["degree_pearsonr"] = nx.degree_pearsonr(ntwk) - except AttributeError: # For NetworkX 1.6 - measures["degree_pearsonr"] = nx.degree_pearson_correlation_coefficient(ntwk) + measures["degree_pearsonr"] = nx.degree_pearson_correlation_coefficient(ntwk) iflogger.info("...Computing degree assortativity...") - try: - measures["degree_assortativity"] = nx.degree_assortativity(ntwk) - except AttributeError: - measures["degree_assortativity"] = nx.degree_assortativity_coefficient(ntwk) + measures["degree_assortativity"] = nx.degree_assortativity_coefficient(ntwk) iflogger.info("...Computing transitivity...") measures["transitivity"] = nx.transitivity(ntwk) iflogger.info("...Computing number of connected_components...") @@ -343,7 +341,7 @@ def add_node_data(node_array, ntwk): node_ntwk = nx.Graph() newdata = {} for idx, data in ntwk.nodes(data=True): - if not int(idx) == 0: + if int(idx) != 0: newdata["value"] = node_array[int(idx) - 1] data.update(newdata) node_ntwk.add_node(int(idx), **data) @@ -354,8 +352,8 @@ def add_edge_data(edge_array, ntwk, above=0, below=0): edge_ntwk = ntwk.copy() data = {} for x, row in enumerate(edge_array): - for y in range(0, np.max(np.shape(edge_array[x]))): - if not edge_array[x, y] == 0: + for y in range(np.max(np.shape(edge_array[x]))): + if edge_array[x, y] != 0: data["value"] = edge_array[x, y] if data["value"] <= below or data["value"] >= above: if edge_ntwk.has_edge(x + 1, y + 1): @@ -466,7 +464,7 @@ def _run_interface(self, runtime): edgentwks = list() kntwks = list() matlab = list() - ntwk = nx.read_gpickle(self.inputs.in_file) + ntwk = _read_pickle(self.inputs.in_file) # Each block computes, writes, and saves a measure # The names are then added to the output .pck file list @@ -489,7 +487,8 @@ def _run_interface(self, runtime): for key in list(node_measures.keys()): newntwk = add_node_data(node_measures[key], ntwk) out_file = op.abspath(self._gen_outfilename(key, "pck")) - nx.write_gpickle(newntwk, out_file) + with open(out_file, 'wb') as f: + pickle.dump(newntwk, f, pickle.HIGHEST_PROTOCOL) nodentwks.append(out_file) if isdefined(self.inputs.out_node_metrics_matlab): node_out_file = op.abspath(self.inputs.out_node_metrics_matlab) @@ -503,7 +502,8 @@ def _run_interface(self, runtime): for key in list(edge_measures.keys()): newntwk = add_edge_data(edge_measures[key], ntwk) out_file = op.abspath(self._gen_outfilename(key, "pck")) - nx.write_gpickle(newntwk, out_file) + with open(out_file, 'wb') as f: + pickle.dump(newntwk, f, pickle.HIGHEST_PROTOCOL) edgentwks.append(out_file) if isdefined(self.inputs.out_edge_metrics_matlab): edge_out_file = op.abspath(self.inputs.out_edge_metrics_matlab) @@ -527,7 +527,8 @@ def _run_interface(self, runtime): out_file = op.abspath( self._gen_outfilename(self.inputs.out_k_crust, "pck") ) - nx.write_gpickle(ntwk_measures[key], out_file) + with open(out_file, 'wb') as f: + pickle.dump(ntwk_measures[key], f, pickle.HIGHEST_PROTOCOL) kntwks.append(out_file) gpickled.extend(kntwks) @@ -539,8 +540,8 @@ def _run_interface(self, runtime): "Saving extra measure file to %s in Pickle format", op.abspath(out_pickled_extra_measures), ) - with open(out_pickled_extra_measures, "w") as fo: - pickle.dump(dict_measures, fo) + with open(out_pickled_extra_measures, "w") as f: + pickle.dump(dict_measures, f) iflogger.info("Saving MATLAB measures as %s", matlab) diff --git a/nipype/interfaces/cmtk/parcellation.py b/nipype/interfaces/cmtk/parcellation.py index 77e22bd6f7..65062247d8 100644 --- a/nipype/interfaces/cmtk/parcellation.py +++ b/nipype/interfaces/cmtk/parcellation.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -11,7 +10,6 @@ from ... import logging from ..base import ( - BaseInterface, LibraryBaseInterface, BaseInterfaceInputSpec, traits, @@ -20,13 +18,12 @@ Directory, isdefined, ) -from .base import have_cmp iflogger = logging.getLogger("nipype.interface") def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): - import cmp + from cmp.configuration import PipelineConfiguration from cmp.util import runCmd iflogger.info("Create the cortical labels necessary for our ROIs") @@ -34,7 +31,7 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): fs_label_dir = op.join(op.join(subjects_dir, subject_id), "label") output_dir = op.abspath(op.curdir) paths = [] - cmp_config = cmp.configuration.PipelineConfiguration() + cmp_config = PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" for hemi in ["lh", "rh"]: spath = ( @@ -264,7 +261,7 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): log = cmp_config.get_logger() for out in comp: - mris_cmd = 'mris_ca_label %s %s "%s/surf/%s.sphere.reg" "%s" "%s" ' % ( + mris_cmd = 'mris_ca_label {} {} "{}/surf/{}.sphere.reg" "{}" "{}" '.format( subject_id, out[0], op.join(subjects_dir, subject_id), @@ -277,11 +274,13 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): annot = '--annotation "%s"' % out[4] - mri_an_cmd = 'mri_annotation2label --subject %s --hemi %s --outdir "%s" %s' % ( - subject_id, - out[0], - op.join(output_dir, out[3]), - annot, + mri_an_cmd = ( + 'mri_annotation2label --subject {} --hemi {} --outdir "{}" {}'.format( + subject_id, + out[0], + op.join(output_dir, out[3]), + annot, + ) ) iflogger.info(mri_an_cmd) runCmd(mri_an_cmd, log) @@ -316,12 +315,12 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): ) runCmd(mri_cmd, log) runCmd("mris_volmask %s" % subject_id, log) - mri_cmd = 'mri_convert -i "%s/mri/ribbon.mgz" -o "%s/mri/ribbon.nii.gz"' % ( + mri_cmd = 'mri_convert -i "{}/mri/ribbon.mgz" -o "{}/mri/ribbon.nii.gz"'.format( op.join(subjects_dir, subject_id), op.join(subjects_dir, subject_id), ) runCmd(mri_cmd, log) - mri_cmd = 'mri_convert -i "%s/mri/aseg.mgz" -o "%s/mri/aseg.nii.gz"' % ( + mri_cmd = 'mri_convert -i "{}/mri/aseg.mgz" -o "{}/mri/aseg.nii.gz"'.format( op.join(subjects_dir, subject_id), op.join(subjects_dir, subject_id), ) @@ -331,15 +330,15 @@ def create_annot_label(subject_id, subjects_dir, fs_dir, parcellation_name): def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): - """ Creates the ROI_%s.nii.gz files using the given parcellation information - from networks. Iteratively create volume. """ - import cmp + """Creates the ROI_%s.nii.gz files using the given parcellation information + from networks. Iteratively create volume.""" + from cmp.configuration import PipelineConfiguration from cmp.util import runCmd iflogger.info("Create the ROIs:") output_dir = op.abspath(op.curdir) fs_dir = op.join(subjects_dir, subject_id) - cmp_config = cmp.configuration.PipelineConfiguration() + cmp_config = PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" log = cmp_config.get_logger() parval = cmp_config._get_lausanne_parcellation("Lausanne2008")[parcellation_name] @@ -407,15 +406,17 @@ def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): labelpath = op.join(output_dir, parval["fs_label_subdir_name"] % hemi) # construct .label file name - fname = "%s.%s.label" % (hemi, brv["dn_fsname"]) + fname = "{}.{}.label".format(hemi, brv["dn_fsname"]) # execute fs mri_label2vol to generate volume roi from the label file # store it in temporary file to be overwritten for each region - mri_cmd = 'mri_label2vol --label "%s" --temp "%s" --o "%s" --identity' % ( - op.join(labelpath, fname), - op.join(fs_dir, "mri", "orig.mgz"), - op.join(output_dir, "tmp.nii.gz"), + mri_cmd = ( + 'mri_label2vol --label "{}" --temp "{}" --o "{}" --identity'.format( + op.join(labelpath, fname), + op.join(fs_dir, "mri", "orig.mgz"), + op.join(output_dir, "tmp.nii.gz"), + ) ) runCmd(mri_cmd, log) @@ -466,12 +467,12 @@ def create_roi(subject_id, subjects_dir, fs_dir, parcellation_name, dilation): def create_wm_mask(subject_id, subjects_dir, fs_dir, parcellation_name): - import cmp + from cmp.configuration import PipelineConfiguration import scipy.ndimage.morphology as nd iflogger.info("Create white matter mask") fs_dir = op.join(subjects_dir, subject_id) - cmp_config = cmp.configuration.PipelineConfiguration() + cmp_config = PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" pgpath = cmp_config._get_lausanne_parcellation("Lausanne2008")[parcellation_name][ "node_information_graphml" @@ -590,7 +591,7 @@ def create_wm_mask(subject_id, subjects_dir, fs_dir, parcellation_name): # check if we should subtract the cortical rois from this parcellation iflogger.info( - "Loading ROI_%s.nii.gz to subtract cortical ROIs from white " "matter mask", + "Loading ROI_%s.nii.gz to subtract cortical ROIs from white matter mask", parcellation_name, ) roi = nb.load(op.join(op.curdir, "ROI_%s.nii.gz" % parcellation_name)) @@ -617,10 +618,11 @@ def create_wm_mask(subject_id, subjects_dir, fs_dir, parcellation_name): def crop_and_move_datasets( subject_id, subjects_dir, fs_dir, parcellation_name, out_roi_file, dilation ): + from cmp.configuration import PipelineConfiguration from cmp.util import runCmd fs_dir = op.join(subjects_dir, subject_id) - cmp_config = cmp.configuration.PipelineConfiguration() + cmp_config = PipelineConfiguration() cmp_config.parcellation_scheme = "Lausanne2008" log = cmp_config.get_logger() output_dir = op.abspath(op.curdir) @@ -656,7 +658,7 @@ def crop_and_move_datasets( raise Exception("File %s does not exist." % d[0]) # reslice to original volume because the roi creation with freesurfer # changed to 256x256x256 resolution - mri_cmd = 'mri_convert -rl "%s" -rt nearest "%s" -nc "%s"' % (orig, d[0], d[1]) + mri_cmd = f'mri_convert -rl "{orig}" -rt nearest "{d[0]}" -nc "{d[1]}"' runCmd(mri_cmd, log) diff --git a/nipype/interfaces/cmtk/tests/__init__.py b/nipype/interfaces/cmtk/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/cmtk/tests/__init__.py +++ b/nipype/interfaces/cmtk/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/cmtk/tests/test_auto_AverageNetworks.py b/nipype/interfaces/cmtk/tests/test_auto_AverageNetworks.py index 41d3f6ecce..e115acad83 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_AverageNetworks.py +++ b/nipype/interfaces/cmtk/tests/test_auto_AverageNetworks.py @@ -4,11 +4,21 @@ def test_AverageNetworks_inputs(): input_map = dict( - group_id=dict(usedefault=True,), - in_files=dict(mandatory=True,), - out_gexf_groupavg=dict(extensions=None,), - out_gpickled_groupavg=dict(extensions=None,), - resolution_network_file=dict(extensions=None,), + group_id=dict( + usedefault=True, + ), + in_files=dict( + mandatory=True, + ), + out_gexf_groupavg=dict( + extensions=None, + ), + out_gpickled_groupavg=dict( + extensions=None, + ), + resolution_network_file=dict( + extensions=None, + ), ) inputs = AverageNetworks.input_spec() @@ -19,8 +29,12 @@ def test_AverageNetworks_inputs(): def test_AverageNetworks_outputs(): output_map = dict( - gexf_groupavg=dict(extensions=None,), - gpickled_groupavg=dict(extensions=None,), + gexf_groupavg=dict( + extensions=None, + ), + gpickled_groupavg=dict( + extensions=None, + ), matlab_groupavgs=dict(), ) outputs = AverageNetworks.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_CFFConverter.py b/nipype/interfaces/cmtk/tests/test_auto_CFFConverter.py index 43240defab..ee7b0459ef 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_CFFConverter.py +++ b/nipype/interfaces/cmtk/tests/test_auto_CFFConverter.py @@ -6,7 +6,9 @@ def test_CFFConverter_inputs(): input_map = dict( creator=dict(), data_files=dict(), - description=dict(usedefault=True,), + description=dict( + usedefault=True, + ), email=dict(), gifti_labels=dict(), gifti_surfaces=dict(), @@ -14,13 +16,18 @@ def test_CFFConverter_inputs(): graphml_networks=dict(), license=dict(), nifti_volumes=dict(), - out_file=dict(extensions=None, usedefault=True,), + out_file=dict( + extensions=None, + usedefault=True, + ), publisher=dict(), references=dict(), relation=dict(), rights=dict(), script_files=dict(), - species=dict(usedefault=True,), + species=dict( + usedefault=True, + ), timeseries_files=dict(), title=dict(), tract_files=dict(), @@ -33,7 +40,11 @@ def test_CFFConverter_inputs(): def test_CFFConverter_outputs(): - output_map = dict(connectome_file=dict(extensions=None,),) + output_map = dict( + connectome_file=dict( + extensions=None, + ), + ) outputs = CFFConverter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/cmtk/tests/test_auto_CreateMatrix.py b/nipype/interfaces/cmtk/tests/test_auto_CreateMatrix.py index 3e68292557..a9466f91be 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_CreateMatrix.py +++ b/nipype/interfaces/cmtk/tests/test_auto_CreateMatrix.py @@ -4,17 +4,49 @@ def test_CreateMatrix_inputs(): input_map = dict( - count_region_intersections=dict(usedefault=True,), - out_endpoint_array_name=dict(extensions=None, genfile=True,), - out_fiber_length_std_matrix_mat_file=dict(extensions=None, genfile=True,), - out_intersection_matrix_mat_file=dict(extensions=None, genfile=True,), - out_matrix_file=dict(extensions=None, genfile=True,), - out_matrix_mat_file=dict(extensions=None, usedefault=True,), - out_mean_fiber_length_matrix_mat_file=dict(extensions=None, genfile=True,), - out_median_fiber_length_matrix_mat_file=dict(extensions=None, genfile=True,), - resolution_network_file=dict(extensions=None, mandatory=True,), - roi_file=dict(extensions=None, mandatory=True,), - tract_file=dict(extensions=None, mandatory=True,), + count_region_intersections=dict( + usedefault=True, + ), + out_endpoint_array_name=dict( + extensions=None, + genfile=True, + ), + out_fiber_length_std_matrix_mat_file=dict( + extensions=None, + genfile=True, + ), + out_intersection_matrix_mat_file=dict( + extensions=None, + genfile=True, + ), + out_matrix_file=dict( + extensions=None, + genfile=True, + ), + out_matrix_mat_file=dict( + extensions=None, + usedefault=True, + ), + out_mean_fiber_length_matrix_mat_file=dict( + extensions=None, + genfile=True, + ), + out_median_fiber_length_matrix_mat_file=dict( + extensions=None, + genfile=True, + ), + resolution_network_file=dict( + extensions=None, + mandatory=True, + ), + roi_file=dict( + extensions=None, + mandatory=True, + ), + tract_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = CreateMatrix.input_spec() @@ -25,24 +57,54 @@ def test_CreateMatrix_inputs(): def test_CreateMatrix_outputs(): output_map = dict( - endpoint_file=dict(extensions=None,), - endpoint_file_mm=dict(extensions=None,), - fiber_label_file=dict(extensions=None,), - fiber_labels_noorphans=dict(extensions=None,), - fiber_length_file=dict(extensions=None,), - fiber_length_std_matrix_mat_file=dict(extensions=None,), + endpoint_file=dict( + extensions=None, + ), + endpoint_file_mm=dict( + extensions=None, + ), + fiber_label_file=dict( + extensions=None, + ), + fiber_labels_noorphans=dict( + extensions=None, + ), + fiber_length_file=dict( + extensions=None, + ), + fiber_length_std_matrix_mat_file=dict( + extensions=None, + ), filtered_tractographies=dict(), - filtered_tractography=dict(extensions=None,), - filtered_tractography_by_intersections=dict(extensions=None,), - intersection_matrix_file=dict(extensions=None,), - intersection_matrix_mat_file=dict(extensions=None,), + filtered_tractography=dict( + extensions=None, + ), + filtered_tractography_by_intersections=dict( + extensions=None, + ), + intersection_matrix_file=dict( + extensions=None, + ), + intersection_matrix_mat_file=dict( + extensions=None, + ), matlab_matrix_files=dict(), - matrix_file=dict(extensions=None,), + matrix_file=dict( + extensions=None, + ), matrix_files=dict(), - matrix_mat_file=dict(extensions=None,), - mean_fiber_length_matrix_mat_file=dict(extensions=None,), - median_fiber_length_matrix_mat_file=dict(extensions=None,), - stats_file=dict(extensions=None,), + matrix_mat_file=dict( + extensions=None, + ), + mean_fiber_length_matrix_mat_file=dict( + extensions=None, + ), + median_fiber_length_matrix_mat_file=dict( + extensions=None, + ), + stats_file=dict( + extensions=None, + ), ) outputs = CreateMatrix.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_CreateNodes.py b/nipype/interfaces/cmtk/tests/test_auto_CreateNodes.py index 95023590d2..f88950d758 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_CreateNodes.py +++ b/nipype/interfaces/cmtk/tests/test_auto_CreateNodes.py @@ -4,9 +4,18 @@ def test_CreateNodes_inputs(): input_map = dict( - out_filename=dict(extensions=None, usedefault=True,), - resolution_network_file=dict(extensions=None, mandatory=True,), - roi_file=dict(extensions=None, mandatory=True,), + out_filename=dict( + extensions=None, + usedefault=True, + ), + resolution_network_file=dict( + extensions=None, + mandatory=True, + ), + roi_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = CreateNodes.input_spec() @@ -16,7 +25,11 @@ def test_CreateNodes_inputs(): def test_CreateNodes_outputs(): - output_map = dict(node_network=dict(extensions=None,),) + output_map = dict( + node_network=dict( + extensions=None, + ), + ) outputs = CreateNodes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/cmtk/tests/test_auto_MergeCNetworks.py b/nipype/interfaces/cmtk/tests/test_auto_MergeCNetworks.py index 30aae80243..17f8990a08 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_MergeCNetworks.py +++ b/nipype/interfaces/cmtk/tests/test_auto_MergeCNetworks.py @@ -4,8 +4,13 @@ def test_MergeCNetworks_inputs(): input_map = dict( - in_files=dict(mandatory=True,), - out_file=dict(extensions=None, usedefault=True,), + in_files=dict( + mandatory=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), ) inputs = MergeCNetworks.input_spec() @@ -15,7 +20,11 @@ def test_MergeCNetworks_inputs(): def test_MergeCNetworks_outputs(): - output_map = dict(connectome_file=dict(extensions=None,),) + output_map = dict( + connectome_file=dict( + extensions=None, + ), + ) outputs = MergeCNetworks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/cmtk/tests/test_auto_NetworkBasedStatistic.py b/nipype/interfaces/cmtk/tests/test_auto_NetworkBasedStatistic.py index af1c68fca2..975e4741cd 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_NetworkBasedStatistic.py +++ b/nipype/interfaces/cmtk/tests/test_auto_NetworkBasedStatistic.py @@ -4,15 +4,33 @@ def test_NetworkBasedStatistic_inputs(): input_map = dict( - edge_key=dict(usedefault=True,), - in_group1=dict(mandatory=True,), - in_group2=dict(mandatory=True,), - node_position_network=dict(extensions=None,), - number_of_permutations=dict(usedefault=True,), - out_nbs_network=dict(extensions=None,), - out_nbs_pval_network=dict(extensions=None,), - t_tail=dict(usedefault=True,), - threshold=dict(usedefault=True,), + edge_key=dict( + usedefault=True, + ), + in_group1=dict( + mandatory=True, + ), + in_group2=dict( + mandatory=True, + ), + node_position_network=dict( + extensions=None, + ), + number_of_permutations=dict( + usedefault=True, + ), + out_nbs_network=dict( + extensions=None, + ), + out_nbs_pval_network=dict( + extensions=None, + ), + t_tail=dict( + usedefault=True, + ), + threshold=dict( + usedefault=True, + ), ) inputs = NetworkBasedStatistic.input_spec() @@ -23,8 +41,12 @@ def test_NetworkBasedStatistic_inputs(): def test_NetworkBasedStatistic_outputs(): output_map = dict( - nbs_network=dict(extensions=None,), - nbs_pval_network=dict(extensions=None,), + nbs_network=dict( + extensions=None, + ), + nbs_pval_network=dict( + extensions=None, + ), network_files=dict(), ) outputs = NetworkBasedStatistic.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_NetworkXMetrics.py b/nipype/interfaces/cmtk/tests/test_auto_NetworkXMetrics.py index 820b447885..d171e6ab7a 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_NetworkXMetrics.py +++ b/nipype/interfaces/cmtk/tests/test_auto_NetworkXMetrics.py @@ -4,16 +4,44 @@ def test_NetworkXMetrics_inputs(): input_map = dict( - compute_clique_related_measures=dict(usedefault=True,), - in_file=dict(extensions=None, mandatory=True,), - out_edge_metrics_matlab=dict(extensions=None, genfile=True,), - out_global_metrics_matlab=dict(extensions=None, genfile=True,), - out_k_core=dict(extensions=None, usedefault=True,), - out_k_crust=dict(extensions=None, usedefault=True,), - out_k_shell=dict(extensions=None, usedefault=True,), - out_node_metrics_matlab=dict(extensions=None, genfile=True,), - out_pickled_extra_measures=dict(extensions=None, usedefault=True,), - treat_as_weighted_graph=dict(usedefault=True,), + compute_clique_related_measures=dict( + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + out_edge_metrics_matlab=dict( + extensions=None, + genfile=True, + ), + out_global_metrics_matlab=dict( + extensions=None, + genfile=True, + ), + out_k_core=dict( + extensions=None, + usedefault=True, + ), + out_k_crust=dict( + extensions=None, + usedefault=True, + ), + out_k_shell=dict( + extensions=None, + usedefault=True, + ), + out_node_metrics_matlab=dict( + extensions=None, + genfile=True, + ), + out_pickled_extra_measures=dict( + extensions=None, + usedefault=True, + ), + treat_as_weighted_graph=dict( + usedefault=True, + ), ) inputs = NetworkXMetrics.input_spec() @@ -25,18 +53,32 @@ def test_NetworkXMetrics_inputs(): def test_NetworkXMetrics_outputs(): output_map = dict( edge_measure_networks=dict(), - edge_measures_matlab=dict(extensions=None,), - global_measures_matlab=dict(extensions=None,), + edge_measures_matlab=dict( + extensions=None, + ), + global_measures_matlab=dict( + extensions=None, + ), gpickled_network_files=dict(), - k_core=dict(extensions=None,), - k_crust=dict(extensions=None,), + k_core=dict( + extensions=None, + ), + k_crust=dict( + extensions=None, + ), k_networks=dict(), - k_shell=dict(extensions=None,), + k_shell=dict( + extensions=None, + ), matlab_dict_measures=dict(), matlab_matrix_files=dict(), node_measure_networks=dict(), - node_measures_matlab=dict(extensions=None,), - pickled_extra_measures=dict(extensions=None,), + node_measures_matlab=dict( + extensions=None, + ), + pickled_extra_measures=dict( + extensions=None, + ), ) outputs = NetworkXMetrics.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_Parcellate.py b/nipype/interfaces/cmtk/tests/test_auto_Parcellate.py index 8c380c5704..800b5b516b 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_Parcellate.py +++ b/nipype/interfaces/cmtk/tests/test_auto_Parcellate.py @@ -4,11 +4,20 @@ def test_Parcellate_inputs(): input_map = dict( - dilation=dict(usedefault=True,), + dilation=dict( + usedefault=True, + ), freesurfer_dir=dict(), - out_roi_file=dict(extensions=None, genfile=True,), - parcellation_name=dict(usedefault=True,), - subject_id=dict(mandatory=True,), + out_roi_file=dict( + extensions=None, + genfile=True, + ), + parcellation_name=dict( + usedefault=True, + ), + subject_id=dict( + mandatory=True, + ), subjects_dir=dict(), ) inputs = Parcellate.input_spec() @@ -20,14 +29,30 @@ def test_Parcellate_inputs(): def test_Parcellate_outputs(): output_map = dict( - aseg_file=dict(extensions=None,), - cc_unknown_file=dict(extensions=None,), - dilated_roi_file_in_structural_space=dict(extensions=None,), - ribbon_file=dict(extensions=None,), - roi_file=dict(extensions=None,), - roi_file_in_structural_space=dict(extensions=None,), - roiv_file=dict(extensions=None,), - white_matter_mask_file=dict(extensions=None,), + aseg_file=dict( + extensions=None, + ), + cc_unknown_file=dict( + extensions=None, + ), + dilated_roi_file_in_structural_space=dict( + extensions=None, + ), + ribbon_file=dict( + extensions=None, + ), + roi_file=dict( + extensions=None, + ), + roi_file_in_structural_space=dict( + extensions=None, + ), + roiv_file=dict( + extensions=None, + ), + white_matter_mask_file=dict( + extensions=None, + ), ) outputs = Parcellate.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_auto_ROIGen.py b/nipype/interfaces/cmtk/tests/test_auto_ROIGen.py index 2191f940ac..54fd9e46e9 100644 --- a/nipype/interfaces/cmtk/tests/test_auto_ROIGen.py +++ b/nipype/interfaces/cmtk/tests/test_auto_ROIGen.py @@ -4,12 +4,28 @@ def test_ROIGen_inputs(): input_map = dict( - LUT_file=dict(extensions=None, xor=["use_freesurfer_LUT"],), - aparc_aseg_file=dict(extensions=None, mandatory=True,), - freesurfer_dir=dict(requires=["use_freesurfer_LUT"],), - out_dict_file=dict(extensions=None, genfile=True,), - out_roi_file=dict(extensions=None, genfile=True,), - use_freesurfer_LUT=dict(xor=["LUT_file"],), + LUT_file=dict( + extensions=None, + xor=["use_freesurfer_LUT"], + ), + aparc_aseg_file=dict( + extensions=None, + mandatory=True, + ), + freesurfer_dir=dict( + requires=["use_freesurfer_LUT"], + ), + out_dict_file=dict( + extensions=None, + genfile=True, + ), + out_roi_file=dict( + extensions=None, + genfile=True, + ), + use_freesurfer_LUT=dict( + xor=["LUT_file"], + ), ) inputs = ROIGen.input_spec() @@ -20,7 +36,12 @@ def test_ROIGen_inputs(): def test_ROIGen_outputs(): output_map = dict( - dict_file=dict(extensions=None,), roi_file=dict(extensions=None,), + dict_file=dict( + extensions=None, + ), + roi_file=dict( + extensions=None, + ), ) outputs = ROIGen.output_spec() diff --git a/nipype/interfaces/cmtk/tests/test_nbs.py b/nipype/interfaces/cmtk/tests/test_nbs.py index 46da939f1a..efc8aed678 100644 --- a/nipype/interfaces/cmtk/tests/test_nbs.py +++ b/nipype/interfaces/cmtk/tests/test_nbs.py @@ -2,12 +2,13 @@ from ....utils.misc import package_check import numpy as np import networkx as nx +import pickle import pytest have_cv = True try: package_check("cviewer") -except Exception as e: +except Exception: have_cv = False @@ -15,12 +16,13 @@ def creating_graphs(tmpdir): graphlist = [] graphnames = ["name" + str(i) for i in range(6)] - for idx, name in enumerate(graphnames): + for idx in range(len(graphnames)): graph = np.random.rand(10, 10) - G = nx.from_numpy_matrix(graph) + G = nx.from_numpy_array(graph) out_file = tmpdir.strpath + graphnames[idx] + ".pck" # Save as pck file - nx.write_gpickle(G, out_file) + with open(out_file, 'wb') as f: + pickle.dump(G, f, pickle.HIGHEST_PROTOCOL) graphlist.append(out_file) return graphlist @@ -37,7 +39,7 @@ def test_importerror(creating_graphs, tmpdir): nbs.inputs.in_group2 = group2 nbs.inputs.edge_key = "weight" - with pytest.raises(ImportError) as e: + with pytest.raises(ImportError): nbs.run() diff --git a/nipype/interfaces/dcm2nii.py b/nipype/interfaces/dcm2nii.py index c88f11ba6a..baeb21c1e8 100644 --- a/nipype/interfaces/dcm2nii.py +++ b/nipype/interfaces/dcm2nii.py @@ -1,9 +1,10 @@ -# -*- coding: utf-8 -*- """dcm2nii converts images from the proprietary scanner DICOM format to NIfTI.""" + import os import re from copy import deepcopy import itertools as it +import glob from glob import iglob from ..utils.filemanip import split_filename @@ -119,7 +120,7 @@ class Dcm2nii(CommandLine): >>> converter.inputs.output_dir = '.' >>> converter.cmdline # doctest: +ELLIPSIS 'dcm2nii -a y -c y -b config.ini -v y -d y -e y -g y -i n -n y -o . -p y -x n -f n functional_1.dcm' -""" + """ input_spec = Dcm2niiInputSpec output_spec = Dcm2niiOutputSpec @@ -149,11 +150,11 @@ def _format_arg(self, opt, spec, val): val = True if opt == "source_names": return spec.argstr % val[0] - return super(Dcm2nii, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _run_interface(self, runtime): self._config_created = False - new_runtime = super(Dcm2nii, self)._run_interface(runtime) + new_runtime = super()._run_interface(runtime) ( self.output_files, self.reoriented_files, @@ -201,7 +202,7 @@ def _parse_stdout(self, stdout): # just above for l in (bvecs, bvals): l[-1] = os.path.join( - os.path.dirname(l[-1]), "x%s" % (os.path.basename(l[-1]),) + os.path.dirname(l[-1]), f"x{os.path.basename(l[-1])}" ) elif re.search(".*->(.*)", line): val = re.search(".*->(.*)", line) @@ -327,8 +328,14 @@ class Dcm2niixInputSpec(CommandLineInputSpec): usedefault=True, desc="Gzip compress images - [y=pigz, i=internal, n=no, 3=no,3D]", ) - merge_imgs = traits.Bool( - False, argstr="-m", usedefault=True, desc="merge 2D slices from same series" + merge_imgs = traits.Enum( + 0, + 1, + 2, + default=0, + usedefault=True, + argstr="-m %d", + desc="merge 2D slices from same series regardless of echo, exposure, etc. - [0=no, 1=yes, 2=auto]", ) single_file = traits.Bool( False, argstr="-s", usedefault=True, desc="Single file mode" @@ -374,6 +381,7 @@ class Dcm2niixInputSpec(CommandLineInputSpec): class Dcm2niixOutputSpec(TraitedSpec): converted_files = OutputMultiPath(File(exists=True)) bvecs = OutputMultiPath(File(exists=True)) + mvecs = OutputMultiPath(File(exists=True)) bvals = OutputMultiPath(File(exists=True)) bids = OutputMultiPath(File(exists=True)) @@ -390,7 +398,7 @@ class Dcm2niix(CommandLine): >>> converter.inputs.compression = 5 >>> converter.inputs.output_dir = 'ds005' >>> converter.cmdline - 'dcm2niix -b y -z y -5 -x n -t n -m n -o ds005 -s n -v n dicomdir' + 'dcm2niix -b y -z y -5 -x n -t n -m 0 -o ds005 -s n -v n dicomdir' >>> converter.run() # doctest: +SKIP In the example below, we note that the current version of dcm2niix @@ -403,7 +411,7 @@ class Dcm2niix(CommandLine): >>> converter.inputs.compression = 5 >>> converter.inputs.output_dir = 'ds005' >>> converter.cmdline - 'dcm2niix -b y -z y -5 -x n -t n -m n -o ds005 -s n -v n .' + 'dcm2niix -b y -z y -5 -x n -t n -m 0 -o ds005 -s n -v n .' >>> converter.run() # doctest: +SKIP """ @@ -418,7 +426,6 @@ def version(self): def _format_arg(self, opt, spec, val): bools = [ "bids_format", - "merge_imgs", "single_file", "verbose", "crop", @@ -437,13 +444,11 @@ def _format_arg(self, opt, spec, val): val = True if opt == "source_names": return spec.argstr % (os.path.dirname(val[0]) or ".") - return super(Dcm2niix, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _run_interface(self, runtime): # may use return code 1 despite conversion - runtime = super(Dcm2niix, self)._run_interface( - runtime, correct_return_codes=(0, 1,) - ) + runtime = super()._run_interface(runtime, correct_return_codes=(0, 1)) self._parse_files(self._parse_stdout(runtime.stdout)) return runtime @@ -456,8 +461,8 @@ def _parse_stdout(self, stdout): return filenames def _parse_files(self, filenames): - outfiles, bvals, bvecs, bids = [], [], [], [] - outtypes = [".bval", ".bvec", ".json", ".txt"] + outfiles, bvals, bvecs, mvecs, bids = [], [], [], [], [] + outtypes = [".bval", ".bvec", ".mvec", ".json", ".txt"] if self.inputs.to_nrrd: outtypes += [".nrrd", ".nhdr", ".raw.gz"] else: @@ -465,22 +470,25 @@ def _parse_files(self, filenames): for filename in filenames: # search for relevant files, and sort accordingly - for fl in search_files(filename, outtypes): - if ( - fl.endswith(".nii") - or fl.endswith(".gz") - or fl.endswith(".nrrd") - or fl.endswith(".nhdr") - ): + for fl in search_files(filename, outtypes, self.inputs.crop): + if fl.endswith((".nii", ".gz", ".nrrd", ".nhdr")): outfiles.append(fl) elif fl.endswith(".bval"): bvals.append(fl) elif fl.endswith(".bvec"): bvecs.append(fl) - elif fl.endswith(".json") or fl.endswith(".txt"): + elif fl.endswith(".mvec"): + mvecs.append(fl) + elif fl.endswith((".json", ".txt")): bids.append(fl) + + # in siemens mosaic conversion nipype misread dcm2niix output and generate a duplicate list of results + # next line remove duplicates from output files array + outfiles = list(dict.fromkeys(outfiles)) + self.output_files = outfiles self.bvecs = bvecs + self.mvecs = mvecs self.bvals = bvals self.bids = bids @@ -489,10 +497,21 @@ def _list_outputs(self): outputs["converted_files"] = self.output_files outputs["bvecs"] = self.bvecs outputs["bvals"] = self.bvals + outputs["mvecs"] = self.mvecs outputs["bids"] = self.bids return outputs # https://stackoverflow.com/a/4829130 -def search_files(prefix, outtypes): - return it.chain.from_iterable(iglob(prefix + outtype) for outtype in outtypes) +def search_files(prefix, outtypes, search_crop): + found = it.chain.from_iterable( + iglob(glob.escape(prefix + outtype)) for outtype in outtypes + ) + if search_crop: + found = it.chain( + it.chain.from_iterable( + iglob(glob.escape(prefix) + "_Crop_*" + outtype) for outtype in outtypes + ), + found, + ) + return found diff --git a/nipype/interfaces/dcmstack.py b/nipype/interfaces/dcmstack.py index f23461814c..7664097c58 100644 --- a/nipype/interfaces/dcmstack.py +++ b/nipype/interfaces/dcmstack.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """dcmstack allows series of DICOM images to be stacked into multi-dimensional arrays.""" import os @@ -8,7 +7,7 @@ from glob import glob import nibabel as nb -import imghdr +import puremagic from .base import ( TraitedSpec, @@ -21,11 +20,10 @@ isdefined, Undefined, ) -from ..utils import NUMPY_MMAP have_dcmstack = True try: - import dicom + import pydicom import dcmstack from dcmstack.dcmmeta import NiftiWrapper except ImportError: @@ -35,7 +33,7 @@ def sanitize_path_comp(path_comp): result = [] for char in path_comp: - if char not in string.letters + string.digits + "-_.": + if char not in string.ascii_letters + string.digits + "-_.": result.append("_") else: result.append(char) @@ -56,7 +54,7 @@ class NiftiGeneratorBase(BaseInterface): embedded meta data.""" def _get_out_path(self, meta, idx=None): - """Return the output path for the gernerated Nifti.""" + """Return the output path for the generated Nifti.""" if self.inputs.out_format: out_fmt = self.inputs.out_format else: @@ -102,10 +100,10 @@ class DcmStackInputSpec(NiftiGeneratorBaseInputSpec): ) embed_meta = traits.Bool(desc="Embed DICOM meta data into result") exclude_regexes = traits.List( - desc="Meta data to exclude, suplementing " "any default exclude filters" + desc="Meta data to exclude, supplementing any default exclude filters" ) include_regexes = traits.List( - desc="Meta data to include, overriding any " "exclude filters" + desc="Meta data to include, overriding any exclude filters" ) force_read = traits.Bool( True, usedefault=True, desc=("Force reading files without DICM marker") @@ -154,8 +152,8 @@ def _run_interface(self, runtime): meta_filter = dcmstack.make_key_regex_filter(exclude_regexes, include_regexes) stack = dcmstack.DicomStack(meta_filter=meta_filter) for src_path in src_paths: - if not imghdr.what(src_path) == "gif": - src_dcm = dicom.read_file(src_path, force=self.inputs.force_read) + if puremagic.what(src_path) != "gif": + src_dcm = pydicom.dcmread(src_path, force=self.inputs.force_read) stack.add_dcm(src_dcm) nii = stack.to_nifti(embed_meta=True) nw = NiftiWrapper(nii) @@ -178,8 +176,7 @@ class GroupAndStackOutputSpec(TraitedSpec): class GroupAndStack(DcmStack): - """Create (potentially) multiple Nifti files for a set of DICOM files. - """ + """Create (potentially) multiple Nifti files for a set of DICOM files.""" input_spec = DcmStackInputSpec output_spec = GroupAndStackOutputSpec @@ -252,7 +249,7 @@ def _make_name_map(self): def _outputs(self): self._make_name_map() - outputs = super(LookupMeta, self)._outputs() + outputs = super()._outputs() undefined_traits = {} for out_name in list(self._meta_keys.values()): outputs.add_trait(out_name, traits.Any) @@ -264,7 +261,7 @@ def _outputs(self): return outputs def _run_interface(self, runtime): - # If the 'meta_keys' input is a list, covert it to a dict + # If the 'meta_keys' input is a list, convert it to a dict self._make_name_map() nw = NiftiWrapper.from_filename(self.inputs.in_file) self.result = {} @@ -287,9 +284,7 @@ class CopyMetaInputSpec(TraitedSpec): "classifications to include. If not " "specified include everything." ) - exclude_classes = traits.List( - desc="List of meta data " "classifications to exclude" - ) + exclude_classes = traits.List(desc="List of meta data classifications to exclude") class CopyMetaOutputSpec(TraitedSpec): @@ -339,12 +334,12 @@ class MergeNiftiInputSpec(NiftiGeneratorBaseInputSpec): sort_order = traits.Either( traits.Str(), traits.List(), - desc="One or more meta data keys to " "sort files by.", + desc="One or more meta data keys to sort files by.", ) merge_dim = traits.Int( desc="Dimension to merge along. If not " "specified, the last singular or " - "non-existant dimension is used." + "non-existent dimension is used." ) @@ -368,7 +363,7 @@ class MergeNifti(NiftiGeneratorBase): output_spec = MergeNiftiOutputSpec def _run_interface(self, runtime): - niis = [nb.load(fn, mmap=NUMPY_MMAP) for fn in self.inputs.in_files] + niis = [nb.load(fn) for fn in self.inputs.in_files] nws = [NiftiWrapper(nii, make_empty=True) for nii in niis] if self.inputs.sort_order: sort_order = self.inputs.sort_order diff --git a/nipype/interfaces/diffusion_toolkit/__init__.py b/nipype/interfaces/diffusion_toolkit/__init__.py index c3927800a3..89b3d059ef 100644 --- a/nipype/interfaces/diffusion_toolkit/__init__.py +++ b/nipype/interfaces/diffusion_toolkit/__init__.py @@ -1,5 +1,5 @@ -# -*- coding: utf-8 -*- """Diffusion Toolkit performs data reconstruction and fiber tracking on diffusion MR images.""" + from .base import Info from .postproc import SplineFilter, TrackMerge from .dti import DTIRecon, DTITracker diff --git a/nipype/interfaces/diffusion_toolkit/base.py b/nipype/interfaces/diffusion_toolkit/base.py index 02c7deceb1..051d80e0f1 100644 --- a/nipype/interfaces/diffusion_toolkit/base.py +++ b/nipype/interfaces/diffusion_toolkit/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The dtk module provides basic functions for interfacing with @@ -19,8 +18,8 @@ __docformat__ = "restructuredtext" -class Info(object): - """ Handle dtk output type and version information. +class Info: + """Handle dtk output type and version information. Examples -------- @@ -47,7 +46,7 @@ def version(): """ clout = CommandLine(command="dti_recon", terminal_output="allatonce").run() - if clout.runtime.returncode is not 0: + if clout.runtime.returncode != 0: return None dtirecon = clout.runtime.stdout diff --git a/nipype/interfaces/diffusion_toolkit/dti.py b/nipype/interfaces/diffusion_toolkit/dti.py index f5715fb443..bf6336c96d 100644 --- a/nipype/interfaces/diffusion_toolkit/dti.py +++ b/nipype/interfaces/diffusion_toolkit/dti.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Provides interfaces to various commands provided by diffusion toolkit -""" +"""Provides interfaces to various commands provided by diffusion toolkit""" import os import re @@ -88,8 +86,7 @@ class DTIReconOutputSpec(TraitedSpec): class DTIRecon(CommandLine): - """Use dti_recon to generate tensors and other maps - """ + """Use dti_recon to generate tensors and other maps""" input_spec = DTIReconInputSpec output_spec = DTIReconOutputSpec @@ -99,7 +96,7 @@ class DTIRecon(CommandLine): def _create_gradient_matrix(self, bvecs_file, bvals_file): _gradient_matrix_file = "gradient_matrix.txt" with open(bvals_file) as fbvals: - bvals = [val for val in re.split(r"\s+", fbvals.readline().strip())] + bvals = fbvals.readline().strip().split() with open(bvecs_file) as fbvecs: bvecs_x = fbvecs.readline().split() bvecs_y = fbvecs.readline().split() @@ -108,15 +105,15 @@ def _create_gradient_matrix(self, bvecs_file, bvals_file): with open(_gradient_matrix_file, "w") as gradient_matrix_f: for i in range(len(bvals)): gradient_matrix_f.write( - "%s, %s, %s, %s\n" % (bvecs_x[i], bvecs_y[i], bvecs_z[i], bvals[i]) + f"{bvecs_x[i]}, {bvecs_y[i]}, {bvecs_z[i]}, {bvals[i]}\n" ) return _gradient_matrix_file def _format_arg(self, name, spec, value): if name == "bvecs": new_val = self._create_gradient_matrix(self.inputs.bvecs, self.inputs.bvals) - return super(DTIRecon, self)._format_arg("bvecs", spec, new_val) - return super(DTIRecon, self)._format_arg(name, spec, value) + return super()._format_arg("bvecs", spec, new_val) + return super()._format_arg(name, spec, value) def _list_outputs(self): out_prefix = self.inputs.out_prefix @@ -174,7 +171,7 @@ class DTITrackerInputSpec(CommandLineInputSpec): Input and output file type. Accepted values are: * analyze -> analyze format 7.5 -* ni1 -> nifti format saved in seperate .hdr and .img file +* ni1 -> nifti format saved in separate .hdr and .img file * nii -> nifti format with one .nii file * nii.gz -> nifti format with compression @@ -209,7 +206,7 @@ class DTITrackerInputSpec(CommandLineInputSpec): desc="set angle threshold. default value is 35 degree", argstr="-at %f" ) angle_threshold_weight = traits.Float( - desc="set angle threshold weighting factor. weighting will be be applied " + desc="set angle threshold weighting factor. weighting will be applied " "on top of the angle_threshold", argstr="-atw %f", ) @@ -278,7 +275,7 @@ def _run_interface(self, runtime): copy=False, ) - return super(DTITracker, self)._run_interface(runtime) + return super()._run_interface(runtime) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/diffusion_toolkit/odf.py b/nipype/interfaces/diffusion_toolkit/odf.py index b3d6574099..daadffc200 100644 --- a/nipype/interfaces/diffusion_toolkit/odf.py +++ b/nipype/interfaces/diffusion_toolkit/odf.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Provides interfaces to various commands provided by diffusion toolkit -""" +"""Provides interfaces to various commands provided by diffusion toolkit""" import os import re @@ -90,8 +88,7 @@ class HARDIMatOutputSpec(TraitedSpec): class HARDIMat(CommandLine): - """Use hardi_mat to calculate a reconstruction matrix from a gradient table - """ + """Use hardi_mat to calculate a reconstruction matrix from a gradient table""" input_spec = HARDIMatInputSpec output_spec = HARDIMatOutputSpec @@ -100,25 +97,25 @@ class HARDIMat(CommandLine): def _create_gradient_matrix(self, bvecs_file, bvals_file): _gradient_matrix_file = "gradient_matrix.txt" - bvals = [val for val in re.split(r"\s+", open(bvals_file).readline().strip())] - bvecs_f = open(bvecs_file) - bvecs_x = [val for val in re.split(r"\s+", bvecs_f.readline().strip())] - bvecs_y = [val for val in re.split(r"\s+", bvecs_f.readline().strip())] - bvecs_z = [val for val in re.split(r"\s+", bvecs_f.readline().strip())] - bvecs_f.close() + with open(bvals_file) as bvals_f: + bvals = bvals_f.readline().strip().split() + with open(bvecs_file) as bvecs_f: + bvecs_x = bvecs_f.readline().strip().split() + bvecs_y = bvecs_f.readline().strip().split() + bvecs_z = bvecs_f.readline().strip().split() gradient_matrix_f = open(_gradient_matrix_file, "w") for i in range(len(bvals)): if int(bvals[i]) == 0: continue - gradient_matrix_f.write("%s %s %s\n" % (bvecs_x[i], bvecs_y[i], bvecs_z[i])) + gradient_matrix_f.write(f"{bvecs_x[i]} {bvecs_y[i]} {bvecs_z[i]}\n") gradient_matrix_f.close() return _gradient_matrix_file def _format_arg(self, name, spec, value): if name == "bvecs": new_val = self._create_gradient_matrix(self.inputs.bvecs, self.inputs.bvals) - return super(HARDIMat, self)._format_arg("bvecs", spec, new_val) - return super(HARDIMat, self)._format_arg(name, spec, value) + return super()._format_arg("bvecs", spec, new_val) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -210,8 +207,7 @@ class ODFReconOutputSpec(TraitedSpec): class ODFRecon(CommandLine): - """Use odf_recon to generate tensors and other maps - """ + """Use odf_recon to generate tensors and other maps""" input_spec = ODFReconInputSpec output_spec = ODFReconOutputSpec @@ -368,8 +364,7 @@ class ODFTrackerOutputSpec(TraitedSpec): class ODFTracker(CommandLine): - """Use odf_tracker to generate track file - """ + """Use odf_tracker to generate track file""" input_spec = ODFTrackerInputSpec output_spec = ODFTrackerOutputSpec @@ -391,7 +386,7 @@ def _run_interface(self, runtime): copy=False, ) - return super(ODFTracker, self)._run_interface(runtime) + return super()._run_interface(runtime) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/diffusion_toolkit/postproc.py b/nipype/interfaces/diffusion_toolkit/postproc.py index 534b747a0d..d05cfadff6 100644 --- a/nipype/interfaces/diffusion_toolkit/postproc.py +++ b/nipype/interfaces/diffusion_toolkit/postproc.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Provides interfaces to various commands provided by diffusion toolkit -""" +"""Provides interfaces to various commands provided by diffusion toolkit""" import os from ..base import ( diff --git a/nipype/interfaces/diffusion_toolkit/tests/__init__.py b/nipype/interfaces/diffusion_toolkit/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/__init__.py +++ b/nipype/interfaces/diffusion_toolkit/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTIRecon.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTIRecon.py index 91e164f35a..f7bf46f327 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTIRecon.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTIRecon.py @@ -4,17 +4,49 @@ def test_DTIRecon_inputs(): input_map = dict( - DWI=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - args=dict(argstr="%s",), - b0_threshold=dict(argstr="-b0_th",), - bvals=dict(extensions=None, mandatory=True,), - bvecs=dict(argstr="-gm %s", extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - image_orientation_vectors=dict(argstr="-iop %f",), - n_averages=dict(argstr="-nex %s",), - oblique_correction=dict(argstr="-oc",), - out_prefix=dict(argstr="%s", position=2, usedefault=True,), - output_type=dict(argstr="-ot %s", usedefault=True,), + DWI=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + args=dict( + argstr="%s", + ), + b0_threshold=dict( + argstr="-b0_th", + ), + bvals=dict( + extensions=None, + mandatory=True, + ), + bvecs=dict( + argstr="-gm %s", + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + image_orientation_vectors=dict( + argstr="-iop %f", + ), + n_averages=dict( + argstr="-nex %s", + ), + oblique_correction=dict( + argstr="-oc", + ), + out_prefix=dict( + argstr="%s", + position=2, + usedefault=True, + ), + output_type=dict( + argstr="-ot %s", + usedefault=True, + ), ) inputs = DTIRecon.input_spec() @@ -25,18 +57,42 @@ def test_DTIRecon_inputs(): def test_DTIRecon_outputs(): output_map = dict( - ADC=dict(extensions=None,), - B0=dict(extensions=None,), - FA=dict(extensions=None,), - FA_color=dict(extensions=None,), - L1=dict(extensions=None,), - L2=dict(extensions=None,), - L3=dict(extensions=None,), - V1=dict(extensions=None,), - V2=dict(extensions=None,), - V3=dict(extensions=None,), - exp=dict(extensions=None,), - tensor=dict(extensions=None,), + ADC=dict( + extensions=None, + ), + B0=dict( + extensions=None, + ), + FA=dict( + extensions=None, + ), + FA_color=dict( + extensions=None, + ), + L1=dict( + extensions=None, + ), + L2=dict( + extensions=None, + ), + L3=dict( + extensions=None, + ), + V1=dict( + extensions=None, + ), + V2=dict( + extensions=None, + ), + V3=dict( + extensions=None, + ), + exp=dict( + extensions=None, + ), + tensor=dict( + extensions=None, + ), ) outputs = DTIRecon.output_spec() diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTITracker.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTITracker.py index d1fd3bd1e8..e550bc4b27 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTITracker.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_DTITracker.py @@ -4,29 +4,87 @@ def test_DTITracker_inputs(): input_map = dict( - angle_threshold=dict(argstr="-at %f",), - angle_threshold_weight=dict(argstr="-atw %f",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - input_data_prefix=dict(argstr="%s", position=0, usedefault=True,), - input_type=dict(argstr="-it %s",), - invert_x=dict(argstr="-ix",), - invert_y=dict(argstr="-iy",), - invert_z=dict(argstr="-iz",), - mask1_file=dict(argstr="-m %s", extensions=None, mandatory=True, position=2,), - mask1_threshold=dict(position=3,), - mask2_file=dict(argstr="-m2 %s", extensions=None, position=4,), - mask2_threshold=dict(position=5,), - output_file=dict(argstr="%s", extensions=None, position=1, usedefault=True,), - output_mask=dict(argstr="-om %s", extensions=None,), - primary_vector=dict(argstr="-%s",), - random_seed=dict(argstr="-rseed %d",), - step_length=dict(argstr="-l %f",), - swap_xy=dict(argstr="-sxy",), - swap_yz=dict(argstr="-syz",), - swap_zx=dict(argstr="-szx",), - tensor_file=dict(extensions=None,), - tracking_method=dict(argstr="-%s",), + angle_threshold=dict( + argstr="-at %f", + ), + angle_threshold_weight=dict( + argstr="-atw %f", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_data_prefix=dict( + argstr="%s", + position=0, + usedefault=True, + ), + input_type=dict( + argstr="-it %s", + ), + invert_x=dict( + argstr="-ix", + ), + invert_y=dict( + argstr="-iy", + ), + invert_z=dict( + argstr="-iz", + ), + mask1_file=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + position=2, + ), + mask1_threshold=dict( + position=3, + ), + mask2_file=dict( + argstr="-m2 %s", + extensions=None, + position=4, + ), + mask2_threshold=dict( + position=5, + ), + output_file=dict( + argstr="%s", + extensions=None, + position=1, + usedefault=True, + ), + output_mask=dict( + argstr="-om %s", + extensions=None, + ), + primary_vector=dict( + argstr="-%s", + ), + random_seed=dict( + argstr="-rseed %d", + ), + step_length=dict( + argstr="-l %f", + ), + swap_xy=dict( + argstr="-sxy", + ), + swap_yz=dict( + argstr="-syz", + ), + swap_zx=dict( + argstr="-szx", + ), + tensor_file=dict( + extensions=None, + ), + tracking_method=dict( + argstr="-%s", + ), ) inputs = DTITracker.input_spec() @@ -37,7 +95,12 @@ def test_DTITracker_inputs(): def test_DTITracker_outputs(): output_map = dict( - mask_file=dict(extensions=None,), track_file=dict(extensions=None,), + mask_file=dict( + extensions=None, + ), + track_file=dict( + extensions=None, + ), ) outputs = DTITracker.output_spec() diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_HARDIMat.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_HARDIMat.py index 6cddb31fdc..a933495672 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_HARDIMat.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_HARDIMat.py @@ -4,17 +4,50 @@ def test_HARDIMat_inputs(): input_map = dict( - args=dict(argstr="%s",), - bvals=dict(extensions=None, mandatory=True,), - bvecs=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - environ=dict(nohash=True, usedefault=True,), - image_info=dict(argstr="-info %s", extensions=None,), - image_orientation_vectors=dict(argstr="-iop %f",), - oblique_correction=dict(argstr="-oc",), - odf_file=dict(argstr="-odf %s", extensions=None,), - order=dict(argstr="-order %s",), - out_file=dict(argstr="%s", extensions=None, position=2, usedefault=True,), - reference_file=dict(argstr="-ref %s", extensions=None,), + args=dict( + argstr="%s", + ), + bvals=dict( + extensions=None, + mandatory=True, + ), + bvecs=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + image_info=dict( + argstr="-info %s", + extensions=None, + ), + image_orientation_vectors=dict( + argstr="-iop %f", + ), + oblique_correction=dict( + argstr="-oc", + ), + odf_file=dict( + argstr="-odf %s", + extensions=None, + ), + order=dict( + argstr="-order %s", + ), + out_file=dict( + argstr="%s", + extensions=None, + position=2, + usedefault=True, + ), + reference_file=dict( + argstr="-ref %s", + extensions=None, + ), ) inputs = HARDIMat.input_spec() @@ -24,7 +57,11 @@ def test_HARDIMat_inputs(): def test_HARDIMat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = HARDIMat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFRecon.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFRecon.py index 0e8132a7f6..b6a18aaf77 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFRecon.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFRecon.py @@ -4,22 +4,68 @@ def test_ODFRecon_inputs(): input_map = dict( - DWI=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - args=dict(argstr="%s",), - dsi=dict(argstr="-dsi",), - environ=dict(nohash=True, usedefault=True,), - filter=dict(argstr="-f",), - image_orientation_vectors=dict(argstr="-iop %f",), - matrix=dict(argstr="-mat %s", extensions=None, mandatory=True,), - n_b0=dict(argstr="-b0 %s", mandatory=True,), - n_directions=dict(argstr="%s", mandatory=True, position=2,), - n_output_directions=dict(argstr="%s", mandatory=True, position=3,), - oblique_correction=dict(argstr="-oc",), - out_prefix=dict(argstr="%s", position=4, usedefault=True,), - output_entropy=dict(argstr="-oe",), - output_type=dict(argstr="-ot %s", usedefault=True,), - sharpness=dict(argstr="-s %f",), - subtract_background=dict(argstr="-bg",), + DWI=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + args=dict( + argstr="%s", + ), + dsi=dict( + argstr="-dsi", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filter=dict( + argstr="-f", + ), + image_orientation_vectors=dict( + argstr="-iop %f", + ), + matrix=dict( + argstr="-mat %s", + extensions=None, + mandatory=True, + ), + n_b0=dict( + argstr="-b0 %s", + mandatory=True, + ), + n_directions=dict( + argstr="%s", + mandatory=True, + position=2, + ), + n_output_directions=dict( + argstr="%s", + mandatory=True, + position=3, + ), + oblique_correction=dict( + argstr="-oc", + ), + out_prefix=dict( + argstr="%s", + position=4, + usedefault=True, + ), + output_entropy=dict( + argstr="-oe", + ), + output_type=dict( + argstr="-ot %s", + usedefault=True, + ), + sharpness=dict( + argstr="-s %f", + ), + subtract_background=dict( + argstr="-bg", + ), ) inputs = ODFRecon.input_spec() @@ -30,11 +76,21 @@ def test_ODFRecon_inputs(): def test_ODFRecon_outputs(): output_map = dict( - B0=dict(extensions=None,), - DWI=dict(extensions=None,), - ODF=dict(extensions=None,), - entropy=dict(extensions=None,), - max=dict(extensions=None,), + B0=dict( + extensions=None, + ), + DWI=dict( + extensions=None, + ), + ODF=dict( + extensions=None, + ), + entropy=dict( + extensions=None, + ), + max=dict( + extensions=None, + ), ) outputs = ODFRecon.output_spec() diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFTracker.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFTracker.py index 233aea3e3a..2118745f3f 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFTracker.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_ODFTracker.py @@ -4,33 +4,101 @@ def test_ODFTracker_inputs(): input_map = dict( - ODF=dict(extensions=None, mandatory=True,), - angle_threshold=dict(argstr="-at %f",), - args=dict(argstr="%s",), - disc=dict(argstr="-disc",), - dsi=dict(argstr="-dsi",), - environ=dict(nohash=True, usedefault=True,), - image_orientation_vectors=dict(argstr="-iop %f",), - input_data_prefix=dict(argstr="%s", position=0, usedefault=True,), - input_output_type=dict(argstr="-it %s", usedefault=True,), - invert_x=dict(argstr="-ix",), - invert_y=dict(argstr="-iy",), - invert_z=dict(argstr="-iz",), - limit=dict(argstr="-limit %d",), - mask1_file=dict(argstr="-m %s", extensions=None, mandatory=True, position=2,), - mask1_threshold=dict(position=3,), - mask2_file=dict(argstr="-m2 %s", extensions=None, position=4,), - mask2_threshold=dict(position=5,), - max=dict(extensions=None, mandatory=True,), - out_file=dict(argstr="%s", extensions=None, position=1, usedefault=True,), - random_seed=dict(argstr="-rseed %s",), - runge_kutta2=dict(argstr="-rk2",), - slice_order=dict(argstr="-sorder %d",), - step_length=dict(argstr="-l %f",), - swap_xy=dict(argstr="-sxy",), - swap_yz=dict(argstr="-syz",), - swap_zx=dict(argstr="-szx",), - voxel_order=dict(argstr="-vorder %s",), + ODF=dict( + extensions=None, + mandatory=True, + ), + angle_threshold=dict( + argstr="-at %f", + ), + args=dict( + argstr="%s", + ), + disc=dict( + argstr="-disc", + ), + dsi=dict( + argstr="-dsi", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + image_orientation_vectors=dict( + argstr="-iop %f", + ), + input_data_prefix=dict( + argstr="%s", + position=0, + usedefault=True, + ), + input_output_type=dict( + argstr="-it %s", + usedefault=True, + ), + invert_x=dict( + argstr="-ix", + ), + invert_y=dict( + argstr="-iy", + ), + invert_z=dict( + argstr="-iz", + ), + limit=dict( + argstr="-limit %d", + ), + mask1_file=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + position=2, + ), + mask1_threshold=dict( + position=3, + ), + mask2_file=dict( + argstr="-m2 %s", + extensions=None, + position=4, + ), + mask2_threshold=dict( + position=5, + ), + max=dict( + extensions=None, + mandatory=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + position=1, + usedefault=True, + ), + random_seed=dict( + argstr="-rseed %s", + ), + runge_kutta2=dict( + argstr="-rk2", + ), + slice_order=dict( + argstr="-sorder %d", + ), + step_length=dict( + argstr="-l %f", + ), + swap_xy=dict( + argstr="-sxy", + ), + swap_yz=dict( + argstr="-syz", + ), + swap_zx=dict( + argstr="-szx", + ), + voxel_order=dict( + argstr="-vorder %s", + ), ) inputs = ODFTracker.input_spec() @@ -40,7 +108,11 @@ def test_ODFTracker_inputs(): def test_ODFTracker_outputs(): - output_map = dict(track_file=dict(extensions=None,),) + output_map = dict( + track_file=dict( + extensions=None, + ), + ) outputs = ODFTracker.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_SplineFilter.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_SplineFilter.py index ddff69b5de..65450952a4 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_SplineFilter.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_SplineFilter.py @@ -4,11 +4,30 @@ def test_SplineFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - output_file=dict(argstr="%s", extensions=None, position=2, usedefault=True,), - step_length=dict(argstr="%f", mandatory=True, position=1,), - track_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + output_file=dict( + argstr="%s", + extensions=None, + position=2, + usedefault=True, + ), + step_length=dict( + argstr="%f", + mandatory=True, + position=1, + ), + track_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), ) inputs = SplineFilter.input_spec() @@ -18,7 +37,11 @@ def test_SplineFilter_inputs(): def test_SplineFilter_outputs(): - output_map = dict(smoothed_track_file=dict(extensions=None,),) + output_map = dict( + smoothed_track_file=dict( + extensions=None, + ), + ) outputs = SplineFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py b/nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py index 1c274533f0..7f668df568 100644 --- a/nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py +++ b/nipype/interfaces/diffusion_toolkit/tests/test_auto_TrackMerge.py @@ -4,10 +4,24 @@ def test_TrackMerge_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - output_file=dict(argstr="%s", extensions=None, position=-1, usedefault=True,), - track_files=dict(argstr="%s...", mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + output_file=dict( + argstr="%s", + extensions=None, + position=-1, + usedefault=True, + ), + track_files=dict( + argstr="%s...", + mandatory=True, + position=0, + ), ) inputs = TrackMerge.input_spec() @@ -17,7 +31,11 @@ def test_TrackMerge_inputs(): def test_TrackMerge_outputs(): - output_map = dict(track_file=dict(extensions=None,),) + output_map = dict( + track_file=dict( + extensions=None, + ), + ) outputs = TrackMerge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/__init__.py b/nipype/interfaces/dipy/__init__.py index ec840871ba..aa74ee46f8 100644 --- a/nipype/interfaces/dipy/__init__.py +++ b/nipype/interfaces/dipy/__init__.py @@ -1,5 +1,5 @@ -# -*- coding: utf-8 -*- """DIPY is a computational neuroimaging tool for diffusion MRI.""" + from .tracks import StreamlineTractography, TrackDensityMap from .tensors import TensorMode, DTI from .preprocess import Resample, Denoise diff --git a/nipype/interfaces/dipy/anisotropic_power.py b/nipype/interfaces/dipy/anisotropic_power.py index 7ad82fb678..c222ea8f6a 100644 --- a/nipype/interfaces/dipy/anisotropic_power.py +++ b/nipype/interfaces/dipy/anisotropic_power.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import numpy as np import nibabel as nb diff --git a/nipype/interfaces/dipy/base.py b/nipype/interfaces/dipy/base.py index a850d730f0..44290cd1d7 100644 --- a/nipype/interfaces/dipy/base.py +++ b/nipype/interfaces/dipy/base.py @@ -1,10 +1,9 @@ -# -*- coding: utf-8 -*- -""" Base interfaces for dipy """ +"""Base interfaces for dipy""" import os.path as op import inspect +from functools import partial import numpy as np -from ... import logging from ..base import ( traits, File, @@ -27,13 +26,13 @@ def no_dipy(): - """ Check if dipy is available """ + """Check if dipy is available.""" global HAVE_DIPY return not HAVE_DIPY def dipy_version(): - """ Check dipy version """ + """Check dipy version.""" if no_dipy(): return None @@ -41,9 +40,7 @@ def dipy_version(): class DipyBaseInterface(LibraryBaseInterface): - """ - A base interface for py:mod:`dipy` computations - """ + """A base interface for py:mod:`dipy` computations.""" _pkg = "dipy" @@ -57,9 +54,7 @@ class DipyBaseInterfaceInputSpec(BaseInterfaceInputSpec): class DipyDiffusionInterface(DipyBaseInterface): - """ - A base interface for py:mod:`dipy` computations - """ + """A base interface for py:mod:`dipy` computations.""" input_spec = DipyBaseInterfaceInputSpec @@ -90,23 +85,43 @@ def _gen_filename(self, name, ext=None): return out_prefix + "_" + name + ext +def get_default_args(func): + """Return optional arguments of a function. + + Parameters + ---------- + func: callable + + Returns + ------- + dict + + """ + signature = inspect.signature(func) + return { + k: v.default + for k, v in signature.parameters.items() + if v.default is not inspect.Parameter.empty + } + + def convert_to_traits_type(dipy_type, is_file=False): """Convert DIPY type to Traits type.""" dipy_type = dipy_type.lower() is_mandatory = bool("optional" not in dipy_type) - if "variable" in dipy_type and "string" in dipy_type: - return traits.ListStr, is_mandatory + if "variable" in dipy_type and "str" in dipy_type: + return partial(traits.List, traits.Str), is_mandatory elif "variable" in dipy_type and "int" in dipy_type: - return traits.ListInt, is_mandatory + return partial(traits.List, traits.Int), is_mandatory elif "variable" in dipy_type and "float" in dipy_type: - return traits.ListFloat, is_mandatory + return partial(traits.List, traits.Float), is_mandatory elif "variable" in dipy_type and "bool" in dipy_type: - return traits.ListBool, is_mandatory + return partial(traits.List, traits.Bool), is_mandatory elif "variable" in dipy_type and "complex" in dipy_type: - return traits.ListComplex, is_mandatory - elif "string" in dipy_type and not is_file: + return partial(traits.List, traits.Complex), is_mandatory + elif "str" in dipy_type and not is_file: return traits.Str, is_mandatory - elif "string" in dipy_type and is_file: + elif "str" in dipy_type and is_file: return File, is_mandatory elif "int" in dipy_type: return traits.Int, is_mandatory @@ -117,11 +132,8 @@ def convert_to_traits_type(dipy_type, is_file=False): elif "complex" in dipy_type: return traits.Complex, is_mandatory else: - msg = ( - "Error during convert_to_traits_type({0}).".format(dipy_type) - + "Unknown DIPY type." - ) - raise IOError(msg) + msg = f"Error during convert_to_traits_type({dipy_type}). Unknown DIPY type." + raise OSError(msg) def create_interface_specs(class_name, params=None, BaseClass=TraitedSpec): @@ -150,9 +162,17 @@ def create_interface_specs(class_name, params=None, BaseClass=TraitedSpec): traits_type, is_mandatory = convert_to_traits_type(dipy_type, is_file) # print(name, dipy_type, desc, is_file, traits_type, is_mandatory) if BaseClass.__name__ == BaseInterfaceInputSpec.__name__: - if len(p) > 3: + if len(p) > 3 and p[3] is not None: + default_value = p[3] + if isinstance(traits_type, traits.List) and not isinstance( + default_value, list + ): + default_value = [default_value] attr[name] = traits_type( - p[3], desc=desc[-1], usedefault=True, mandatory=is_mandatory + default_value, + desc=desc[-1], + usedefault=True, + mandatory=is_mandatory, ) else: attr[name] = traits_type(desc=desc[-1], mandatory=is_mandatory) @@ -176,7 +196,7 @@ def dipy_to_nipype_interface(cls_name, dipy_flow, BaseClass=DipyBaseInterface): cls_name: string new class name dipy_flow: Workflow class type. - It should be any children class of `dipy.workflows.workflow.Worflow` + It should be any children class of `dipy.workflows.workflow.Workflow` BaseClass: object nipype instance object @@ -189,7 +209,7 @@ def dipy_to_nipype_interface(cls_name, dipy_flow, BaseClass=DipyBaseInterface): parser = IntrospectiveArgumentParser() flow = dipy_flow() parser.add_workflow(flow) - default_values = inspect.getfullargspec(flow.run).defaults + default_values = list(get_default_args(flow.run).values()) optional_params = [ args + (val,) for args, val in zip(parser.optional_parameters, default_values) ] @@ -202,13 +222,13 @@ def dipy_to_nipype_interface(cls_name, dipy_flow, BaseClass=DipyBaseInterface): input_parameters = parser.positional_parameters + optional_params input_spec = create_interface_specs( - "{}InputSpec".format(cls_name), + f"{cls_name}InputSpec", input_parameters, BaseClass=BaseInterfaceInputSpec, ) output_spec = create_interface_specs( - "{}OutputSpec".format(cls_name), output_parameters, BaseClass=TraitedSpec + f"{cls_name}OutputSpec", output_parameters, BaseClass=TraitedSpec ) def _run_interface(self, runtime): @@ -249,7 +269,7 @@ def get_dipy_workflows(module): ------- l_wkflw : list of tuple This a list of tuple containing 2 elements: - Worflow name, Workflow class obj + Workflow name, Workflow class obj Examples -------- diff --git a/nipype/interfaces/dipy/preprocess.py b/nipype/interfaces/dipy/preprocess.py index 3e89d1b88a..eb44a9bcef 100644 --- a/nipype/interfaces/dipy/preprocess.py +++ b/nipype/interfaces/dipy/preprocess.py @@ -1,14 +1,10 @@ -# -*- coding: utf-8 -*- - import os.path as op import nibabel as nb import numpy as np -from distutils.version import LooseVersion - -from ...utils import NUMPY_MMAP +from looseversion import LooseVersion from ... import logging -from ..base import traits, TraitedSpec, File, isdefined +from ..base import traits, Tuple, TraitedSpec, File, isdefined from .base import ( HAVE_DIPY, dipy_version, @@ -39,7 +35,7 @@ class ResampleInputSpec(TraitedSpec): in_file = File( exists=True, mandatory=True, desc="The input 4D diffusion-weighted image file" ) - vox_size = traits.Tuple( + vox_size = Tuple( traits.Float, traits.Float, traits.Float, @@ -105,7 +101,7 @@ def _gen_outfilename(self): if fext == ".gz": fname, fext2 = op.splitext(fname) fext = fext2 + fext - return op.abspath("%s_reslice%s" % (fname, fext)) + return op.abspath(f"{fname}_reslice{fext}") class DenoiseInputSpec(TraitedSpec): @@ -121,10 +117,10 @@ class DenoiseInputSpec(TraitedSpec): desc=("noise distribution model"), ) signal_mask = File( - desc=("mask in which the mean signal " "will be computed"), exists=True + desc=("mask in which the mean signal will be computed"), exists=True ) noise_mask = File( - desc=("mask in which the standard deviation of noise " "will be computed"), + desc=("mask in which the standard deviation of noise will be computed"), exists=True, ) patch_radius = traits.Int(1, usedefault=True, desc="patch radius") @@ -206,7 +202,7 @@ def _gen_outfilename(self): if fext == ".gz": fname, fext2 = op.splitext(fname) fext = fext2 + fext - return op.abspath("%s_denoise%s" % (fname, fext)) + return op.abspath(f"{fname}_denoise{fext}") def resample_proxy(in_file, order=3, new_zooms=None, out_file=None): @@ -220,9 +216,9 @@ def resample_proxy(in_file, order=3, new_zooms=None, out_file=None): if fext == ".gz": fname, fext2 = op.splitext(fname) fext = fext2 + fext - out_file = op.abspath("./%s_reslice%s" % (fname, fext)) + out_file = op.abspath(f"./{fname}_reslice{fext}") - img = nb.load(in_file, mmap=NUMPY_MMAP) + img = nb.load(in_file) hdr = img.header.copy() data = img.get_fdata(dtype=np.float32) affine = img.affine @@ -260,9 +256,9 @@ def nlmeans_proxy(in_file, settings, snr=None, smask=None, nmask=None, out_file= if fext == ".gz": fname, fext2 = op.splitext(fname) fext = fext2 + fext - out_file = op.abspath("./%s_denoise%s" % (fname, fext)) + out_file = op.abspath(f"./{fname}_denoise{fext}") - img = nb.load(in_file, mmap=NUMPY_MMAP) + img = nb.load(in_file) hdr = img.header data = img.get_fdata() aff = img.affine diff --git a/nipype/interfaces/dipy/reconstruction.py b/nipype/interfaces/dipy/reconstruction.py index 27a9e632ad..084fd7c501 100644 --- a/nipype/interfaces/dipy/reconstruction.py +++ b/nipype/interfaces/dipy/reconstruction.py @@ -1,13 +1,13 @@ -# -*- coding: utf-8 -*- """ Interfaces to the reconstruction algorithms in dipy """ + import os.path as op import numpy as np import nibabel as nb -from distutils.version import LooseVersion +from looseversion import LooseVersion from ... import logging from ..base import TraitedSpec, File, traits, isdefined @@ -45,13 +45,11 @@ class RESTOREInputSpec(DipyBaseInterfaceInputSpec): class RESTOREOutputSpec(TraitedSpec): - fa = File( - desc="output fractional anisotropy (FA) map computed from " "the fitted DTI" - ) - md = File(desc="output mean diffusivity (MD) map computed from the " "fitted DTI") - rd = File(desc="output radial diffusivity (RD) map computed from " "the fitted DTI") + fa = File(desc="output fractional anisotropy (FA) map computed from the fitted DTI") + md = File(desc="output mean diffusivity (MD) map computed from the fitted DTI") + rd = File(desc="output radial diffusivity (RD) map computed from the fitted DTI") mode = File(desc=("output mode (MO) map computed from the fitted DTI")) - trace = File(desc=("output the tensor trace map computed from the " "fitted DTI")) + trace = File(desc=("output the tensor trace map computed from the fitted DTI")) evals = File(desc=("output the eigenvalues of the fitted DTI")) evecs = File(desc=("output the eigenvectors of the fitted DTI")) @@ -87,7 +85,6 @@ class RESTORE(DipyDiffusionInterface): def _run_interface(self, runtime): from scipy.special import gamma from dipy.reconst.dti import TensorModel - import gc img = nb.load(self.inputs.in_file) hdr = img.header.copy() @@ -126,7 +123,7 @@ def _run_interface(self, runtime): else: nodiff = np.where(~gtab.b0s_mask) nodiffidx = nodiff[0].tolist() - n = 20 if len(nodiffidx) >= 20 else len(nodiffidx) + n = min(20, len(nodiffidx)) idxs = np.random.choice(nodiffidx, size=n, replace=False) noise_data = dsample.take(idxs, axis=-1)[noise_msk == 1, ...] @@ -138,7 +135,6 @@ def _run_interface(self, runtime): ) except: bias = 0.0 - pass sigma = mean_std * (1 + bias) @@ -225,7 +221,6 @@ class EstimateResponseSH(DipyDiffusionInterface): output_spec = EstimateResponseSHOutputSpec def _run_interface(self, runtime): - from dipy.core.gradients import GradientTable from dipy.reconst.dti import fractional_anisotropy, mean_diffusivity from dipy.reconst.csdeconv import recursive_response, auto_response @@ -285,7 +280,7 @@ def _run_interface(self, runtime): if ratio > 0.25: IFLOGGER.warning( - "Estimated response is not prolate enough. " "Ratio=%0.3f.", ratio + "Estimated response is not prolate enough. Ratio=%0.3f.", ratio ) elif ratio < 1.0e-5 or np.any(np.isnan(response)): response = np.array([1.8e-3, 3.6e-4, 3.6e-4, S0]) @@ -375,7 +370,7 @@ def _run_interface(self, runtime): if abs(ratio - 0.2) > 0.1: IFLOGGER.warning( - "Estimated response is not prolate enough. " "Ratio=%0.3f.", ratio + "Estimated response is not prolate enough. Ratio=%0.3f.", ratio ) csd_model = ConstrainedSphericalDeconvModel( diff --git a/nipype/interfaces/dipy/registration.py b/nipype/interfaces/dipy/registration.py index f70c566194..b9b818a66a 100644 --- a/nipype/interfaces/dipy/registration.py +++ b/nipype/interfaces/dipy/registration.py @@ -1,4 +1,4 @@ -from distutils.version import LooseVersion +from looseversion import LooseVersion from ... import logging from .base import HAVE_DIPY, dipy_version, dipy_to_nipype_interface, get_dipy_workflows diff --git a/nipype/interfaces/dipy/setup.py b/nipype/interfaces/dipy/setup.py index 082d88f841..38a7622894 100644 --- a/nipype/interfaces/dipy/setup.py +++ b/nipype/interfaces/dipy/setup.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/interfaces/dipy/simulate.py b/nipype/interfaces/dipy/simulate.py index e1867342bb..6959e0a31d 100644 --- a/nipype/interfaces/dipy/simulate.py +++ b/nipype/interfaces/dipy/simulate.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from multiprocessing import Pool, cpu_count import os.path as op @@ -8,6 +7,7 @@ from ... import logging from ..base import ( traits, + Tuple, TraitedSpec, BaseInterfaceInputSpec, File, @@ -29,7 +29,7 @@ class SimulateMultiTensorInputSpec(BaseInterfaceInputSpec): in_vfms = InputMultiPath( File(exists=True), mandatory=True, - desc=("volume fractions of isotropic " "compartiments"), + desc=("volume fractions of isotropic compartiments"), ) in_mask = File(exists=True, desc="mask to simulate data") @@ -39,7 +39,7 @@ class SimulateMultiTensorInputSpec(BaseInterfaceInputSpec): usedefault=True, desc="Diffusivity of isotropic compartments", ) - diff_sf = traits.Tuple( + diff_sf = Tuple( (1700e-6, 200e-6, 200e-6), traits.Float, traits.Float, @@ -56,15 +56,13 @@ class SimulateMultiTensorInputSpec(BaseInterfaceInputSpec): num_dirs = traits.Int( 32, usedefault=True, - desc=( - "number of gradient directions (when table " "is automatically generated)" - ), + desc=("number of gradient directions (when table is automatically generated)"), ) bvalues = traits.List( traits.Int, value=[1000, 3000], usedefault=True, - desc=("list of b-values (when table " "is automatically generated)"), + desc=("list of b-values (when table is automatically generated)"), ) out_file = File( "sim_dwi.nii.gz", @@ -134,7 +132,7 @@ def _run_interface(self, runtime): nsticks = len(self.inputs.in_dirs) if len(self.inputs.in_frac) != nsticks: raise RuntimeError( - ("Number of sticks and their volume fractions" " must match.") + "Number of sticks and their volume fractions must match." ) # Volume fractions of isotropic compartments @@ -224,20 +222,17 @@ def _run_interface(self, runtime): mevals = [sf_evals] * nsticks + [[ba_evals[d]] * 3 for d in range(nballs)] b0 = b0_im.get_fdata()[msk > 0] - args = [] - for i in range(nvox): - args.append( - { - "fractions": fracs[i, ...].tolist(), - "sticks": [ - tuple(dirs[i, j : j + 3]) for j in range(nsticks + nballs) - ], - "gradients": gtab, - "mevals": mevals, - "S0": b0[i], - "snr": self.inputs.snr, - } - ) + args = [ + { + "fractions": fracs[i, ...].tolist(), + "sticks": [tuple(dirs[i, j : j + 3]) for j in range(nsticks + nballs)], + "gradients": gtab, + "mevals": mevals, + "S0": b0[i], + "snr": self.inputs.snr, + } + for i in range(nvox) + ] n_proc = self.inputs.n_proc if n_proc == 0: @@ -256,9 +251,7 @@ def _run_interface(self, runtime): ) result = np.array(pool.map(_compute_voxel, args)) if np.shape(result)[1] != ndirs: - raise RuntimeError( - ("Computed directions do not match number" "of b-values.") - ) + raise RuntimeError("Computed directions do not match number of b-values.") signal = np.zeros((shape[0], shape[1], shape[2], ndirs)) signal[msk > 0] = result @@ -331,7 +324,7 @@ def _generate_gradients(ndirs=64, values=[1000, 3000], nb0s=1): """ import numpy as np - from dipy.core.sphere import disperse_charges, Sphere, HemiSphere + from dipy.core.sphere import disperse_charges, HemiSphere from dipy.core.gradients import gradient_table theta = np.pi * np.random.rand(ndirs) @@ -348,7 +341,7 @@ def _generate_gradients(ndirs=64, values=[1000, 3000], nb0s=1): bvecs = np.vstack((bvecs, vertices)) bvals = np.hstack((bvals, v * np.ones(vertices.shape[0]))) - for i in range(0, nb0s): + for i in range(nb0s): bvals = bvals.tolist() bvals.insert(0, 0) diff --git a/nipype/interfaces/dipy/stats.py b/nipype/interfaces/dipy/stats.py index fff0184a56..f2de24ca33 100644 --- a/nipype/interfaces/dipy/stats.py +++ b/nipype/interfaces/dipy/stats.py @@ -1,4 +1,4 @@ -from distutils.version import LooseVersion +from looseversion import LooseVersion from ... import logging from .base import HAVE_DIPY, dipy_version, dipy_to_nipype_interface, get_dipy_workflows diff --git a/nipype/interfaces/dipy/tensors.py b/nipype/interfaces/dipy/tensors.py index f2b197f372..f8be2b5c70 100644 --- a/nipype/interfaces/dipy/tensors.py +++ b/nipype/interfaces/dipy/tensors.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import numpy as np import nibabel as nb @@ -77,7 +75,7 @@ def _list_outputs(self): outputs["out_file"] = self._gen_filename("dti") for metric in ["fa", "md", "rd", "ad", "color_fa"]: - outputs["{}_file".format(metric)] = self._gen_filename(metric) + outputs[f"{metric}_file"] = self._gen_filename(metric) return outputs diff --git a/nipype/interfaces/dipy/tests/__init__.py b/nipype/interfaces/dipy/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/dipy/tests/__init__.py +++ b/nipype/interfaces/dipy/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/dipy/tests/test_auto_APMQball.py b/nipype/interfaces/dipy/tests/test_auto_APMQball.py index fcc97ebf70..81ff397cb8 100644 --- a/nipype/interfaces/dipy/tests/test_auto_APMQball.py +++ b/nipype/interfaces/dipy/tests/test_auto_APMQball.py @@ -4,11 +4,24 @@ def test_APMQball_inputs(): input_map = dict( - b0_thres=dict(usedefault=True,), - in_bval=dict(extensions=None, mandatory=True,), - in_bvec=dict(extensions=None, mandatory=True,), - in_file=dict(extensions=None, mandatory=True,), - mask_file=dict(extensions=None,), + b0_thres=dict( + usedefault=True, + ), + in_bval=dict( + extensions=None, + mandatory=True, + ), + in_bvec=dict( + extensions=None, + mandatory=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + mask_file=dict( + extensions=None, + ), out_prefix=dict(), ) inputs = APMQball.input_spec() @@ -19,7 +32,11 @@ def test_APMQball_inputs(): def test_APMQball_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = APMQball.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_CSD.py b/nipype/interfaces/dipy/tests/test_auto_CSD.py index a9c92b02b1..7cdab47f9b 100644 --- a/nipype/interfaces/dipy/tests/test_auto_CSD.py +++ b/nipype/interfaces/dipy/tests/test_auto_CSD.py @@ -4,16 +4,37 @@ def test_CSD_inputs(): input_map = dict( - b0_thres=dict(usedefault=True,), - in_bval=dict(extensions=None, mandatory=True,), - in_bvec=dict(extensions=None, mandatory=True,), - in_file=dict(extensions=None, mandatory=True,), - in_mask=dict(extensions=None,), - out_fods=dict(extensions=None,), + b0_thres=dict( + usedefault=True, + ), + in_bval=dict( + extensions=None, + mandatory=True, + ), + in_bvec=dict( + extensions=None, + mandatory=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + in_mask=dict( + extensions=None, + ), + out_fods=dict( + extensions=None, + ), out_prefix=dict(), - response=dict(extensions=None,), - save_fods=dict(usedefault=True,), - sh_order=dict(usedefault=True,), + response=dict( + extensions=None, + ), + save_fods=dict( + usedefault=True, + ), + sh_order=dict( + usedefault=True, + ), ) inputs = CSD.input_spec() @@ -23,7 +44,14 @@ def test_CSD_inputs(): def test_CSD_outputs(): - output_map = dict(model=dict(extensions=None,), out_fods=dict(extensions=None,),) + output_map = dict( + model=dict( + extensions=None, + ), + out_fods=dict( + extensions=None, + ), + ) outputs = CSD.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_DTI.py b/nipype/interfaces/dipy/tests/test_auto_DTI.py index 8e2482b129..1cea142a36 100644 --- a/nipype/interfaces/dipy/tests/test_auto_DTI.py +++ b/nipype/interfaces/dipy/tests/test_auto_DTI.py @@ -4,11 +4,24 @@ def test_DTI_inputs(): input_map = dict( - b0_thres=dict(usedefault=True,), - in_bval=dict(extensions=None, mandatory=True,), - in_bvec=dict(extensions=None, mandatory=True,), - in_file=dict(extensions=None, mandatory=True,), - mask_file=dict(extensions=None,), + b0_thres=dict( + usedefault=True, + ), + in_bval=dict( + extensions=None, + mandatory=True, + ), + in_bvec=dict( + extensions=None, + mandatory=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + mask_file=dict( + extensions=None, + ), out_prefix=dict(), ) inputs = DTI.input_spec() @@ -20,12 +33,24 @@ def test_DTI_inputs(): def test_DTI_outputs(): output_map = dict( - ad_file=dict(extensions=None,), - color_fa_file=dict(extensions=None,), - fa_file=dict(extensions=None,), - md_file=dict(extensions=None,), - out_file=dict(extensions=None,), - rd_file=dict(extensions=None,), + ad_file=dict( + extensions=None, + ), + color_fa_file=dict( + extensions=None, + ), + fa_file=dict( + extensions=None, + ), + md_file=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + rd_file=dict( + extensions=None, + ), ) outputs = DTI.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_Denoise.py b/nipype/interfaces/dipy/tests/test_auto_Denoise.py index 453e794f39..e85d2644c2 100644 --- a/nipype/interfaces/dipy/tests/test_auto_Denoise.py +++ b/nipype/interfaces/dipy/tests/test_auto_Denoise.py @@ -4,13 +4,29 @@ def test_Denoise_inputs(): input_map = dict( - block_radius=dict(usedefault=True,), - in_file=dict(extensions=None, mandatory=True,), - in_mask=dict(extensions=None,), - noise_mask=dict(extensions=None,), - noise_model=dict(mandatory=True, usedefault=True,), - patch_radius=dict(usedefault=True,), - signal_mask=dict(extensions=None,), + block_radius=dict( + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + in_mask=dict( + extensions=None, + ), + noise_mask=dict( + extensions=None, + ), + noise_model=dict( + mandatory=True, + usedefault=True, + ), + patch_radius=dict( + usedefault=True, + ), + signal_mask=dict( + extensions=None, + ), snr=dict(), ) inputs = Denoise.input_spec() @@ -21,7 +37,11 @@ def test_Denoise_inputs(): def test_Denoise_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Denoise.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_DipyDiffusionInterface.py b/nipype/interfaces/dipy/tests/test_auto_DipyDiffusionInterface.py index 657128b050..e292135ba0 100644 --- a/nipype/interfaces/dipy/tests/test_auto_DipyDiffusionInterface.py +++ b/nipype/interfaces/dipy/tests/test_auto_DipyDiffusionInterface.py @@ -4,10 +4,21 @@ def test_DipyDiffusionInterface_inputs(): input_map = dict( - b0_thres=dict(usedefault=True,), - in_bval=dict(extensions=None, mandatory=True,), - in_bvec=dict(extensions=None, mandatory=True,), - in_file=dict(extensions=None, mandatory=True,), + b0_thres=dict( + usedefault=True, + ), + in_bval=dict( + extensions=None, + mandatory=True, + ), + in_bvec=dict( + extensions=None, + mandatory=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), out_prefix=dict(), ) inputs = DipyDiffusionInterface.input_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_EstimateResponseSH.py b/nipype/interfaces/dipy/tests/test_auto_EstimateResponseSH.py index 9b9cf49d6f..00c8c1ba0d 100644 --- a/nipype/interfaces/dipy/tests/test_auto_EstimateResponseSH.py +++ b/nipype/interfaces/dipy/tests/test_auto_EstimateResponseSH.py @@ -4,19 +4,49 @@ def test_EstimateResponseSH_inputs(): input_map = dict( - auto=dict(xor=["recursive"],), - b0_thres=dict(usedefault=True,), - fa_thresh=dict(usedefault=True,), - in_bval=dict(extensions=None, mandatory=True,), - in_bvec=dict(extensions=None, mandatory=True,), - in_evals=dict(extensions=None, mandatory=True,), - in_file=dict(extensions=None, mandatory=True,), - in_mask=dict(extensions=None,), - out_mask=dict(extensions=None, usedefault=True,), + auto=dict( + xor=["recursive"], + ), + b0_thres=dict( + usedefault=True, + ), + fa_thresh=dict( + usedefault=True, + ), + in_bval=dict( + extensions=None, + mandatory=True, + ), + in_bvec=dict( + extensions=None, + mandatory=True, + ), + in_evals=dict( + extensions=None, + mandatory=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + in_mask=dict( + extensions=None, + ), + out_mask=dict( + extensions=None, + usedefault=True, + ), out_prefix=dict(), - recursive=dict(xor=["auto"],), - response=dict(extensions=None, usedefault=True,), - roi_radius=dict(usedefault=True,), + recursive=dict( + xor=["auto"], + ), + response=dict( + extensions=None, + usedefault=True, + ), + roi_radius=dict( + usedefault=True, + ), ) inputs = EstimateResponseSH.input_spec() @@ -26,7 +56,14 @@ def test_EstimateResponseSH_inputs(): def test_EstimateResponseSH_outputs(): - output_map = dict(out_mask=dict(extensions=None,), response=dict(extensions=None,),) + output_map = dict( + out_mask=dict( + extensions=None, + ), + response=dict( + extensions=None, + ), + ) outputs = EstimateResponseSH.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_RESTORE.py b/nipype/interfaces/dipy/tests/test_auto_RESTORE.py index a172847174..f25127f9c9 100644 --- a/nipype/interfaces/dipy/tests/test_auto_RESTORE.py +++ b/nipype/interfaces/dipy/tests/test_auto_RESTORE.py @@ -4,12 +4,27 @@ def test_RESTORE_inputs(): input_map = dict( - b0_thres=dict(usedefault=True,), - in_bval=dict(extensions=None, mandatory=True,), - in_bvec=dict(extensions=None, mandatory=True,), - in_file=dict(extensions=None, mandatory=True,), - in_mask=dict(extensions=None,), - noise_mask=dict(extensions=None,), + b0_thres=dict( + usedefault=True, + ), + in_bval=dict( + extensions=None, + mandatory=True, + ), + in_bvec=dict( + extensions=None, + mandatory=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + in_mask=dict( + extensions=None, + ), + noise_mask=dict( + extensions=None, + ), out_prefix=dict(), ) inputs = RESTORE.input_spec() @@ -21,13 +36,27 @@ def test_RESTORE_inputs(): def test_RESTORE_outputs(): output_map = dict( - evals=dict(extensions=None,), - evecs=dict(extensions=None,), - fa=dict(extensions=None,), - md=dict(extensions=None,), - mode=dict(extensions=None,), - rd=dict(extensions=None,), - trace=dict(extensions=None,), + evals=dict( + extensions=None, + ), + evecs=dict( + extensions=None, + ), + fa=dict( + extensions=None, + ), + md=dict( + extensions=None, + ), + mode=dict( + extensions=None, + ), + rd=dict( + extensions=None, + ), + trace=dict( + extensions=None, + ), ) outputs = RESTORE.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_Resample.py b/nipype/interfaces/dipy/tests/test_auto_Resample.py index ac1b6ce9cd..6c765b2fa9 100644 --- a/nipype/interfaces/dipy/tests/test_auto_Resample.py +++ b/nipype/interfaces/dipy/tests/test_auto_Resample.py @@ -4,8 +4,14 @@ def test_Resample_inputs(): input_map = dict( - in_file=dict(extensions=None, mandatory=True,), - interp=dict(mandatory=True, usedefault=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), + interp=dict( + mandatory=True, + usedefault=True, + ), vox_size=dict(), ) inputs = Resample.input_spec() @@ -16,7 +22,11 @@ def test_Resample_inputs(): def test_Resample_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Resample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_SimulateMultiTensor.py b/nipype/interfaces/dipy/tests/test_auto_SimulateMultiTensor.py index 3202306026..16fff2aeff 100644 --- a/nipype/interfaces/dipy/tests/test_auto_SimulateMultiTensor.py +++ b/nipype/interfaces/dipy/tests/test_auto_SimulateMultiTensor.py @@ -4,24 +4,65 @@ def test_SimulateMultiTensor_inputs(): input_map = dict( - baseline=dict(extensions=None, mandatory=True,), - bvalues=dict(usedefault=True,), - diff_iso=dict(usedefault=True,), - diff_sf=dict(usedefault=True,), - gradients=dict(extensions=None,), - in_bval=dict(extensions=None,), - in_bvec=dict(extensions=None,), - in_dirs=dict(mandatory=True,), - in_frac=dict(mandatory=True,), - in_mask=dict(extensions=None,), - in_vfms=dict(mandatory=True,), - n_proc=dict(usedefault=True,), - num_dirs=dict(usedefault=True,), - out_bval=dict(extensions=None, usedefault=True,), - out_bvec=dict(extensions=None, usedefault=True,), - out_file=dict(extensions=None, usedefault=True,), - out_mask=dict(extensions=None, usedefault=True,), - snr=dict(usedefault=True,), + baseline=dict( + extensions=None, + mandatory=True, + ), + bvalues=dict( + usedefault=True, + ), + diff_iso=dict( + usedefault=True, + ), + diff_sf=dict( + usedefault=True, + ), + gradients=dict( + extensions=None, + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + extensions=None, + ), + in_dirs=dict( + mandatory=True, + ), + in_frac=dict( + mandatory=True, + ), + in_mask=dict( + extensions=None, + ), + in_vfms=dict( + mandatory=True, + ), + n_proc=dict( + usedefault=True, + ), + num_dirs=dict( + usedefault=True, + ), + out_bval=dict( + extensions=None, + usedefault=True, + ), + out_bvec=dict( + extensions=None, + usedefault=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), + out_mask=dict( + extensions=None, + usedefault=True, + ), + snr=dict( + usedefault=True, + ), ) inputs = SimulateMultiTensor.input_spec() @@ -32,10 +73,18 @@ def test_SimulateMultiTensor_inputs(): def test_SimulateMultiTensor_outputs(): output_map = dict( - out_bval=dict(extensions=None,), - out_bvec=dict(extensions=None,), - out_file=dict(extensions=None,), - out_mask=dict(extensions=None,), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + out_mask=dict( + extensions=None, + ), ) outputs = SimulateMultiTensor.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py b/nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py index bbe4abce94..ad97523ce2 100644 --- a/nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py +++ b/nipype/interfaces/dipy/tests/test_auto_StreamlineTractography.py @@ -4,19 +4,50 @@ def test_StreamlineTractography_inputs(): input_map = dict( - gfa_thresh=dict(mandatory=True, usedefault=True,), - in_file=dict(extensions=None, mandatory=True,), - in_model=dict(extensions=None,), - in_peaks=dict(extensions=None,), - min_angle=dict(mandatory=True, usedefault=True,), - multiprocess=dict(mandatory=True, usedefault=True,), - num_seeds=dict(mandatory=True, usedefault=True,), + gfa_thresh=dict( + mandatory=True, + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + in_model=dict( + extensions=None, + ), + in_peaks=dict( + extensions=None, + ), + min_angle=dict( + mandatory=True, + usedefault=True, + ), + multiprocess=dict( + mandatory=True, + usedefault=True, + ), + num_seeds=dict( + mandatory=True, + usedefault=True, + ), out_prefix=dict(), - peak_threshold=dict(mandatory=True, usedefault=True,), - save_seeds=dict(mandatory=True, usedefault=True,), - seed_coord=dict(extensions=None,), - seed_mask=dict(extensions=None,), - tracking_mask=dict(extensions=None,), + peak_threshold=dict( + mandatory=True, + usedefault=True, + ), + save_seeds=dict( + mandatory=True, + usedefault=True, + ), + seed_coord=dict( + extensions=None, + ), + seed_mask=dict( + extensions=None, + ), + tracking_mask=dict( + extensions=None, + ), ) inputs = StreamlineTractography.input_spec() @@ -27,10 +58,18 @@ def test_StreamlineTractography_inputs(): def test_StreamlineTractography_outputs(): output_map = dict( - gfa=dict(extensions=None,), - odf_peaks=dict(extensions=None,), - out_seeds=dict(extensions=None,), - tracks=dict(extensions=None,), + gfa=dict( + extensions=None, + ), + odf_peaks=dict( + extensions=None, + ), + out_seeds=dict( + extensions=None, + ), + tracks=dict( + extensions=None, + ), ) outputs = StreamlineTractography.output_spec() diff --git a/nipype/interfaces/dipy/tests/test_auto_TensorMode.py b/nipype/interfaces/dipy/tests/test_auto_TensorMode.py index 29a01e4a75..59b1b30e8b 100644 --- a/nipype/interfaces/dipy/tests/test_auto_TensorMode.py +++ b/nipype/interfaces/dipy/tests/test_auto_TensorMode.py @@ -4,11 +4,24 @@ def test_TensorMode_inputs(): input_map = dict( - b0_thres=dict(usedefault=True,), - in_bval=dict(extensions=None, mandatory=True,), - in_bvec=dict(extensions=None, mandatory=True,), - in_file=dict(extensions=None, mandatory=True,), - mask_file=dict(extensions=None,), + b0_thres=dict( + usedefault=True, + ), + in_bval=dict( + extensions=None, + mandatory=True, + ), + in_bvec=dict( + extensions=None, + mandatory=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + mask_file=dict( + extensions=None, + ), out_prefix=dict(), ) inputs = TensorMode.input_spec() @@ -19,7 +32,11 @@ def test_TensorMode_inputs(): def test_TensorMode_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TensorMode.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_auto_TrackDensityMap.py b/nipype/interfaces/dipy/tests/test_auto_TrackDensityMap.py index 06265ffd0f..0c7855c507 100644 --- a/nipype/interfaces/dipy/tests/test_auto_TrackDensityMap.py +++ b/nipype/interfaces/dipy/tests/test_auto_TrackDensityMap.py @@ -5,10 +5,20 @@ def test_TrackDensityMap_inputs(): input_map = dict( data_dims=dict(), - in_file=dict(extensions=None, mandatory=True,), - out_filename=dict(extensions=None, usedefault=True,), - points_space=dict(usedefault=True,), - reference=dict(extensions=None,), + in_file=dict( + extensions=None, + mandatory=True, + ), + out_filename=dict( + extensions=None, + usedefault=True, + ), + points_space=dict( + usedefault=True, + ), + reference=dict( + extensions=None, + ), voxel_dims=dict(), ) inputs = TrackDensityMap.input_spec() @@ -19,7 +29,11 @@ def test_TrackDensityMap_inputs(): def test_TrackDensityMap_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TrackDensityMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dipy/tests/test_base.py b/nipype/interfaces/dipy/tests/test_base.py index 38922ba0b7..015215054d 100644 --- a/nipype/interfaces/dipy/tests/test_base.py +++ b/nipype/interfaces/dipy/tests/test_base.py @@ -1,4 +1,5 @@ import pytest +from packaging.version import Version from collections import namedtuple from ...base import traits, File, TraitedSpec, BaseInterfaceInputSpec from ..base import ( @@ -8,12 +9,14 @@ DipyBaseInterface, no_dipy, get_dipy_workflows, + get_default_args, + dipy_version, ) def test_convert_to_traits_type(): Params = namedtuple("Params", "traits_type is_file") - Res = namedtuple("Res", "traits_type is_mandatory") + Res = namedtuple("Res", "traits_type subtype is_mandatory") l_entries = [ Params("variable string", False), Params("variable int", False), @@ -39,35 +42,38 @@ def test_convert_to_traits_type(): Params("complex, optional", False), ] l_expected = [ - Res(traits.ListStr, True), - Res(traits.ListInt, True), - Res(traits.ListFloat, True), - Res(traits.ListBool, True), - Res(traits.ListComplex, True), - Res(traits.ListInt, False), - Res(traits.ListStr, False), - Res(traits.ListFloat, False), - Res(traits.ListBool, False), - Res(traits.ListComplex, False), - Res(traits.Str, True), - Res(traits.Int, True), - Res(File, True), - Res(traits.Float, True), - Res(traits.Bool, True), - Res(traits.Complex, True), - Res(traits.Str, False), - Res(traits.Int, False), - Res(File, False), - Res(traits.Float, False), - Res(traits.Bool, False), - Res(traits.Complex, False), + Res(traits.List, traits.Str, True), + Res(traits.List, traits.Int, True), + Res(traits.List, traits.Float, True), + Res(traits.List, traits.Bool, True), + Res(traits.List, traits.Complex, True), + Res(traits.List, traits.Int, False), + Res(traits.List, traits.Str, False), + Res(traits.List, traits.Float, False), + Res(traits.List, traits.Bool, False), + Res(traits.List, traits.Complex, False), + Res(traits.Str, None, True), + Res(traits.Int, None, True), + Res(File, None, True), + Res(traits.Float, None, True), + Res(traits.Bool, None, True), + Res(traits.Complex, None, True), + Res(traits.Str, None, False), + Res(traits.Int, None, False), + Res(File, None, False), + Res(traits.Float, None, False), + Res(traits.Bool, None, False), + Res(traits.Complex, None, False), ] for entry, res in zip(l_entries, l_expected): traits_type, is_mandatory = convert_to_traits_type( entry.traits_type, entry.is_file ) - assert traits_type == res.traits_type + trait_instance = traits_type() + assert isinstance(trait_instance, res.traits_type) + if res.subtype: + assert isinstance(trait_instance.inner_traits()[0].trait_type, res.subtype) assert is_mandatory == res.is_mandatory with pytest.raises(IOError): @@ -106,10 +112,36 @@ def test_create_interface_specs(): assert new_interface.__name__ == "MyInterface" current_params = new_interface().get() assert len(current_params) == 4 - assert "params1" in current_params.keys() - assert "params2_files" in current_params.keys() - assert "params3" in current_params.keys() - assert "out_params" in current_params.keys() + assert "params1" in current_params + assert "params2_files" in current_params + assert "params3" in current_params + assert "out_params" in current_params + + +@pytest.mark.skipif( + no_dipy() or Version(dipy_version()) < Version("1.4"), reason="DIPY >=1.4 required" +) +def test_get_default_args(): + from dipy.utils.deprecator import deprecated_params + + def test(dummy=11, x=3): + return dummy, x + + @deprecated_params('x', None, '0.3', '0.5', alternative='test2.y') + def test2(dummy=11, x=3): + return dummy, x + + @deprecated_params(['dummy', 'x'], None, '0.3', alternative='test2.y') + def test3(dummy=11, x=3): + return dummy, x + + @deprecated_params(['dummy', 'x'], None, '0.3', '0.5', alternative='test2.y') + def test4(dummy=11, x=3): + return dummy, x + + expected_res = {'dummy': 11, 'x': 3} + for func in [test, test2, test3, test4]: + assert get_default_args(func) == expected_res @pytest.mark.skipif(no_dipy(), reason="DIPY is not installed") @@ -155,10 +187,10 @@ def run(self, in_files, param1=1, out_dir="", out_ref="out1.txt"): params_in = new_specs().inputs.get() params_out = new_specs()._outputs().get() assert len(params_in) == 4 - assert "in_files" in params_in.keys() - assert "param1" in params_in.keys() - assert "out_dir" in params_out.keys() - assert "out_ref" in params_out.keys() + assert "in_files" in params_in + assert "param1" in params_in + assert "out_dir" in params_out + assert "out_ref" in params_out with pytest.raises(ValueError): new_specs().run() @@ -178,3 +210,4 @@ def test_get_dipy_workflows(): test_convert_to_traits_type() test_create_interface_specs() test_dipy_to_nipype_interface() + test_get_default_args() diff --git a/nipype/interfaces/dipy/tracks.py b/nipype/interfaces/dipy/tracks.py index 9ac9e0b59c..0a782b652e 100644 --- a/nipype/interfaces/dipy/tracks.py +++ b/nipype/interfaces/dipy/tracks.py @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- - import os.path as op import numpy as np import nibabel as nb -from distutils.version import LooseVersion +from looseversion import LooseVersion from ... import logging from ..base import TraitedSpec, BaseInterfaceInputSpec, File, isdefined, traits @@ -63,7 +61,7 @@ class TrackDensityMapInputSpec(BaseInterfaceInputSpec): out_filename = File( "tdi.nii", usedefault=True, - desc="The output filename for the tracks in TrackVis " "(.trk) format", + desc="The output filename for the tracks in TrackVis (.trk) format", ) @@ -149,7 +147,7 @@ class StreamlineTractographyInputSpec(BaseInterfaceInputSpec): in_peaks = File(exists=True, desc=("peaks computed from the odf")) seed_coord = File( exists=True, - desc=("file containing the list of seed voxel " "coordinates (N,3)"), + desc=("file containing the list of seed voxel coordinates (N,3)"), ) gfa_thresh = traits.Float( 0.2, @@ -184,13 +182,11 @@ class StreamlineTractographyInputSpec(BaseInterfaceInputSpec): class StreamlineTractographyOutputSpec(TraitedSpec): tracks = File(desc="TrackVis file containing extracted streamlines") gfa = File( - desc=( - "The resulting GFA (generalized FA) computed using the " "peaks of the ODF" - ) + desc=("The resulting GFA (generalized FA) computed using the peaks of the ODF") ) odf_peaks = File(desc=("peaks computed from the odf")) out_seeds = File( - desc=("file containing the (N,3) *voxel* coordinates used" " in seeding.") + desc=("file containing the (N,3) *voxel* coordinates used in seeding.") ) @@ -226,7 +222,7 @@ def _run_interface(self, runtime): if not (isdefined(self.inputs.in_model) or isdefined(self.inputs.in_peaks)): raise RuntimeError( - ("At least one of in_model or in_peaks should " "be supplied") + "At least one of in_model or in_peaks should be supplied" ) img = nb.load(self.inputs.in_file) diff --git a/nipype/interfaces/dtitk/__init__.py b/nipype/interfaces/dtitk/__init__.py index d1420c3afb..4210c1dd5d 100644 --- a/nipype/interfaces/dtitk/__init__.py +++ b/nipype/interfaces/dtitk/__init__.py @@ -5,6 +5,7 @@ `_ command line tools. """ + from .registration import ( Rigid, Affine, diff --git a/nipype/interfaces/dtitk/base.py b/nipype/interfaces/dtitk/base.py index aad1b4d521..6f46f8d404 100644 --- a/nipype/interfaces/dtitk/base.py +++ b/nipype/interfaces/dtitk/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The dtitk module provides classes for interfacing with the `DTITK @@ -36,7 +35,7 @@ LOGGER = logging.getLogger("nipype.interface") -class DTITKRenameMixin(object): +class DTITKRenameMixin: def __init__(self, *args, **kwargs): classes = [cls.__name__ for cls in self.__class__.mro()] dep_name = classes[0] @@ -50,7 +49,7 @@ def __init__(self, *args, **kwargs): "".format(dep_name, new_name), DeprecationWarning, ) - super(DTITKRenameMixin, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) class CommandLineDtitk(CommandLine): @@ -58,8 +57,8 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, ext=None) """Generate a filename based on the given parameters. The filename will take the form: cwd/basename. - If change_ext is True, it will use the extentions specified in - intputs.output_type. + If change_ext is True, it will use the extensions specified in + inputs.output_type. Parameters ---------- @@ -90,7 +89,7 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, ext=None) ext = Info.output_type_to_ext(self.inputs.output_type) if change_ext: if suffix: - suffix = "".join((suffix, ext)) + suffix = f"{suffix}{ext}" else: suffix = ext if suffix is None: diff --git a/nipype/interfaces/dtitk/registration.py b/nipype/interfaces/dtitk/registration.py index 4a50d5b1ad..f077c37b75 100644 --- a/nipype/interfaces/dtitk/registration.py +++ b/nipype/interfaces/dtitk/registration.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """DTITK registration interfaces @@ -24,7 +23,7 @@ """ -from ..base import TraitedSpec, CommandLineInputSpec, traits, File, isdefined +from ..base import TraitedSpec, CommandLineInputSpec, traits, Tuple, File, isdefined from ...utils.filemanip import fname_presuffix, split_filename from .base import CommandLineDtitk, DTITKRenameMixin import os @@ -60,7 +59,7 @@ class RigidInputSpec(CommandLineInputSpec): desc="similarity metric", usedefault=True, ) - sampling_xyz = traits.Tuple( + sampling_xyz = Tuple( (4, 4, 4), mandatory=True, position=3, @@ -78,7 +77,7 @@ class RigidInputSpec(CommandLineInputSpec): ) initialize_xfm = File( copyfile=True, - desc="Initialize w/DTITK-FORMAT" "affine", + desc="Initialize w/DTITK-FORMAT affine", position=5, argstr="%s", exists=True, @@ -118,7 +117,7 @@ class Rigid(CommandLineDtitk): return super(Rigid, self)._format_arg(name, spec, value)""" def _run_interface(self, runtime): - runtime = super(Rigid, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if """.aff doesn't exist or can't be opened""" in runtime.stderr: self.raise_exception(runtime) return runtime @@ -318,21 +317,21 @@ class AffSymTensor3DVolInputSpec(CommandLineInputSpec): exists=True, argstr="-target %s", xor=["transform"], - desc="output volume specification read from the target " "volume if specified", + desc="output volume specification read from the target volume if specified", ) - translation = traits.Tuple( + translation = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="translation (x,y,z) in mm", argstr="-translation %g %g %g", xor=["transform"], ) - euler = traits.Tuple( + euler = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="(theta, phi, psi) in degrees", xor=["transform"], argstr="-euler %g %g %g", ) - deformation = traits.Tuple( + deformation = Tuple( (traits.Float(),) * 6, desc="(xx,yy,zz,xy,yz,xz)", xor=["transform"], @@ -389,27 +388,27 @@ class AffScalarVolInputSpec(CommandLineInputSpec): "NN", usedefault=True, argstr="-interp %s", - desc="trilinear or nearest neighbor" " interpolation", + desc="trilinear or nearest neighbor interpolation", ) target = File( exists=True, argstr="-target %s", xor=["transform"], - desc="output volume specification read from the target " "volume if specified", + desc="output volume specification read from the target volume if specified", ) - translation = traits.Tuple( + translation = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="translation (x,y,z) in mm", argstr="-translation %g %g %g", xor=["transform"], ) - euler = traits.Tuple( + euler = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="(theta, phi, psi) in degrees", xor=["transform"], argstr="-euler %g %g %g", ) - deformation = traits.Tuple( + deformation = Tuple( (traits.Float(),) * 6, desc="(xx,yy,zz,xy,yz,xz)", xor=["transform"], @@ -445,7 +444,7 @@ class AffScalarVol(CommandLineDtitk): def _format_arg(self, name, spec, value): if name == "interpolation": value = {"trilinear": 0, "NN": 1}[value] - return super(AffScalarVol, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class DiffeoSymTensor3DVolInputSpec(CommandLineInputSpec): @@ -483,17 +482,15 @@ class DiffeoSymTensor3DVolInputSpec(CommandLineInputSpec): exists=True, argstr="-target %s", xor=["voxel_size"], - desc="output volume specification read from the target " "volume if specified", + desc="output volume specification read from the target volume if specified", ) - voxel_size = traits.Tuple( + voxel_size = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="xyz voxel size (superseded by target)", argstr="-vsize %g %g %g", xor=["target"], ) - flip = traits.Tuple( - (traits.Int(), traits.Int(), traits.Int()), argstr="-flip %d %d %d" - ) + flip = Tuple((traits.Int(), traits.Int(), traits.Int()), argstr="-flip %d %d %d") resampling_type = traits.Enum( "backward", "forward", @@ -530,7 +527,7 @@ class DiffeoSymTensor3DVol(CommandLineDtitk): def _format_arg(self, name, spec, value): if name == "resampling_type": value = {"forward": 0, "backward": 1}[value] - return super(DiffeoSymTensor3DVol, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class DiffeoScalarVolInputSpec(CommandLineInputSpec): @@ -551,17 +548,15 @@ class DiffeoScalarVolInputSpec(CommandLineInputSpec): exists=True, argstr="-target %s", xor=["voxel_size"], - desc="output volume specification read from the target " "volume if specified", + desc="output volume specification read from the target volume if specified", ) - voxel_size = traits.Tuple( + voxel_size = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="xyz voxel size (superseded by target)", argstr="-vsize %g %g %g", xor=["target"], ) - flip = traits.Tuple( - (traits.Int(), traits.Int(), traits.Int()), argstr="-flip %d %d %d" - ) + flip = Tuple((traits.Int(), traits.Int(), traits.Int()), argstr="-flip %d %d %d") resampling_type = traits.Enum( "backward", "forward", @@ -607,7 +602,7 @@ def _format_arg(self, name, spec, value): value = {"forward": 0, "backward": 1}[value] elif name == "interpolation": value = {"trilinear": 0, "NN": 1}[value] - return super(DiffeoScalarVol, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class RigidTask(DTITKRenameMixin, Rigid): diff --git a/nipype/interfaces/dtitk/tests/__init__.py b/nipype/interfaces/dtitk/tests/__init__.py index 99fb243f19..349937997e 100644 --- a/nipype/interfaces/dtitk/tests/__init__.py +++ b/nipype/interfaces/dtitk/tests/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/interfaces/dtitk/tests/test_auto_AffScalarVol.py b/nipype/interfaces/dtitk/tests/test_auto_AffScalarVol.py index e48312d3f2..2988e44e8d 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_AffScalarVol.py +++ b/nipype/interfaces/dtitk/tests/test_auto_AffScalarVol.py @@ -4,12 +4,30 @@ def test_AffScalarVol_inputs(): input_map = dict( - args=dict(argstr="%s",), - deformation=dict(argstr="-deformation %g %g %g %g %g %g", xor=["transform"],), - environ=dict(nohash=True, usedefault=True,), - euler=dict(argstr="-euler %g %g %g", xor=["transform"],), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s", usedefault=True,), + args=dict( + argstr="%s", + ), + deformation=dict( + argstr="-deformation %g %g %g %g %g %g", + xor=["transform"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + euler=dict( + argstr="-euler %g %g %g", + xor=["transform"], + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -17,13 +35,20 @@ def test_AffScalarVol_inputs(): name_source="in_file", name_template="%s_affxfmd", ), - target=dict(argstr="-target %s", extensions=None, xor=["transform"],), + target=dict( + argstr="-target %s", + extensions=None, + xor=["transform"], + ), transform=dict( argstr="-trans %s", extensions=None, xor=["target", "translation", "euler", "deformation"], ), - translation=dict(argstr="-translation %g %g %g", xor=["transform"],), + translation=dict( + argstr="-translation %g %g %g", + xor=["transform"], + ), ) inputs = AffScalarVol.input_spec() @@ -33,7 +58,11 @@ def test_AffScalarVol_inputs(): def test_AffScalarVol_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AffScalarVol.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_AffSymTensor3DVol.py b/nipype/interfaces/dtitk/tests/test_auto_AffSymTensor3DVol.py index 54a562e8be..d1ba18a8ac 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_AffSymTensor3DVol.py +++ b/nipype/interfaces/dtitk/tests/test_auto_AffSymTensor3DVol.py @@ -4,12 +4,30 @@ def test_AffSymTensor3DVol_inputs(): input_map = dict( - args=dict(argstr="%s",), - deformation=dict(argstr="-deformation %g %g %g %g %g %g", xor=["transform"],), - environ=dict(nohash=True, usedefault=True,), - euler=dict(argstr="-euler %g %g %g", xor=["transform"],), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s", usedefault=True,), + args=dict( + argstr="%s", + ), + deformation=dict( + argstr="-deformation %g %g %g %g %g %g", + xor=["transform"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + euler=dict( + argstr="-euler %g %g %g", + xor=["transform"], + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -17,14 +35,24 @@ def test_AffSymTensor3DVol_inputs(): name_source="in_file", name_template="%s_affxfmd", ), - reorient=dict(argstr="-reorient %s", usedefault=True,), - target=dict(argstr="-target %s", extensions=None, xor=["transform"],), + reorient=dict( + argstr="-reorient %s", + usedefault=True, + ), + target=dict( + argstr="-target %s", + extensions=None, + xor=["transform"], + ), transform=dict( argstr="-trans %s", extensions=None, xor=["target", "translation", "euler", "deformation"], ), - translation=dict(argstr="-translation %g %g %g", xor=["transform"],), + translation=dict( + argstr="-translation %g %g %g", + xor=["transform"], + ), ) inputs = AffSymTensor3DVol.input_spec() @@ -34,7 +62,11 @@ def test_AffSymTensor3DVol_inputs(): def test_AffSymTensor3DVol_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AffSymTensor3DVol.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_Affine.py b/nipype/interfaces/dtitk/tests/test_auto_Affine.py index e095ce3922..0ff24b788c 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_Affine.py +++ b/nipype/interfaces/dtitk/tests/test_auto_Affine.py @@ -4,21 +4,50 @@ def test_Affine_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), fixed_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=0, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=0, + ), + ftol=dict( + argstr="%g", + mandatory=True, + position=4, + usedefault=True, + ), + initialize_xfm=dict( + argstr="%s", + copyfile=True, + extensions=None, + position=5, ), - ftol=dict(argstr="%g", mandatory=True, position=4, usedefault=True,), - initialize_xfm=dict(argstr="%s", copyfile=True, extensions=None, position=5,), moving_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=1, ), sampling_xyz=dict( - argstr="%g %g %g", mandatory=True, position=3, usedefault=True, + argstr="%g %g %g", + mandatory=True, + position=3, + usedefault=True, ), similarity_metric=dict( - argstr="%s", mandatory=True, position=2, usedefault=True, + argstr="%s", + mandatory=True, + position=2, + usedefault=True, ), ) inputs = Affine.input_spec() @@ -30,7 +59,12 @@ def test_Affine_inputs(): def test_Affine_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_file_xfm=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_file_xfm=dict( + extensions=None, + ), ) outputs = Affine.output_spec() diff --git a/nipype/interfaces/dtitk/tests/test_auto_AffineTask.py b/nipype/interfaces/dtitk/tests/test_auto_AffineTask.py index 31820fc56d..c680c08815 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_AffineTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_AffineTask.py @@ -4,21 +4,50 @@ def test_AffineTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), fixed_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=0, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=0, + ), + ftol=dict( + argstr="%g", + mandatory=True, + position=4, + usedefault=True, + ), + initialize_xfm=dict( + argstr="%s", + copyfile=True, + extensions=None, + position=5, ), - ftol=dict(argstr="%g", mandatory=True, position=4, usedefault=True,), - initialize_xfm=dict(argstr="%s", copyfile=True, extensions=None, position=5,), moving_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=1, ), sampling_xyz=dict( - argstr="%g %g %g", mandatory=True, position=3, usedefault=True, + argstr="%g %g %g", + mandatory=True, + position=3, + usedefault=True, ), similarity_metric=dict( - argstr="%s", mandatory=True, position=2, usedefault=True, + argstr="%s", + mandatory=True, + position=2, + usedefault=True, ), ) inputs = AffineTask.input_spec() @@ -30,7 +59,12 @@ def test_AffineTask_inputs(): def test_AffineTask_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_file_xfm=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_file_xfm=dict( + extensions=None, + ), ) outputs = AffineTask.output_spec() diff --git a/nipype/interfaces/dtitk/tests/test_auto_BinThresh.py b/nipype/interfaces/dtitk/tests/test_auto_BinThresh.py index d1780ffe5c..994c8a2b8d 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_BinThresh.py +++ b/nipype/interfaces/dtitk/tests/test_auto_BinThresh.py @@ -4,11 +4,31 @@ def test_BinThresh_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), - inside_value=dict(argstr="%g", mandatory=True, position=4, usedefault=True,), - lower_bound=dict(argstr="%g", mandatory=True, position=2, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + inside_value=dict( + argstr="%g", + mandatory=True, + position=4, + usedefault=True, + ), + lower_bound=dict( + argstr="%g", + mandatory=True, + position=2, + usedefault=True, + ), out_file=dict( argstr="%s", extensions=None, @@ -17,8 +37,18 @@ def test_BinThresh_inputs(): name_template="%s_thrbin", position=1, ), - outside_value=dict(argstr="%g", mandatory=True, position=5, usedefault=True,), - upper_bound=dict(argstr="%g", mandatory=True, position=3, usedefault=True,), + outside_value=dict( + argstr="%g", + mandatory=True, + position=5, + usedefault=True, + ), + upper_bound=dict( + argstr="%g", + mandatory=True, + position=3, + usedefault=True, + ), ) inputs = BinThresh.input_spec() @@ -28,7 +58,11 @@ def test_BinThresh_inputs(): def test_BinThresh_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BinThresh.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_BinThreshTask.py b/nipype/interfaces/dtitk/tests/test_auto_BinThreshTask.py index b8e03f023b..cccf7eed27 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_BinThreshTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_BinThreshTask.py @@ -4,11 +4,31 @@ def test_BinThreshTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), - inside_value=dict(argstr="%g", mandatory=True, position=4, usedefault=True,), - lower_bound=dict(argstr="%g", mandatory=True, position=2, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + inside_value=dict( + argstr="%g", + mandatory=True, + position=4, + usedefault=True, + ), + lower_bound=dict( + argstr="%g", + mandatory=True, + position=2, + usedefault=True, + ), out_file=dict( argstr="%s", extensions=None, @@ -17,8 +37,18 @@ def test_BinThreshTask_inputs(): name_template="%s_thrbin", position=1, ), - outside_value=dict(argstr="%g", mandatory=True, position=5, usedefault=True,), - upper_bound=dict(argstr="%g", mandatory=True, position=3, usedefault=True,), + outside_value=dict( + argstr="%g", + mandatory=True, + position=5, + usedefault=True, + ), + upper_bound=dict( + argstr="%g", + mandatory=True, + position=3, + usedefault=True, + ), ) inputs = BinThreshTask.input_spec() @@ -28,7 +58,11 @@ def test_BinThreshTask_inputs(): def test_BinThreshTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BinThreshTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_CommandLineDtitk.py b/nipype/interfaces/dtitk/tests/test_auto_CommandLineDtitk.py index ba76666b1f..03044b6bc4 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_CommandLineDtitk.py +++ b/nipype/interfaces/dtitk/tests/test_auto_CommandLineDtitk.py @@ -4,7 +4,13 @@ def test_CommandLineDtitk_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = CommandLineDtitk.input_spec() diff --git a/nipype/interfaces/dtitk/tests/test_auto_ComposeXfm.py b/nipype/interfaces/dtitk/tests/test_auto_ComposeXfm.py index 88dac765f2..fa34fdcdb3 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_ComposeXfm.py +++ b/nipype/interfaces/dtitk/tests/test_auto_ComposeXfm.py @@ -4,11 +4,28 @@ def test_ComposeXfm_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_aff=dict(argstr="-aff %s", extensions=None, mandatory=True,), - in_df=dict(argstr="-df %s", extensions=None, mandatory=True,), - out_file=dict(argstr="-out %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_aff=dict( + argstr="-aff %s", + extensions=None, + mandatory=True, + ), + in_df=dict( + argstr="-df %s", + extensions=None, + mandatory=True, + ), + out_file=dict( + argstr="-out %s", + extensions=None, + genfile=True, + ), ) inputs = ComposeXfm.input_spec() @@ -18,7 +35,11 @@ def test_ComposeXfm_inputs(): def test_ComposeXfm_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ComposeXfm.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_ComposeXfmTask.py b/nipype/interfaces/dtitk/tests/test_auto_ComposeXfmTask.py index 3f573a1815..b4b2f7509e 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_ComposeXfmTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_ComposeXfmTask.py @@ -4,11 +4,28 @@ def test_ComposeXfmTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_aff=dict(argstr="-aff %s", extensions=None, mandatory=True,), - in_df=dict(argstr="-df %s", extensions=None, mandatory=True,), - out_file=dict(argstr="-out %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_aff=dict( + argstr="-aff %s", + extensions=None, + mandatory=True, + ), + in_df=dict( + argstr="-df %s", + extensions=None, + mandatory=True, + ), + out_file=dict( + argstr="-out %s", + extensions=None, + genfile=True, + ), ) inputs = ComposeXfmTask.input_spec() @@ -18,7 +35,11 @@ def test_ComposeXfmTask_inputs(): def test_ComposeXfmTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ComposeXfmTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_Diffeo.py b/nipype/interfaces/dtitk/tests/test_auto_Diffeo.py index cc354b0cde..89a1bdcfc8 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_Diffeo.py +++ b/nipype/interfaces/dtitk/tests/test_auto_Diffeo.py @@ -4,14 +4,47 @@ def test_Diffeo_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixed_file=dict(argstr="%s", extensions=None, position=0,), - ftol=dict(argstr="%g", mandatory=True, position=5, usedefault=True,), - legacy=dict(argstr="%d", mandatory=True, position=3, usedefault=True,), - mask_file=dict(argstr="%s", extensions=None, position=2,), - moving_file=dict(argstr="%s", copyfile=False, extensions=None, position=1,), - n_iters=dict(argstr="%d", mandatory=True, position=4, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_file=dict( + argstr="%s", + extensions=None, + position=0, + ), + ftol=dict( + argstr="%g", + mandatory=True, + position=5, + usedefault=True, + ), + legacy=dict( + argstr="%d", + mandatory=True, + position=3, + usedefault=True, + ), + mask_file=dict( + argstr="%s", + extensions=None, + position=2, + ), + moving_file=dict( + argstr="%s", + copyfile=False, + extensions=None, + position=1, + ), + n_iters=dict( + argstr="%d", + mandatory=True, + position=4, + usedefault=True, + ), ) inputs = Diffeo.input_spec() @@ -22,7 +55,12 @@ def test_Diffeo_inputs(): def test_Diffeo_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_file_xfm=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_file_xfm=dict( + extensions=None, + ), ) outputs = Diffeo.output_spec() diff --git a/nipype/interfaces/dtitk/tests/test_auto_DiffeoScalarVol.py b/nipype/interfaces/dtitk/tests/test_auto_DiffeoScalarVol.py index cc85e03870..39255fb5c1 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_DiffeoScalarVol.py +++ b/nipype/interfaces/dtitk/tests/test_auto_DiffeoScalarVol.py @@ -4,11 +4,25 @@ def test_DiffeoScalarVol_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - flip=dict(argstr="-flip %d %d %d",), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s", usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip=dict( + argstr="-flip %d %d %d", + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -16,10 +30,23 @@ def test_DiffeoScalarVol_inputs(): name_source="in_file", name_template="%s_diffeoxfmd", ), - resampling_type=dict(argstr="-type %s",), - target=dict(argstr="-target %s", extensions=None, xor=["voxel_size"],), - transform=dict(argstr="-trans %s", extensions=None, mandatory=True,), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target"],), + resampling_type=dict( + argstr="-type %s", + ), + target=dict( + argstr="-target %s", + extensions=None, + xor=["voxel_size"], + ), + transform=dict( + argstr="-trans %s", + extensions=None, + mandatory=True, + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target"], + ), ) inputs = DiffeoScalarVol.input_spec() @@ -29,7 +56,11 @@ def test_DiffeoScalarVol_inputs(): def test_DiffeoScalarVol_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = DiffeoScalarVol.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_DiffeoSymTensor3DVol.py b/nipype/interfaces/dtitk/tests/test_auto_DiffeoSymTensor3DVol.py index 67626f3ce6..123b741645 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_DiffeoSymTensor3DVol.py +++ b/nipype/interfaces/dtitk/tests/test_auto_DiffeoSymTensor3DVol.py @@ -4,12 +4,29 @@ def test_DiffeoSymTensor3DVol_inputs(): input_map = dict( - args=dict(argstr="%s",), - df=dict(argstr="-df %s", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - flip=dict(argstr="-flip %d %d %d",), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s", usedefault=True,), + args=dict( + argstr="%s", + ), + df=dict( + argstr="-df %s", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip=dict( + argstr="-flip %d %d %d", + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -17,11 +34,27 @@ def test_DiffeoSymTensor3DVol_inputs(): name_source="in_file", name_template="%s_diffeoxfmd", ), - reorient=dict(argstr="-reorient %s", usedefault=True,), - resampling_type=dict(argstr="-type %s",), - target=dict(argstr="-target %s", extensions=None, xor=["voxel_size"],), - transform=dict(argstr="-trans %s", extensions=None, mandatory=True,), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target"],), + reorient=dict( + argstr="-reorient %s", + usedefault=True, + ), + resampling_type=dict( + argstr="-type %s", + ), + target=dict( + argstr="-target %s", + extensions=None, + xor=["voxel_size"], + ), + transform=dict( + argstr="-trans %s", + extensions=None, + mandatory=True, + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target"], + ), ) inputs = DiffeoSymTensor3DVol.input_spec() @@ -31,7 +64,11 @@ def test_DiffeoSymTensor3DVol_inputs(): def test_DiffeoSymTensor3DVol_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = DiffeoSymTensor3DVol.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_DiffeoTask.py b/nipype/interfaces/dtitk/tests/test_auto_DiffeoTask.py index 0eb20d64d6..f7914ab9cc 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_DiffeoTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_DiffeoTask.py @@ -4,14 +4,47 @@ def test_DiffeoTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixed_file=dict(argstr="%s", extensions=None, position=0,), - ftol=dict(argstr="%g", mandatory=True, position=5, usedefault=True,), - legacy=dict(argstr="%d", mandatory=True, position=3, usedefault=True,), - mask_file=dict(argstr="%s", extensions=None, position=2,), - moving_file=dict(argstr="%s", copyfile=False, extensions=None, position=1,), - n_iters=dict(argstr="%d", mandatory=True, position=4, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_file=dict( + argstr="%s", + extensions=None, + position=0, + ), + ftol=dict( + argstr="%g", + mandatory=True, + position=5, + usedefault=True, + ), + legacy=dict( + argstr="%d", + mandatory=True, + position=3, + usedefault=True, + ), + mask_file=dict( + argstr="%s", + extensions=None, + position=2, + ), + moving_file=dict( + argstr="%s", + copyfile=False, + extensions=None, + position=1, + ), + n_iters=dict( + argstr="%d", + mandatory=True, + position=4, + usedefault=True, + ), ) inputs = DiffeoTask.input_spec() @@ -22,7 +55,12 @@ def test_DiffeoTask_inputs(): def test_DiffeoTask_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_file_xfm=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_file_xfm=dict( + extensions=None, + ), ) outputs = DiffeoTask.output_spec() diff --git a/nipype/interfaces/dtitk/tests/test_auto_Rigid.py b/nipype/interfaces/dtitk/tests/test_auto_Rigid.py index 629fd5b780..dbcc6f0fcf 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_Rigid.py +++ b/nipype/interfaces/dtitk/tests/test_auto_Rigid.py @@ -4,21 +4,50 @@ def test_Rigid_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), fixed_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=0, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=0, + ), + ftol=dict( + argstr="%g", + mandatory=True, + position=4, + usedefault=True, + ), + initialize_xfm=dict( + argstr="%s", + copyfile=True, + extensions=None, + position=5, ), - ftol=dict(argstr="%g", mandatory=True, position=4, usedefault=True,), - initialize_xfm=dict(argstr="%s", copyfile=True, extensions=None, position=5,), moving_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=1, ), sampling_xyz=dict( - argstr="%g %g %g", mandatory=True, position=3, usedefault=True, + argstr="%g %g %g", + mandatory=True, + position=3, + usedefault=True, ), similarity_metric=dict( - argstr="%s", mandatory=True, position=2, usedefault=True, + argstr="%s", + mandatory=True, + position=2, + usedefault=True, ), ) inputs = Rigid.input_spec() @@ -30,7 +59,12 @@ def test_Rigid_inputs(): def test_Rigid_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_file_xfm=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_file_xfm=dict( + extensions=None, + ), ) outputs = Rigid.output_spec() diff --git a/nipype/interfaces/dtitk/tests/test_auto_RigidTask.py b/nipype/interfaces/dtitk/tests/test_auto_RigidTask.py index ec280e06a9..6c5236607c 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_RigidTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_RigidTask.py @@ -4,21 +4,50 @@ def test_RigidTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), fixed_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=0, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=0, + ), + ftol=dict( + argstr="%g", + mandatory=True, + position=4, + usedefault=True, + ), + initialize_xfm=dict( + argstr="%s", + copyfile=True, + extensions=None, + position=5, ), - ftol=dict(argstr="%g", mandatory=True, position=4, usedefault=True,), - initialize_xfm=dict(argstr="%s", copyfile=True, extensions=None, position=5,), moving_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=1, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=1, ), sampling_xyz=dict( - argstr="%g %g %g", mandatory=True, position=3, usedefault=True, + argstr="%g %g %g", + mandatory=True, + position=3, + usedefault=True, ), similarity_metric=dict( - argstr="%s", mandatory=True, position=2, usedefault=True, + argstr="%s", + mandatory=True, + position=2, + usedefault=True, ), ) inputs = RigidTask.input_spec() @@ -30,7 +59,12 @@ def test_RigidTask_inputs(): def test_RigidTask_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_file_xfm=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_file_xfm=dict( + extensions=None, + ), ) outputs = RigidTask.output_spec() diff --git a/nipype/interfaces/dtitk/tests/test_auto_SVAdjustVoxSp.py b/nipype/interfaces/dtitk/tests/test_auto_SVAdjustVoxSp.py index c01e08a66e..3d32a314bd 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_SVAdjustVoxSp.py +++ b/nipype/interfaces/dtitk/tests/test_auto_SVAdjustVoxSp.py @@ -4,10 +4,22 @@ def test_SVAdjustVoxSp_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -16,9 +28,14 @@ def test_SVAdjustVoxSp_inputs(): name_template="%s_avs", ), target_file=dict( - argstr="-target %s", extensions=None, xor=["voxel_size", "origin"], + argstr="-target %s", + extensions=None, + xor=["voxel_size", "origin"], + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), ) inputs = SVAdjustVoxSp.input_spec() @@ -28,7 +45,11 @@ def test_SVAdjustVoxSp_inputs(): def test_SVAdjustVoxSp_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SVAdjustVoxSp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_SVAdjustVoxSpTask.py b/nipype/interfaces/dtitk/tests/test_auto_SVAdjustVoxSpTask.py index 0ca4e416ae..cedc693a24 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_SVAdjustVoxSpTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_SVAdjustVoxSpTask.py @@ -4,10 +4,22 @@ def test_SVAdjustVoxSpTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -16,9 +28,14 @@ def test_SVAdjustVoxSpTask_inputs(): name_template="%s_avs", ), target_file=dict( - argstr="-target %s", extensions=None, xor=["voxel_size", "origin"], + argstr="-target %s", + extensions=None, + xor=["voxel_size", "origin"], + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), ) inputs = SVAdjustVoxSpTask.input_spec() @@ -28,7 +45,11 @@ def test_SVAdjustVoxSpTask_inputs(): def test_SVAdjustVoxSpTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SVAdjustVoxSpTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_SVResample.py b/nipype/interfaces/dtitk/tests/test_auto_SVResample.py index c08df4bfbb..fc880cd3e7 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_SVResample.py +++ b/nipype/interfaces/dtitk/tests/test_auto_SVResample.py @@ -4,12 +4,29 @@ def test_SVResample_inputs(): input_map = dict( - align=dict(argstr="-align %s",), - args=dict(argstr="%s",), - array_size=dict(argstr="-size %d %d %d", xor=["target_file"],), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + align=dict( + argstr="-align %s", + ), + args=dict( + argstr="%s", + ), + array_size=dict( + argstr="-size %d %d %d", + xor=["target_file"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -22,7 +39,10 @@ def test_SVResample_inputs(): extensions=None, xor=["array_size", "voxel_size", "origin"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], + ), ) inputs = SVResample.input_spec() @@ -32,7 +52,11 @@ def test_SVResample_inputs(): def test_SVResample_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SVResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_SVResampleTask.py b/nipype/interfaces/dtitk/tests/test_auto_SVResampleTask.py index 467163504b..88412e68ae 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_SVResampleTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_SVResampleTask.py @@ -4,12 +4,29 @@ def test_SVResampleTask_inputs(): input_map = dict( - align=dict(argstr="-align %s",), - args=dict(argstr="%s",), - array_size=dict(argstr="-size %d %d %d", xor=["target_file"],), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + align=dict( + argstr="-align %s", + ), + args=dict( + argstr="%s", + ), + array_size=dict( + argstr="-size %d %d %d", + xor=["target_file"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -22,7 +39,10 @@ def test_SVResampleTask_inputs(): extensions=None, xor=["array_size", "voxel_size", "origin"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], + ), ) inputs = SVResampleTask.input_spec() @@ -32,7 +52,11 @@ def test_SVResampleTask_inputs(): def test_SVResampleTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SVResampleTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_TVAdjustOriginTask.py b/nipype/interfaces/dtitk/tests/test_auto_TVAdjustOriginTask.py index d22aa78c9c..333e05628d 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_TVAdjustOriginTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_TVAdjustOriginTask.py @@ -4,10 +4,22 @@ def test_TVAdjustOriginTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -16,9 +28,14 @@ def test_TVAdjustOriginTask_inputs(): name_template="%s_avs", ), target_file=dict( - argstr="-target %s", extensions=None, xor=["voxel_size", "origin"], + argstr="-target %s", + extensions=None, + xor=["voxel_size", "origin"], + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), ) inputs = TVAdjustOriginTask.input_spec() @@ -28,7 +45,11 @@ def test_TVAdjustOriginTask_inputs(): def test_TVAdjustOriginTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TVAdjustOriginTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_TVAdjustVoxSp.py b/nipype/interfaces/dtitk/tests/test_auto_TVAdjustVoxSp.py index 70dc59c5a3..9c6596042b 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_TVAdjustVoxSp.py +++ b/nipype/interfaces/dtitk/tests/test_auto_TVAdjustVoxSp.py @@ -4,10 +4,22 @@ def test_TVAdjustVoxSp_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -16,9 +28,14 @@ def test_TVAdjustVoxSp_inputs(): name_template="%s_avs", ), target_file=dict( - argstr="-target %s", extensions=None, xor=["voxel_size", "origin"], + argstr="-target %s", + extensions=None, + xor=["voxel_size", "origin"], + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), ) inputs = TVAdjustVoxSp.input_spec() @@ -28,7 +45,11 @@ def test_TVAdjustVoxSp_inputs(): def test_TVAdjustVoxSp_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TVAdjustVoxSp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_TVAdjustVoxSpTask.py b/nipype/interfaces/dtitk/tests/test_auto_TVAdjustVoxSpTask.py index a23056e502..f34a76ae7b 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_TVAdjustVoxSpTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_TVAdjustVoxSpTask.py @@ -4,10 +4,22 @@ def test_TVAdjustVoxSpTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -16,9 +28,14 @@ def test_TVAdjustVoxSpTask_inputs(): name_template="%s_avs", ), target_file=dict( - argstr="-target %s", extensions=None, xor=["voxel_size", "origin"], + argstr="-target %s", + extensions=None, + xor=["voxel_size", "origin"], + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), ) inputs = TVAdjustVoxSpTask.input_spec() @@ -28,7 +45,11 @@ def test_TVAdjustVoxSpTask_inputs(): def test_TVAdjustVoxSpTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TVAdjustVoxSpTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_TVResample.py b/nipype/interfaces/dtitk/tests/test_auto_TVResample.py index 13142572f9..2ca99176f8 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_TVResample.py +++ b/nipype/interfaces/dtitk/tests/test_auto_TVResample.py @@ -4,13 +4,32 @@ def test_TVResample_inputs(): input_map = dict( - align=dict(argstr="-align %s",), - args=dict(argstr="%s",), - array_size=dict(argstr="-size %d %d %d", xor=["target_file"],), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s",), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + align=dict( + argstr="-align %s", + ), + args=dict( + argstr="%s", + ), + array_size=dict( + argstr="-size %d %d %d", + xor=["target_file"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -23,7 +42,10 @@ def test_TVResample_inputs(): extensions=None, xor=["array_size", "voxel_size", "origin"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], + ), ) inputs = TVResample.input_spec() @@ -33,7 +55,11 @@ def test_TVResample_inputs(): def test_TVResample_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TVResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_TVResampleTask.py b/nipype/interfaces/dtitk/tests/test_auto_TVResampleTask.py index 3bf6221d24..d1f908fca8 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_TVResampleTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_TVResampleTask.py @@ -4,13 +4,32 @@ def test_TVResampleTask_inputs(): input_map = dict( - align=dict(argstr="-align %s",), - args=dict(argstr="%s",), - array_size=dict(argstr="-size %d %d %d", xor=["target_file"],), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s",), - origin=dict(argstr="-origin %g %g %g", xor=["target_file"],), + align=dict( + argstr="-align %s", + ), + args=dict( + argstr="%s", + ), + array_size=dict( + argstr="-size %d %d %d", + xor=["target_file"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + ), + origin=dict( + argstr="-origin %g %g %g", + xor=["target_file"], + ), out_file=dict( argstr="-out %s", extensions=None, @@ -23,7 +42,10 @@ def test_TVResampleTask_inputs(): extensions=None, xor=["array_size", "voxel_size", "origin"], ), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target_file"],), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target_file"], + ), ) inputs = TVResampleTask.input_spec() @@ -33,7 +55,11 @@ def test_TVResampleTask_inputs(): def test_TVResampleTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TVResampleTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_TVtool.py b/nipype/interfaces/dtitk/tests/test_auto_TVtool.py index 812049f83b..11e2d05acc 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_TVtool.py +++ b/nipype/interfaces/dtitk/tests/test_auto_TVtool.py @@ -4,11 +4,26 @@ def test_TVtool_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - in_flag=dict(argstr="-%s",), - out_file=dict(argstr="-out %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + in_flag=dict( + argstr="-%s", + ), + out_file=dict( + argstr="-out %s", + extensions=None, + genfile=True, + ), ) inputs = TVtool.input_spec() @@ -18,7 +33,11 @@ def test_TVtool_inputs(): def test_TVtool_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TVtool.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_TVtoolTask.py b/nipype/interfaces/dtitk/tests/test_auto_TVtoolTask.py index a26d2e76f2..7af7bcb75b 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_TVtoolTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_TVtoolTask.py @@ -4,11 +4,26 @@ def test_TVtoolTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - in_flag=dict(argstr="-%s",), - out_file=dict(argstr="-out %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + in_flag=dict( + argstr="-%s", + ), + out_file=dict( + argstr="-out %s", + extensions=None, + genfile=True, + ), ) inputs = TVtoolTask.input_spec() @@ -18,7 +33,11 @@ def test_TVtoolTask_inputs(): def test_TVtoolTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TVtoolTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_affScalarVolTask.py b/nipype/interfaces/dtitk/tests/test_auto_affScalarVolTask.py index 67b1d0efbb..8d3ebfad98 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_affScalarVolTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_affScalarVolTask.py @@ -4,12 +4,30 @@ def test_affScalarVolTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - deformation=dict(argstr="-deformation %g %g %g %g %g %g", xor=["transform"],), - environ=dict(nohash=True, usedefault=True,), - euler=dict(argstr="-euler %g %g %g", xor=["transform"],), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s", usedefault=True,), + args=dict( + argstr="%s", + ), + deformation=dict( + argstr="-deformation %g %g %g %g %g %g", + xor=["transform"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + euler=dict( + argstr="-euler %g %g %g", + xor=["transform"], + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -17,13 +35,20 @@ def test_affScalarVolTask_inputs(): name_source="in_file", name_template="%s_affxfmd", ), - target=dict(argstr="-target %s", extensions=None, xor=["transform"],), + target=dict( + argstr="-target %s", + extensions=None, + xor=["transform"], + ), transform=dict( argstr="-trans %s", extensions=None, xor=["target", "translation", "euler", "deformation"], ), - translation=dict(argstr="-translation %g %g %g", xor=["transform"],), + translation=dict( + argstr="-translation %g %g %g", + xor=["transform"], + ), ) inputs = affScalarVolTask.input_spec() @@ -33,7 +58,11 @@ def test_affScalarVolTask_inputs(): def test_affScalarVolTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = affScalarVolTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_affSymTensor3DVolTask.py b/nipype/interfaces/dtitk/tests/test_auto_affSymTensor3DVolTask.py index 33778b661e..fbfde68e86 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_affSymTensor3DVolTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_affSymTensor3DVolTask.py @@ -4,12 +4,30 @@ def test_affSymTensor3DVolTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - deformation=dict(argstr="-deformation %g %g %g %g %g %g", xor=["transform"],), - environ=dict(nohash=True, usedefault=True,), - euler=dict(argstr="-euler %g %g %g", xor=["transform"],), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s", usedefault=True,), + args=dict( + argstr="%s", + ), + deformation=dict( + argstr="-deformation %g %g %g %g %g %g", + xor=["transform"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + euler=dict( + argstr="-euler %g %g %g", + xor=["transform"], + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -17,14 +35,24 @@ def test_affSymTensor3DVolTask_inputs(): name_source="in_file", name_template="%s_affxfmd", ), - reorient=dict(argstr="-reorient %s", usedefault=True,), - target=dict(argstr="-target %s", extensions=None, xor=["transform"],), + reorient=dict( + argstr="-reorient %s", + usedefault=True, + ), + target=dict( + argstr="-target %s", + extensions=None, + xor=["transform"], + ), transform=dict( argstr="-trans %s", extensions=None, xor=["target", "translation", "euler", "deformation"], ), - translation=dict(argstr="-translation %g %g %g", xor=["transform"],), + translation=dict( + argstr="-translation %g %g %g", + xor=["transform"], + ), ) inputs = affSymTensor3DVolTask.input_spec() @@ -34,7 +62,11 @@ def test_affSymTensor3DVolTask_inputs(): def test_affSymTensor3DVolTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = affSymTensor3DVolTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_diffeoScalarVolTask.py b/nipype/interfaces/dtitk/tests/test_auto_diffeoScalarVolTask.py index e1e2468b5c..4a7ffee6f4 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_diffeoScalarVolTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_diffeoScalarVolTask.py @@ -4,11 +4,25 @@ def test_diffeoScalarVolTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - flip=dict(argstr="-flip %d %d %d",), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s", usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip=dict( + argstr="-flip %d %d %d", + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -16,10 +30,23 @@ def test_diffeoScalarVolTask_inputs(): name_source="in_file", name_template="%s_diffeoxfmd", ), - resampling_type=dict(argstr="-type %s",), - target=dict(argstr="-target %s", extensions=None, xor=["voxel_size"],), - transform=dict(argstr="-trans %s", extensions=None, mandatory=True,), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target"],), + resampling_type=dict( + argstr="-type %s", + ), + target=dict( + argstr="-target %s", + extensions=None, + xor=["voxel_size"], + ), + transform=dict( + argstr="-trans %s", + extensions=None, + mandatory=True, + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target"], + ), ) inputs = diffeoScalarVolTask.input_spec() @@ -29,7 +56,11 @@ def test_diffeoScalarVolTask_inputs(): def test_diffeoScalarVolTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = diffeoScalarVolTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/tests/test_auto_diffeoSymTensor3DVolTask.py b/nipype/interfaces/dtitk/tests/test_auto_diffeoSymTensor3DVolTask.py index 0956ec615a..6724343e69 100644 --- a/nipype/interfaces/dtitk/tests/test_auto_diffeoSymTensor3DVolTask.py +++ b/nipype/interfaces/dtitk/tests/test_auto_diffeoSymTensor3DVolTask.py @@ -4,12 +4,29 @@ def test_diffeoSymTensor3DVolTask_inputs(): input_map = dict( - args=dict(argstr="%s",), - df=dict(argstr="-df %s", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - flip=dict(argstr="-flip %d %d %d",), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="-interp %s", usedefault=True,), + args=dict( + argstr="%s", + ), + df=dict( + argstr="-df %s", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip=dict( + argstr="-flip %d %d %d", + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -17,11 +34,27 @@ def test_diffeoSymTensor3DVolTask_inputs(): name_source="in_file", name_template="%s_diffeoxfmd", ), - reorient=dict(argstr="-reorient %s", usedefault=True,), - resampling_type=dict(argstr="-type %s",), - target=dict(argstr="-target %s", extensions=None, xor=["voxel_size"],), - transform=dict(argstr="-trans %s", extensions=None, mandatory=True,), - voxel_size=dict(argstr="-vsize %g %g %g", xor=["target"],), + reorient=dict( + argstr="-reorient %s", + usedefault=True, + ), + resampling_type=dict( + argstr="-type %s", + ), + target=dict( + argstr="-target %s", + extensions=None, + xor=["voxel_size"], + ), + transform=dict( + argstr="-trans %s", + extensions=None, + mandatory=True, + ), + voxel_size=dict( + argstr="-vsize %g %g %g", + xor=["target"], + ), ) inputs = diffeoSymTensor3DVolTask.input_spec() @@ -31,7 +64,11 @@ def test_diffeoSymTensor3DVolTask_inputs(): def test_diffeoSymTensor3DVolTask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = diffeoSymTensor3DVolTask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/dtitk/utils.py b/nipype/interfaces/dtitk/utils.py index c5850450a6..6f185fe393 100644 --- a/nipype/interfaces/dtitk/utils.py +++ b/nipype/interfaces/dtitk/utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """DTITK utility interfaces @@ -24,7 +23,7 @@ """ -from ..base import TraitedSpec, CommandLineInputSpec, File, traits, isdefined +from ..base import TraitedSpec, CommandLineInputSpec, File, traits, Tuple, isdefined from ...utils.filemanip import fname_presuffix from .base import CommandLineDtitk, DTITKRenameMixin import os @@ -46,13 +45,13 @@ class TVAdjustVoxSpInputSpec(CommandLineInputSpec): target_file = File( desc="target volume to match", argstr="-target %s", xor=["voxel_size", "origin"] ) - voxel_size = traits.Tuple( + voxel_size = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="xyz voxel size (superseded by target)", argstr="-vsize %g %g %g", xor=["target_file"], ) - origin = traits.Tuple( + origin = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="xyz origin (superseded by target)", argstr="-origin %g %g %g", @@ -99,13 +98,13 @@ class SVAdjustVoxSpInputSpec(CommandLineInputSpec): target_file = File( desc="target volume to match", argstr="-target %s", xor=["voxel_size", "origin"] ) - voxel_size = traits.Tuple( + voxel_size = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="xyz voxel size (superseded by target)", argstr="-vsize %g %g %g", xor=["target_file"], ) - origin = traits.Tuple( + origin = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="xyz origin (superseded by target)", argstr="-origin %g %g %g", @@ -161,21 +160,21 @@ class TVResampleInputSpec(CommandLineInputSpec): desc="how to align output volume to input volume", ) interpolation = traits.Enum( - "LEI", "EI", argstr="-interp %s", desc="Log Euclidean Euclidean Interpolation" + "LEI", "EI", argstr="-interp %s", desc="Log Euclidean Interpolation" ) - array_size = traits.Tuple( + array_size = Tuple( (traits.Int(), traits.Int(), traits.Int()), desc="resampled array size", xor=["target_file"], argstr="-size %d %d %d", ) - voxel_size = traits.Tuple( + voxel_size = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="resampled voxel size", xor=["target_file"], argstr="-vsize %g %g %g", ) - origin = traits.Tuple( + origin = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="xyz origin", xor=["target_file"], @@ -230,19 +229,19 @@ class SVResampleInputSpec(CommandLineInputSpec): argstr="-align %s", desc="how to align output volume to input volume", ) - array_size = traits.Tuple( + array_size = Tuple( (traits.Int(), traits.Int(), traits.Int()), desc="resampled array size", xor=["target_file"], argstr="-size %d %d %d", ) - voxel_size = traits.Tuple( + voxel_size = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="resampled voxel size", xor=["target_file"], argstr="-vsize %g %g %g", ) - origin = traits.Tuple( + origin = Tuple( (traits.Float(), traits.Float(), traits.Float()), desc="xyz origin", xor=["target_file"], @@ -365,7 +364,7 @@ class BinThreshInputSpec(CommandLineInputSpec): argstr="%g", usedefault=True, mandatory=True, - desc="value for voxels in " "binarization range", + desc="value for voxels in binarization range", ) outside_value = traits.Float( 0, @@ -373,7 +372,7 @@ class BinThreshInputSpec(CommandLineInputSpec): argstr="%g", usedefault=True, mandatory=True, - desc="value for voxels" "outside of binarization range", + desc="value for voxels outside of binarization range", ) diff --git a/nipype/interfaces/dynamic_slicer.py b/nipype/interfaces/dynamic_slicer.py index 6dc6a7e154..1fede10507 100644 --- a/nipype/interfaces/dynamic_slicer.py +++ b/nipype/interfaces/dynamic_slicer.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Experimental Slicer wrapper - Work in progress.""" @@ -39,7 +38,7 @@ def _grab_xml(self, module): raise Exception(cmd.cmdline + " failed:\n%s" % ret.runtime.stderr) def _outputs(self): - base = super(SlicerCommandLine, self)._outputs() + base = super()._outputs() undefined_output_traits = {} for key in [ node.getElementsByTagName("name")[0].firstChild.nodeValue @@ -53,9 +52,7 @@ def _outputs(self): def __init__(self, module, **inputs): warnings.warn("slicer is Not fully implemented", RuntimeWarning) - super(SlicerCommandLine, self).__init__( - command="Slicer3 --launch %s " % module, name=module, **inputs - ) + super().__init__(command="Slicer3 --launch %s " % module, name=module, **inputs) dom = self._grab_xml(module) self._outputs_filenames = {} @@ -193,7 +190,7 @@ def _format_arg(self, name, spec, value): else: fname = value return spec.argstr % fname - return super(SlicerCommandLine, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) # test = SlicerCommandLine(module="BRAINSFit") diff --git a/nipype/interfaces/elastix/__init__.py b/nipype/interfaces/elastix/__init__.py index 8f60ed8ff1..1f1116af69 100644 --- a/nipype/interfaces/elastix/__init__.py +++ b/nipype/interfaces/elastix/__init__.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -# coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """elastix is a toolbox for rigid and nonrigid registration of images.""" diff --git a/nipype/interfaces/elastix/base.py b/nipype/interfaces/elastix/base.py index 6e26937793..61fe288ff6 100644 --- a/nipype/interfaces/elastix/base.py +++ b/nipype/interfaces/elastix/base.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -# coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The :py:mod:`nipype.interfaces.elastix` provides the interface to diff --git a/nipype/interfaces/elastix/registration.py b/nipype/interfaces/elastix/registration.py index 9c6074014b..ead163de0b 100644 --- a/nipype/interfaces/elastix/registration.py +++ b/nipype/interfaces/elastix/registration.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -# coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -83,8 +81,8 @@ def _list_outputs(self): for i, params in enumerate(self.inputs.parameters): config = {} - with open(params, "r") as f: - for line in f.readlines(): + with open(params) as f: + for line in f: line = line.strip() if not line.startswith("//") and line: m = regex.search(line) diff --git a/nipype/interfaces/elastix/tests/__init__.py b/nipype/interfaces/elastix/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/elastix/tests/__init__.py +++ b/nipype/interfaces/elastix/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py b/nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py index 509c0a5a77..b7895e1cf1 100644 --- a/nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py +++ b/nipype/interfaces/elastix/tests/test_auto_AnalyzeWarp.py @@ -4,15 +4,45 @@ def test_AnalyzeWarp_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - jac=dict(argstr="-jac %s", usedefault=True,), - jacmat=dict(argstr="-jacmat %s", usedefault=True,), - moving_image=dict(argstr="-in %s", extensions=None,), - num_threads=dict(argstr="-threads %01d", nohash=True, usedefault=True,), - output_path=dict(argstr="-out %s", mandatory=True, usedefault=True,), - points=dict(argstr="-def %s", position=0, usedefault=True,), - transform_file=dict(argstr="-tp %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + jac=dict( + argstr="-jac %s", + usedefault=True, + ), + jacmat=dict( + argstr="-jacmat %s", + usedefault=True, + ), + moving_image=dict( + argstr="-in %s", + extensions=None, + ), + num_threads=dict( + argstr="-threads %01d", + nohash=True, + usedefault=True, + ), + output_path=dict( + argstr="-out %s", + mandatory=True, + usedefault=True, + ), + points=dict( + argstr="-def %s", + position=0, + usedefault=True, + ), + transform_file=dict( + argstr="-tp %s", + extensions=None, + mandatory=True, + ), ) inputs = AnalyzeWarp.input_spec() @@ -23,9 +53,15 @@ def test_AnalyzeWarp_inputs(): def test_AnalyzeWarp_outputs(): output_map = dict( - disp_field=dict(extensions=None,), - jacdet_map=dict(extensions=None,), - jacmat_map=dict(extensions=None,), + disp_field=dict( + extensions=None, + ), + jacdet_map=dict( + extensions=None, + ), + jacmat_map=dict( + extensions=None, + ), ) outputs = AnalyzeWarp.output_spec() diff --git a/nipype/interfaces/elastix/tests/test_auto_ApplyWarp.py b/nipype/interfaces/elastix/tests/test_auto_ApplyWarp.py index fd77478270..0eebfb0665 100644 --- a/nipype/interfaces/elastix/tests/test_auto_ApplyWarp.py +++ b/nipype/interfaces/elastix/tests/test_auto_ApplyWarp.py @@ -4,12 +4,33 @@ def test_ApplyWarp_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - moving_image=dict(argstr="-in %s", extensions=None, mandatory=True,), - num_threads=dict(argstr="-threads %01d", nohash=True, usedefault=True,), - output_path=dict(argstr="-out %s", mandatory=True, usedefault=True,), - transform_file=dict(argstr="-tp %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + moving_image=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + num_threads=dict( + argstr="-threads %01d", + nohash=True, + usedefault=True, + ), + output_path=dict( + argstr="-out %s", + mandatory=True, + usedefault=True, + ), + transform_file=dict( + argstr="-tp %s", + extensions=None, + mandatory=True, + ), ) inputs = ApplyWarp.input_spec() @@ -19,7 +40,11 @@ def test_ApplyWarp_inputs(): def test_ApplyWarp_outputs(): - output_map = dict(warped_file=dict(extensions=None,),) + output_map = dict( + warped_file=dict( + extensions=None, + ), + ) outputs = ApplyWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/elastix/tests/test_auto_EditTransform.py b/nipype/interfaces/elastix/tests/test_auto_EditTransform.py index 687906f8b0..a8617c4988 100644 --- a/nipype/interfaces/elastix/tests/test_auto_EditTransform.py +++ b/nipype/interfaces/elastix/tests/test_auto_EditTransform.py @@ -4,12 +4,26 @@ def test_EditTransform_inputs(): input_map = dict( - interpolation=dict(argstr="FinalBSplineInterpolationOrder", usedefault=True,), - output_file=dict(extensions=None,), - output_format=dict(argstr="ResultImageFormat",), - output_type=dict(argstr="ResultImagePixelType",), - reference_image=dict(extensions=None,), - transform_file=dict(extensions=None, mandatory=True,), + interpolation=dict( + argstr="FinalBSplineInterpolationOrder", + usedefault=True, + ), + output_file=dict( + extensions=None, + ), + output_format=dict( + argstr="ResultImageFormat", + ), + output_type=dict( + argstr="ResultImagePixelType", + ), + reference_image=dict( + extensions=None, + ), + transform_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = EditTransform.input_spec() @@ -19,7 +33,11 @@ def test_EditTransform_inputs(): def test_EditTransform_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = EditTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/elastix/tests/test_auto_PointsWarp.py b/nipype/interfaces/elastix/tests/test_auto_PointsWarp.py index 83e3092f28..bce2a3c662 100644 --- a/nipype/interfaces/elastix/tests/test_auto_PointsWarp.py +++ b/nipype/interfaces/elastix/tests/test_auto_PointsWarp.py @@ -4,12 +4,33 @@ def test_PointsWarp_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - num_threads=dict(argstr="-threads %01d", nohash=True, usedefault=True,), - output_path=dict(argstr="-out %s", mandatory=True, usedefault=True,), - points_file=dict(argstr="-def %s", extensions=None, mandatory=True,), - transform_file=dict(argstr="-tp %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + num_threads=dict( + argstr="-threads %01d", + nohash=True, + usedefault=True, + ), + output_path=dict( + argstr="-out %s", + mandatory=True, + usedefault=True, + ), + points_file=dict( + argstr="-def %s", + extensions=None, + mandatory=True, + ), + transform_file=dict( + argstr="-tp %s", + extensions=None, + mandatory=True, + ), ) inputs = PointsWarp.input_spec() @@ -19,7 +40,11 @@ def test_PointsWarp_inputs(): def test_PointsWarp_outputs(): - output_map = dict(warped_file=dict(extensions=None,),) + output_map = dict( + warped_file=dict( + extensions=None, + ), + ) outputs = PointsWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/elastix/tests/test_auto_Registration.py b/nipype/interfaces/elastix/tests/test_auto_Registration.py index 18ad8f93a2..ae6d929950 100644 --- a/nipype/interfaces/elastix/tests/test_auto_Registration.py +++ b/nipype/interfaces/elastix/tests/test_auto_Registration.py @@ -4,16 +4,49 @@ def test_Registration_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixed_image=dict(argstr="-f %s", extensions=None, mandatory=True,), - fixed_mask=dict(argstr="-fMask %s", extensions=None,), - initial_transform=dict(argstr="-t0 %s", extensions=None,), - moving_image=dict(argstr="-m %s", extensions=None, mandatory=True,), - moving_mask=dict(argstr="-mMask %s", extensions=None,), - num_threads=dict(argstr="-threads %01d", nohash=True, usedefault=True,), - output_path=dict(argstr="-out %s", mandatory=True, usedefault=True,), - parameters=dict(argstr="-p %s...", mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_image=dict( + argstr="-f %s", + extensions=None, + mandatory=True, + ), + fixed_mask=dict( + argstr="-fMask %s", + extensions=None, + ), + initial_transform=dict( + argstr="-t0 %s", + extensions=None, + ), + moving_image=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + ), + moving_mask=dict( + argstr="-mMask %s", + extensions=None, + ), + num_threads=dict( + argstr="-threads %01d", + nohash=True, + usedefault=True, + ), + output_path=dict( + argstr="-out %s", + mandatory=True, + usedefault=True, + ), + parameters=dict( + argstr="-p %s...", + mandatory=True, + ), ) inputs = Registration.input_spec() @@ -25,7 +58,9 @@ def test_Registration_inputs(): def test_Registration_outputs(): output_map = dict( transform=dict(), - warped_file=dict(extensions=None,), + warped_file=dict( + extensions=None, + ), warped_files=dict(), warped_files_flags=dict(), ) diff --git a/nipype/interfaces/elastix/utils.py b/nipype/interfaces/elastix/utils.py index 0cddcaba5d..912216af9a 100644 --- a/nipype/interfaces/elastix/utils.py +++ b/nipype/interfaces/elastix/utils.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -# coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -28,7 +26,7 @@ class EditTransformInputSpec(BaseInterfaceInputSpec): ) reference_image = File( exists=True, - desc=("set a new reference image to change the " "target coordinate system."), + desc=("set a new reference image to change the target coordinate system."), ) interpolation = traits.Enum( "cubic", @@ -96,7 +94,7 @@ def _run_interface(self, runtime): contents = "" - with open(self.inputs.transform_file, "r") as f: + with open(self.inputs.transform_file) as f: contents = f.read() if isdefined(self.inputs.output_type): @@ -166,18 +164,18 @@ def _run_interface(self, runtime): def _list_outputs(self): outputs = self.output_spec().get() - outputs["output_file"] = getattr(self, "_out_file") + outputs["output_file"] = self._out_file return outputs def _get_outfile(self): - val = getattr(self, "_out_file") + val = self._out_file if val is not None and val != "": return val if isdefined(self.inputs.output_file): - setattr(self, "_out_file", self.inputs.output_file) + self._out_file = self.inputs.output_file return self.inputs.output_file out_file = op.abspath(op.basename(self.inputs.transform_file)) - setattr(self, "_out_file", out_file) + self._out_file = out_file return out_file diff --git a/nipype/interfaces/freesurfer/__init__.py b/nipype/interfaces/freesurfer/__init__.py index 705cf895e4..b6863c9ded 100644 --- a/nipype/interfaces/freesurfer/__init__.py +++ b/nipype/interfaces/freesurfer/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """FreeSurfer is an open source software suite for processing and analyzing brain MRI images.""" @@ -93,3 +92,7 @@ Paint, MRICoreg, ) +from .petsurfer import ( + GTMSeg, + GTMPVC, +) diff --git a/nipype/interfaces/freesurfer/base.py b/nipype/interfaces/freesurfer/base.py index 66023386da..c84fc78cd5 100644 --- a/nipype/interfaces/freesurfer/base.py +++ b/nipype/interfaces/freesurfer/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The freesurfer module provides basic functions for interfacing with @@ -16,7 +15,8 @@ """ import os -from ... import LooseVersion +from looseversion import LooseVersion + from ...utils.filemanip import fname_presuffix from ..base import ( CommandLine, @@ -33,7 +33,7 @@ class Info(PackageInfo): - """ Freesurfer subject directory and version information. + """Freesurfer subject directory and version information. Examples -------- @@ -53,7 +53,7 @@ def parse_version(raw_info): @classmethod def looseversion(cls): - """ Return a comparable version object + """Return a comparable version object If no version found, use LooseVersion('0.0.0') """ @@ -76,6 +76,9 @@ def looseversion(cls): vstr = "6.0.0-dev" + githash elif vinfo[5][0] == "v": vstr = vinfo[5][1:] + elif len([1 for val in vinfo[3] if val == "."]) == 2: + "version string: freesurfer-linux-centos7_x86_64-7.1.0-20200511-813297b" + vstr = vinfo[3] else: raise RuntimeError("Unknown version string: " + ver) # Retain pre-6.0.0 heuristics @@ -115,7 +118,7 @@ class FSTraitedSpec(CommandLineInputSpec): class FSCommand(CommandLine): """General support for FreeSurfer commands. - Every FS command accepts 'subjects_dir' input. + Every FS command accepts 'subjects_dir' input. """ input_spec = FSTraitedSpec @@ -123,7 +126,7 @@ class FSCommand(CommandLine): _subjects_dir = None def __init__(self, **inputs): - super(FSCommand, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._subjects_dir_update, "subjects_dir") if not self._subjects_dir: self._subjects_dir = Info.subjectsdir() @@ -143,7 +146,7 @@ def run(self, **inputs): if "subjects_dir" in inputs: self.inputs.subjects_dir = inputs["subjects_dir"] self._subjects_dir_update() - return super(FSCommand, self).run(**inputs) + return super().run(**inputs) def _gen_fname(self, basename, fname=None, cwd=None, suffix="_fs", use_ext=True): """Define a generic mapping for a single outfile @@ -205,8 +208,7 @@ def _associated_file(in_file, out_name): class FSScriptCommand(FSCommand): - """ Support for Freesurfer script commands with log terminal_output - """ + """Support for Freesurfer script commands with log terminal_output""" _terminal_output = "file" _always_run = False @@ -239,7 +241,7 @@ class FSCommandOpenMP(FSCommand): _num_threads = None def __init__(self, **inputs): - super(FSCommandOpenMP, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._num_threads_update, "num_threads") if not self._num_threads: self._num_threads = os.environ.get("OMP_NUM_THREADS", None) @@ -259,7 +261,7 @@ def run(self, **inputs): if "num_threads" in inputs: self.inputs.num_threads = inputs["num_threads"] self._num_threads_update() - return super(FSCommandOpenMP, self).run(**inputs) + return super().run(**inputs) def no_freesurfer(): @@ -267,7 +269,4 @@ def no_freesurfer(): used with skipif to skip tests that will fail if FreeSurfer is not installed""" - if Info.version() is None: - return True - else: - return False + return Info.version() is None diff --git a/nipype/interfaces/freesurfer/longitudinal.py b/nipype/interfaces/freesurfer/longitudinal.py index aa5f928550..41e95c091b 100644 --- a/nipype/interfaces/freesurfer/longitudinal.py +++ b/nipype/interfaces/freesurfer/longitudinal.py @@ -1,14 +1,24 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Provides interfaces to various longitudinal commands provided by freesurfer -""" +"""Provides interfaces to various longitudinal commands provided by freesurfer""" import os from ... import logging -from ..base import TraitedSpec, File, traits, InputMultiPath, OutputMultiPath, isdefined -from .base import FSCommand, FSTraitedSpec, FSCommandOpenMP, FSTraitedSpecOpenMP +from ..base import ( + TraitedSpec, + File, + traits, + InputMultiPath, + OutputMultiPath, + isdefined, +) +from .base import ( + FSCommand, + FSTraitedSpec, + FSCommandOpenMP, + FSTraitedSpecOpenMP, +) __docformat__ = "restructuredtext" iflogger = logging.getLogger("nipype.interface") @@ -20,7 +30,7 @@ class RobustTemplateInputSpec(FSTraitedSpecOpenMP): File(exists=True), mandatory=True, argstr="--mov %s", - desc="input movable volumes to be aligned to common mean/median " "template", + desc="input movable volumes to be aligned to common mean/median template", ) out_file = File( "mri_robust_template_out.mgz", @@ -73,12 +83,12 @@ class RobustTemplateInputSpec(FSTraitedSpecOpenMP): ) initial_timepoint = traits.Int( argstr="--inittp %d", - desc="use TP# for spacial init (default random), 0: no init", + desc="use TP# for special init (default random), 0: no init", ) fixed_timepoint = traits.Bool( default_value=False, argstr="--fixtp", - desc="map everthing to init TP# (init TP is not resampled)", + desc="map everything to init TP# (init TP is not resampled)", ) no_iteration = traits.Bool( default_value=False, @@ -108,7 +118,7 @@ class RobustTemplateOutputSpec(TraitedSpec): class RobustTemplate(FSCommandOpenMP): - """ construct an unbiased robust template for longitudinal volumes + """construct an unbiased robust template for longitudinal volumes Examples -------- @@ -157,7 +167,7 @@ def _format_arg(self, name, spec, value): return spec.argstr % {"mean": 0, "median": 1}[value] if name in ("transform_outputs", "scaled_intensity_outputs"): value = self._list_outputs()[name] - return super(RobustTemplate, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -221,7 +231,7 @@ class FuseSegmentationsOutputSpec(TraitedSpec): class FuseSegmentations(FSCommand): - """ fuse segmentations together from multiple timepoints + """fuse segmentations together from multiple timepoints Examples -------- @@ -245,7 +255,7 @@ def _format_arg(self, name, spec, value): if name in ("in_segmentations", "in_segmentations_noCC", "in_norms"): # return enumeration value return spec.argstr % os.path.basename(value[0]) - return super(FuseSegmentations, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/freesurfer/model.py b/nipype/interfaces/freesurfer/model.py index 9e7d35d096..5e245a9a85 100644 --- a/nipype/interfaces/freesurfer/model.py +++ b/nipype/interfaces/freesurfer/model.py @@ -1,8 +1,7 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The freesurfer module provides basic functions for interfacing with - freesurfer tools. +freesurfer tools. """ import os @@ -12,6 +11,7 @@ TraitedSpec, File, traits, + Tuple, InputMultiPath, OutputMultiPath, Directory, @@ -73,7 +73,7 @@ class MRISPreprocInputSpec(FSTraitedSpec): argstr="--surfdir %s", desc="alternative directory (instead of surf)" ) vol_measure_file = InputMultiPath( - traits.Tuple(File(exists=True), File(exists=True)), + Tuple(File(exists=True), File(exists=True)), argstr="--iv %s %s...", desc="list of volume measure and reg file tuples", ) @@ -137,7 +137,7 @@ def _list_outputs(self): outputs["out_file"] = outfile if not isdefined(outfile): outputs["out_file"] = os.path.join( - os.getcwd(), "concat_%s_%s.mgz" % (self.inputs.hemi, self.inputs.target) + os.getcwd(), f"concat_{self.inputs.hemi}_{self.inputs.target}.mgz" ) return outputs @@ -231,7 +231,7 @@ def run(self, **inputs): if isdefined(self.inputs.surf_measure_file): copy2subjdir(self, self.inputs.surf_measure_file, folder) - return super(MRISPreprocReconAll, self).run(**inputs) + return super().run(**inputs) def _format_arg(self, name, spec, value): # mris_preproc looks for these files in the surf dir @@ -241,7 +241,7 @@ def _format_arg(self, name, spec, value): if name == "surf_measure_file": basename = os.path.basename(value) return spec.argstr % basename.lstrip("rh.").lstrip("lh.") - return super(MRISPreprocReconAll, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class GLMFitInputSpec(FSTraitedSpec): @@ -250,7 +250,7 @@ class GLMFitInputSpec(FSTraitedSpec): desc="input 4D file", argstr="--y %s", mandatory=True, copyfile=False ) _design_xor = ("fsgd", "design", "one_sample") - fsgd = traits.Tuple( + fsgd = Tuple( File(exists=True), traits.Enum("doss", "dods"), argstr="--fsgd %s %s", @@ -275,7 +275,7 @@ class GLMFitInputSpec(FSTraitedSpec): per_voxel_reg = InputMultiPath( File(exists=True), argstr="--pvr %s...", desc="per-voxel regressors" ) - self_reg = traits.Tuple( + self_reg = Tuple( traits.Int, traits.Int, traits.Int, @@ -366,7 +366,7 @@ class GLMFitInputSpec(FSTraitedSpec): surf_geo = traits.Str( "white", usedefault=True, desc="surface geometry name (e.g. white, pial)" ) - simulation = traits.Tuple( + simulation = Tuple( traits.Enum("perm", "mc-full", "mc-z"), traits.Int(min=1), traits.Float, @@ -377,7 +377,7 @@ class GLMFitInputSpec(FSTraitedSpec): sim_sign = traits.Enum( "abs", "pos", "neg", argstr="--sim-sign %s", desc="abs, pos, or neg" ) - uniform = traits.Tuple( + uniform = Tuple( traits.Float, traits.Float, argstr="--uniform %f %f", @@ -390,7 +390,7 @@ class GLMFitInputSpec(FSTraitedSpec): save_cond = traits.Bool( argstr="--save-cond", desc="flag to save design matrix condition at each voxel" ) - vox_dump = traits.Tuple( + vox_dump = Tuple( traits.Int, traits.Int, traits.Int, @@ -401,11 +401,39 @@ class GLMFitInputSpec(FSTraitedSpec): synth = traits.Bool(argstr="--synth", desc="replace input with gaussian") resynth_test = traits.Int(argstr="--resynthtest %d", desc="test GLM by resynthsis") profile = traits.Int(argstr="--profile %d", desc="niters : test speed") + mrtm1 = Tuple( + File(exists=True), + File(exists=True), + argstr="--mrtm1 %s %s", + desc="RefTac TimeSec : perform MRTM1 kinetic modeling", + ) + mrtm2 = Tuple( + File(exists=True), + File(exists=True), + traits.Float, + argstr="--mrtm2 %s %s %f", + desc="RefTac TimeSec k2prime : perform MRTM2 kinetic modeling", + ) + logan = Tuple( + File(exists=True), + File(exists=True), + traits.Float, + argstr="--logan %s %s %f", + desc="RefTac TimeSec tstar : perform Logan kinetic modeling", + ) + bp_clip_neg = traits.Bool( + argstr="--bp-clip-neg", + desc="set negative BP voxels to zero", + ) + bp_clip_max = traits.Float( + argstr="--bp-clip-max %f", + desc="set BP voxels above max to max", + ) force_perm = traits.Bool( argstr="--perm-force", desc="force perumtation test, even when design matrix is not orthog", ) - diag = traits.Int(argstr="--diag %d", desc="Gdiag_no : set diagnositc level") + diag = traits.Int(argstr="--diag %d", desc="Gdiag_no : set diagnostic level") diag_cluster = traits.Bool( argstr="--diag-cluster", desc="save sig volume and exit from first sim loop" ) @@ -423,10 +451,12 @@ class GLMFitInputSpec(FSTraitedSpec): sim_done_file = File( argstr="--sim-done %s", desc="create file when simulation finished" ) + _ext_xor = ['nii', 'nii_gz'] + nii = traits.Bool(argstr='--nii', desc='save outputs as nii', xor=_ext_xor) + nii_gz = traits.Bool(argstr='--nii.gz', desc='save outputs as nii.gz', xor=_ext_xor) class GLMFitOutputSpec(TraitedSpec): - glm_dir = Directory(exists=True, desc="output directory") beta_file = File(exists=True, desc="map of regression coefficients") error_file = File(desc="map of residual error") @@ -444,6 +474,8 @@ class GLMFitOutputSpec(TraitedSpec): frame_eigenvectors = File(desc="matrix of frame eigenvectors from residual PCA") singular_values = File(desc="matrix singular values from residual PCA") svd_stats_file = File(desc="text file summarizing the residual PCA") + k2p_file = File(desc="estimate of k2p parameter") + bp_file = File(desc="Binding potential estimates") class GLMFit(FSCommand): @@ -467,7 +499,7 @@ def _format_arg(self, name, spec, value): if name == "surf": _si = self.inputs return spec.argstr % (_si.subject_id, _si.hemi, _si.surf_geo) - return super(GLMFit, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -478,22 +510,33 @@ def _list_outputs(self): glmdir = os.path.abspath(self.inputs.glm_dir) outputs["glm_dir"] = glmdir + if isdefined(self.inputs.nii_gz): + ext = 'nii.gz' + elif isdefined(self.inputs.nii): + ext = 'nii' + else: + ext = 'mgh' + # Assign the output files that always get created - outputs["beta_file"] = os.path.join(glmdir, "beta.mgh") - outputs["error_var_file"] = os.path.join(glmdir, "rvar.mgh") - outputs["error_stddev_file"] = os.path.join(glmdir, "rstd.mgh") - outputs["mask_file"] = os.path.join(glmdir, "mask.mgh") + outputs["beta_file"] = os.path.join(glmdir, f"beta.{ext}") + outputs["error_var_file"] = os.path.join(glmdir, f"rvar.{ext}") + outputs["error_stddev_file"] = os.path.join(glmdir, f"rstd.{ext}") + outputs["mask_file"] = os.path.join(glmdir, f"mask.{ext}") outputs["fwhm_file"] = os.path.join(glmdir, "fwhm.dat") outputs["dof_file"] = os.path.join(glmdir, "dof.dat") # Assign the conditional outputs - if isdefined(self.inputs.save_residual) and self.inputs.save_residual: - outputs["error_file"] = os.path.join(glmdir, "eres.mgh") - if isdefined(self.inputs.save_estimate) and self.inputs.save_estimate: - outputs["estimate_file"] = os.path.join(glmdir, "yhat.mgh") + if self.inputs.save_residual: + outputs["error_file"] = os.path.join(glmdir, f"eres.{ext}") + if self.inputs.save_estimate: + outputs["estimate_file"] = os.path.join(glmdir, f"yhat.{ext}") + if any((self.inputs.mrtm1, self.inputs.mrtm2, self.inputs.logan)): + outputs["bp_file"] = os.path.join(glmdir, f"bp.{ext}") + if self.inputs.mrtm1: + outputs["k2p_file"] = os.path.join(glmdir, "k2prime.dat") # Get the contrast directory name(s) + contrasts = [] if isdefined(self.inputs.contrast): - contrasts = [] for c in self.inputs.contrast: if split_filename(c)[2] in [".mat", ".dat", ".mtx", ".con"]: contrasts.append(split_filename(c)[1]) @@ -503,19 +546,19 @@ def _list_outputs(self): contrasts = ["osgm"] # Add in the contrast images - outputs["sig_file"] = [os.path.join(glmdir, c, "sig.mgh") for c in contrasts] - outputs["ftest_file"] = [os.path.join(glmdir, c, "F.mgh") for c in contrasts] + outputs["sig_file"] = [os.path.join(glmdir, c, f"sig.{ext}") for c in contrasts] + outputs["ftest_file"] = [os.path.join(glmdir, c, f"F.{ext}") for c in contrasts] outputs["gamma_file"] = [ - os.path.join(glmdir, c, "gamma.mgh") for c in contrasts + os.path.join(glmdir, c, f"gamma.{ext}") for c in contrasts ] outputs["gamma_var_file"] = [ - os.path.join(glmdir, c, "gammavar.mgh") for c in contrasts + os.path.join(glmdir, c, f"gammavar.{ext}") for c in contrasts ] # Add in the PCA results, if relevant if isdefined(self.inputs.pca) and self.inputs.pca: pcadir = os.path.join(glmdir, "pca-eres") - outputs["spatial_eigenvectors"] = os.path.join(pcadir, "v.mgh") + outputs["spatial_eigenvectors"] = os.path.join(pcadir, f"v.{ext}") outputs["frame_eigenvectors"] = os.path.join(pcadir, "u.mtx") outputs["singluar_values"] = os.path.join(pcadir, "sdiag.mat") outputs["svd_stats_file"] = os.path.join(pcadir, "stats.dat") @@ -530,7 +573,7 @@ def _gen_filename(self, name): class OneSampleTTest(GLMFit): def __init__(self, **kwargs): - super(OneSampleTTest, self).__init__(**kwargs) + super().__init__(**kwargs) self.inputs.one_sample = True @@ -617,7 +660,7 @@ class Binarize(FSCommand): >>> binvol.cmdline 'mri_binarize --o foo_out.nii --i structural.nii --min 10.000000' - """ + """ _cmd = "mri_binarize" input_spec = BinarizeInputSpec @@ -631,7 +674,7 @@ def _list_outputs(self): outfile = fname_presuffix( self.inputs.in_file, newpath=os.getcwd(), - suffix=".".join(("_thresh", self.inputs.out_type)), + suffix=f"_thresh.{self.inputs.out_type}", use_ext=False, ) else: @@ -662,7 +705,7 @@ def _format_arg(self, name, spec, value): return spec.argstr % fname if name == "out_type": return "" - return super(Binarize, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_filename(self, name): if name == "binary_file": @@ -737,7 +780,7 @@ class ConcatenateInputSpec(FSTraitedSpec): mask_file = File(exists=True, argstr="--mask %s", desc="Mask input with a volume") vote = traits.Bool( argstr="--vote", - desc="Most frequent value at each voxel and fraction of occurances", + desc="Most frequent value at each voxel and fraction of occurrences", ) sort = traits.Bool(argstr="--sort", desc="Sort each voxel by ascending frame value") @@ -791,7 +834,7 @@ class SegStatsInputSpec(FSTraitedSpec): mandatory=True, desc="segmentation volume path", ) - annot = traits.Tuple( + annot = Tuple( traits.Str, traits.Enum("lh", "rh"), traits.Str, @@ -800,7 +843,7 @@ class SegStatsInputSpec(FSTraitedSpec): mandatory=True, desc="subject hemi parc : use surface parcellation", ) - surf_label = traits.Tuple( + surf_label = Tuple( traits.Str, traits.Enum("lh", "rh"), traits.Str, @@ -1031,7 +1074,7 @@ def _format_arg(self, name, spec, value): ".mgz", "" ) return spec.argstr % (value, intensity_name) - return super(SegStats, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_filename(self, name): if name == "summary_file": @@ -1082,7 +1125,7 @@ class SegStatsReconAll(SegStats): """ This class inherits SegStats and modifies it for use in a recon-all workflow. This implementation mandates implicit inputs that SegStats. - To ensure backwards compatability of SegStats, this class was created. + To ensure backwards compatibility of SegStats, this class was created. Examples -------- @@ -1123,7 +1166,7 @@ class SegStatsReconAll(SegStats): def _format_arg(self, name, spec, value): if name == "brainmask_file": return spec.argstr % os.path.basename(value) - return super(SegStatsReconAll, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def run(self, **inputs): if self.inputs.copy_inputs: @@ -1147,7 +1190,7 @@ def run(self, **inputs): ) copy2subjdir(self, self.inputs.in_intensity, "mri") copy2subjdir(self, self.inputs.brainmask_file, "mri") - return super(SegStatsReconAll, self).run(**inputs) + return super().run(**inputs) class Label2VolInputSpec(FSTraitedSpec): @@ -1209,7 +1252,7 @@ class Label2VolInputSpec(FSTraitedSpec): label_voxel_volume = traits.Float( argstr="--labvoxvol %f", desc="volume of each label point (def 1mm3)" ) - proj = traits.Tuple( + proj = Tuple( traits.Enum("abs", "frac"), traits.Float, traits.Float, @@ -1249,7 +1292,7 @@ class Label2Vol(FSCommand): >>> binvol.cmdline 'mri_label2vol --fillthresh 0.5 --label cortex.label --reg register.dat --temp structural.nii --o foo_out.nii' - """ + """ _cmd = "mri_label2vol" input_spec = Label2VolInputSpec @@ -1298,7 +1341,7 @@ class MS_LDAInputSpec(FSTraitedSpec): exists=False, argstr="-synth %s", mandatory=True, - desc=("filename for the synthesized output " "volume"), + desc=("filename for the synthesized output volume"), ) label_file = File( exists=True, argstr="-label %s", desc="filename of the label volume" @@ -1311,10 +1354,10 @@ class MS_LDAInputSpec(FSTraitedSpec): ) conform = traits.Bool( argstr="-conform", - desc=("Conform the input volumes (brain mask " "typically already conformed)"), + desc=("Conform the input volumes (brain mask typically already conformed)"), ) use_weights = traits.Bool( - argstr="-W", desc=("Use the weights from a previously " "generated weight file") + argstr="-W", desc=("Use the weights from a previously generated weight file") ) images = InputMultiPath( File(exists=True), @@ -1376,7 +1419,7 @@ def _format_arg(self, name, spec, value): else: return "" # TODO: Fix bug when boolean values are set explicitly to false - return super(MS_LDA, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_filename(self, name): pass @@ -1426,9 +1469,8 @@ class Label2LabelInputSpec(FSTraitedSpec): desc="Registration method", ) copy_inputs = traits.Bool( - desc="If running as a node, set this to True." - + "This will copy the input files to the node " - + "directory." + desc="If running as a node, set this to True. " + "This will copy the input files to the node directory." ) @@ -1484,22 +1526,20 @@ def run(self, **inputs): if "subjects_dir" in inputs: inputs["subjects_dir"] = self.inputs.subjects_dir hemi = self.inputs.hemisphere - copy2subjdir( - self, self.inputs.sphere_reg, "surf", "{0}.sphere.reg".format(hemi) - ) - copy2subjdir(self, self.inputs.white, "surf", "{0}.white".format(hemi)) + copy2subjdir(self, self.inputs.sphere_reg, "surf", f"{hemi}.sphere.reg") + copy2subjdir(self, self.inputs.white, "surf", f"{hemi}.white") copy2subjdir( self, self.inputs.source_sphere_reg, "surf", - "{0}.sphere.reg".format(hemi), + f"{hemi}.sphere.reg", subject_id=self.inputs.source_subject, ) copy2subjdir( self, self.inputs.source_white, "surf", - "{0}.white".format(hemi), + f"{hemi}.white", subject_id=self.inputs.source_subject, ) @@ -1510,7 +1550,7 @@ def run(self, **inputs): if not os.path.isdir(label_dir): os.makedirs(label_dir) - return super(Label2Label, self).run(**inputs) + return super().run(**inputs) class Label2AnnotInputSpec(FSTraitedSpec): @@ -1583,7 +1623,7 @@ def run(self, **inputs): self, self.inputs.orig, folder="surf", - basename="{0}.orig".format(self.inputs.hemisphere), + basename=f"{self.inputs.hemisphere}.orig", ) # label dir must exist in order for output file to be written label_dir = os.path.join( @@ -1591,7 +1631,7 @@ def run(self, **inputs): ) if not os.path.isdir(label_dir): os.makedirs(label_dir) - return super(Label2Annot, self).run(**inputs) + return super().run(**inputs) def _list_outputs(self): outputs = self._outputs().get() @@ -1681,7 +1721,7 @@ def _format_arg(self, name, spec, value): for item in ["lh.", "rh."]: surf = surf.replace(item, "") return spec.argstr % surf - return super(SphericalAverage, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_filename(self, name): if name == "in_average": diff --git a/nipype/interfaces/freesurfer/petsurfer.py b/nipype/interfaces/freesurfer/petsurfer.py new file mode 100644 index 0000000000..28aa763b06 --- /dev/null +++ b/nipype/interfaces/freesurfer/petsurfer.py @@ -0,0 +1,664 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +"""Provides interfaces to various commands for running PET analyses provided by FreeSurfer""" + +import os + +from ... import logging +from ..base import ( + TraitedSpec, + File, + traits, + Tuple, + Directory, + InputMultiPath, + isdefined, +) +from .base import FSCommand, FSTraitedSpec + +from .model import GLMFitInputSpec, GLMFit + +__docformat__ = "restructuredtext" +iflogger = logging.getLogger("nipype.interface") + + +class GTMSegInputSpec(FSTraitedSpec): + subject_id = traits.String(argstr="--s %s", desc="subject id", mandatory=True) + + xcerseg = traits.Bool( + argstr="--xcerseg", + desc="run xcerebralseg on this subject to create apas+head.mgz", + ) + + out_file = File( + "gtmseg.mgz", + argstr="--o %s", + desc="output volume relative to subject/mri", + usedefault=True, + ) + + upsampling_factor = traits.Int( + argstr="--usf %i", desc="upsampling factor (default is 2)" + ) + + subsegwm = traits.Bool( + argstr="--subsegwm", default=True, desc="subsegment WM into lobes (default)" + ) + + keep_hypo = traits.Bool( + argstr="--keep-hypo", + desc="do not relabel hypointensities as WM when subsegmenting WM", + ) + + keep_cc = traits.Bool( + argstr="--keep-cc", desc="do not relabel corpus callosum as WM" + ) + + dmax = traits.Float( + argstr="--dmax %f", + desc="distance threshold to use when subsegmenting WM (default is 5)", + ) + + ctx_annot = Tuple( + traits.String, + traits.Int, + traits.Int, + argstr="--ctx-annot %s %i %i", + desc="annot lhbase rhbase : annotation to use for cortical segmentation (default is aparc 1000 2000)", + ) + + wm_annot = Tuple( + traits.String, + traits.Int, + traits.Int, + argstr="--wm-annot %s %i %i", + desc="annot lhbase rhbase : annotation to use for WM segmentation (with --subsegwm, default is lobes 3200 4200)", + ) + + output_upsampling_factor = traits.Int( + argstr="--output-usf %i", + desc="set output USF different than USF, mostly for debugging", + ) + + head = traits.String( + argstr="--head %s", desc="use headseg instead of apas+head.mgz" + ) + + subseg_cblum_wm = traits.Bool( + argstr="--subseg-cblum-wm", desc="subsegment cerebellum WM into core and gyri" + ) + + no_pons = traits.Bool( + argstr="--no-pons", desc="do not add pons segmentation when doing ---xcerseg" + ) + + no_vermis = traits.Bool( + argstr="--no-vermis", + desc="do not add vermis segmentation when doing ---xcerseg", + ) + + colortable = File(exists=True, argstr="--ctab %s", desc="colortable") + no_seg_stats = traits.Bool( + argstr="--no-seg-stats", desc="do not compute segmentation stats" + ) + + +class GTMSegOutputSpec(TraitedSpec): + out_file = File(desc="GTM segmentation") + + +class GTMSeg(FSCommand): + """create an anatomical segmentation for the geometric transfer matrix (GTM). + + Examples + -------- + >>> gtmseg = GTMSeg() + >>> gtmseg.inputs.subject_id = 'subject_id' + >>> gtmseg.cmdline + 'gtmseg --o gtmseg.mgz --s subject_id' + """ + + _cmd = "gtmseg" + input_spec = GTMSegInputSpec + output_spec = GTMSegOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs['out_file'] = os.path.join( + self.inputs.subjects_dir, + self.inputs.subject_id, + 'mri', + self.inputs.out_file, + ) + return outputs + + +class GTMPVCInputSpec(FSTraitedSpec): + in_file = File( + exists=True, + argstr="--i %s", + mandatory=True, + copyfile=False, + desc="input volume - source data to pvc", + ) + + frame = traits.Int( + argstr="--frame %i", desc="only process 0-based frame F from inputvol" + ) + + psf = traits.Float(argstr="--psf %f", desc="scanner PSF FWHM in mm") + + segmentation = File( + argstr="--seg %s", + exists=True, + mandatory=True, + desc="segfile : anatomical segmentation to define regions for GTM", + ) + + _reg_xor = ["reg_file", "regheader", "reg_identity"] + reg_file = File( + exists=True, + argstr="--reg %s", + mandatory=True, + desc="LTA registration file that maps PET to anatomical", + xor=_reg_xor, + ) + + regheader = traits.Bool( + argstr="--regheader", + mandatory=True, + desc="assume input and seg share scanner space", + xor=_reg_xor, + ) + + reg_identity = traits.Bool( + argstr="--reg-identity", + mandatory=True, + desc="assume that input is in anatomical space", + xor=_reg_xor, + ) + + pvc_dir = traits.Str(argstr="--o %s", desc="save outputs to dir", genfile=True) + + mask_file = File( + exists=True, + argstr="--mask %s", + desc="ignore areas outside of the mask (in input vol space)", + ) + + auto_mask = Tuple( + traits.Float, + traits.Float, + argstr="--auto-mask %f %f", + desc="FWHM thresh : automatically compute mask", + ) + + no_reduce_fov = traits.Bool( + argstr="--no-reduce-fov", desc="do not reduce FoV to encompass mask" + ) + + reduce_fox_eqodd = traits.Bool( + argstr="--reduce-fox-eqodd", + desc="reduce FoV to encompass mask but force nc=nr and ns to be odd", + ) + + contrast = InputMultiPath( + File(exists=True), argstr="--C %s...", desc="contrast file" + ) + + default_seg_merge = traits.Bool( + argstr="--default-seg-merge", desc="default schema for merging ROIs" + ) + + merge_hypos = traits.Bool( + argstr="--merge-hypos", desc="merge left and right hypointensites into to ROI" + ) + + merge_cblum_wm_gyri = traits.Bool( + argstr="--merge-cblum-wm-gyri", + desc="cerebellum WM gyri back into cerebellum WM", + ) + + tt_reduce = traits.Bool( + argstr="--tt-reduce", desc="reduce segmentation to that of a tissue type" + ) + + replace = Tuple( + traits.Int, + traits.Int, + argstr="--replace %i %i", + desc="Id1 Id2 : replace seg Id1 with seg Id2", + ) + + rescale = traits.List( + argstr="--rescale %s...", + desc="Id1 : specify reference region(s) used to rescale (default is pons)", + ) + + no_rescale = traits.Bool( + argstr="--no-rescale", + desc="do not global rescale such that mean of reference region is scaleref", + ) + + scale_refval = traits.Float( + argstr="--scale-refval %f", + desc="refval : scale such that mean in reference region is refval", + ) + + _ctab_inputs = ("color_table_file", "default_color_table") + color_table_file = File( + exists=True, + argstr="--ctab %s", + xor=_ctab_inputs, + desc="color table file with seg id names", + ) + + default_color_table = traits.Bool( + argstr="--ctab-default", + xor=_ctab_inputs, + desc="use $FREESURFER_HOME/FreeSurferColorLUT.txt", + ) + + tt_update = traits.Bool( + argstr="--tt-update", + desc="changes tissue type of VentralDC, BrainStem, and Pons to be SubcortGM", + ) + + lat = traits.Bool(argstr="--lat", desc="lateralize tissue types") + + no_tfe = traits.Bool( + argstr="--no-tfe", + desc="do not correct for tissue fraction effect (with --psf 0 turns off PVC entirely)", + ) + + no_pvc = traits.Bool( + argstr="--no-pvc", + desc="turns off PVC entirely (both PSF and TFE)", + ) + + tissue_fraction_resolution = traits.Float( + argstr="--segpvfres %f", + desc="set the tissue fraction resolution parameter (def is 0.5)", + ) + + rbv = traits.Bool( + argstr="--rbv", + requires=["subjects_dir"], + desc="perform Region-based Voxelwise (RBV) PVC", + ) + + rbv_res = traits.Float( + argstr="--rbv-res %f", + desc="voxsize : set RBV voxel resolution (good for when standard res takes too much memory)", + ) + + mg = Tuple( + traits.Float, + traits.List(traits.String), + argstr="--mg %g %s", + desc="gmthresh RefId1 RefId2 ...: perform Mueller-Gaertner PVC, gmthresh is min gm pvf bet 0 and 1", + ) + + mg_ref_cerebral_wm = traits.Bool( + argstr="--mg-ref-cerebral-wm", desc=" set MG RefIds to 2 and 41" + ) + + mg_ref_lobes_wm = traits.Bool( + argstr="--mg-ref-lobes-wm", + desc="set MG RefIds to those for lobes when using wm subseg", + ) + + mgx = traits.Float( + argstr="--mgx %f", + desc="gmxthresh : GLM-based Mueller-Gaertner PVC, gmxthresh is min gm pvf bet 0 and 1", + ) + + km_ref = traits.List( + argstr="--km-ref %s...", + desc="RefId1 RefId2 ... : compute reference TAC for KM as mean of given RefIds", + ) + + km_hb = traits.List( + argstr="--km-hb %s...", + desc="RefId1 RefId2 ... : compute HiBinding TAC for KM as mean of given RefIds", + ) + + steady_state_params = Tuple( + traits.Float, + traits.Float, + traits.Float, + argstr="--ss %f %f %f", + desc="bpc scale dcf : steady-state analysis spec blood plasma concentration, unit scale and decay correction factor. You must also spec --km-ref. Turns off rescaling", + ) + + X = traits.Bool( + argstr="--X", desc="save X matrix in matlab4 format as X.mat (it will be big)" + ) + + y = traits.Bool(argstr="--y", desc="save y matrix in matlab4 format as y.mat") + + beta = traits.Bool( + argstr="--beta", desc="save beta matrix in matlab4 format as beta.mat" + ) + + X0 = traits.Bool( + argstr="--X0", + desc="save X0 matrix in matlab4 format as X0.mat (it will be big)", + ) + + save_input = traits.Bool( + argstr="--save-input", desc="saves rescaled input as input.rescaled.nii.gz" + ) + + save_eres = traits.Bool(argstr="--save-eres", desc="saves residual error") + + save_yhat = traits.Bool( + argstr="--save-yhat", + xor=["save_yhat_with_noise"], + desc="save signal estimate (yhat) smoothed with the PSF", + ) + + save_yhat_with_noise = Tuple( + traits.Int, + traits.Int, + argstr="--save-yhat-with-noise %i %i", + xor=["save_yhat"], + desc="seed nreps : save signal estimate (yhat) with noise", + ) + + save_yhat_full_fov = traits.Bool( + argstr="--save-yhat-full-fov", desc="save signal estimate (yhat)" + ) + + save_yhat0 = traits.Bool(argstr="--save-yhat0", desc="save signal estimate (yhat)") + + optimization_schema = traits.Enum( + "3D", + "2D", + "1D", + "3D_MB", + "2D_MB", + "1D_MB", + "MBZ", + "MB3", + argstr="--opt %s", + desc="opt : optimization schema for applying adaptive GTM", + ) + + opt_tol = Tuple( + traits.Int, + traits.Float, + traits.Float, + argstr="--opt-tol %i %f %f", + desc="n_iters_max ftol lin_min_tol : optimization parameters for adaptive gtm using fminsearch", + ) + + opt_brain = traits.Bool(argstr="--opt-brain", desc="apply adaptive GTM") + + opt_seg_merge = traits.Bool( + argstr="--opt-seg-merge", + desc="optimal schema for merging ROIs when applying adaptive GTM", + ) + + num_threads = traits.Int( + argstr="--threads %i", desc="threads : number of threads to use" + ) + + psf_col = traits.Float( + argstr="--psf-col %f", desc="xFWHM : full-width-half-maximum in the x-direction" + ) + + psf_row = traits.Float( + argstr="--psf-row %f", desc="yFWHM : full-width-half-maximum in the y-direction" + ) + + psf_slice = traits.Float( + argstr="--psf-slice %f", + desc="zFWHM : full-width-half-maximum in the z-direction", + ) + + +class GTMPVCOutputSpec(TraitedSpec): + pvc_dir = Directory(desc="output directory") + ref_file = File(desc="Reference TAC in .dat") + hb_nifti = File(desc="High-binding TAC in nifti") + hb_dat = File(desc="High-binding TAC in .dat") + nopvc_file = File(desc="TACs for all regions with no PVC") + gtm_file = File(desc="TACs for all regions with GTM PVC") + gtm_stats = File(desc="Statistics for the GTM PVC") + input_file = File(desc="4D PET file in native volume space") + reg_pet2anat = File(desc="Registration file to go from PET to anat") + reg_anat2pet = File(desc="Registration file to go from anat to PET") + reg_rbvpet2anat = File( + desc="Registration file to go from RBV corrected PET to anat" + ) + reg_anat2rbvpet = File( + desc="Registration file to go from anat to RBV corrected PET" + ) + mgx_ctxgm = File( + desc="Cortical GM voxel-wise values corrected using the extended Muller-Gartner method", + ) + mgx_subctxgm = File( + desc="Subcortical GM voxel-wise values corrected using the extended Muller-Gartner method", + ) + mgx_gm = File( + desc="All GM voxel-wise values corrected using the extended Muller-Gartner method", + ) + rbv = File(desc="All GM voxel-wise values corrected using the RBV method") + opt_params = File( + desc="Optimal parameter estimates for the FWHM using adaptive GTM" + ) + yhat0 = File(desc="4D PET file of signal estimate (yhat) after PVC (unsmoothed)") + yhat = File( + desc="4D PET file of signal estimate (yhat) after PVC (smoothed with PSF)", + ) + yhat_full_fov = File( + desc="4D PET file with full FOV of signal estimate (yhat) after PVC (smoothed with PSF)", + ) + yhat_with_noise = File( + desc="4D PET file with full FOV of signal estimate (yhat) with noise after PVC (smoothed with PSF)", + ) + eres = File( + desc="4D PET file of residual error after PVC (smoothed with PSF)", + ) + tissue_fraction = File( + desc="4D PET file of tissue fraction before PVC", + ) + tissue_fraction_psf = File( + desc="4D PET file of tissue fraction after PVC (smoothed with PSF)", + ) + seg = File( + desc="Segmentation file of regions used for PVC", + ) + seg_ctab = File( + desc="Color table file for segmentation file", + ) + + +class GTMPVC(FSCommand): + """Perform Partial Volume Correction (PVC) to PET Data. + + Examples + -------- + >>> gtmpvc = GTMPVC() + >>> gtmpvc.inputs.in_file = 'sub-01_ses-baseline_pet.nii.gz' + >>> gtmpvc.inputs.segmentation = 'gtmseg.mgz' + >>> gtmpvc.inputs.reg_file = 'sub-01_ses-baseline_pet_mean_reg.lta' + >>> gtmpvc.inputs.pvc_dir = 'pvc' + >>> gtmpvc.inputs.psf = 4 + >>> gtmpvc.inputs.default_seg_merge = True + >>> gtmpvc.inputs.auto_mask = (1, 0.1) + >>> gtmpvc.inputs.km_ref = ['8 47'] + >>> gtmpvc.inputs.km_hb = ['11 12 50 51'] + >>> gtmpvc.inputs.no_rescale = True + >>> gtmpvc.inputs.save_input = True + >>> gtmpvc.cmdline # doctest: +NORMALIZE_WHITESPACE + 'mri_gtmpvc --auto-mask 1.000000 0.100000 --default-seg-merge \ + --i sub-01_ses-baseline_pet.nii.gz --km-hb 11 12 50 51 --km-ref 8 47 --no-rescale \ + --psf 4.000000 --o pvc --reg sub-01_ses-baseline_pet_mean_reg.lta --save-input \ + --seg gtmseg.mgz' + + >>> gtmpvc = GTMPVC() + >>> gtmpvc.inputs.in_file = 'sub-01_ses-baseline_pet.nii.gz' + >>> gtmpvc.inputs.segmentation = 'gtmseg.mgz' + >>> gtmpvc.inputs.regheader = True + >>> gtmpvc.inputs.pvc_dir = 'pvc' + >>> gtmpvc.inputs.mg = (0.5, ["ROI1", "ROI2"]) + >>> gtmpvc.cmdline # doctest: +NORMALIZE_WHITESPACE + 'mri_gtmpvc --i sub-01_ses-baseline_pet.nii.gz --mg 0.5 ROI1 ROI2 --o pvc --regheader --seg gtmseg.mgz' + """ + + _cmd = "mri_gtmpvc" + input_spec = GTMPVCInputSpec + output_spec = GTMPVCOutputSpec + + def _format_arg(self, name, spec, val): + # Values taken from + # https://github.com/freesurfer/freesurfer/blob/fs-7.2/mri_gtmpvc/mri_gtmpvc.cpp#L115-L122 + if name == 'optimization_schema': + return ( + spec.argstr + % { + "3D": 1, + "2D": 2, + "1D": 3, + "3D_MB": 4, + "2D_MB": 5, + "1D_MB": 6, + "MBZ": 7, + "MB3": 8, + }[val] + ) + if name == 'mg': + return spec.argstr % (val[0], ' '.join(val[1])) + return super()._format_arg(name, spec, val) + + def _list_outputs(self): + outputs = self.output_spec().get() + # Get the top-level output directory + if not isdefined(self.inputs.pvc_dir): + pvcdir = os.getcwd() + else: + pvcdir = os.path.abspath(self.inputs.pvc_dir) + outputs["pvc_dir"] = pvcdir + + # Assign the output files that always get created + outputs["ref_file"] = os.path.join(pvcdir, "km.ref.tac.dat") + outputs["hb_nifti"] = os.path.join(pvcdir, "km.hb.tac.nii.gz") + outputs["hb_dat"] = os.path.join(pvcdir, "km.hb.tac.dat") + outputs["nopvc_file"] = os.path.join(pvcdir, "nopvc.nii.gz") + outputs["gtm_file"] = os.path.join(pvcdir, "gtm.nii.gz") + outputs["gtm_stats"] = os.path.join(pvcdir, "gtm.stats.dat") + outputs["reg_pet2anat"] = os.path.join(pvcdir, "aux", "bbpet2anat.lta") + outputs["reg_anat2pet"] = os.path.join(pvcdir, "aux", "anat2bbpet.lta") + outputs["eres"] = os.path.join(pvcdir, "eres.nii.gz") + outputs["tissue_fraction"] = os.path.join( + pvcdir, "aux", "tissue.fraction.nii.gz" + ) + outputs["tissue_fraction_psf"] = os.path.join( + pvcdir, "aux", "tissue.fraction.psf.nii.gz" + ) + outputs["seg"] = os.path.join(pvcdir, "aux", "seg.nii.gz") + outputs["seg_ctab"] = os.path.join(pvcdir, "aux", "seg.ctab") + + # Assign the conditional outputs + if self.inputs.save_input: + outputs["input_file"] = os.path.join(pvcdir, "input.nii.gz") + if self.inputs.save_yhat0: + outputs["yhat0"] = os.path.join(pvcdir, "yhat0.nii.gz") + if self.inputs.save_yhat: + outputs["yhat"] = os.path.join(pvcdir, "yhat.nii.gz") + if self.inputs.save_yhat_full_fov: + outputs["yhat_full_fov"] = os.path.join(pvcdir, "yhat.fullfov.nii.gz") + if self.inputs.save_yhat_with_noise: + outputs["yhat_with_noise"] = os.path.join(pvcdir, "yhat.nii.gz") + if self.inputs.mgx: + outputs["mgx_ctxgm"] = os.path.join(pvcdir, "mgx.ctxgm.nii.gz") + outputs["mgx_subctxgm"] = os.path.join(pvcdir, "mgx.subctxgm.nii.gz") + outputs["mgx_gm"] = os.path.join(pvcdir, "mgx.gm.nii.gz") + if self.inputs.rbv: + outputs["rbv"] = os.path.join(pvcdir, "rbv.nii.gz") + outputs["reg_rbvpet2anat"] = os.path.join(pvcdir, "aux", "rbv2anat.lta") + outputs["reg_anat2rbvpet"] = os.path.join(pvcdir, "aux", "anat2rbv.lta") + if self.inputs.optimization_schema: + outputs["opt_params"] = os.path.join(pvcdir, "aux", "opt.params.dat") + + return outputs + + +class MRTM1InputSpec(GLMFitInputSpec): + mrtm1 = Tuple( + File(exists=True), + File(exists=True), + mandatory=True, + argstr="--mrtm1 %s %s", + desc="RefTac TimeSec : perform MRTM1 kinetic modeling", + ) + + +class MRTM1(GLMFit): + """Perform MRTM1 kinetic modeling. + + Examples + -------- + >>> mrtm = MRTM1() + >>> mrtm.inputs.in_file = 'tac.nii' + >>> mrtm.inputs.mrtm1 = ('ref_tac.dat', 'timing.dat') + >>> mrtm.inputs.glm_dir = 'mrtm' + >>> mrtm.cmdline + 'mri_glmfit --glmdir mrtm --y tac.nii --mrtm1 ref_tac.dat timing.dat' + """ + + input_spec = MRTM1InputSpec + + +class MRTM2InputSpec(GLMFitInputSpec): + mrtm2 = Tuple( + File(exists=True), + File(exists=True), + traits.Float, + mandatory=True, + argstr="--mrtm2 %s %s %f", + desc="RefTac TimeSec k2prime : perform MRTM2 kinetic modeling", + ) + + +class MRTM2(GLMFit): + """Perform MRTM2 kinetic modeling. + Examples + -------- + >>> mrtm2 = MRTM2() + >>> mrtm2.inputs.in_file = 'tac.nii' + >>> mrtm2.inputs.mrtm2 = ('ref_tac.dat', 'timing.dat', 0.07872) + >>> mrtm2.inputs.glm_dir = 'mrtm2' + >>> mrtm2.cmdline + 'mri_glmfit --glmdir mrtm2 --y tac.nii --mrtm2 ref_tac.dat timing.dat 0.078720' + """ + + input_spec = MRTM2InputSpec + + +class LoganInputSpec(GLMFitInputSpec): + logan = Tuple( + File(exists=True), + File(exists=True), + traits.Float, + mandatory=True, + argstr="--logan %s %s %g", + desc="RefTac TimeSec tstar : perform Logan kinetic modeling", + ) + + +class Logan(GLMFit): + """Perform Logan kinetic modeling. + Examples + -------- + >>> logan = Logan() + >>> logan.inputs.in_file = 'tac.nii' + >>> logan.inputs.logan = ('ref_tac.dat', 'timing.dat', 2600) + >>> logan.inputs.glm_dir = 'logan' + >>> logan.cmdline + 'mri_glmfit --glmdir logan --y tac.nii --logan ref_tac.dat timing.dat 2600' + """ + + input_spec = LoganInputSpec diff --git a/nipype/interfaces/freesurfer/preprocess.py b/nipype/interfaces/freesurfer/preprocess.py index 39a444495c..89c218f969 100644 --- a/nipype/interfaces/freesurfer/preprocess.py +++ b/nipype/interfaces/freesurfer/preprocess.py @@ -1,29 +1,31 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Provides interfaces to various commands provided by FreeSurfer -""" +"""Provides interfaces to various commands provided by FreeSurfer""" import os import os.path as op from glob import glob import shutil +import sys +from looseversion import LooseVersion import numpy as np from nibabel import load -from ... import logging, LooseVersion +from ... import logging from ...utils.filemanip import fname_presuffix, check_depends from ..io import FreeSurferSource from ..base import ( TraitedSpec, File, traits, + Tuple, Directory, InputMultiPath, OutputMultiPath, CommandLine, CommandLineInputSpec, isdefined, + InputMultiObject, ) from .base import FSCommand, FSTraitedSpec, FSTraitedSpecOpenMP, FSCommandOpenMP, Info from .utils import copy2subjdir @@ -73,7 +75,7 @@ class ParseDICOMDir(FSCommand): >>> dcminfo.cmdline 'mri_parse_sdcmdir --d . --o dicominfo.txt --sortbyrun --summarize' - """ + """ _cmd = "mri_parse_sdcmdir" input_spec = ParseDICOMDirInputSpec @@ -98,7 +100,7 @@ class UnpackSDICOMDirInputSpec(FSTraitedSpec): output_dir = Directory( argstr="-targ %s", desc="top directory into which the files will be unpacked" ) - run_info = traits.Tuple( + run_info = Tuple( traits.Int, traits.Str, traits.Str, @@ -134,7 +136,7 @@ class UnpackSDICOMDirInputSpec(FSTraitedSpec): argstr="-scanonly %s", desc="only scan the directory and put result in file", ) - log_file = File(exists=True, argstr="-log %s", desc="explicilty set log file") + log_file = File(exists=True, argstr="-log %s", desc="explicitly set log file") spm_zeropad = traits.Int( argstr="-nspmzeropad %d", desc="set frame number zero padding width for SPM" ) @@ -181,21 +183,21 @@ class MRIConvertInputSpec(FSTraitedSpec): force_ras = traits.Bool( argstr="--force_ras_good", desc="use default when orientation info absent" ) - in_i_dir = traits.Tuple( + in_i_dir = Tuple( traits.Float, traits.Float, traits.Float, argstr="--in_i_direction %f %f %f", desc=" ", ) - in_j_dir = traits.Tuple( + in_j_dir = Tuple( traits.Float, traits.Float, traits.Float, argstr="--in_j_direction %f %f %f", desc=" ", ) - in_k_dir = traits.Tuple( + in_k_dir = Tuple( traits.Float, traits.Float, traits.Float, @@ -274,7 +276,7 @@ class MRIConvertInputSpec(FSTraitedSpec): out_k_count = traits.Int( argstr="--out_k_count %d", desc="some count ?? in k direction" ) - vox_size = traits.Tuple( + vox_size = Tuple( traits.Float, traits.Float, traits.Float, @@ -284,21 +286,21 @@ class MRIConvertInputSpec(FSTraitedSpec): out_i_size = traits.Int(argstr="--out_i_size %d", desc="output i size") out_j_size = traits.Int(argstr="--out_j_size %d", desc="output j size") out_k_size = traits.Int(argstr="--out_k_size %d", desc="output k size") - out_i_dir = traits.Tuple( + out_i_dir = Tuple( traits.Float, traits.Float, traits.Float, argstr="--out_i_direction %f %f %f", desc=" ", ) - out_j_dir = traits.Tuple( + out_j_dir = Tuple( traits.Float, traits.Float, traits.Float, argstr="--out_j_direction %f %f %f", desc=" ", ) - out_k_dir = traits.Tuple( + out_k_dir = Tuple( traits.Float, traits.Float, traits.Float, @@ -310,7 +312,7 @@ class MRIConvertInputSpec(FSTraitedSpec): argstr="--out_orientation %s", desc="specify the output orientation", ) - out_center = traits.Tuple( + out_center = Tuple( traits.Float, traits.Float, traits.Float, @@ -356,14 +358,14 @@ class MRIConvertInputSpec(FSTraitedSpec): desc="apply inverse transformation xfm file", ) devolve_transform = traits.Str(argstr="--devolvexfm %s", desc="subject id") - crop_center = traits.Tuple( + crop_center = Tuple( traits.Int, traits.Int, traits.Int, argstr="--crop %d %d %d", desc=" crop to 256 around center (x, y, z)", ) - crop_size = traits.Tuple( + crop_size = Tuple( traits.Int, traits.Int, traits.Int, @@ -373,7 +375,7 @@ class MRIConvertInputSpec(FSTraitedSpec): cut_ends = traits.Int( argstr="--cutends %d", desc="remove ncut slices from the ends" ) - slice_crop = traits.Tuple( + slice_crop = Tuple( traits.Int, traits.Int, argstr="--slice-crop %d %d", @@ -414,7 +416,7 @@ class MRIConvertInputSpec(FSTraitedSpec): ascii = traits.Bool( argstr="--ascii", desc="save output as ascii col>row>slice>frame" ) - reorder = traits.Tuple( + reorder = Tuple( traits.Int, traits.Int, traits.Int, @@ -463,7 +465,7 @@ class MRIConvertInputSpec(FSTraitedSpec): midframe = traits.Bool(argstr="--mid-frame", desc="keep only the middle frame") skip_n = traits.Int(argstr="--nskip %d", desc="skip the first n frames") drop_n = traits.Int(argstr="--ndrop %d", desc="drop the last n frames") - frame_subsample = traits.Tuple( + frame_subsample = Tuple( traits.Int, traits.Int, traits.Int, @@ -544,7 +546,7 @@ def _format_arg(self, name, spec, value): if name in ["in_type", "out_type", "template_type"]: if value == "niigz": return spec.argstr % "nii" - return super(MRIConvert, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _get_outfilename(self): outfile = self.inputs.out_file @@ -577,7 +579,7 @@ def _list_outputs(self): stem = ".".join(outfile.split(".")[:-1]) ext = "." + outfile.split(".")[-1] outfile = [] - for idx in range(0, tp): + for idx in range(tp): outfile.append(stem + "%04d" % idx + ext) if isdefined(self.inputs.out_type): if self.inputs.out_type in ["spm", "analyze"]: @@ -591,10 +593,10 @@ def _list_outputs(self): raise Exception( "Not taking frame manipulations into account- please warn the developers" ) - outfiles = [] outfile = self._get_outfilename() - for i in range(tp): - outfiles.append(fname_presuffix(outfile, suffix="%03d" % (i + 1))) + outfiles = [ + fname_presuffix(outfile, suffix="%03d" % (i + 1)) for i in range(tp) + ] outfile = outfiles outputs["out_file"] = outfile return outputs @@ -619,7 +621,7 @@ class DICOMConvertInputSpec(FSTraitedSpec): ) subject_id = traits.Any(desc="subject identifier to insert into template") file_mapping = traits.List( - traits.Tuple(traits.Str, traits.Str), + Tuple(traits.Str, traits.Str), desc="defines the output fields of interface", ) out_type = traits.Enum( @@ -689,11 +691,11 @@ def _get_runs(self): if self.inputs.seq_list: if self.inputs.ignore_single_slice: if (int(s[8]) > 1) and any( - [s[12].startswith(sn) for sn in self.inputs.seq_list] + s[12].startswith(sn) for sn in self.inputs.seq_list ): runs.append(int(s[2])) else: - if any([s[12].startswith(sn) for sn in self.inputs.seq_list]): + if any(s[12].startswith(sn) for sn in self.inputs.seq_list): runs.append(int(s[2])) else: runs.append(int(s[2])) @@ -720,22 +722,25 @@ def _get_filelist(self, outdir): @property def cmdline(self): - """ `command` plus any arguments (args) + """`command` plus any arguments (args) validates arguments and generates command line""" self._check_mandatory_inputs() outdir = self._get_outdir() cmd = [] if not os.path.exists(outdir): - cmdstr = "python -c \"import os; os.makedirs('%s')\"" % outdir + cmdstr = "{} -c \"import os; os.makedirs('{}')\"".format( + op.basename(sys.executable), + outdir, + ) cmd.extend([cmdstr]) infofile = os.path.join(outdir, "shortinfo.txt") if not os.path.exists(infofile): - cmdstr = "dcmdir-info-mgh %s > %s" % (self.inputs.dicom_dir, infofile) + cmdstr = f"dcmdir-info-mgh {self.inputs.dicom_dir} > {infofile}" cmd.extend([cmdstr]) files = self._get_filelist(outdir) for infile, outfile in files: if not os.path.exists(outfile): - single_cmd = "%s%s %s %s" % ( + single_cmd = "{}{} {} {}".format( self._cmd_prefix, self.cmd, infile, @@ -756,7 +761,7 @@ class ResampleInputSpec(FSTraitedSpec): resampled_file = File( argstr="-o %s", desc="output filename", genfile=True, position=-1 ) - voxel_size = traits.Tuple( + voxel_size = Tuple( traits.Float, traits.Float, traits.Float, @@ -812,7 +817,10 @@ def _gen_filename(self, name): class ReconAllInputSpec(CommandLineInputSpec): subject_id = traits.Str( - "recon_all", argstr="-subjid %s", desc="subject name", usedefault=True + "recon_all", + argstr="-subjid %s", + desc="subject name", + xor=["base_template_id", "longitudinal_timepoint_id"], ) directive = traits.Enum( "all", @@ -838,21 +846,32 @@ class ReconAllInputSpec(CommandLineInputSpec): usedefault=True, position=0, ) - hemi = traits.Enum("lh", "rh", desc="hemisphere to process", argstr="-hemi %s") + hemi = traits.Enum( + "lh", + "rh", + desc="hemisphere to process", + argstr="-hemi %s", + requires=["subject_id"], + ) T1_files = InputMultiPath( - File(exists=True), argstr="-i %s...", desc="name of T1 file to process" + File(exists=True), + argstr="-i %s...", + desc="name of T1 file to process", + requires=["subject_id"], ) T2_file = File( exists=True, argstr="-T2 %s", min_ver="5.3.0", desc="Convert T2 image to orig directory", + requires=["subject_id"], ) FLAIR_file = File( exists=True, argstr="-FLAIR %s", min_ver="5.3.0", desc="Convert FLAIR image to orig directory", + requires=["subject_id"], ) use_T2 = traits.Bool( argstr="-T2pial", @@ -881,20 +900,24 @@ class ReconAllInputSpec(CommandLineInputSpec): "Assume scan parameters are MGH MP-RAGE " "protocol, which produces darker gray matter" ), + requires=["subject_id"], ) big_ventricles = traits.Bool( argstr="-bigventricles", - desc=("For use in subjects with enlarged " "ventricles"), + desc=("For use in subjects with enlarged ventricles"), ) brainstem = traits.Bool( - argstr="-brainstem-structures", desc="Segment brainstem structures" + argstr="-brainstem-structures", + desc="Segment brainstem structures", + requires=["subject_id"], ) hippocampal_subfields_T1 = traits.Bool( argstr="-hippocampal-subfields-T1", min_ver="6.0.0", desc="segment hippocampal subfields using input T1 scan", + requires=["subject_id"], ) - hippocampal_subfields_T2 = traits.Tuple( + hippocampal_subfields_T2 = Tuple( File(exists=True), traits.Str(), argstr="-hippocampal-subfields-T2 %s %s", @@ -903,6 +926,7 @@ class ReconAllInputSpec(CommandLineInputSpec): "segment hippocampal subfields using T2 scan, identified by " "ID (may be combined with hippocampal_subfields_T1)" ), + requires=["subject_id"], ) expert = File( exists=True, argstr="-expert %s", desc="Set parameters using expert file" @@ -923,6 +947,29 @@ class ReconAllInputSpec(CommandLineInputSpec): ) flags = InputMultiPath(traits.Str, argstr="%s", desc="additional parameters") + # Longitudinal runs + base_template_id = traits.Str( + argstr="-base %s", + desc="base template id", + xor=["subject_id", "longitudinal_timepoint_id"], + requires=["base_timepoint_ids"], + ) + base_timepoint_ids = InputMultiObject( + traits.Str(), + argstr="-base-tp %s...", + desc="processed timepoint to use in template", + ) + longitudinal_timepoint_id = traits.Str( + argstr="-long %s", + desc="longitudinal session/timepoint id", + xor=["subject_id", "base_template_id"], + requires=["longitudinal_template_id"], + position=1, + ) + longitudinal_template_id = traits.Str( + argstr="%s", desc="longitudinal base template id", position=2 + ) + # Expert options talairach = traits.Str(desc="Flags to pass to talairach commands", xor=["expert"]) mri_normalize = traits.Str( @@ -1015,7 +1062,7 @@ class ReconAll(CommandLine): >>> reconall.inputs.subject_id = 'foo' >>> reconall.inputs.directive = 'all' >>> reconall.inputs.subjects_dir = '.' - >>> reconall.inputs.T1_files = 'structural.nii' + >>> reconall.inputs.T1_files = ['structural.nii'] >>> reconall.cmdline 'recon-all -all -i structural.nii -subjid foo -sd .' >>> reconall.inputs.flags = "-qcache" @@ -1045,7 +1092,7 @@ class ReconAll(CommandLine): >>> reconall_subfields.inputs.subject_id = 'foo' >>> reconall_subfields.inputs.directive = 'all' >>> reconall_subfields.inputs.subjects_dir = '.' - >>> reconall_subfields.inputs.T1_files = 'structural.nii' + >>> reconall_subfields.inputs.T1_files = ['structural.nii'] >>> reconall_subfields.inputs.hippocampal_subfields_T1 = True >>> reconall_subfields.cmdline 'recon-all -all -i structural.nii -hippocampal-subfields-T1 -subjid foo -sd .' @@ -1056,6 +1103,24 @@ class ReconAll(CommandLine): >>> reconall_subfields.inputs.hippocampal_subfields_T1 = False >>> reconall_subfields.cmdline 'recon-all -all -i structural.nii -hippocampal-subfields-T2 structural.nii test -subjid foo -sd .' + + Base template creation for longitudinal pipeline: + >>> baserecon = ReconAll() + >>> baserecon.inputs.base_template_id = 'sub-template' + >>> baserecon.inputs.base_timepoint_ids = ['ses-1','ses-2'] + >>> baserecon.inputs.directive = 'all' + >>> baserecon.inputs.subjects_dir = '.' + >>> baserecon.cmdline + 'recon-all -all -base sub-template -base-tp ses-1 -base-tp ses-2 -sd .' + + Longitudinal timepoint run: + >>> longrecon = ReconAll() + >>> longrecon.inputs.longitudinal_timepoint_id = 'ses-1' + >>> longrecon.inputs.longitudinal_template_id = 'sub-template' + >>> longrecon.inputs.directive = 'all' + >>> longrecon.inputs.subjects_dir = '.' + >>> longrecon.cmdline + 'recon-all -all -long ses-1 sub-template -sd .' """ _cmd = "recon-all" @@ -1077,6 +1142,7 @@ class ReconAll(CommandLine): # # [0] https://surfer.nmr.mgh.harvard.edu/fswiki/ReconAllTableStableV5.3 # [1] https://surfer.nmr.mgh.harvard.edu/fswiki/ReconAllTableStableV6.0 + # [2] https://surfer.nmr.mgh.harvard.edu/fswiki/ReconAllTableStableV6.0#ReconAllTableStable7.1.1 _autorecon1_steps = [ ("motioncor", ["mri/rawavg.mgz", "mri/orig.mgz"], []), ( @@ -1206,7 +1272,7 @@ class ReconAll(CommandLine): ("wmparc", ["mri/wmparc.mgz", "stats/wmparc.stats"], []), ("balabels", ["label/BA.ctab", "label/BA.thresh.ctab"], []), ] - else: + elif Info.looseversion() < LooseVersion("7.0.0"): _autorecon2_volonly_steps = [ ("gcareg", ["mri/transforms/talairach.lta"], []), ("canorm", ["mri/norm.mgz"], []), @@ -1318,6 +1384,124 @@ class ReconAll(CommandLine): [], ), ] + else: + _autorecon2_volonly_steps = [ + ("gcareg", ["mri/transforms/talairach.lta"], []), + ("canorm", ["mri/norm.mgz"], []), + ("careg", ["mri/transforms/talairach.m3z"], []), + ( + "calabel", + [ + "mri/aseg.auto_noCCseg.mgz", + "mri/aseg.auto.mgz", + "mri/aseg.presurf.mgz", + ], + [], + ), + ("normalization2", ["mri/brain.mgz"], []), + ("maskbfs", ["mri/brain.finalsurfs.mgz"], []), + ( + "segmentation", + ["mri/wm.seg.mgz", "mri/wm.asegedit.mgz", "mri/wm.mgz"], + [], + ), + ( + "fill", + [ + "mri/filled.mgz", + # 'scripts/ponscc.cut.log', + ], + [], + ), + ] + _autorecon2_lh_steps = [ + ("tessellate", ["surf/lh.orig.nofix"], []), + ("smooth1", ["surf/lh.smoothwm.nofix"], []), + ("inflate1", ["surf/lh.inflated.nofix"], []), + ("qsphere", ["surf/lh.qsphere.nofix"], []), + ("fix", ["surf/lh.inflated", "surf/lh.orig"], []), + ( + "white", + [ + "surf/lh.white.preaparc", + "surf/lh.curv", + "surf/lh.area", + "label/lh.cortex.label", + ], + [], + ), + ("smooth2", ["surf/lh.smoothwm"], []), + ("inflate2", ["surf/lh.inflated", "surf/lh.sulc"], []), + ( + "curvHK", + [ + "surf/lh.white.H", + "surf/lh.white.K", + "surf/lh.inflated.H", + "surf/lh.inflated.K", + ], + [], + ), + ("curvstats", ["stats/lh.curv.stats"], []), + ] + _autorecon3_lh_steps = [ + ("sphere", ["surf/lh.sphere"], []), + ("surfreg", ["surf/lh.sphere.reg"], []), + ("jacobian_white", ["surf/lh.jacobian_white"], []), + ("avgcurv", ["surf/lh.avg_curv"], []), + ("cortparc", ["label/lh.aparc.annot"], []), + ( + "pial", + [ + "surf/lh.pial", + "surf/lh.curv.pial", + "surf/lh.area.pial", + "surf/lh.thickness", + "surf/lh.white", + ], + [], + ), + ("parcstats", ["stats/lh.aparc.stats"], []), + ("cortparc2", ["label/lh.aparc.a2009s.annot"], []), + ("parcstats2", ["stats/lh.aparc.a2009s.stats"], []), + ("cortparc3", ["label/lh.aparc.DKTatlas.annot"], []), + ("parcstats3", ["stats/lh.aparc.DKTatlas.stats"], []), + ("pctsurfcon", ["surf/lh.w-g.pct.mgh", "stats/lh.w-g.pct.stats"], []), + ] + _autorecon3_added_steps = [ + ( + "cortribbon", + ["mri/lh.ribbon.mgz", "mri/rh.ribbon.mgz", "mri/ribbon.mgz"], + [], + ), + ("hyporelabel", ["mri/aseg.presurf.hypos.mgz"], []), + ( + "aparc2aseg", + [ + "mri/aparc+aseg.mgz", + "mri/aparc.a2009s+aseg.mgz", + "mri/aparc.DKTatlas+aseg.mgz", + ], + [], + ), + ("apas2aseg", ["mri/aseg.mgz"], ["mri/aparc+aseg.mgz"]), + ("segstats", ["stats/aseg.stats"], []), + ("wmparc", ["mri/wmparc.mgz", "stats/wmparc.stats"], []), + # Note that this is a very incomplete list; however the ctab + # files are last to be touched, so this should be reasonable + ( + "balabels", + [ + "label/BA_exvivo.ctab", + "label/BA_exvivo.thresh.ctab", + "label/lh.entorhinal_exvivo.label", + "label/rh.entorhinal_exvivo.label", + "label/lh.perirhinal_exvivo.label", + "label/rh.perirhinal_exvivo.label", + ], + [], + ), + ] # Fill out autorecon2 steps _autorecon2_rh_steps = [ @@ -1400,12 +1584,35 @@ def _list_outputs(self): outputs = self._outputs().get() - outputs.update( - FreeSurferSource( - subject_id=self.inputs.subject_id, subjects_dir=subjects_dir, hemi=hemi - )._list_outputs() - ) - outputs["subject_id"] = self.inputs.subject_id + # If using longitudinal pipeline, update subject id accordingly, + # otherwise use original/default subject_id + if isdefined(self.inputs.base_template_id): + outputs.update( + FreeSurferSource( + subject_id=self.inputs.base_template_id, + subjects_dir=subjects_dir, + hemi=hemi, + )._list_outputs() + ) + outputs["subject_id"] = self.inputs.base_template_id + elif isdefined(self.inputs.longitudinal_timepoint_id): + subject_id = f"{self.inputs.longitudinal_timepoint_id}.long.{self.inputs.longitudinal_template_id}" + outputs.update( + FreeSurferSource( + subject_id=subject_id, subjects_dir=subjects_dir, hemi=hemi + )._list_outputs() + ) + outputs["subject_id"] = subject_id + else: + outputs.update( + FreeSurferSource( + subject_id=self.inputs.subject_id, + subjects_dir=subjects_dir, + hemi=hemi, + )._list_outputs() + ) + outputs["subject_id"] = self.inputs.subject_id + outputs["subjects_dir"] = subjects_dir return outputs @@ -1413,8 +1620,26 @@ def _is_resuming(self): subjects_dir = self.inputs.subjects_dir if not isdefined(subjects_dir): subjects_dir = self._gen_subjects_dir() - if os.path.isdir(os.path.join(subjects_dir, self.inputs.subject_id, "mri")): - return True + + # Check for longitudinal pipeline + if not isdefined(self.inputs.subject_id): + if isdefined(self.inputs.base_template_id): + if os.path.isdir( + os.path.join(subjects_dir, self.inputs.base_template_id, "mri") + ): + return True + elif isdefined(self.inputs.longitudinal_template_id): + if os.path.isdir( + os.path.join( + subjects_dir, + f"{self.inputs.longitudinal_timepoint_id}.long.{self.inputs.longitudinal_template_id}", + "mri", + ) + ): + return True + else: + if os.path.isdir(os.path.join(subjects_dir, self.inputs.subject_id, "mri")): + return True return False def _format_arg(self, name, trait_spec, value): @@ -1437,7 +1662,7 @@ def _format_arg(self, name, trait_spec, value): if name == "directive" and value == "autorecon-hemi": if not isdefined(self.inputs.hemi): raise ValueError( - "Directive 'autorecon-hemi' requires hemi " "input to be set" + "Directive 'autorecon-hemi' requires hemi input to be set" ) value += " " + self.inputs.hemi if all( @@ -1448,11 +1673,11 @@ def _format_arg(self, name, trait_spec, value): ) ): return None - return super(ReconAll, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) @property def cmdline(self): - cmd = super(ReconAll, self).cmdline + cmd = super().cmdline # Adds '-expert' flag if expert flags are passed # Mutually exclusive with 'expert' input parameter @@ -1495,8 +1720,8 @@ def cmdline(self): no_run = True flags = [] for step, outfiles, infiles in steps: - flag = "-{}".format(step) - noflag = "-no{}".format(step) + flag = f"-{step}" + noflag = f"-no{step}" if noflag in cmd: continue elif flag in cmd: @@ -1528,7 +1753,7 @@ def _prep_expert_file(self): for binary in self._binaries: args = getattr(self.inputs, binary) if isdefined(args): - lines.append("{} {}\n".format(binary, args)) + lines.append(f"{binary} {args}\n") if lines == []: return "" @@ -1540,7 +1765,7 @@ def _prep_expert_file(self): expert_fname = os.path.abspath("expert.opts") with open(expert_fname, "w") as fobj: fobj.write(contents) - return " -expert {}".format(expert_fname) + return f" -expert {expert_fname}" def _get_expert_file(self): # Read pre-existing options file, if it exists @@ -1554,7 +1779,7 @@ def _get_expert_file(self): ) if not os.path.exists(xopts_file): return "" - with open(xopts_file, "r") as fobj: + with open(xopts_file) as fobj: return fobj.read() @property @@ -1710,7 +1935,6 @@ class BBRegister(FSCommand): output_spec = BBRegisterOutputSpec def _list_outputs(self): - outputs = self.output_spec().get() _in = self.inputs @@ -1767,10 +1991,9 @@ def _format_arg(self, name, spec, value): "init_cost_file", ) and isinstance(value, bool): value = self._list_outputs()[name] - return super(BBRegister, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_filename(self, name): - if name == "out_reg_file": return self._list_outputs()[name] return None @@ -1979,7 +2202,7 @@ class SmoothInputSpec(FSTraitedSpec): exists=True, ) smoothed_file = File(desc="output volume", argstr="--o %s", genfile=True) - proj_frac_avg = traits.Tuple( + proj_frac_avg = Tuple( traits.Float, traits.Float, traits.Float, @@ -2057,7 +2280,6 @@ def _gen_filename(self, name): class RobustRegisterInputSpec(FSTraitedSpec): - source_file = File( exists=True, mandatory=True, argstr="--mov %s", desc="volume to be registered" ) @@ -2179,7 +2401,6 @@ class RobustRegisterInputSpec(FSTraitedSpec): class RobustRegisterOutputSpec(TraitedSpec): - out_reg_file = File(exists=True, desc="output registration file") registered_file = File(exists=True, desc="output image with registration applied") weights_file = File(exists=True, desc="image of weights used") @@ -2233,13 +2454,13 @@ def _format_arg(self, name, spec, value): ) if name in options and isinstance(value, bool): value = self._list_outputs()[name] - return super(RobustRegister, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() cwd = os.getcwd() - prefices = dict(src=self.inputs.source_file, trg=self.inputs.target_file) - suffices = dict( + prefixes = dict(src=self.inputs.source_file, trg=self.inputs.target_file) + suffixes = dict( out_reg_file=("src", "_robustreg.lta", False), registered_file=("src", "_robustreg", True), weights_file=("src", "_robustweights", True), @@ -2249,12 +2470,12 @@ def _list_outputs(self): half_source_xfm=("src", "_robustxfm.lta", False), half_targ_xfm=("trg", "_robustxfm.lta", False), ) - for name, sufftup in list(suffices.items()): + for name, sufftup in list(suffixes.items()): value = getattr(self.inputs, name) if value: if value is True: outputs[name] = fname_presuffix( - prefices[sufftup[0]], + prefixes[sufftup[0]], suffix=sufftup[1], newpath=cwd, use_ext=sufftup[2], @@ -2265,7 +2486,6 @@ def _list_outputs(self): class FitMSParamsInputSpec(FSTraitedSpec): - in_files = traits.List( File(exists=True), argstr="%s", @@ -2285,14 +2505,13 @@ class FitMSParamsInputSpec(FSTraitedSpec): class FitMSParamsOutputSpec(TraitedSpec): - t1_image = File(exists=True, desc="image of estimated T1 relaxation values") pd_image = File(exists=True, desc="image of estimated proton density values") t2star_image = File(exists=True, desc="image of estimated T2* values") class FitMSParams(FSCommand): - """Estimate tissue paramaters from a set of FLASH images. + """Estimate tissue parameters from a set of FLASH images. Examples -------- @@ -2321,9 +2540,9 @@ def _format_arg(self, name, spec, value): cmd = " ".join((cmd, "-fa %.1f" % self.inputs.flip_list[i])) if isdefined(self.inputs.xfm_list): cmd = " ".join((cmd, "-at %s" % self.inputs.xfm_list[i])) - cmd = " ".join((cmd, file)) + cmd = f"{cmd} {file}" return cmd - return super(FitMSParams, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -2343,7 +2562,6 @@ def _gen_filename(self, name): class SynthesizeFLASHInputSpec(FSTraitedSpec): - fixed_weighting = traits.Bool( position=1, argstr="-w", @@ -2372,7 +2590,6 @@ class SynthesizeFLASHInputSpec(FSTraitedSpec): class SynthesizeFLASHOutputSpec(TraitedSpec): - out_file = File(exists=True, desc="synthesized FLASH acquisition") @@ -2427,20 +2644,20 @@ class MNIBiasCorrectionInputSpec(FSTraitedSpec): hash_files=False, keep_extension=True, desc="output volume. Output can be any format accepted by mri_convert. " - + "If the output format is COR, then the directory must exist.", + "If the output format is COR, then the directory must exist.", ) iterations = traits.Int( 4, usedefault=True, argstr="--n %d", desc="Number of iterations to run nu_correct. Default is 4. This is the number of times " - + "that nu_correct is repeated (ie, using the output from the previous run as the input for " - + "the next). This is different than the -iterations option to nu_correct.", + "that nu_correct is repeated (ie, using the output from the previous run as the input for " + "the next). This is different than the -iterations option to nu_correct.", ) protocol_iterations = traits.Int( argstr="--proto-iters %d", desc="Passes Np as argument of the -iterations flag of nu_correct. This is different " - + "than the --n flag above. Default is not to pass nu_correct the -iterations flag.", + "than the --n flag above. Default is not to pass nu_correct the -iterations flag.", ) distance = traits.Int(argstr="--distance %d", desc="N3 -distance option") no_rescale = traits.Bool( @@ -2471,7 +2688,7 @@ class MNIBiasCorrectionOutputSpec(TraitedSpec): class MNIBiasCorrection(FSCommand): - """ Wrapper for nu_correct, a program from the Montreal Neurological Insitute (MNI) + """Wrapper for nu_correct, a program from the Montreal Neurological Institute (MNI) used for correcting intensity non-uniformity (ie, bias fields). You must have the MNI software installed on your system to run this. See [www.bic.mni.mcgill.ca/software/N3] for more info. @@ -2529,10 +2746,10 @@ class WatershedSkullStripOutputSpec(TraitedSpec): class WatershedSkullStrip(FSCommand): - """ This program strips skull and other outer non-brain tissue and + """This program strips skull and other outer non-brain tissue and produces the brain volume from T1 volume or the scanned volume. - The "watershed" segmentation algorithm was used to dertermine the + The "watershed" segmentation algorithm was used to determine the intensity values for white matter, grey matter, and CSF. A force field was then used to fit a spherical surface to the brain. The shape of the surface fit was then evaluated against a previously @@ -2593,7 +2810,7 @@ class NormalizeInputSpec(FSTraitedSpec): argstr="-aseg %s", exists=True, desc="The input segmentation for Normalize" ) transform = File( - exists=True, desc="Tranform file from the header of the input file" + exists=True, desc="Transform file from the header of the input file" ) @@ -2656,7 +2873,7 @@ class CANormalizeInputSpec(FSTraitedSpec): exists=True, mandatory=True, position=-2, - desc="The tranform file in lta format", + desc="The transform file in lta format", ) # optional mask = File(argstr="-mask %s", exists=True, desc="Specifies volume to use as mask") @@ -2778,7 +2995,7 @@ class CARegister(FSCommandOpenMP): def _format_arg(self, name, spec, value): if name == "l_files" and len(value) == 1: value.append("identity.nofile") - return super(CARegister, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_fname(self, name): if name == "out_file": @@ -2831,7 +3048,7 @@ class CALabelInputSpec(FSTraitedSpecOpenMP): no_big_ventricles = traits.Bool(argstr="-nobigventricles", desc="No big ventricles") align = traits.Bool(argstr="-align", desc="Align CALabel") prior = traits.Float(argstr="-prior %.1f", desc="Prior for CALabel") - relabel_unlikely = traits.Tuple( + relabel_unlikely = Tuple( traits.Int, traits.Float, argstr="-relabel_unlikely %d %.1f", @@ -2949,8 +3166,8 @@ class MRIsCALabelInputSpec(FSTraitedSpecOpenMP): seed = traits.Int(argstr="-seed %d", desc="") copy_inputs = traits.Bool( desc="Copies implicit inputs to node directory " - + "and creates a temp subjects_directory. " - + "Use this when running as a node" + "and creates a temp subjects_directory. " + "Use this when running as a node" ) @@ -2999,19 +3216,19 @@ def run(self, **inputs): self, self.inputs.smoothwm, folder="surf", - basename="{0}.smoothwm".format(self.inputs.hemisphere), + basename=f"{self.inputs.hemisphere}.smoothwm", ) copy2subjdir( self, self.inputs.curv, folder="surf", - basename="{0}.curv".format(self.inputs.hemisphere), + basename=f"{self.inputs.hemisphere}.curv", ) copy2subjdir( self, self.inputs.sulc, folder="surf", - basename="{0}.sulc".format(self.inputs.hemisphere), + basename=f"{self.inputs.hemisphere}.sulc", ) # The label directory must exist in order for an output to be written @@ -3021,7 +3238,7 @@ def run(self, **inputs): if not os.path.isdir(label_dir): os.makedirs(label_dir) - return super(MRIsCALabel, self).run(**inputs) + return super().run(**inputs) def _list_outputs(self): outputs = self.output_spec().get() @@ -3068,14 +3285,13 @@ class SegmentCCInputSpec(FSTraitedSpec): desc="Subject name", ) copy_inputs = traits.Bool( - desc="If running as a node, set this to True." - + "This will copy the input files to the node " - + "directory." + desc="If running as a node, set this to True. " + "This will copy the input files to the node directory." ) class SegmentCCOutputSpec(TraitedSpec): - out_file = File(exists=False, desc="Output segmentation uncluding corpus collosum") + out_file = File(exists=False, desc="Output segmentation including corpus collosum") out_rotation = File(exists=False, desc="Output lta rotation file") @@ -3115,7 +3331,7 @@ def _format_arg(self, name, spec, value): # mri_cc can't use abspaths just the basename basename = os.path.basename(value) return spec.argstr % basename - return super(SegmentCC, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -3130,11 +3346,11 @@ def run(self, **inputs): inputs["subjects_dir"] = self.inputs.subjects_dir for originalfile in [self.inputs.in_file, self.inputs.in_norm]: copy2subjdir(self, originalfile, folder="mri") - return super(SegmentCC, self).run(**inputs) + return super().run(**inputs) def aggregate_outputs(self, runtime=None, needed_outputs=None): # it is necessary to find the output files and move - # them to the correct loacation + # them to the correct location predicted_outputs = self._list_outputs() for name in ["out_file", "out_rotation"]: out_file = predicted_outputs[name] @@ -3157,7 +3373,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): if not os.path.isdir(os.path.dirname(out_tmp)): os.makedirs(os.path.dirname(out_tmp)) shutil.move(out_tmp, out_file) - return super(SegmentCC, self).aggregate_outputs(runtime, needed_outputs) + return super().aggregate_outputs(runtime, needed_outputs) class SegmentWMInputSpec(FSTraitedSpec): @@ -3335,7 +3551,7 @@ class ConcatenateLTAOutputSpec(TraitedSpec): class ConcatenateLTA(FSCommand): - """ Concatenates two consecutive LTA transformations into one overall + """Concatenates two consecutive LTA transformations into one overall transformation Out = LTA2*LTA1 @@ -3371,4 +3587,4 @@ class ConcatenateLTA(FSCommand): def _format_arg(self, name, spec, value): if name == "out_type": value = {"VOX2VOX": 0, "RAS2RAS": 1}[value] - return super(ConcatenateLTA, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) diff --git a/nipype/interfaces/freesurfer/registration.py b/nipype/interfaces/freesurfer/registration.py index d6fd82cc15..790066d0ec 100644 --- a/nipype/interfaces/freesurfer/registration.py +++ b/nipype/interfaces/freesurfer/registration.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Provides interfaces to various longitudinal commands provided by freesurfer -""" +"""Provides interfaces to various longitudinal commands provided by freesurfer""" import os import os.path @@ -18,7 +16,7 @@ FSCommandOpenMP, FSTraitedSpecOpenMP, ) -from ..base import isdefined, TraitedSpec, File, traits, Directory +from ..base import isdefined, TraitedSpec, File, traits, Tuple, Directory __docformat__ = "restructuredtext" iflogger = logging.getLogger("nipype.interface") @@ -71,7 +69,7 @@ class MPRtoMNI305(FSScriptCommand): output_spec = MPRtoMNI305OutputSpec def __init__(self, **inputs): - super(MPRtoMNI305, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._environ_update, "target") self.inputs.on_trait_change(self._environ_update, "reference_dir") @@ -85,7 +83,7 @@ def _format_arg(self, opt, spec, val): val, os.path.abspath(retval + ext), copy=True, hashmethod="content" ) return retval - return super(MPRtoMNI305, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _environ_update(self): # refdir = os.path.join(Info.home(), val) @@ -98,7 +96,7 @@ def _get_fname(self, fname): return split_filename(fname)[1] def _list_outputs(self): - outputs = super(MPRtoMNI305, self)._list_outputs() + outputs = super()._list_outputs() fullname = "_".join( [ self._get_fname(self.inputs.in_file), @@ -211,7 +209,7 @@ class EMRegisterOutputSpec(TraitedSpec): class EMRegister(FSCommandOpenMP): - """ This program creates a tranform in lta format + """This program creates a transform in lta format Examples ======== @@ -252,7 +250,7 @@ class RegisterInputSpec(FSTraitedSpec): mandatory=True, position=-2, desc="The data to register to. In normal recon-all usage, " - + "this is a template file for average surface.", + "this is a template file for average surface.", ) in_sulc = File( exists=True, @@ -285,7 +283,7 @@ class RegisterOutputSpec(TraitedSpec): class Register(FSCommand): - """ This program registers a surface to an average surface template. + """This program registers a surface to an average surface template. Examples ======== @@ -308,7 +306,7 @@ class Register(FSCommand): def _format_arg(self, opt, spec, val): if opt == "curv": return spec.argstr - return super(Register, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _gen_filename(self, name): if name == "out_file": @@ -332,7 +330,7 @@ class PaintInputSpec(FSTraitedSpec): mandatory=True, position=-2, desc="Surface file with grid (vertices) onto which the " - + "template data is to be sampled or 'painted'", + "template data is to be sampled or 'painted'", ) template = File( argstr="%s", exists=True, mandatory=True, position=-3, desc="Template file" @@ -349,7 +347,7 @@ class PaintInputSpec(FSTraitedSpec): name_source=["in_surf"], keep_extension=False, desc="File containing a surface-worth of per-vertex values, " - + "saved in 'curvature' format.", + "saved in 'curvature' format.", ) @@ -388,7 +386,7 @@ def _format_arg(self, opt, spec, val): if opt == "template": if isdefined(self.inputs.template_param): return spec.argstr % (val + "#" + str(self.inputs.template_param)) - return super(Paint, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self.output_spec().get() @@ -463,28 +461,28 @@ class MRICoregInputSpec(FSTraitedSpec): maxlen=2, desc="set spatial scales, in voxels (default [2, 4])", ) - initial_translation = traits.Tuple( + initial_translation = Tuple( traits.Float, traits.Float, traits.Float, argstr="--trans %g %g %g", desc="initial translation in mm (implies no_cras0)", ) - initial_rotation = traits.Tuple( + initial_rotation = Tuple( traits.Float, traits.Float, traits.Float, argstr="--rot %g %g %g", desc="initial rotation in degrees", ) - initial_scale = traits.Tuple( + initial_scale = Tuple( traits.Float, traits.Float, traits.Float, argstr="--scale %g %g %g", desc="initial scale", ) - initial_shear = traits.Tuple( + initial_shear = Tuple( traits.Float, traits.Float, traits.Float, @@ -543,7 +541,7 @@ class MRICoregOutputSpec(TraitedSpec): class MRICoreg(FSCommand): - """ This program registers one volume to another + """This program registers one volume to another mri_coreg is a C reimplementation of spm_coreg in FreeSurfer @@ -587,7 +585,7 @@ def _format_arg(self, opt, spec, val): val = self._list_outputs()[opt] elif opt == "reference_mask" and val is False: return "--no-ref-mask" - return super(MRICoreg, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/freesurfer/tests/__init__.py b/nipype/interfaces/freesurfer/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/freesurfer/tests/__init__.py +++ b/nipype/interfaces/freesurfer/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/freesurfer/tests/test_BBRegister.py b/nipype/interfaces/freesurfer/tests/test_BBRegister.py index b9ed6a8bcd..1b3496c516 100644 --- a/nipype/interfaces/freesurfer/tests/test_BBRegister.py +++ b/nipype/interfaces/freesurfer/tests/test_BBRegister.py @@ -3,47 +3,47 @@ def test_BBRegister_inputs(): input_map_5_3 = dict( - args=dict(argstr="%s",), - contrast_type=dict(argstr="--%s", mandatory=True,), - dof=dict(argstr="--%d",), - environ=dict(nohash=True, usedefault=True,), - epi_mask=dict(argstr="--epi-mask",), - fsldof=dict(argstr="--fsl-dof %d",), - init=dict(argstr="--init-%s", mandatory=True, xor=["init_reg_file"],), - init_cost_file=dict(argstr="--initcost %s",), - init_reg_file=dict(argstr="--init-reg %s", mandatory=True, xor=["init"],), - intermediate_file=dict(argstr="--int %s",), - out_fsl_file=dict(argstr="--fslmat %s",), - out_lta_file=dict(argstr="--lta %s", min_ver="5.2.0",), - out_reg_file=dict(argstr="--reg %s", genfile=True,), - reg_frame=dict(argstr="--frame %d", xor=["reg_middle_frame"],), - reg_middle_frame=dict(argstr="--mid-frame", xor=["reg_frame"],), - registered_file=dict(argstr="--o %s",), - source_file=dict(argstr="--mov %s", copyfile=False, mandatory=True,), - spm_nifti=dict(argstr="--spm-nii",), - subject_id=dict(argstr="--s %s", mandatory=True,), + args=dict(argstr="%s"), + contrast_type=dict(argstr="--%s", mandatory=True), + dof=dict(argstr="--%d"), + environ=dict(nohash=True, usedefault=True), + epi_mask=dict(argstr="--epi-mask"), + fsldof=dict(argstr="--fsl-dof %d"), + init=dict(argstr="--init-%s", mandatory=True, xor=["init_reg_file"]), + init_cost_file=dict(argstr="--initcost %s"), + init_reg_file=dict(argstr="--init-reg %s", mandatory=True, xor=["init"]), + intermediate_file=dict(argstr="--int %s"), + out_fsl_file=dict(argstr="--fslmat %s"), + out_lta_file=dict(argstr="--lta %s", min_ver="5.2.0"), + out_reg_file=dict(argstr="--reg %s", genfile=True), + reg_frame=dict(argstr="--frame %d", xor=["reg_middle_frame"]), + reg_middle_frame=dict(argstr="--mid-frame", xor=["reg_frame"]), + registered_file=dict(argstr="--o %s"), + source_file=dict(argstr="--mov %s", copyfile=False, mandatory=True), + spm_nifti=dict(argstr="--spm-nii"), + subject_id=dict(argstr="--s %s", mandatory=True), subjects_dir=dict(), ) input_map_6_0 = dict( - args=dict(argstr="%s",), - contrast_type=dict(argstr="--%s", mandatory=True,), - dof=dict(argstr="--%d",), - environ=dict(nohash=True, usedefault=True,), - epi_mask=dict(argstr="--epi-mask",), - fsldof=dict(argstr="--fsl-dof %d",), - init=dict(argstr="--init-%s", xor=["init_reg_file"],), - init_reg_file=dict(argstr="--init-reg %s", xor=["init"],), - init_cost_file=dict(argstr="--initcost %s",), - intermediate_file=dict(argstr="--int %s",), - out_fsl_file=dict(argstr="--fslmat %s",), - out_lta_file=dict(argstr="--lta %s", min_ver="5.2.0",), - out_reg_file=dict(argstr="--reg %s", genfile=True,), - reg_frame=dict(argstr="--frame %d", xor=["reg_middle_frame"],), - reg_middle_frame=dict(argstr="--mid-frame", xor=["reg_frame"],), - registered_file=dict(argstr="--o %s",), - source_file=dict(argstr="--mov %s", copyfile=False, mandatory=True,), - spm_nifti=dict(argstr="--spm-nii",), - subject_id=dict(argstr="--s %s", mandatory=True,), + args=dict(argstr="%s"), + contrast_type=dict(argstr="--%s", mandatory=True), + dof=dict(argstr="--%d"), + environ=dict(nohash=True, usedefault=True), + epi_mask=dict(argstr="--epi-mask"), + fsldof=dict(argstr="--fsl-dof %d"), + init=dict(argstr="--init-%s", xor=["init_reg_file"]), + init_reg_file=dict(argstr="--init-reg %s", xor=["init"]), + init_cost_file=dict(argstr="--initcost %s"), + intermediate_file=dict(argstr="--int %s"), + out_fsl_file=dict(argstr="--fslmat %s"), + out_lta_file=dict(argstr="--lta %s", min_ver="5.2.0"), + out_reg_file=dict(argstr="--reg %s", genfile=True), + reg_frame=dict(argstr="--frame %d", xor=["reg_middle_frame"]), + reg_middle_frame=dict(argstr="--mid-frame", xor=["reg_frame"]), + registered_file=dict(argstr="--o %s"), + source_file=dict(argstr="--mov %s", copyfile=False, mandatory=True), + spm_nifti=dict(argstr="--spm-nii"), + subject_id=dict(argstr="--s %s", mandatory=True), subjects_dir=dict(), ) diff --git a/nipype/interfaces/freesurfer/tests/test_FSSurfaceCommand.py b/nipype/interfaces/freesurfer/tests/test_FSSurfaceCommand.py index 6c377c9579..cdc2cc3131 100644 --- a/nipype/interfaces/freesurfer/tests/test_FSSurfaceCommand.py +++ b/nipype/interfaces/freesurfer/tests/test_FSSurfaceCommand.py @@ -35,7 +35,6 @@ def test_associated_file(tmpdir): ("./lh.white", "./lh.pial"), (fsavginfo["white"], fsavginfo["pial"]), ]: - # Unspecified paths, possibly with missing hemisphere information, # are equivalent to using the same directory and hemisphere for name in ("pial", "lh.pial", pial): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_AddXFormToHeader.py b/nipype/interfaces/freesurfer/tests/test_auto_AddXFormToHeader.py index 499d85a437..23618b2aa8 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_AddXFormToHeader.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_AddXFormToHeader.py @@ -4,14 +4,38 @@ def test_AddXFormToHeader_inputs(): input_map = dict( - args=dict(argstr="%s",), - copy_name=dict(argstr="-c",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - out_file=dict(argstr="%s", extensions=None, position=-1, usedefault=True,), + args=dict( + argstr="%s", + ), + copy_name=dict( + argstr="-c", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + out_file=dict( + argstr="%s", + extensions=None, + position=-1, + usedefault=True, + ), subjects_dir=dict(), - transform=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - verbose=dict(argstr="-v",), + transform=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + verbose=dict( + argstr="-v", + ), ) inputs = AddXFormToHeader.input_spec() @@ -21,7 +45,11 @@ def test_AddXFormToHeader_inputs(): def test_AddXFormToHeader_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AddXFormToHeader.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Aparc2Aseg.py b/nipype/interfaces/freesurfer/tests/test_auto_Aparc2Aseg.py index 2c0d0ad5ef..bc65ee096c 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Aparc2Aseg.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Aparc2Aseg.py @@ -4,29 +4,87 @@ def test_Aparc2Aseg_inputs(): input_map = dict( - a2009s=dict(argstr="--a2009s",), - args=dict(argstr="%s",), - aseg=dict(argstr="--aseg %s", extensions=None,), + a2009s=dict( + argstr="--a2009s", + ), + args=dict( + argstr="%s", + ), + aseg=dict( + argstr="--aseg %s", + extensions=None, + ), copy_inputs=dict(), - ctxseg=dict(argstr="--ctxseg %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - filled=dict(extensions=None,), - hypo_wm=dict(argstr="--hypo-as-wm",), - label_wm=dict(argstr="--labelwm",), - lh_annotation=dict(extensions=None, mandatory=True,), - lh_pial=dict(extensions=None, mandatory=True,), - lh_ribbon=dict(extensions=None, mandatory=True,), - lh_white=dict(extensions=None, mandatory=True,), - out_file=dict(argstr="--o %s", extensions=None, mandatory=True,), - rh_annotation=dict(extensions=None, mandatory=True,), - rh_pial=dict(extensions=None, mandatory=True,), - rh_ribbon=dict(extensions=None, mandatory=True,), - rh_white=dict(extensions=None, mandatory=True,), - ribbon=dict(extensions=None, mandatory=True,), - rip_unknown=dict(argstr="--rip-unknown",), - subject_id=dict(argstr="--s %s", mandatory=True, usedefault=True,), + ctxseg=dict( + argstr="--ctxseg %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filled=dict( + extensions=None, + ), + hypo_wm=dict( + argstr="--hypo-as-wm", + ), + label_wm=dict( + argstr="--labelwm", + ), + lh_annotation=dict( + extensions=None, + mandatory=True, + ), + lh_pial=dict( + extensions=None, + mandatory=True, + ), + lh_ribbon=dict( + extensions=None, + mandatory=True, + ), + lh_white=dict( + extensions=None, + mandatory=True, + ), + out_file=dict( + argstr="--o %s", + extensions=None, + mandatory=True, + ), + rh_annotation=dict( + extensions=None, + mandatory=True, + ), + rh_pial=dict( + extensions=None, + mandatory=True, + ), + rh_ribbon=dict( + extensions=None, + mandatory=True, + ), + rh_white=dict( + extensions=None, + mandatory=True, + ), + ribbon=dict( + extensions=None, + mandatory=True, + ), + rip_unknown=dict( + argstr="--rip-unknown", + ), + subject_id=dict( + argstr="--s %s", + mandatory=True, + usedefault=True, + ), subjects_dir=dict(), - volmask=dict(argstr="--volmask",), + volmask=dict( + argstr="--volmask", + ), ) inputs = Aparc2Aseg.input_spec() @@ -36,7 +94,12 @@ def test_Aparc2Aseg_inputs(): def test_Aparc2Aseg_outputs(): - output_map = dict(out_file=dict(argstr="%s", extensions=None,),) + output_map = dict( + out_file=dict( + argstr="%s", + extensions=None, + ), + ) outputs = Aparc2Aseg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Apas2Aseg.py b/nipype/interfaces/freesurfer/tests/test_auto_Apas2Aseg.py index 295a376884..e2738ac746 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Apas2Aseg.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Apas2Aseg.py @@ -4,10 +4,23 @@ def test_Apas2Aseg_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="--i %s", extensions=None, mandatory=True,), - out_file=dict(argstr="--o %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="--i %s", + extensions=None, + mandatory=True, + ), + out_file=dict( + argstr="--o %s", + extensions=None, + mandatory=True, + ), subjects_dir=dict(), ) inputs = Apas2Aseg.input_spec() @@ -18,7 +31,12 @@ def test_Apas2Aseg_inputs(): def test_Apas2Aseg_outputs(): - output_map = dict(out_file=dict(argstr="%s", extensions=None,),) + output_map = dict( + out_file=dict( + argstr="%s", + extensions=None, + ), + ) outputs = Apas2Aseg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ApplyMask.py b/nipype/interfaces/freesurfer/tests/test_auto_ApplyMask.py index 44bd9eba25..b3a8e80806 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ApplyMask.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ApplyMask.py @@ -4,13 +4,34 @@ def test_ApplyMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - invert_xfm=dict(argstr="-invert",), - keep_mask_deletion_edits=dict(argstr="-keep_mask_deletion_edits",), - mask_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - mask_thresh=dict(argstr="-T %.4f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + invert_xfm=dict( + argstr="-invert", + ), + keep_mask_deletion_edits=dict( + argstr="-keep_mask_deletion_edits", + ), + mask_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + mask_thresh=dict( + argstr="-T %.4f", + ), out_file=dict( argstr="%s", extensions=None, @@ -21,11 +42,24 @@ def test_ApplyMask_inputs(): position=-1, ), subjects_dir=dict(), - transfer=dict(argstr="-transfer %d",), - use_abs=dict(argstr="-abs",), - xfm_file=dict(argstr="-xform %s", extensions=None,), - xfm_source=dict(argstr="-lta_src %s", extensions=None,), - xfm_target=dict(argstr="-lta_dst %s", extensions=None,), + transfer=dict( + argstr="-transfer %d", + ), + use_abs=dict( + argstr="-abs", + ), + xfm_file=dict( + argstr="-xform %s", + extensions=None, + ), + xfm_source=dict( + argstr="-lta_src %s", + extensions=None, + ), + xfm_target=dict( + argstr="-lta_dst %s", + extensions=None, + ), ) inputs = ApplyMask.input_spec() @@ -35,7 +69,11 @@ def test_ApplyMask_inputs(): def test_ApplyMask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ApplyMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py b/nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py index 1eedade07a..2aa4ae59f8 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ApplyVolTransform.py @@ -4,8 +4,13 @@ def test_ApplyVolTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), fs_target=dict( argstr="--fstarg", mandatory=True, @@ -27,9 +32,16 @@ def test_ApplyVolTransform_inputs(): "subject", ), ), - interp=dict(argstr="--interp %s",), - inverse=dict(argstr="--inv",), - invert_morph=dict(argstr="--inv-morph", requires=["m3z_file"],), + interp=dict( + argstr="--interp %s", + ), + inverse=dict( + argstr="--inv", + ), + invert_morph=dict( + argstr="--inv-morph", + requires=["m3z_file"], + ), lta_file=dict( argstr="--lta %s", extensions=None, @@ -60,7 +72,10 @@ def test_ApplyVolTransform_inputs(): "subject", ), ), - m3z_file=dict(argstr="--m3z %s", extensions=None,), + m3z_file=dict( + argstr="--m3z %s", + extensions=None, + ), mni_152_reg=dict( argstr="--regheader", mandatory=True, @@ -75,8 +90,13 @@ def test_ApplyVolTransform_inputs(): "subject", ), ), - no_ded_m3z_path=dict(argstr="--noDefM3zPath", requires=["m3z_file"],), - no_resample=dict(argstr="--no-resample",), + no_ded_m3z_path=dict( + argstr="--noDefM3zPath", + requires=["m3z_file"], + ), + no_resample=dict( + argstr="--no-resample", + ), reg_file=dict( argstr="--reg %s", extensions=None, @@ -107,7 +127,10 @@ def test_ApplyVolTransform_inputs(): ), ), source_file=dict( - argstr="--mov %s", copyfile=False, extensions=None, mandatory=True, + argstr="--mov %s", + copyfile=False, + extensions=None, + mandatory=True, ), subject=dict( argstr="--s %s", @@ -125,16 +148,24 @@ def test_ApplyVolTransform_inputs(): ), subjects_dir=dict(), tal=dict( - argstr="--tal", mandatory=True, xor=("target_file", "tal", "fs_target"), + argstr="--tal", + mandatory=True, + xor=("target_file", "tal", "fs_target"), + ), + tal_resolution=dict( + argstr="--talres %.10f", ), - tal_resolution=dict(argstr="--talres %.10f",), target_file=dict( argstr="--targ %s", extensions=None, mandatory=True, xor=("target_file", "tal", "fs_target"), ), - transformed_file=dict(argstr="--o %s", extensions=None, genfile=True,), + transformed_file=dict( + argstr="--o %s", + extensions=None, + genfile=True, + ), xfm_reg_file=dict( argstr="--xfm %s", extensions=None, @@ -159,7 +190,11 @@ def test_ApplyVolTransform_inputs(): def test_ApplyVolTransform_outputs(): - output_map = dict(transformed_file=dict(extensions=None,),) + output_map = dict( + transformed_file=dict( + extensions=None, + ), + ) outputs = ApplyVolTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Binarize.py b/nipype/interfaces/freesurfer/tests/test_auto_Binarize.py index 28211d63db..e7a95d1a3d 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Binarize.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Binarize.py @@ -4,35 +4,102 @@ def test_Binarize_inputs(): input_map = dict( - abs=dict(argstr="--abs",), - args=dict(argstr="%s",), - bin_col_num=dict(argstr="--bincol",), - bin_val=dict(argstr="--binval %d",), - bin_val_not=dict(argstr="--binvalnot %d",), - binary_file=dict(argstr="--o %s", extensions=None, genfile=True,), - count_file=dict(argstr="--count %s",), - dilate=dict(argstr="--dilate %d",), - environ=dict(nohash=True, usedefault=True,), - erode=dict(argstr="--erode %d",), - erode2d=dict(argstr="--erode2d %d",), - frame_no=dict(argstr="--frame %s",), - in_file=dict(argstr="--i %s", copyfile=False, extensions=None, mandatory=True,), - invert=dict(argstr="--inv",), - mask_file=dict(argstr="--mask maskvol", extensions=None,), - mask_thresh=dict(argstr="--mask-thresh %f",), - match=dict(argstr="--match %d...",), - max=dict(argstr="--max %f", xor=["wm_ven_csf"],), - merge_file=dict(argstr="--merge %s", extensions=None,), - min=dict(argstr="--min %f", xor=["wm_ven_csf"],), - out_type=dict(argstr="",), - rmax=dict(argstr="--rmax %f",), - rmin=dict(argstr="--rmin %f",), + abs=dict( + argstr="--abs", + ), + args=dict( + argstr="%s", + ), + bin_col_num=dict( + argstr="--bincol", + ), + bin_val=dict( + argstr="--binval %d", + ), + bin_val_not=dict( + argstr="--binvalnot %d", + ), + binary_file=dict( + argstr="--o %s", + extensions=None, + genfile=True, + ), + count_file=dict( + argstr="--count %s", + ), + dilate=dict( + argstr="--dilate %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + erode=dict( + argstr="--erode %d", + ), + erode2d=dict( + argstr="--erode2d %d", + ), + frame_no=dict( + argstr="--frame %s", + ), + in_file=dict( + argstr="--i %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + invert=dict( + argstr="--inv", + ), + mask_file=dict( + argstr="--mask maskvol", + extensions=None, + ), + mask_thresh=dict( + argstr="--mask-thresh %f", + ), + match=dict( + argstr="--match %d...", + ), + max=dict( + argstr="--max %f", + xor=["wm_ven_csf"], + ), + merge_file=dict( + argstr="--merge %s", + extensions=None, + ), + min=dict( + argstr="--min %f", + xor=["wm_ven_csf"], + ), + out_type=dict( + argstr="", + ), + rmax=dict( + argstr="--rmax %f", + ), + rmin=dict( + argstr="--rmin %f", + ), subjects_dir=dict(), - ventricles=dict(argstr="--ventricles",), - wm=dict(argstr="--wm",), - wm_ven_csf=dict(argstr="--wm+vcsf", xor=["min", "max"],), - zero_edges=dict(argstr="--zero-edges",), - zero_slice_edge=dict(argstr="--zero-slice-edges",), + ventricles=dict( + argstr="--ventricles", + ), + wm=dict( + argstr="--wm", + ), + wm_ven_csf=dict( + argstr="--wm+vcsf", + xor=["min", "max"], + ), + zero_edges=dict( + argstr="--zero-edges", + ), + zero_slice_edge=dict( + argstr="--zero-slice-edges", + ), ) inputs = Binarize.input_spec() @@ -43,7 +110,12 @@ def test_Binarize_inputs(): def test_Binarize_outputs(): output_map = dict( - binary_file=dict(extensions=None,), count_file=dict(extensions=None,), + binary_file=dict( + extensions=None, + ), + count_file=dict( + extensions=None, + ), ) outputs = Binarize.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CALabel.py b/nipype/interfaces/freesurfer/tests/test_auto_CALabel.py index dfc1f86d97..d89e51841b 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CALabel.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CALabel.py @@ -4,22 +4,67 @@ def test_CALabel_inputs(): input_map = dict( - align=dict(argstr="-align",), - args=dict(argstr="%s",), - aseg=dict(argstr="-aseg %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-4,), - in_vol=dict(argstr="-r %s", extensions=None,), - intensities=dict(argstr="-r %s", extensions=None,), - label=dict(argstr="-l %s", extensions=None,), - no_big_ventricles=dict(argstr="-nobigventricles",), + align=dict( + argstr="-align", + ), + args=dict( + argstr="%s", + ), + aseg=dict( + argstr="-aseg %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-4, + ), + in_vol=dict( + argstr="-r %s", + extensions=None, + ), + intensities=dict( + argstr="-r %s", + extensions=None, + ), + label=dict( + argstr="-l %s", + extensions=None, + ), + no_big_ventricles=dict( + argstr="-nobigventricles", + ), num_threads=dict(), - out_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - prior=dict(argstr="-prior %.1f",), - relabel_unlikely=dict(argstr="-relabel_unlikely %d %.1f",), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + prior=dict( + argstr="-prior %.1f", + ), + relabel_unlikely=dict( + argstr="-relabel_unlikely %d %.1f", + ), subjects_dir=dict(), - template=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - transform=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), + template=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + transform=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), ) inputs = CALabel.input_spec() @@ -29,7 +74,11 @@ def test_CALabel_inputs(): def test_CALabel_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = CALabel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CANormalize.py b/nipype/interfaces/freesurfer/tests/test_auto_CANormalize.py index 84018f9a01..58788da3a4 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CANormalize.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CANormalize.py @@ -4,13 +4,37 @@ def test_CANormalize_inputs(): input_map = dict( - args=dict(argstr="%s",), - atlas=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - control_points=dict(argstr="-c %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-4,), - long_file=dict(argstr="-long %s", extensions=None,), - mask=dict(argstr="-mask %s", extensions=None,), + args=dict( + argstr="%s", + ), + atlas=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + control_points=dict( + argstr="-c %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-4, + ), + long_file=dict( + argstr="-long %s", + extensions=None, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), out_file=dict( argstr="%s", extensions=None, @@ -21,7 +45,12 @@ def test_CANormalize_inputs(): position=-1, ), subjects_dir=dict(), - transform=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + transform=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), ) inputs = CANormalize.input_spec() @@ -32,7 +61,12 @@ def test_CANormalize_inputs(): def test_CANormalize_outputs(): output_map = dict( - control_points=dict(extensions=None,), out_file=dict(extensions=None,), + control_points=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), ) outputs = CANormalize.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CARegister.py b/nipype/interfaces/freesurfer/tests/test_auto_CARegister.py index 5ce22ecfa0..3f410524f0 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CARegister.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CARegister.py @@ -4,21 +4,59 @@ def test_CARegister_inputs(): input_map = dict( - A=dict(argstr="-A %d",), - align=dict(argstr="-align-%s",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - invert_and_save=dict(argstr="-invert-and-save", position=-4,), - l_files=dict(argstr="-l %s",), - levels=dict(argstr="-levels %d",), - mask=dict(argstr="-mask %s", extensions=None,), - no_big_ventricles=dict(argstr="-nobigventricles",), + A=dict( + argstr="-A %d", + ), + align=dict( + argstr="-align-%s", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + invert_and_save=dict( + argstr="-invert-and-save", + position=-4, + ), + l_files=dict( + argstr="-l %s", + ), + levels=dict( + argstr="-levels %d", + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + no_big_ventricles=dict( + argstr="-nobigventricles", + ), num_threads=dict(), - out_file=dict(argstr="%s", extensions=None, genfile=True, position=-1,), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), subjects_dir=dict(), - template=dict(argstr="%s", extensions=None, position=-2,), - transform=dict(argstr="-T %s", extensions=None,), + template=dict( + argstr="%s", + extensions=None, + position=-2, + ), + transform=dict( + argstr="-T %s", + extensions=None, + ), ) inputs = CARegister.input_spec() @@ -28,7 +66,11 @@ def test_CARegister_inputs(): def test_CARegister_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = CARegister.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CheckTalairachAlignment.py b/nipype/interfaces/freesurfer/tests/test_auto_CheckTalairachAlignment.py index 8dcede267e..d14e203079 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CheckTalairachAlignment.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CheckTalairachAlignment.py @@ -4,8 +4,13 @@ def test_CheckTalairachAlignment_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( argstr="-xfm %s", extensions=None, @@ -13,9 +18,17 @@ def test_CheckTalairachAlignment_inputs(): position=-1, xor=["subject"], ), - subject=dict(argstr="-subj %s", mandatory=True, position=-1, xor=["in_file"],), + subject=dict( + argstr="-subj %s", + mandatory=True, + position=-1, + xor=["in_file"], + ), subjects_dir=dict(), - threshold=dict(argstr="-T %.3f", usedefault=True,), + threshold=dict( + argstr="-T %.3f", + usedefault=True, + ), ) inputs = CheckTalairachAlignment.input_spec() @@ -25,7 +38,11 @@ def test_CheckTalairachAlignment_inputs(): def test_CheckTalairachAlignment_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = CheckTalairachAlignment.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Concatenate.py b/nipype/interfaces/freesurfer/tests/test_auto_Concatenate.py index c841be04ad..992f3e308c 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Concatenate.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Concatenate.py @@ -4,26 +4,70 @@ def test_Concatenate_inputs(): input_map = dict( - add_val=dict(argstr="--add %f",), - args=dict(argstr="%s",), - combine=dict(argstr="--combine",), - concatenated_file=dict(argstr="--o %s", extensions=None, genfile=True,), - environ=dict(nohash=True, usedefault=True,), - gmean=dict(argstr="--gmean %d",), - in_files=dict(argstr="--i %s...", mandatory=True,), - keep_dtype=dict(argstr="--keep-datatype",), - mask_file=dict(argstr="--mask %s", extensions=None,), - max_bonfcor=dict(argstr="--max-bonfcor",), - max_index=dict(argstr="--max-index",), - mean_div_n=dict(argstr="--mean-div-n",), - multiply_by=dict(argstr="--mul %f",), - multiply_matrix_file=dict(argstr="--mtx %s", extensions=None,), - paired_stats=dict(argstr="--paired-%s",), - sign=dict(argstr="--%s",), - sort=dict(argstr="--sort",), - stats=dict(argstr="--%s",), + add_val=dict( + argstr="--add %f", + ), + args=dict( + argstr="%s", + ), + combine=dict( + argstr="--combine", + ), + concatenated_file=dict( + argstr="--o %s", + extensions=None, + genfile=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gmean=dict( + argstr="--gmean %d", + ), + in_files=dict( + argstr="--i %s...", + mandatory=True, + ), + keep_dtype=dict( + argstr="--keep-datatype", + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + max_bonfcor=dict( + argstr="--max-bonfcor", + ), + max_index=dict( + argstr="--max-index", + ), + mean_div_n=dict( + argstr="--mean-div-n", + ), + multiply_by=dict( + argstr="--mul %f", + ), + multiply_matrix_file=dict( + argstr="--mtx %s", + extensions=None, + ), + paired_stats=dict( + argstr="--paired-%s", + ), + sign=dict( + argstr="--%s", + ), + sort=dict( + argstr="--sort", + ), + stats=dict( + argstr="--%s", + ), subjects_dir=dict(), - vote=dict(argstr="--vote",), + vote=dict( + argstr="--vote", + ), ) inputs = Concatenate.input_spec() @@ -33,7 +77,11 @@ def test_Concatenate_inputs(): def test_Concatenate_outputs(): - output_map = dict(concatenated_file=dict(extensions=None,),) + output_map = dict( + concatenated_file=dict( + extensions=None, + ), + ) outputs = Concatenate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py b/nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py index b9750aecbf..dad221b734 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ConcatenateLTA.py @@ -4,13 +4,33 @@ def test_ConcatenateLTA_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_lta1=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - in_lta2=dict(argstr="%s", mandatory=True, position=-2,), - invert_1=dict(argstr="-invert1",), - invert_2=dict(argstr="-invert2",), - invert_out=dict(argstr="-invertout",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_lta1=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + in_lta2=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + invert_1=dict( + argstr="-invert1", + ), + invert_2=dict( + argstr="-invert2", + ), + invert_out=dict( + argstr="-invertout", + ), out_file=dict( argstr="%s", extensions=None, @@ -20,8 +40,12 @@ def test_ConcatenateLTA_inputs(): name_template="%s_concat", position=-1, ), - out_type=dict(argstr="-out_type %d",), - subject=dict(argstr="-subject %s",), + out_type=dict( + argstr="-out_type %d", + ), + subject=dict( + argstr="-subject %s", + ), subjects_dir=dict(), tal_source_file=dict( argstr="-tal %s", @@ -30,7 +54,10 @@ def test_ConcatenateLTA_inputs(): requires=["tal_template_file"], ), tal_template_file=dict( - argstr="%s", extensions=None, position=-4, requires=["tal_source_file"], + argstr="%s", + extensions=None, + position=-4, + requires=["tal_source_file"], ), ) inputs = ConcatenateLTA.input_spec() @@ -41,7 +68,11 @@ def test_ConcatenateLTA_inputs(): def test_ConcatenateLTA_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ConcatenateLTA.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Contrast.py b/nipype/interfaces/freesurfer/tests/test_auto_Contrast.py index 68e450315d..8409f26757 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Contrast.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Contrast.py @@ -4,18 +4,48 @@ def test_Contrast_inputs(): input_map = dict( - annotation=dict(extensions=None, mandatory=True,), - args=dict(argstr="%s",), + annotation=dict( + extensions=None, + mandatory=True, + ), + args=dict( + argstr="%s", + ), copy_inputs=dict(), - cortex=dict(extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - hemisphere=dict(argstr="--%s-only", mandatory=True,), - orig=dict(extensions=None, mandatory=True,), - rawavg=dict(extensions=None, mandatory=True,), - subject_id=dict(argstr="--s %s", mandatory=True, usedefault=True,), + cortex=dict( + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr="--%s-only", + mandatory=True, + ), + orig=dict( + extensions=None, + mandatory=True, + ), + rawavg=dict( + extensions=None, + mandatory=True, + ), + subject_id=dict( + argstr="--s %s", + mandatory=True, + usedefault=True, + ), subjects_dir=dict(), - thickness=dict(extensions=None, mandatory=True,), - white=dict(extensions=None, mandatory=True,), + thickness=dict( + extensions=None, + mandatory=True, + ), + white=dict( + extensions=None, + mandatory=True, + ), ) inputs = Contrast.input_spec() @@ -26,9 +56,15 @@ def test_Contrast_inputs(): def test_Contrast_outputs(): output_map = dict( - out_contrast=dict(extensions=None,), - out_log=dict(extensions=None,), - out_stats=dict(extensions=None,), + out_contrast=dict( + extensions=None, + ), + out_log=dict( + extensions=None, + ), + out_stats=dict( + extensions=None, + ), ) outputs = Contrast.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Curvature.py b/nipype/interfaces/freesurfer/tests/test_auto_Curvature.py index 906d961740..c230edb8ba 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Curvature.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Curvature.py @@ -4,18 +4,37 @@ def test_Curvature_inputs(): input_map = dict( - args=dict(argstr="%s",), - averages=dict(argstr="-a %d",), + args=dict( + argstr="%s", + ), + averages=dict( + argstr="-a %d", + ), copy_input=dict(), - distances=dict(argstr="-distances %d %d",), - environ=dict(nohash=True, usedefault=True,), + distances=dict( + argstr="-distances %d %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=-2, + ), + n=dict( + argstr="-n", + ), + save=dict( + argstr="-w", ), - n=dict(argstr="-n",), - save=dict(argstr="-w",), subjects_dir=dict(), - threshold=dict(argstr="-thresh %.3f",), + threshold=dict( + argstr="-thresh %.3f", + ), ) inputs = Curvature.input_spec() @@ -26,7 +45,12 @@ def test_Curvature_inputs(): def test_Curvature_outputs(): output_map = dict( - out_gauss=dict(extensions=None,), out_mean=dict(extensions=None,), + out_gauss=dict( + extensions=None, + ), + out_mean=dict( + extensions=None, + ), ) outputs = Curvature.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_CurvatureStats.py b/nipype/interfaces/freesurfer/tests/test_auto_CurvatureStats.py index 3b69b41def..4e8e3d5bc2 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_CurvatureStats.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_CurvatureStats.py @@ -4,13 +4,34 @@ def test_CurvatureStats_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), copy_inputs=dict(), - curvfile1=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - curvfile2=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - environ=dict(nohash=True, usedefault=True,), - hemisphere=dict(argstr="%s", mandatory=True, position=-3,), - min_max=dict(argstr="-m",), + curvfile1=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + curvfile2=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr="%s", + mandatory=True, + position=-3, + ), + min_max=dict( + argstr="-m", + ), out_file=dict( argstr="-o %s", extensions=None, @@ -18,11 +39,23 @@ def test_CurvatureStats_inputs(): name_source=["hemisphere"], name_template="%s.curv.stats", ), - subject_id=dict(argstr="%s", mandatory=True, position=-4, usedefault=True,), + subject_id=dict( + argstr="%s", + mandatory=True, + position=-4, + usedefault=True, + ), subjects_dir=dict(), - surface=dict(argstr="-F %s", extensions=None,), - values=dict(argstr="-G",), - write=dict(argstr="--writeCurvatureFiles",), + surface=dict( + argstr="-F %s", + extensions=None, + ), + values=dict( + argstr="-G", + ), + write=dict( + argstr="--writeCurvatureFiles", + ), ) inputs = CurvatureStats.input_spec() @@ -32,7 +65,11 @@ def test_CurvatureStats_inputs(): def test_CurvatureStats_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = CurvatureStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_DICOMConvert.py b/nipype/interfaces/freesurfer/tests/test_auto_DICOMConvert.py index 3eae700dc6..bda2620fe1 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_DICOMConvert.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_DICOMConvert.py @@ -4,16 +4,35 @@ def test_DICOMConvert_inputs(): input_map = dict( - args=dict(argstr="%s",), - base_output_dir=dict(mandatory=True,), - dicom_dir=dict(mandatory=True,), - dicom_info=dict(extensions=None,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + base_output_dir=dict( + mandatory=True, + ), + dicom_dir=dict( + mandatory=True, + ), + dicom_info=dict( + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), file_mapping=dict(), - ignore_single_slice=dict(requires=["dicom_info"],), - out_type=dict(usedefault=True,), - seq_list=dict(requires=["dicom_info"],), - subject_dir_template=dict(usedefault=True,), + ignore_single_slice=dict( + requires=["dicom_info"], + ), + out_type=dict( + usedefault=True, + ), + seq_list=dict( + requires=["dicom_info"], + ), + subject_dir_template=dict( + usedefault=True, + ), subject_id=dict(), subjects_dir=dict(), ) diff --git a/nipype/interfaces/freesurfer/tests/test_auto_EMRegister.py b/nipype/interfaces/freesurfer/tests/test_auto_EMRegister.py index d87052cebc..7bf1b895f1 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_EMRegister.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_EMRegister.py @@ -4,11 +4,26 @@ def test_EMRegister_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - mask=dict(argstr="-mask %s", extensions=None,), - nbrspacing=dict(argstr="-uns %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + nbrspacing=dict( + argstr="-uns %d", + ), num_threads=dict(), out_file=dict( argstr="%s", @@ -19,10 +34,20 @@ def test_EMRegister_inputs(): name_template="%s_transform.lta", position=-1, ), - skull=dict(argstr="-skull",), + skull=dict( + argstr="-skull", + ), subjects_dir=dict(), - template=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - transform=dict(argstr="-t %s", extensions=None,), + template=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + transform=dict( + argstr="-t %s", + extensions=None, + ), ) inputs = EMRegister.input_spec() @@ -32,7 +57,11 @@ def test_EMRegister_inputs(): def test_EMRegister_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = EMRegister.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_EditWMwithAseg.py b/nipype/interfaces/freesurfer/tests/test_auto_EditWMwithAseg.py index 725980b7ab..5c51ed848d 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_EditWMwithAseg.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_EditWMwithAseg.py @@ -4,13 +4,40 @@ def test_EditWMwithAseg_inputs(): input_map = dict( - args=dict(argstr="%s",), - brain_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-4,), - keep_in=dict(argstr="-keep-in",), - out_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - seg_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + brain_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-4, + ), + keep_in=dict( + argstr="-keep-in", + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + seg_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), subjects_dir=dict(), ) inputs = EditWMwithAseg.input_spec() @@ -21,7 +48,11 @@ def test_EditWMwithAseg_inputs(): def test_EditWMwithAseg_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = EditWMwithAseg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_EulerNumber.py b/nipype/interfaces/freesurfer/tests/test_auto_EulerNumber.py index d31c9278bc..9d05019824 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_EulerNumber.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_EulerNumber.py @@ -4,9 +4,19 @@ def test_EulerNumber_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), subjects_dir=dict(), ) inputs = EulerNumber.input_spec() @@ -17,7 +27,10 @@ def test_EulerNumber_inputs(): def test_EulerNumber_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + defects=dict(), + euler=dict(), + ) outputs = EulerNumber.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ExtractMainComponent.py b/nipype/interfaces/freesurfer/tests/test_auto_ExtractMainComponent.py index 424d6bdb23..59997ad5b4 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ExtractMainComponent.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ExtractMainComponent.py @@ -4,9 +4,19 @@ def test_ExtractMainComponent_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), out_file=dict( argstr="%s", extensions=None, @@ -23,7 +33,11 @@ def test_ExtractMainComponent_inputs(): def test_ExtractMainComponent_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ExtractMainComponent.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FSCommand.py b/nipype/interfaces/freesurfer/tests/test_auto_FSCommand.py index 87f836e34b..aa53727cc8 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FSCommand.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FSCommand.py @@ -4,8 +4,13 @@ def test_FSCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), subjects_dir=dict(), ) inputs = FSCommand.input_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FSCommandOpenMP.py b/nipype/interfaces/freesurfer/tests/test_auto_FSCommandOpenMP.py index 165191e96c..f61b52c1ea 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FSCommandOpenMP.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FSCommandOpenMP.py @@ -4,8 +4,13 @@ def test_FSCommandOpenMP_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), num_threads=dict(), subjects_dir=dict(), ) diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FSScriptCommand.py b/nipype/interfaces/freesurfer/tests/test_auto_FSScriptCommand.py index 162962f578..03cf55eb69 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FSScriptCommand.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FSScriptCommand.py @@ -4,8 +4,13 @@ def test_FSScriptCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), subjects_dir=dict(), ) inputs = FSScriptCommand.input_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FitMSParams.py b/nipype/interfaces/freesurfer/tests/test_auto_FitMSParams.py index 3133f52445..7842c5333a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FitMSParams.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FitMSParams.py @@ -4,11 +4,24 @@ def test_FitMSParams_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), flip_list=dict(), - in_files=dict(argstr="%s", mandatory=True, position=-2,), - out_dir=dict(argstr="%s", genfile=True, position=-1,), + in_files=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + out_dir=dict( + argstr="%s", + genfile=True, + position=-1, + ), subjects_dir=dict(), te_list=dict(), tr_list=dict(), @@ -23,9 +36,15 @@ def test_FitMSParams_inputs(): def test_FitMSParams_outputs(): output_map = dict( - pd_image=dict(extensions=None,), - t1_image=dict(extensions=None,), - t2star_image=dict(extensions=None,), + pd_image=dict( + extensions=None, + ), + t1_image=dict( + extensions=None, + ), + t2star_image=dict( + extensions=None, + ), ) outputs = FitMSParams.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FixTopology.py b/nipype/interfaces/freesurfer/tests/test_auto_FixTopology.py index bfdb140216..0037c02270 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FixTopology.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FixTopology.py @@ -4,19 +4,56 @@ def test_FixTopology_inputs(): input_map = dict( - args=dict(argstr="%s",), - copy_inputs=dict(mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - ga=dict(argstr="-ga",), - hemisphere=dict(argstr="%s", mandatory=True, position=-1,), - in_brain=dict(extensions=None, mandatory=True,), - in_inflated=dict(extensions=None, mandatory=True,), - in_orig=dict(extensions=None, mandatory=True,), - in_wm=dict(extensions=None, mandatory=True,), - mgz=dict(argstr="-mgz",), - seed=dict(argstr="-seed %d",), - sphere=dict(argstr="-sphere %s", extensions=None,), - subject_id=dict(argstr="%s", mandatory=True, position=-2, usedefault=True,), + args=dict( + argstr="%s", + ), + copy_inputs=dict( + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ga=dict( + argstr="-ga", + ), + hemisphere=dict( + argstr="%s", + mandatory=True, + position=-1, + ), + in_brain=dict( + extensions=None, + mandatory=True, + ), + in_inflated=dict( + extensions=None, + mandatory=True, + ), + in_orig=dict( + extensions=None, + mandatory=True, + ), + in_wm=dict( + extensions=None, + mandatory=True, + ), + mgz=dict( + argstr="-mgz", + ), + seed=dict( + argstr="-seed %d", + ), + sphere=dict( + argstr="-sphere %s", + extensions=None, + ), + subject_id=dict( + argstr="%s", + mandatory=True, + position=-2, + usedefault=True, + ), subjects_dir=dict(), ) inputs = FixTopology.input_spec() @@ -27,7 +64,11 @@ def test_FixTopology_inputs(): def test_FixTopology_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = FixTopology.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_FuseSegmentations.py b/nipype/interfaces/freesurfer/tests/test_auto_FuseSegmentations.py index 2ffc84eada..12550be8b3 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_FuseSegmentations.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_FuseSegmentations.py @@ -4,15 +4,40 @@ def test_FuseSegmentations_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_norms=dict(argstr="-n %s", mandatory=True,), - in_segmentations=dict(argstr="-a %s", mandatory=True,), - in_segmentations_noCC=dict(argstr="-c %s", mandatory=True,), - out_file=dict(extensions=None, mandatory=True, position=-1,), - subject_id=dict(argstr="%s", position=-3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_norms=dict( + argstr="-n %s", + mandatory=True, + ), + in_segmentations=dict( + argstr="-a %s", + mandatory=True, + ), + in_segmentations_noCC=dict( + argstr="-c %s", + mandatory=True, + ), + out_file=dict( + extensions=None, + mandatory=True, + position=-1, + ), + subject_id=dict( + argstr="%s", + position=-3, + ), subjects_dir=dict(), - timepoints=dict(argstr="%s", mandatory=True, position=-2,), + timepoints=dict( + argstr="%s", + mandatory=True, + position=-2, + ), ) inputs = FuseSegmentations.input_spec() @@ -22,7 +47,11 @@ def test_FuseSegmentations_inputs(): def test_FuseSegmentations_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = FuseSegmentations.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_GLMFit.py b/nipype/interfaces/freesurfer/tests/test_auto_GLMFit.py index a883f39732..4d62a03be6 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_GLMFit.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_GLMFit.py @@ -4,68 +4,215 @@ def test_GLMFit_inputs(): input_map = dict( - allow_ill_cond=dict(argstr="--illcond",), - allow_repeated_subjects=dict(argstr="--allowsubjrep",), - args=dict(argstr="%s",), - calc_AR1=dict(argstr="--tar1",), - check_opts=dict(argstr="--checkopts",), - compute_log_y=dict(argstr="--logy",), - contrast=dict(argstr="--C %s...",), - cortex=dict(argstr="--cortex", xor=["label_file"],), - debug=dict(argstr="--debug",), + allow_ill_cond=dict( + argstr="--illcond", + ), + allow_repeated_subjects=dict( + argstr="--allowsubjrep", + ), + args=dict( + argstr="%s", + ), + bp_clip_max=dict( + argstr="--bp-clip-max %f", + ), + bp_clip_neg=dict( + argstr="--bp-clip-neg", + ), + calc_AR1=dict( + argstr="--tar1", + ), + check_opts=dict( + argstr="--checkopts", + ), + compute_log_y=dict( + argstr="--logy", + ), + contrast=dict( + argstr="--C %s...", + ), + cortex=dict( + argstr="--cortex", + xor=["label_file"], + ), + debug=dict( + argstr="--debug", + ), design=dict( - argstr="--X %s", extensions=None, xor=("fsgd", "design", "one_sample"), + argstr="--X %s", + extensions=None, + xor=("fsgd", "design", "one_sample"), + ), + diag=dict( + argstr="--diag %d", + ), + diag_cluster=dict( + argstr="--diag-cluster", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_fx_dof=dict( + argstr="--ffxdof %d", + xor=["fixed_fx_dof_file"], ), - diag=dict(argstr="--diag %d",), - diag_cluster=dict(argstr="--diag-cluster",), - environ=dict(nohash=True, usedefault=True,), - fixed_fx_dof=dict(argstr="--ffxdof %d", xor=["fixed_fx_dof_file"],), fixed_fx_dof_file=dict( - argstr="--ffxdofdat %d", extensions=None, xor=["fixed_fx_dof"], + argstr="--ffxdofdat %d", + extensions=None, + xor=["fixed_fx_dof"], + ), + fixed_fx_var=dict( + argstr="--yffxvar %s", + extensions=None, + ), + force_perm=dict( + argstr="--perm-force", + ), + fsgd=dict( + argstr="--fsgd %s %s", + xor=("fsgd", "design", "one_sample"), + ), + fwhm=dict( + argstr="--fwhm %f", + ), + glm_dir=dict( + argstr="--glmdir %s", + genfile=True, ), - fixed_fx_var=dict(argstr="--yffxvar %s", extensions=None,), - force_perm=dict(argstr="--perm-force",), - fsgd=dict(argstr="--fsgd %s %s", xor=("fsgd", "design", "one_sample"),), - fwhm=dict(argstr="--fwhm %f",), - glm_dir=dict(argstr="--glmdir %s", genfile=True,), hemi=dict(), - in_file=dict(argstr="--y %s", copyfile=False, extensions=None, mandatory=True,), - invert_mask=dict(argstr="--mask-inv",), - label_file=dict(argstr="--label %s", extensions=None, xor=["cortex"],), - mask_file=dict(argstr="--mask %s", extensions=None,), - no_contrast_ok=dict(argstr="--no-contrasts-ok",), - no_est_fwhm=dict(argstr="--no-est-fwhm",), - no_mask_smooth=dict(argstr="--no-mask-smooth",), - no_prune=dict(argstr="--no-prune", xor=["prunethresh"],), + in_file=dict( + argstr="--y %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + invert_mask=dict( + argstr="--mask-inv", + ), + label_file=dict( + argstr="--label %s", + extensions=None, + xor=["cortex"], + ), + logan=dict( + argstr="--logan %s %s %f", + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + mrtm1=dict( + argstr="--mrtm1 %s %s", + ), + mrtm2=dict( + argstr="--mrtm2 %s %s %f", + ), + nii=dict( + argstr="--nii", + xor=["nii", "nii_gz"], + ), + nii_gz=dict( + argstr="--nii.gz", + xor=["nii", "nii_gz"], + ), + no_contrast_ok=dict( + argstr="--no-contrasts-ok", + ), + no_est_fwhm=dict( + argstr="--no-est-fwhm", + ), + no_mask_smooth=dict( + argstr="--no-mask-smooth", + ), + no_prune=dict( + argstr="--no-prune", + xor=["prunethresh"], + ), one_sample=dict( - argstr="--osgm", xor=("one_sample", "fsgd", "design", "contrast"), - ), - pca=dict(argstr="--pca",), - per_voxel_reg=dict(argstr="--pvr %s...",), - profile=dict(argstr="--profile %d",), - prune=dict(argstr="--prune",), - prune_thresh=dict(argstr="--prune_thr %f", xor=["noprune"],), - resynth_test=dict(argstr="--resynthtest %d",), - save_cond=dict(argstr="--save-cond",), - save_estimate=dict(argstr="--yhat-save",), - save_res_corr_mtx=dict(argstr="--eres-scm",), - save_residual=dict(argstr="--eres-save",), - seed=dict(argstr="--seed %d",), - self_reg=dict(argstr="--selfreg %d %d %d",), - sim_done_file=dict(argstr="--sim-done %s", extensions=None,), - sim_sign=dict(argstr="--sim-sign %s",), - simulation=dict(argstr="--sim %s %d %f %s",), + argstr="--osgm", + xor=("one_sample", "fsgd", "design", "contrast"), + ), + pca=dict( + argstr="--pca", + ), + per_voxel_reg=dict( + argstr="--pvr %s...", + ), + profile=dict( + argstr="--profile %d", + ), + prune=dict( + argstr="--prune", + ), + prune_thresh=dict( + argstr="--prune_thr %f", + xor=["noprune"], + ), + resynth_test=dict( + argstr="--resynthtest %d", + ), + save_cond=dict( + argstr="--save-cond", + ), + save_estimate=dict( + argstr="--yhat-save", + ), + save_res_corr_mtx=dict( + argstr="--eres-scm", + ), + save_residual=dict( + argstr="--eres-save", + ), + seed=dict( + argstr="--seed %d", + ), + self_reg=dict( + argstr="--selfreg %d %d %d", + ), + sim_done_file=dict( + argstr="--sim-done %s", + extensions=None, + ), + sim_sign=dict( + argstr="--sim-sign %s", + ), + simulation=dict( + argstr="--sim %s %d %f %s", + ), subject_id=dict(), subjects_dir=dict(), - surf=dict(argstr="--surf %s %s %s", requires=["subject_id", "hemi"],), - surf_geo=dict(usedefault=True,), - synth=dict(argstr="--synth",), - uniform=dict(argstr="--uniform %f %f",), - var_fwhm=dict(argstr="--var-fwhm %f",), - vox_dump=dict(argstr="--voxdump %d %d %d",), - weight_file=dict(extensions=None, xor=["weighted_ls"],), - weight_inv=dict(argstr="--w-inv", xor=["weighted_ls"],), - weight_sqrt=dict(argstr="--w-sqrt", xor=["weighted_ls"],), + surf=dict( + argstr="--surf %s %s %s", + requires=["subject_id", "hemi"], + ), + surf_geo=dict( + usedefault=True, + ), + synth=dict( + argstr="--synth", + ), + uniform=dict( + argstr="--uniform %f %f", + ), + var_fwhm=dict( + argstr="--var-fwhm %f", + ), + vox_dump=dict( + argstr="--voxdump %d %d %d", + ), + weight_file=dict( + extensions=None, + xor=["weighted_ls"], + ), + weight_inv=dict( + argstr="--w-inv", + xor=["weighted_ls"], + ), + weight_sqrt=dict( + argstr="--w-sqrt", + xor=["weighted_ls"], + ), weighted_ls=dict( argstr="--wls %s", extensions=None, @@ -81,23 +228,53 @@ def test_GLMFit_inputs(): def test_GLMFit_outputs(): output_map = dict( - beta_file=dict(extensions=None,), - dof_file=dict(extensions=None,), - error_file=dict(extensions=None,), - error_stddev_file=dict(extensions=None,), - error_var_file=dict(extensions=None,), - estimate_file=dict(extensions=None,), - frame_eigenvectors=dict(extensions=None,), + beta_file=dict( + extensions=None, + ), + bp_file=dict( + extensions=None, + ), + dof_file=dict( + extensions=None, + ), + error_file=dict( + extensions=None, + ), + error_stddev_file=dict( + extensions=None, + ), + error_var_file=dict( + extensions=None, + ), + estimate_file=dict( + extensions=None, + ), + frame_eigenvectors=dict( + extensions=None, + ), ftest_file=dict(), - fwhm_file=dict(extensions=None,), + fwhm_file=dict( + extensions=None, + ), gamma_file=dict(), gamma_var_file=dict(), glm_dir=dict(), - mask_file=dict(extensions=None,), + k2p_file=dict( + extensions=None, + ), + mask_file=dict( + extensions=None, + ), sig_file=dict(), - singular_values=dict(extensions=None,), - spatial_eigenvectors=dict(extensions=None,), - svd_stats_file=dict(extensions=None,), + singular_values=dict( + extensions=None, + ), + spatial_eigenvectors=dict( + extensions=None, + ), + svd_stats_file=dict( + extensions=None, + ), ) outputs = GLMFit.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_GTMPVC.py b/nipype/interfaces/freesurfer/tests/test_auto_GTMPVC.py new file mode 100644 index 0000000000..99c0002be4 --- /dev/null +++ b/nipype/interfaces/freesurfer/tests/test_auto_GTMPVC.py @@ -0,0 +1,291 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..petsurfer import GTMPVC + + +def test_GTMPVC_inputs(): + input_map = dict( + X=dict( + argstr="--X", + ), + X0=dict( + argstr="--X0", + ), + args=dict( + argstr="%s", + ), + auto_mask=dict( + argstr="--auto-mask %f %f", + ), + beta=dict( + argstr="--beta", + ), + color_table_file=dict( + argstr="--ctab %s", + extensions=None, + xor=("color_table_file", "default_color_table"), + ), + contrast=dict( + argstr="--C %s...", + ), + default_color_table=dict( + argstr="--ctab-default", + xor=("color_table_file", "default_color_table"), + ), + default_seg_merge=dict( + argstr="--default-seg-merge", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + frame=dict( + argstr="--frame %i", + ), + in_file=dict( + argstr="--i %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + km_hb=dict( + argstr="--km-hb %s...", + ), + km_ref=dict( + argstr="--km-ref %s...", + ), + lat=dict( + argstr="--lat", + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + merge_cblum_wm_gyri=dict( + argstr="--merge-cblum-wm-gyri", + ), + merge_hypos=dict( + argstr="--merge-hypos", + ), + mg=dict( + argstr="--mg %g %s", + ), + mg_ref_cerebral_wm=dict( + argstr="--mg-ref-cerebral-wm", + ), + mg_ref_lobes_wm=dict( + argstr="--mg-ref-lobes-wm", + ), + mgx=dict( + argstr="--mgx %f", + ), + no_pvc=dict( + argstr="--no-pvc", + ), + no_reduce_fov=dict( + argstr="--no-reduce-fov", + ), + no_rescale=dict( + argstr="--no-rescale", + ), + no_tfe=dict( + argstr="--no-tfe", + ), + num_threads=dict( + argstr="--threads %i", + ), + opt_brain=dict( + argstr="--opt-brain", + ), + opt_seg_merge=dict( + argstr="--opt-seg-merge", + ), + opt_tol=dict( + argstr="--opt-tol %i %f %f", + ), + optimization_schema=dict( + argstr="--opt %s", + ), + psf=dict( + argstr="--psf %f", + ), + psf_col=dict( + argstr="--psf-col %f", + ), + psf_row=dict( + argstr="--psf-row %f", + ), + psf_slice=dict( + argstr="--psf-slice %f", + ), + pvc_dir=dict( + argstr="--o %s", + genfile=True, + ), + rbv=dict( + argstr="--rbv", + requires=["subjects_dir"], + ), + rbv_res=dict( + argstr="--rbv-res %f", + ), + reduce_fox_eqodd=dict( + argstr="--reduce-fox-eqodd", + ), + reg_file=dict( + argstr="--reg %s", + extensions=None, + mandatory=True, + xor=["reg_file", "regheader", "reg_identity"], + ), + reg_identity=dict( + argstr="--reg-identity", + mandatory=True, + xor=["reg_file", "regheader", "reg_identity"], + ), + regheader=dict( + argstr="--regheader", + mandatory=True, + xor=["reg_file", "regheader", "reg_identity"], + ), + replace=dict( + argstr="--replace %i %i", + ), + rescale=dict( + argstr="--rescale %s...", + ), + save_eres=dict( + argstr="--save-eres", + ), + save_input=dict( + argstr="--save-input", + ), + save_yhat=dict( + argstr="--save-yhat", + xor=["save_yhat_with_noise"], + ), + save_yhat0=dict( + argstr="--save-yhat0", + ), + save_yhat_full_fov=dict( + argstr="--save-yhat-full-fov", + ), + save_yhat_with_noise=dict( + argstr="--save-yhat-with-noise %i %i", + xor=["save_yhat"], + ), + scale_refval=dict( + argstr="--scale-refval %f", + ), + segmentation=dict( + argstr="--seg %s", + extensions=None, + mandatory=True, + ), + steady_state_params=dict( + argstr="--ss %f %f %f", + ), + subjects_dir=dict(), + tissue_fraction_resolution=dict( + argstr="--segpvfres %f", + ), + tt_reduce=dict( + argstr="--tt-reduce", + ), + tt_update=dict( + argstr="--tt-update", + ), + y=dict( + argstr="--y", + ), + ) + inputs = GTMPVC.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_GTMPVC_outputs(): + output_map = dict( + eres=dict( + extensions=None, + ), + gtm_file=dict( + extensions=None, + ), + gtm_stats=dict( + extensions=None, + ), + hb_dat=dict( + extensions=None, + ), + hb_nifti=dict( + extensions=None, + ), + input_file=dict( + extensions=None, + ), + mgx_ctxgm=dict( + extensions=None, + ), + mgx_gm=dict( + extensions=None, + ), + mgx_subctxgm=dict( + extensions=None, + ), + nopvc_file=dict( + extensions=None, + ), + opt_params=dict( + extensions=None, + ), + pvc_dir=dict(), + rbv=dict( + extensions=None, + ), + ref_file=dict( + extensions=None, + ), + reg_anat2pet=dict( + extensions=None, + ), + reg_anat2rbvpet=dict( + extensions=None, + ), + reg_pet2anat=dict( + extensions=None, + ), + reg_rbvpet2anat=dict( + extensions=None, + ), + seg=dict( + extensions=None, + ), + seg_ctab=dict( + extensions=None, + ), + tissue_fraction=dict( + extensions=None, + ), + tissue_fraction_psf=dict( + extensions=None, + ), + yhat=dict( + extensions=None, + ), + yhat0=dict( + extensions=None, + ), + yhat_full_fov=dict( + extensions=None, + ), + yhat_with_noise=dict( + extensions=None, + ), + ) + outputs = GTMPVC.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/freesurfer/tests/test_auto_GTMSeg.py b/nipype/interfaces/freesurfer/tests/test_auto_GTMSeg.py new file mode 100644 index 0000000000..026cc33b77 --- /dev/null +++ b/nipype/interfaces/freesurfer/tests/test_auto_GTMSeg.py @@ -0,0 +1,88 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..petsurfer import GTMSeg + + +def test_GTMSeg_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + colortable=dict( + argstr="--ctab %s", + extensions=None, + ), + ctx_annot=dict( + argstr="--ctx-annot %s %i %i", + ), + dmax=dict( + argstr="--dmax %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + head=dict( + argstr="--head %s", + ), + keep_cc=dict( + argstr="--keep-cc", + ), + keep_hypo=dict( + argstr="--keep-hypo", + ), + no_pons=dict( + argstr="--no-pons", + ), + no_seg_stats=dict( + argstr="--no-seg-stats", + ), + no_vermis=dict( + argstr="--no-vermis", + ), + out_file=dict( + argstr="--o %s", + extensions=None, + usedefault=True, + ), + output_upsampling_factor=dict( + argstr="--output-usf %i", + ), + subject_id=dict( + argstr="--s %s", + mandatory=True, + ), + subjects_dir=dict(), + subseg_cblum_wm=dict( + argstr="--subseg-cblum-wm", + ), + subsegwm=dict( + argstr="--subsegwm", + ), + upsampling_factor=dict( + argstr="--usf %i", + ), + wm_annot=dict( + argstr="--wm-annot %s %i %i", + ), + xcerseg=dict( + argstr="--xcerseg", + ), + ) + inputs = GTMSeg.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_GTMSeg_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = GTMSeg.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ImageInfo.py b/nipype/interfaces/freesurfer/tests/test_auto_ImageInfo.py index 2a80c0743b..aa6d5d302e 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ImageInfo.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ImageInfo.py @@ -4,9 +4,18 @@ def test_ImageInfo_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + position=1, + ), subjects_dir=dict(), ) inputs = ImageInfo.input_spec() @@ -26,7 +35,9 @@ def test_ImageInfo_outputs(): file_format=dict(), info=dict(), orientation=dict(), - out_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), ph_enc_dir=dict(), vox_sizes=dict(), ) diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Jacobian.py b/nipype/interfaces/freesurfer/tests/test_auto_Jacobian.py index 14cd9fa9f0..f62c085839 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Jacobian.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Jacobian.py @@ -4,10 +4,25 @@ def test_Jacobian_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_mappedsurf=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - in_origsurf=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_mappedsurf=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + in_origsurf=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), out_file=dict( argstr="%s", extensions=None, @@ -27,7 +42,11 @@ def test_Jacobian_inputs(): def test_Jacobian_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Jacobian.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_LTAConvert.py b/nipype/interfaces/freesurfer/tests/test_auto_LTAConvert.py index ab59b01867..b70bd34c45 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_LTAConvert.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_LTAConvert.py @@ -4,8 +4,13 @@ def test_LTAConvert_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_fsl=dict( argstr="--infsl %s", extensions=None, @@ -41,16 +46,39 @@ def test_LTAConvert_inputs(): mandatory=True, xor=("in_lta", "in_fsl", "in_mni", "in_reg", "in_niftyreg", "in_itk"), ), - invert=dict(argstr="--invert",), - ltavox2vox=dict(argstr="--ltavox2vox", requires=["out_lta"],), - out_fsl=dict(argstr="--outfsl %s",), - out_itk=dict(argstr="--outitk %s",), - out_lta=dict(argstr="--outlta %s",), - out_mni=dict(argstr="--outmni %s",), - out_reg=dict(argstr="--outreg %s",), - source_file=dict(argstr="--src %s", extensions=None,), - target_conform=dict(argstr="--trgconform",), - target_file=dict(argstr="--trg %s", extensions=None,), + invert=dict( + argstr="--invert", + ), + ltavox2vox=dict( + argstr="--ltavox2vox", + requires=["out_lta"], + ), + out_fsl=dict( + argstr="--outfsl %s", + ), + out_itk=dict( + argstr="--outitk %s", + ), + out_lta=dict( + argstr="--outlta %s", + ), + out_mni=dict( + argstr="--outmni %s", + ), + out_reg=dict( + argstr="--outreg %s", + ), + source_file=dict( + argstr="--src %s", + extensions=None, + ), + target_conform=dict( + argstr="--trgconform", + ), + target_file=dict( + argstr="--trg %s", + extensions=None, + ), ) inputs = LTAConvert.input_spec() @@ -61,11 +89,21 @@ def test_LTAConvert_inputs(): def test_LTAConvert_outputs(): output_map = dict( - out_fsl=dict(extensions=None,), - out_itk=dict(extensions=None,), - out_lta=dict(extensions=None,), - out_mni=dict(extensions=None,), - out_reg=dict(extensions=None,), + out_fsl=dict( + extensions=None, + ), + out_itk=dict( + extensions=None, + ), + out_lta=dict( + extensions=None, + ), + out_mni=dict( + extensions=None, + ), + out_reg=dict( + extensions=None, + ), ) outputs = LTAConvert.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Label2Annot.py b/nipype/interfaces/freesurfer/tests/test_auto_Label2Annot.py index f800c560f7..7e1caf88cc 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Label2Annot.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Label2Annot.py @@ -4,18 +4,46 @@ def test_Label2Annot_inputs(): input_map = dict( - args=dict(argstr="%s",), - color_table=dict(argstr="--ctab %s", extensions=None,), + args=dict( + argstr="%s", + ), + color_table=dict( + argstr="--ctab %s", + extensions=None, + ), copy_inputs=dict(), - environ=dict(nohash=True, usedefault=True,), - hemisphere=dict(argstr="--hemi %s", mandatory=True,), - in_labels=dict(argstr="--l %s...", mandatory=True,), - keep_max=dict(argstr="--maxstatwinner",), - orig=dict(extensions=None, mandatory=True,), - out_annot=dict(argstr="--a %s", mandatory=True,), - subject_id=dict(argstr="--s %s", mandatory=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr="--hemi %s", + mandatory=True, + ), + in_labels=dict( + argstr="--l %s...", + mandatory=True, + ), + keep_max=dict( + argstr="--maxstatwinner", + ), + orig=dict( + extensions=None, + mandatory=True, + ), + out_annot=dict( + argstr="--a %s", + mandatory=True, + ), + subject_id=dict( + argstr="--s %s", + mandatory=True, + usedefault=True, + ), subjects_dir=dict(), - verbose_off=dict(argstr="--noverbose",), + verbose_off=dict( + argstr="--noverbose", + ), ) inputs = Label2Annot.input_spec() @@ -25,7 +53,11 @@ def test_Label2Annot_inputs(): def test_Label2Annot_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Label2Annot.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Label2Label.py b/nipype/interfaces/freesurfer/tests/test_auto_Label2Label.py index e5e227c5a9..34f99e1a24 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Label2Label.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Label2Label.py @@ -4,10 +4,18 @@ def test_Label2Label_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), copy_inputs=dict(), - environ=dict(nohash=True, usedefault=True,), - hemisphere=dict(argstr="--hemi %s", mandatory=True,), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr="--hemi %s", + mandatory=True, + ), out_file=dict( argstr="--trglabel %s", extensions=None, @@ -16,15 +24,41 @@ def test_Label2Label_inputs(): name_source=["source_label"], name_template="%s_converted", ), - registration_method=dict(argstr="--regmethod %s", usedefault=True,), - source_label=dict(argstr="--srclabel %s", extensions=None, mandatory=True,), - source_sphere_reg=dict(extensions=None, mandatory=True,), - source_subject=dict(argstr="--srcsubject %s", mandatory=True,), - source_white=dict(extensions=None, mandatory=True,), - sphere_reg=dict(extensions=None, mandatory=True,), - subject_id=dict(argstr="--trgsubject %s", mandatory=True, usedefault=True,), + registration_method=dict( + argstr="--regmethod %s", + usedefault=True, + ), + source_label=dict( + argstr="--srclabel %s", + extensions=None, + mandatory=True, + ), + source_sphere_reg=dict( + extensions=None, + mandatory=True, + ), + source_subject=dict( + argstr="--srcsubject %s", + mandatory=True, + ), + source_white=dict( + extensions=None, + mandatory=True, + ), + sphere_reg=dict( + extensions=None, + mandatory=True, + ), + subject_id=dict( + argstr="--trgsubject %s", + mandatory=True, + usedefault=True, + ), subjects_dir=dict(), - white=dict(extensions=None, mandatory=True,), + white=dict( + extensions=None, + mandatory=True, + ), ) inputs = Label2Label.input_spec() @@ -34,7 +68,11 @@ def test_Label2Label_inputs(): def test_Label2Label_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Label2Label.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Label2Vol.py b/nipype/interfaces/freesurfer/tests/test_auto_Label2Vol.py index dd890531c9..aa1b19f564 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Label2Vol.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Label2Vol.py @@ -17,23 +17,50 @@ def test_Label2Vol_inputs(): mandatory=True, xor=("label_file", "annot_file", "seg_file", "aparc_aseg"), ), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fill_thresh=dict(argstr="--fillthresh %g",), - hemi=dict(argstr="--hemi %s",), - identity=dict(argstr="--identity", xor=("reg_file", "reg_header", "identity"),), - invert_mtx=dict(argstr="--invertmtx",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_thresh=dict( + argstr="--fillthresh %g", + ), + hemi=dict( + argstr="--hemi %s", + ), + identity=dict( + argstr="--identity", + xor=("reg_file", "reg_header", "identity"), + ), + invert_mtx=dict( + argstr="--invertmtx", + ), label_file=dict( argstr="--label %s...", copyfile=False, mandatory=True, xor=("label_file", "annot_file", "seg_file", "aparc_aseg"), ), - label_hit_file=dict(argstr="--hits %s", extensions=None,), - label_voxel_volume=dict(argstr="--labvoxvol %f",), - map_label_stat=dict(argstr="--label-stat %s", extensions=None,), - native_vox2ras=dict(argstr="--native-vox2ras",), - proj=dict(argstr="--proj %s %f %f %f", requires=("subject_id", "hemi"),), + label_hit_file=dict( + argstr="--hits %s", + extensions=None, + ), + label_voxel_volume=dict( + argstr="--labvoxvol %f", + ), + map_label_stat=dict( + argstr="--label-stat %s", + extensions=None, + ), + native_vox2ras=dict( + argstr="--native-vox2ras", + ), + proj=dict( + argstr="--proj %s %f %f %f", + requires=("subject_id", "hemi"), + ), reg_file=dict( argstr="--reg %s", extensions=None, @@ -51,11 +78,23 @@ def test_Label2Vol_inputs(): mandatory=True, xor=("label_file", "annot_file", "seg_file", "aparc_aseg"), ), - subject_id=dict(argstr="--subject %s",), + subject_id=dict( + argstr="--subject %s", + ), subjects_dir=dict(), - surface=dict(argstr="--surf %s",), - template_file=dict(argstr="--temp %s", extensions=None, mandatory=True,), - vol_label_file=dict(argstr="--o %s", extensions=None, genfile=True,), + surface=dict( + argstr="--surf %s", + ), + template_file=dict( + argstr="--temp %s", + extensions=None, + mandatory=True, + ), + vol_label_file=dict( + argstr="--o %s", + extensions=None, + genfile=True, + ), ) inputs = Label2Vol.input_spec() @@ -65,7 +104,11 @@ def test_Label2Vol_inputs(): def test_Label2Vol_outputs(): - output_map = dict(vol_label_file=dict(extensions=None,),) + output_map = dict( + vol_label_file=dict( + extensions=None, + ), + ) outputs = Label2Vol.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Logan.py b/nipype/interfaces/freesurfer/tests/test_auto_Logan.py new file mode 100644 index 0000000000..34c6dfa6c7 --- /dev/null +++ b/nipype/interfaces/freesurfer/tests/test_auto_Logan.py @@ -0,0 +1,284 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..petsurfer import Logan + + +def test_Logan_inputs(): + input_map = dict( + allow_ill_cond=dict( + argstr="--illcond", + ), + allow_repeated_subjects=dict( + argstr="--allowsubjrep", + ), + args=dict( + argstr="%s", + ), + bp_clip_max=dict( + argstr="--bp-clip-max %f", + ), + bp_clip_neg=dict( + argstr="--bp-clip-neg", + ), + calc_AR1=dict( + argstr="--tar1", + ), + check_opts=dict( + argstr="--checkopts", + ), + compute_log_y=dict( + argstr="--logy", + ), + contrast=dict( + argstr="--C %s...", + ), + cortex=dict( + argstr="--cortex", + xor=["label_file"], + ), + debug=dict( + argstr="--debug", + ), + design=dict( + argstr="--X %s", + extensions=None, + xor=("fsgd", "design", "one_sample"), + ), + diag=dict( + argstr="--diag %d", + ), + diag_cluster=dict( + argstr="--diag-cluster", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_fx_dof=dict( + argstr="--ffxdof %d", + xor=["fixed_fx_dof_file"], + ), + fixed_fx_dof_file=dict( + argstr="--ffxdofdat %d", + extensions=None, + xor=["fixed_fx_dof"], + ), + fixed_fx_var=dict( + argstr="--yffxvar %s", + extensions=None, + ), + force_perm=dict( + argstr="--perm-force", + ), + fsgd=dict( + argstr="--fsgd %s %s", + xor=("fsgd", "design", "one_sample"), + ), + fwhm=dict( + argstr="--fwhm %f", + ), + glm_dir=dict( + argstr="--glmdir %s", + genfile=True, + ), + hemi=dict(), + in_file=dict( + argstr="--y %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + invert_mask=dict( + argstr="--mask-inv", + ), + label_file=dict( + argstr="--label %s", + extensions=None, + xor=["cortex"], + ), + logan=dict( + argstr="--logan %s %s %g", + mandatory=True, + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + mrtm1=dict( + argstr="--mrtm1 %s %s", + ), + mrtm2=dict( + argstr="--mrtm2 %s %s %f", + ), + nii=dict( + argstr="--nii", + xor=["nii", "nii_gz"], + ), + nii_gz=dict( + argstr="--nii.gz", + xor=["nii", "nii_gz"], + ), + no_contrast_ok=dict( + argstr="--no-contrasts-ok", + ), + no_est_fwhm=dict( + argstr="--no-est-fwhm", + ), + no_mask_smooth=dict( + argstr="--no-mask-smooth", + ), + no_prune=dict( + argstr="--no-prune", + xor=["prunethresh"], + ), + one_sample=dict( + argstr="--osgm", + xor=("one_sample", "fsgd", "design", "contrast"), + ), + pca=dict( + argstr="--pca", + ), + per_voxel_reg=dict( + argstr="--pvr %s...", + ), + profile=dict( + argstr="--profile %d", + ), + prune=dict( + argstr="--prune", + ), + prune_thresh=dict( + argstr="--prune_thr %f", + xor=["noprune"], + ), + resynth_test=dict( + argstr="--resynthtest %d", + ), + save_cond=dict( + argstr="--save-cond", + ), + save_estimate=dict( + argstr="--yhat-save", + ), + save_res_corr_mtx=dict( + argstr="--eres-scm", + ), + save_residual=dict( + argstr="--eres-save", + ), + seed=dict( + argstr="--seed %d", + ), + self_reg=dict( + argstr="--selfreg %d %d %d", + ), + sim_done_file=dict( + argstr="--sim-done %s", + extensions=None, + ), + sim_sign=dict( + argstr="--sim-sign %s", + ), + simulation=dict( + argstr="--sim %s %d %f %s", + ), + subject_id=dict(), + subjects_dir=dict(), + surf=dict( + argstr="--surf %s %s %s", + requires=["subject_id", "hemi"], + ), + surf_geo=dict( + usedefault=True, + ), + synth=dict( + argstr="--synth", + ), + uniform=dict( + argstr="--uniform %f %f", + ), + var_fwhm=dict( + argstr="--var-fwhm %f", + ), + vox_dump=dict( + argstr="--voxdump %d %d %d", + ), + weight_file=dict( + extensions=None, + xor=["weighted_ls"], + ), + weight_inv=dict( + argstr="--w-inv", + xor=["weighted_ls"], + ), + weight_sqrt=dict( + argstr="--w-sqrt", + xor=["weighted_ls"], + ), + weighted_ls=dict( + argstr="--wls %s", + extensions=None, + xor=("weight_file", "weight_inv", "weight_sqrt"), + ), + ) + inputs = Logan.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_Logan_outputs(): + output_map = dict( + beta_file=dict( + extensions=None, + ), + bp_file=dict( + extensions=None, + ), + dof_file=dict( + extensions=None, + ), + error_file=dict( + extensions=None, + ), + error_stddev_file=dict( + extensions=None, + ), + error_var_file=dict( + extensions=None, + ), + estimate_file=dict( + extensions=None, + ), + frame_eigenvectors=dict( + extensions=None, + ), + ftest_file=dict(), + fwhm_file=dict( + extensions=None, + ), + gamma_file=dict(), + gamma_var_file=dict(), + glm_dir=dict(), + k2p_file=dict( + extensions=None, + ), + mask_file=dict( + extensions=None, + ), + sig_file=dict(), + singular_values=dict( + extensions=None, + ), + spatial_eigenvectors=dict( + extensions=None, + ), + svd_stats_file=dict( + extensions=None, + ), + ) + outputs = Logan.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MNIBiasCorrection.py b/nipype/interfaces/freesurfer/tests/test_auto_MNIBiasCorrection.py index 16ed15d093..3b3c2f0852 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MNIBiasCorrection.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MNIBiasCorrection.py @@ -4,13 +4,32 @@ def test_MNIBiasCorrection_inputs(): input_map = dict( - args=dict(argstr="%s",), - distance=dict(argstr="--distance %d",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="--i %s", extensions=None, mandatory=True,), - iterations=dict(argstr="--n %d", usedefault=True,), - mask=dict(argstr="--mask %s", extensions=None,), - no_rescale=dict(argstr="--no-rescale",), + args=dict( + argstr="%s", + ), + distance=dict( + argstr="--distance %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="--i %s", + extensions=None, + mandatory=True, + ), + iterations=dict( + argstr="--n %d", + usedefault=True, + ), + mask=dict( + argstr="--mask %s", + extensions=None, + ), + no_rescale=dict( + argstr="--no-rescale", + ), out_file=dict( argstr="--o %s", extensions=None, @@ -19,11 +38,20 @@ def test_MNIBiasCorrection_inputs(): name_source=["in_file"], name_template="%s_output", ), - protocol_iterations=dict(argstr="--proto-iters %d",), - shrink=dict(argstr="--shrink %d",), - stop=dict(argstr="--stop %f",), + protocol_iterations=dict( + argstr="--proto-iters %d", + ), + shrink=dict( + argstr="--shrink %d", + ), + stop=dict( + argstr="--stop %f", + ), subjects_dir=dict(), - transform=dict(argstr="--uchar %s", extensions=None,), + transform=dict( + argstr="--uchar %s", + extensions=None, + ), ) inputs = MNIBiasCorrection.input_spec() @@ -33,7 +61,11 @@ def test_MNIBiasCorrection_inputs(): def test_MNIBiasCorrection_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MNIBiasCorrection.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MPRtoMNI305.py b/nipype/interfaces/freesurfer/tests/test_auto_MPRtoMNI305.py index ae81998809..4f21cc2f61 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MPRtoMNI305.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MPRtoMNI305.py @@ -4,12 +4,27 @@ def test_MPRtoMNI305_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, usedefault=True,), - reference_dir=dict(mandatory=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + usedefault=True, + ), + reference_dir=dict( + mandatory=True, + usedefault=True, + ), subjects_dir=dict(), - target=dict(mandatory=True, usedefault=True,), + target=dict( + mandatory=True, + usedefault=True, + ), ) inputs = MPRtoMNI305.input_spec() @@ -20,8 +35,13 @@ def test_MPRtoMNI305_inputs(): def test_MPRtoMNI305_outputs(): output_map = dict( - log_file=dict(extensions=None, usedefault=True,), - out_file=dict(extensions=None,), + log_file=dict( + extensions=None, + usedefault=True, + ), + out_file=dict( + extensions=None, + ), ) outputs = MPRtoMNI305.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIConvert.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIConvert.py index b75f338f31..9e229078ef 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIConvert.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIConvert.py @@ -5,97 +5,276 @@ def test_MRIConvert_inputs(): input_map = dict( apply_inv_transform=dict( - argstr="--apply_inverse_transform %s", extensions=None, - ), - apply_transform=dict(argstr="--apply_transform %s", extensions=None,), - args=dict(argstr="%s",), - ascii=dict(argstr="--ascii",), - autoalign_matrix=dict(argstr="--autoalign %s", extensions=None,), - color_file=dict(argstr="--color_file %s", extensions=None,), - conform=dict(argstr="--conform",), - conform_min=dict(argstr="--conform_min",), - conform_size=dict(argstr="--conform_size %s",), - crop_center=dict(argstr="--crop %d %d %d",), - crop_gdf=dict(argstr="--crop_gdf",), - crop_size=dict(argstr="--cropsize %d %d %d",), - cut_ends=dict(argstr="--cutends %d",), - cw256=dict(argstr="--cw256",), - devolve_transform=dict(argstr="--devolvexfm %s",), - drop_n=dict(argstr="--ndrop %d",), - environ=dict(nohash=True, usedefault=True,), - fill_parcellation=dict(argstr="--fill_parcellation",), - force_ras=dict(argstr="--force_ras_good",), - frame=dict(argstr="--frame %d",), - frame_subsample=dict(argstr="--fsubsample %d %d %d",), - fwhm=dict(argstr="--fwhm %f",), - in_center=dict(argstr="--in_center %s",), + argstr="--apply_inverse_transform %s", + extensions=None, + ), + apply_transform=dict( + argstr="--apply_transform %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + ascii=dict( + argstr="--ascii", + ), + autoalign_matrix=dict( + argstr="--autoalign %s", + extensions=None, + ), + color_file=dict( + argstr="--color_file %s", + extensions=None, + ), + conform=dict( + argstr="--conform", + ), + conform_min=dict( + argstr="--conform_min", + ), + conform_size=dict( + argstr="--conform_size %s", + ), + crop_center=dict( + argstr="--crop %d %d %d", + ), + crop_gdf=dict( + argstr="--crop_gdf", + ), + crop_size=dict( + argstr="--cropsize %d %d %d", + ), + cut_ends=dict( + argstr="--cutends %d", + ), + cw256=dict( + argstr="--cw256", + ), + devolve_transform=dict( + argstr="--devolvexfm %s", + ), + drop_n=dict( + argstr="--ndrop %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_parcellation=dict( + argstr="--fill_parcellation", + ), + force_ras=dict( + argstr="--force_ras_good", + ), + frame=dict( + argstr="--frame %d", + ), + frame_subsample=dict( + argstr="--fsubsample %d %d %d", + ), + fwhm=dict( + argstr="--fwhm %f", + ), + in_center=dict( + argstr="--in_center %s", + ), in_file=dict( - argstr="--input_volume %s", extensions=None, mandatory=True, position=-2, - ), - in_i_dir=dict(argstr="--in_i_direction %f %f %f",), - in_i_size=dict(argstr="--in_i_size %d",), - in_info=dict(argstr="--in_info",), - in_j_dir=dict(argstr="--in_j_direction %f %f %f",), - in_j_size=dict(argstr="--in_j_size %d",), - in_k_dir=dict(argstr="--in_k_direction %f %f %f",), - in_k_size=dict(argstr="--in_k_size %d",), - in_like=dict(argstr="--in_like %s", extensions=None,), - in_matrix=dict(argstr="--in_matrix",), - in_orientation=dict(argstr="--in_orientation %s",), - in_scale=dict(argstr="--scale %f",), - in_stats=dict(argstr="--in_stats",), - in_type=dict(argstr="--in_type %s",), - invert_contrast=dict(argstr="--invert_contrast %f",), - midframe=dict(argstr="--mid-frame",), - no_change=dict(argstr="--nochange",), - no_scale=dict(argstr="--no_scale 1",), - no_translate=dict(argstr="--no_translate",), - no_write=dict(argstr="--no_write",), - out_center=dict(argstr="--out_center %f %f %f",), - out_datatype=dict(argstr="--out_data_type %s",), + argstr="--input_volume %s", + extensions=None, + mandatory=True, + position=-2, + ), + in_i_dir=dict( + argstr="--in_i_direction %f %f %f", + ), + in_i_size=dict( + argstr="--in_i_size %d", + ), + in_info=dict( + argstr="--in_info", + ), + in_j_dir=dict( + argstr="--in_j_direction %f %f %f", + ), + in_j_size=dict( + argstr="--in_j_size %d", + ), + in_k_dir=dict( + argstr="--in_k_direction %f %f %f", + ), + in_k_size=dict( + argstr="--in_k_size %d", + ), + in_like=dict( + argstr="--in_like %s", + extensions=None, + ), + in_matrix=dict( + argstr="--in_matrix", + ), + in_orientation=dict( + argstr="--in_orientation %s", + ), + in_scale=dict( + argstr="--scale %f", + ), + in_stats=dict( + argstr="--in_stats", + ), + in_type=dict( + argstr="--in_type %s", + ), + invert_contrast=dict( + argstr="--invert_contrast %f", + ), + midframe=dict( + argstr="--mid-frame", + ), + no_change=dict( + argstr="--nochange", + ), + no_scale=dict( + argstr="--no_scale 1", + ), + no_translate=dict( + argstr="--no_translate", + ), + no_write=dict( + argstr="--no_write", + ), + out_center=dict( + argstr="--out_center %f %f %f", + ), + out_datatype=dict( + argstr="--out_data_type %s", + ), out_file=dict( - argstr="--output_volume %s", extensions=None, genfile=True, position=-1, - ), - out_i_count=dict(argstr="--out_i_count %d",), - out_i_dir=dict(argstr="--out_i_direction %f %f %f",), - out_i_size=dict(argstr="--out_i_size %d",), - out_info=dict(argstr="--out_info",), - out_j_count=dict(argstr="--out_j_count %d",), - out_j_dir=dict(argstr="--out_j_direction %f %f %f",), - out_j_size=dict(argstr="--out_j_size %d",), - out_k_count=dict(argstr="--out_k_count %d",), - out_k_dir=dict(argstr="--out_k_direction %f %f %f",), - out_k_size=dict(argstr="--out_k_size %d",), - out_matrix=dict(argstr="--out_matrix",), - out_orientation=dict(argstr="--out_orientation %s",), - out_scale=dict(argstr="--out-scale %d",), - out_stats=dict(argstr="--out_stats",), - out_type=dict(argstr="--out_type %s",), - parse_only=dict(argstr="--parse_only",), - read_only=dict(argstr="--read_only",), - reorder=dict(argstr="--reorder %d %d %d",), - resample_type=dict(argstr="--resample_type %s",), - reslice_like=dict(argstr="--reslice_like %s", extensions=None,), - sdcm_list=dict(argstr="--sdcmlist %s", extensions=None,), - skip_n=dict(argstr="--nskip %d",), - slice_bias=dict(argstr="--slice-bias %f",), - slice_crop=dict(argstr="--slice-crop %d %d",), - slice_reverse=dict(argstr="--slice-reverse",), - smooth_parcellation=dict(argstr="--smooth_parcellation",), - sphinx=dict(argstr="--sphinx",), - split=dict(argstr="--split",), - status_file=dict(argstr="--status %s", extensions=None,), - subject_name=dict(argstr="--subject_name %s",), + argstr="--output_volume %s", + extensions=None, + genfile=True, + position=-1, + ), + out_i_count=dict( + argstr="--out_i_count %d", + ), + out_i_dir=dict( + argstr="--out_i_direction %f %f %f", + ), + out_i_size=dict( + argstr="--out_i_size %d", + ), + out_info=dict( + argstr="--out_info", + ), + out_j_count=dict( + argstr="--out_j_count %d", + ), + out_j_dir=dict( + argstr="--out_j_direction %f %f %f", + ), + out_j_size=dict( + argstr="--out_j_size %d", + ), + out_k_count=dict( + argstr="--out_k_count %d", + ), + out_k_dir=dict( + argstr="--out_k_direction %f %f %f", + ), + out_k_size=dict( + argstr="--out_k_size %d", + ), + out_matrix=dict( + argstr="--out_matrix", + ), + out_orientation=dict( + argstr="--out_orientation %s", + ), + out_scale=dict( + argstr="--out-scale %d", + ), + out_stats=dict( + argstr="--out_stats", + ), + out_type=dict( + argstr="--out_type %s", + ), + parse_only=dict( + argstr="--parse_only", + ), + read_only=dict( + argstr="--read_only", + ), + reorder=dict( + argstr="--reorder %d %d %d", + ), + resample_type=dict( + argstr="--resample_type %s", + ), + reslice_like=dict( + argstr="--reslice_like %s", + extensions=None, + ), + sdcm_list=dict( + argstr="--sdcmlist %s", + extensions=None, + ), + skip_n=dict( + argstr="--nskip %d", + ), + slice_bias=dict( + argstr="--slice-bias %f", + ), + slice_crop=dict( + argstr="--slice-crop %d %d", + ), + slice_reverse=dict( + argstr="--slice-reverse", + ), + smooth_parcellation=dict( + argstr="--smooth_parcellation", + ), + sphinx=dict( + argstr="--sphinx", + ), + split=dict( + argstr="--split", + ), + status_file=dict( + argstr="--status %s", + extensions=None, + ), + subject_name=dict( + argstr="--subject_name %s", + ), subjects_dir=dict(), - te=dict(argstr="-te %d",), - template_info=dict(argstr="--template_info",), - template_type=dict(argstr="--template_type %s",), - ti=dict(argstr="-ti %d",), - tr=dict(argstr="-tr %d",), - unwarp_gradient=dict(argstr="--unwarp_gradient_nonlinearity",), - vox_size=dict(argstr="-voxsize %f %f %f",), - zero_ge_z_offset=dict(argstr="--zero_ge_z_offset",), - zero_outlines=dict(argstr="--zero_outlines",), + te=dict( + argstr="-te %d", + ), + template_info=dict( + argstr="--template_info", + ), + template_type=dict( + argstr="--template_type %s", + ), + ti=dict( + argstr="-ti %d", + ), + tr=dict( + argstr="-tr %d", + ), + unwarp_gradient=dict( + argstr="--unwarp_gradient_nonlinearity", + ), + vox_size=dict( + argstr="-voxsize %f %f %f", + ), + zero_ge_z_offset=dict( + argstr="--zero_ge_z_offset", + ), + zero_outlines=dict( + argstr="--zero_outlines", + ), ) inputs = MRIConvert.input_spec() @@ -105,7 +284,9 @@ def test_MRIConvert_inputs(): def test_MRIConvert_outputs(): - output_map = dict(out_file=dict(),) + output_map = dict( + out_file=dict(), + ) outputs = MRIConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRICoreg.py b/nipype/interfaces/freesurfer/tests/test_auto_MRICoreg.py index 1cef259c82..3d85129f3d 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRICoreg.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRICoreg.py @@ -4,29 +4,79 @@ def test_MRICoreg_inputs(): input_map = dict( - args=dict(argstr="%s",), - brute_force_limit=dict(argstr="--bf-lim %g", xor=["no_brute_force"],), - brute_force_samples=dict(argstr="--bf-nsamp %d", xor=["no_brute_force"],), - conform_reference=dict(argstr="--conf-ref",), - dof=dict(argstr="--dof %d",), - environ=dict(nohash=True, usedefault=True,), - ftol=dict(argstr="--ftol %e",), - initial_rotation=dict(argstr="--rot %g %g %g",), - initial_scale=dict(argstr="--scale %g %g %g",), - initial_shear=dict(argstr="--shear %g %g %g",), - initial_translation=dict(argstr="--trans %g %g %g",), - linmintol=dict(argstr="--linmintol %e",), - max_iters=dict(argstr="--nitersmax %d",), - no_brute_force=dict(argstr="--no-bf",), - no_coord_dithering=dict(argstr="--no-coord-dither",), - no_cras0=dict(argstr="--no-cras0",), - no_intensity_dithering=dict(argstr="--no-intensity-dither",), - no_smooth=dict(argstr="--no-smooth",), - num_threads=dict(argstr="--threads %d",), - out_lta_file=dict(argstr="--lta %s", usedefault=True,), - out_params_file=dict(argstr="--params %s",), - out_reg_file=dict(argstr="--regdat %s",), - ref_fwhm=dict(argstr="--ref-fwhm",), + args=dict( + argstr="%s", + ), + brute_force_limit=dict( + argstr="--bf-lim %g", + xor=["no_brute_force"], + ), + brute_force_samples=dict( + argstr="--bf-nsamp %d", + xor=["no_brute_force"], + ), + conform_reference=dict( + argstr="--conf-ref", + ), + dof=dict( + argstr="--dof %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ftol=dict( + argstr="--ftol %e", + ), + initial_rotation=dict( + argstr="--rot %g %g %g", + ), + initial_scale=dict( + argstr="--scale %g %g %g", + ), + initial_shear=dict( + argstr="--shear %g %g %g", + ), + initial_translation=dict( + argstr="--trans %g %g %g", + ), + linmintol=dict( + argstr="--linmintol %e", + ), + max_iters=dict( + argstr="--nitersmax %d", + ), + no_brute_force=dict( + argstr="--no-bf", + ), + no_coord_dithering=dict( + argstr="--no-coord-dither", + ), + no_cras0=dict( + argstr="--no-cras0", + ), + no_intensity_dithering=dict( + argstr="--no-intensity-dither", + ), + no_smooth=dict( + argstr="--no-smooth", + ), + num_threads=dict( + argstr="--threads %d", + ), + out_lta_file=dict( + argstr="--lta %s", + usedefault=True, + ), + out_params_file=dict( + argstr="--params %s", + ), + out_reg_file=dict( + argstr="--regdat %s", + ), + ref_fwhm=dict( + argstr="--ref-fwhm", + ), reference_file=dict( argstr="--ref %s", copyfile=False, @@ -34,14 +84,28 @@ def test_MRICoreg_inputs(): mandatory=True, xor=["subject_id"], ), - reference_mask=dict(argstr="--ref-mask %s", position=2,), - saturation_threshold=dict(argstr="--sat %g",), - sep=dict(argstr="--sep %s...",), + reference_mask=dict( + argstr="--ref-mask %s", + position=2, + ), + saturation_threshold=dict( + argstr="--sat %g", + ), + sep=dict( + argstr="--sep %s...", + ), source_file=dict( - argstr="--mov %s", copyfile=False, extensions=None, mandatory=True, + argstr="--mov %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + source_mask=dict( + argstr="--mov-mask", + ), + source_oob=dict( + argstr="--mov-oob", ), - source_mask=dict(argstr="--mov-mask",), - source_oob=dict(argstr="--mov-oob",), subject_id=dict( argstr="--s %s", mandatory=True, @@ -49,7 +113,9 @@ def test_MRICoreg_inputs(): requires=["subjects_dir"], xor=["reference_file"], ), - subjects_dir=dict(argstr="--sd %s",), + subjects_dir=dict( + argstr="--sd %s", + ), ) inputs = MRICoreg.input_spec() @@ -60,9 +126,15 @@ def test_MRICoreg_inputs(): def test_MRICoreg_outputs(): output_map = dict( - out_lta_file=dict(extensions=None,), - out_params_file=dict(extensions=None,), - out_reg_file=dict(extensions=None,), + out_lta_file=dict( + extensions=None, + ), + out_params_file=dict( + extensions=None, + ), + out_reg_file=dict( + extensions=None, + ), ) outputs = MRICoreg.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIFill.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIFill.py index c8a2f7090c..bf359364ba 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIFill.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIFill.py @@ -4,14 +4,38 @@ def test_MRIFill_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - log_file=dict(argstr="-a %s", extensions=None,), - out_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - segmentation=dict(argstr="-segmentation %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + log_file=dict( + argstr="-a %s", + extensions=None, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + segmentation=dict( + argstr="-segmentation %s", + extensions=None, + ), subjects_dir=dict(), - transform=dict(argstr="-xform %s", extensions=None,), + transform=dict( + argstr="-xform %s", + extensions=None, + ), ) inputs = MRIFill.input_spec() @@ -21,7 +45,14 @@ def test_MRIFill_inputs(): def test_MRIFill_outputs(): - output_map = dict(log_file=dict(extensions=None,), out_file=dict(extensions=None,),) + output_map = dict( + log_file=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + ) outputs = MRIFill.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIMarchingCubes.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIMarchingCubes.py index 25137a53a8..ccb2ab4388 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIMarchingCubes.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIMarchingCubes.py @@ -4,12 +4,35 @@ def test_MRIMarchingCubes_inputs(): input_map = dict( - args=dict(argstr="%s",), - connectivity_value=dict(argstr="%d", position=-1, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - label_value=dict(argstr="%d", mandatory=True, position=2,), - out_file=dict(argstr="./%s", extensions=None, genfile=True, position=-2,), + args=dict( + argstr="%s", + ), + connectivity_value=dict( + argstr="%d", + position=-1, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + label_value=dict( + argstr="%d", + mandatory=True, + position=2, + ), + out_file=dict( + argstr="./%s", + extensions=None, + genfile=True, + position=-2, + ), subjects_dir=dict(), ) inputs = MRIMarchingCubes.input_spec() @@ -20,7 +43,11 @@ def test_MRIMarchingCubes_inputs(): def test_MRIMarchingCubes_outputs(): - output_map = dict(surface=dict(extensions=None,),) + output_map = dict( + surface=dict( + extensions=None, + ), + ) outputs = MRIMarchingCubes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIPretess.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIPretess.py index 195472d4ad..e6a239fbd5 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIPretess.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIPretess.py @@ -4,13 +4,37 @@ def test_MRIPretess_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_filled=dict(argstr="%s", extensions=None, mandatory=True, position=-4,), - in_norm=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - keep=dict(argstr="-keep",), - label=dict(argstr="%s", mandatory=True, position=-3, usedefault=True,), - nocorners=dict(argstr="-nocorners",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_filled=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-4, + ), + in_norm=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + keep=dict( + argstr="-keep", + ), + label=dict( + argstr="%s", + mandatory=True, + position=-3, + usedefault=True, + ), + nocorners=dict( + argstr="-nocorners", + ), out_file=dict( argstr="%s", extensions=None, @@ -20,7 +44,9 @@ def test_MRIPretess_inputs(): position=-1, ), subjects_dir=dict(), - test=dict(argstr="-test",), + test=dict( + argstr="-test", + ), ) inputs = MRIPretess.input_spec() @@ -30,7 +56,11 @@ def test_MRIPretess_inputs(): def test_MRIPretess_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRIPretess.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py b/nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py index 03d9ccd2e4..845e6c6c3c 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRISPreproc.py @@ -4,43 +4,84 @@ def test_MRISPreproc_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), fsgd_file=dict( argstr="--fsgd %s", extensions=None, xor=("subjects", "fsgd_file", "subject_file"), ), - fwhm=dict(argstr="--fwhm %f", xor=["num_iters"],), - fwhm_source=dict(argstr="--fwhm-src %f", xor=["num_iters_source"],), - hemi=dict(argstr="--hemi %s", mandatory=True,), - num_iters=dict(argstr="--niters %d", xor=["fwhm"],), - num_iters_source=dict(argstr="--niterssrc %d", xor=["fwhm_source"],), - out_file=dict(argstr="--out %s", extensions=None, genfile=True,), - proj_frac=dict(argstr="--projfrac %s",), - smooth_cortex_only=dict(argstr="--smooth-cortex-only",), - source_format=dict(argstr="--srcfmt %s",), + fwhm=dict( + argstr="--fwhm %f", + xor=["num_iters"], + ), + fwhm_source=dict( + argstr="--fwhm-src %f", + xor=["num_iters_source"], + ), + hemi=dict( + argstr="--hemi %s", + mandatory=True, + ), + num_iters=dict( + argstr="--niters %d", + xor=["fwhm"], + ), + num_iters_source=dict( + argstr="--niterssrc %d", + xor=["fwhm_source"], + ), + out_file=dict( + argstr="--out %s", + extensions=None, + genfile=True, + ), + proj_frac=dict( + argstr="--projfrac %s", + ), + smooth_cortex_only=dict( + argstr="--smooth-cortex-only", + ), + source_format=dict( + argstr="--srcfmt %s", + ), subject_file=dict( argstr="--f %s", extensions=None, xor=("subjects", "fsgd_file", "subject_file"), ), subjects=dict( - argstr="--s %s...", xor=("subjects", "fsgd_file", "subject_file"), + argstr="--s %s...", + xor=("subjects", "fsgd_file", "subject_file"), ), subjects_dir=dict(), surf_area=dict( - argstr="--area %s", xor=("surf_measure", "surf_measure_file", "surf_area"), + argstr="--area %s", + xor=("surf_measure", "surf_measure_file", "surf_area"), + ), + surf_dir=dict( + argstr="--surfdir %s", ), - surf_dir=dict(argstr="--surfdir %s",), surf_measure=dict( - argstr="--meas %s", xor=("surf_measure", "surf_measure_file", "surf_area"), + argstr="--meas %s", + xor=("surf_measure", "surf_measure_file", "surf_area"), ), surf_measure_file=dict( - argstr="--is %s...", xor=("surf_measure", "surf_measure_file", "surf_area"), + argstr="--is %s...", + xor=("surf_measure", "surf_measure_file", "surf_area"), + ), + target=dict( + argstr="--target %s", + mandatory=True, + ), + vol_measure_file=dict( + argstr="--iv %s %s...", ), - target=dict(argstr="--target %s", mandatory=True,), - vol_measure_file=dict(argstr="--iv %s %s...",), ) inputs = MRISPreproc.input_spec() @@ -50,7 +91,11 @@ def test_MRISPreproc_inputs(): def test_MRISPreproc_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRISPreproc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRISPreprocReconAll.py b/nipype/interfaces/freesurfer/tests/test_auto_MRISPreprocReconAll.py index 5a7a711263..5bdb0614e5 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRISPreprocReconAll.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRISPreprocReconAll.py @@ -4,25 +4,61 @@ def test_MRISPreprocReconAll_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), copy_inputs=dict(), - environ=dict(nohash=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), fsgd_file=dict( argstr="--fsgd %s", extensions=None, xor=("subjects", "fsgd_file", "subject_file"), ), - fwhm=dict(argstr="--fwhm %f", xor=["num_iters"],), - fwhm_source=dict(argstr="--fwhm-src %f", xor=["num_iters_source"],), - hemi=dict(argstr="--hemi %s", mandatory=True,), - lh_surfreg_target=dict(extensions=None, requires=["surfreg_files"],), - num_iters=dict(argstr="--niters %d", xor=["fwhm"],), - num_iters_source=dict(argstr="--niterssrc %d", xor=["fwhm_source"],), - out_file=dict(argstr="--out %s", extensions=None, genfile=True,), - proj_frac=dict(argstr="--projfrac %s",), - rh_surfreg_target=dict(extensions=None, requires=["surfreg_files"],), - smooth_cortex_only=dict(argstr="--smooth-cortex-only",), - source_format=dict(argstr="--srcfmt %s",), + fwhm=dict( + argstr="--fwhm %f", + xor=["num_iters"], + ), + fwhm_source=dict( + argstr="--fwhm-src %f", + xor=["num_iters_source"], + ), + hemi=dict( + argstr="--hemi %s", + mandatory=True, + ), + lh_surfreg_target=dict( + extensions=None, + requires=["surfreg_files"], + ), + num_iters=dict( + argstr="--niters %d", + xor=["fwhm"], + ), + num_iters_source=dict( + argstr="--niterssrc %d", + xor=["fwhm_source"], + ), + out_file=dict( + argstr="--out %s", + extensions=None, + genfile=True, + ), + proj_frac=dict( + argstr="--projfrac %s", + ), + rh_surfreg_target=dict( + extensions=None, + requires=["surfreg_files"], + ), + smooth_cortex_only=dict( + argstr="--smooth-cortex-only", + ), + source_format=dict( + argstr="--srcfmt %s", + ), subject_file=dict( argstr="--f %s", extensions=None, @@ -34,15 +70,20 @@ def test_MRISPreprocReconAll_inputs(): xor=("subjects", "fsgd_file", "subject_file", "subject_id"), ), subjects=dict( - argstr="--s %s...", xor=("subjects", "fsgd_file", "subject_file"), + argstr="--s %s...", + xor=("subjects", "fsgd_file", "subject_file"), ), subjects_dir=dict(), surf_area=dict( - argstr="--area %s", xor=("surf_measure", "surf_measure_file", "surf_area"), + argstr="--area %s", + xor=("surf_measure", "surf_measure_file", "surf_area"), + ), + surf_dir=dict( + argstr="--surfdir %s", ), - surf_dir=dict(argstr="--surfdir %s",), surf_measure=dict( - argstr="--meas %s", xor=("surf_measure", "surf_measure_file", "surf_area"), + argstr="--meas %s", + xor=("surf_measure", "surf_measure_file", "surf_area"), ), surf_measure_file=dict( argstr="--meas %s", @@ -50,10 +91,16 @@ def test_MRISPreprocReconAll_inputs(): xor=("surf_measure", "surf_measure_file", "surf_area"), ), surfreg_files=dict( - argstr="--surfreg %s", requires=["lh_surfreg_target", "rh_surfreg_target"], + argstr="--surfreg %s", + requires=["lh_surfreg_target", "rh_surfreg_target"], + ), + target=dict( + argstr="--target %s", + mandatory=True, + ), + vol_measure_file=dict( + argstr="--iv %s %s...", ), - target=dict(argstr="--target %s", mandatory=True,), - vol_measure_file=dict(argstr="--iv %s %s...",), ) inputs = MRISPreprocReconAll.input_spec() @@ -63,7 +110,11 @@ def test_MRISPreprocReconAll_inputs(): def test_MRISPreprocReconAll_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRISPreprocReconAll.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRITessellate.py b/nipype/interfaces/freesurfer/tests/test_auto_MRITessellate.py index 8bba694bf7..8aa7210d0e 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRITessellate.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRITessellate.py @@ -4,14 +4,37 @@ def test_MRITessellate_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - label_value=dict(argstr="%d", mandatory=True, position=-2,), - out_file=dict(argstr="%s", extensions=None, genfile=True, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + label_value=dict( + argstr="%d", + mandatory=True, + position=-2, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), subjects_dir=dict(), - tesselate_all_voxels=dict(argstr="-a",), - use_real_RAS_coordinates=dict(argstr="-n",), + tesselate_all_voxels=dict( + argstr="-a", + ), + use_real_RAS_coordinates=dict( + argstr="-n", + ), ) inputs = MRITessellate.input_spec() @@ -21,7 +44,11 @@ def test_MRITessellate_inputs(): def test_MRITessellate_outputs(): - output_map = dict(surface=dict(extensions=None,),) + output_map = dict( + surface=dict( + extensions=None, + ), + ) outputs = MRITessellate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCALabel.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCALabel.py index 560f7e4fce..e37cf0723a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCALabel.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCALabel.py @@ -4,15 +4,43 @@ def test_MRIsCALabel_inputs(): input_map = dict( - args=dict(argstr="%s",), - aseg=dict(argstr="-aseg %s", extensions=None,), - canonsurf=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - classifier=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + aseg=dict( + argstr="-aseg %s", + extensions=None, + ), + canonsurf=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + classifier=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), copy_inputs=dict(), - curv=dict(extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - hemisphere=dict(argstr="%s", mandatory=True, position=-4,), - label=dict(argstr="-l %s", extensions=None,), + curv=dict( + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr="%s", + mandatory=True, + position=-4, + ), + label=dict( + argstr="-l %s", + extensions=None, + ), num_threads=dict(), out_file=dict( argstr="%s", @@ -23,11 +51,24 @@ def test_MRIsCALabel_inputs(): name_template="%s.aparc.annot", position=-1, ), - seed=dict(argstr="-seed %d",), - smoothwm=dict(extensions=None, mandatory=True,), - subject_id=dict(argstr="%s", mandatory=True, position=-5, usedefault=True,), + seed=dict( + argstr="-seed %d", + ), + smoothwm=dict( + extensions=None, + mandatory=True, + ), + subject_id=dict( + argstr="%s", + mandatory=True, + position=-5, + usedefault=True, + ), subjects_dir=dict(), - sulc=dict(extensions=None, mandatory=True,), + sulc=dict( + extensions=None, + mandatory=True, + ), ) inputs = MRIsCALabel.input_spec() @@ -37,7 +78,11 @@ def test_MRIsCALabel_inputs(): def test_MRIsCALabel_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRIsCALabel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCalc.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCalc.py index 521c1d5d6c..1ef9c95c46 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCalc.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCalc.py @@ -4,16 +4,45 @@ def test_MRIsCalc_inputs(): input_map = dict( - action=dict(argstr="%s", mandatory=True, position=-2,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file1=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), + action=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file1=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), in_file2=dict( - argstr="%s", extensions=None, position=-1, xor=["in_float", "in_int"], + argstr="%s", + extensions=None, + position=-1, + xor=["in_float", "in_int"], + ), + in_float=dict( + argstr="%f", + position=-1, + xor=["in_file2", "in_int"], + ), + in_int=dict( + argstr="%d", + position=-1, + xor=["in_file2", "in_float"], + ), + out_file=dict( + argstr="-o %s", + extensions=None, + mandatory=True, ), - in_float=dict(argstr="%f", position=-1, xor=["in_file2", "in_int"],), - in_int=dict(argstr="%d", position=-1, xor=["in_file2", "in_float"],), - out_file=dict(argstr="-o %s", extensions=None, mandatory=True,), subjects_dir=dict(), ) inputs = MRIsCalc.input_spec() @@ -24,7 +53,11 @@ def test_MRIsCalc_inputs(): def test_MRIsCalc_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRIsCalc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCombine.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCombine.py index 56fd270efc..01aef41a01 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsCombine.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsCombine.py @@ -4,11 +4,24 @@ def test_MRIsCombine_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="--combinesurfs %s", mandatory=True, position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="--combinesurfs %s", + mandatory=True, + position=1, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, mandatory=True, position=-1, + argstr="%s", + extensions=None, + genfile=True, + mandatory=True, + position=-1, ), subjects_dir=dict(), ) @@ -20,7 +33,11 @@ def test_MRIsCombine_inputs(): def test_MRIsCombine_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRIsCombine.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsConvert.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsConvert.py index 6972ae4f33..daf4462ff8 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsConvert.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsConvert.py @@ -4,17 +4,48 @@ def test_MRIsConvert_inputs(): input_map = dict( - annot_file=dict(argstr="--annot %s", extensions=None,), - args=dict(argstr="%s",), - dataarray_num=dict(argstr="--da_num %d",), - environ=dict(nohash=True, usedefault=True,), - functional_file=dict(argstr="-f %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - label_file=dict(argstr="--label %s", extensions=None,), - labelstats_outfile=dict(argstr="--labelstats %s", extensions=None,), - normal=dict(argstr="-n",), - origname=dict(argstr="-o %s",), - out_datatype=dict(mandatory=True, xor=["out_file"],), + annot_file=dict( + argstr="--annot %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + dataarray_num=dict( + argstr="--da_num %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + functional_file=dict( + argstr="-f %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + label_file=dict( + argstr="--label %s", + extensions=None, + ), + labelstats_outfile=dict( + argstr="--labelstats %s", + extensions=None, + ), + normal=dict( + argstr="-n", + ), + origname=dict( + argstr="-o %s", + ), + out_datatype=dict( + mandatory=True, + xor=["out_file"], + ), out_file=dict( argstr="%s", extensions=None, @@ -23,17 +54,39 @@ def test_MRIsConvert_inputs(): position=-1, xor=["out_datatype"], ), - parcstats_file=dict(argstr="--parcstats %s", extensions=None,), - patch=dict(argstr="-p",), - rescale=dict(argstr="-r",), - scalarcurv_file=dict(argstr="-c %s", extensions=None,), - scale=dict(argstr="-s %.3f",), + parcstats_file=dict( + argstr="--parcstats %s", + extensions=None, + ), + patch=dict( + argstr="-p", + ), + rescale=dict( + argstr="-r", + ), + scalarcurv_file=dict( + argstr="-c %s", + extensions=None, + ), + scale=dict( + argstr="-s %.3f", + ), subjects_dir=dict(), - talairachxfm_subjid=dict(argstr="-t %s",), - to_scanner=dict(argstr="--to-scanner",), - to_tkr=dict(argstr="--to-tkr",), - vertex=dict(argstr="-v",), - xyz_ascii=dict(argstr="-a",), + talairachxfm_subjid=dict( + argstr="-t %s", + ), + to_scanner=dict( + argstr="--to-scanner", + ), + to_tkr=dict( + argstr="--to-tkr", + ), + vertex=dict( + argstr="-v", + ), + xyz_ascii=dict( + argstr="-a", + ), ) inputs = MRIsConvert.input_spec() @@ -43,7 +96,11 @@ def test_MRIsConvert_inputs(): def test_MRIsConvert_outputs(): - output_map = dict(converted=dict(extensions=None,),) + output_map = dict( + converted=dict( + extensions=None, + ), + ) outputs = MRIsConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsExpand.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsExpand.py index b2d97f0d48..05e34a29b5 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsExpand.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsExpand.py @@ -4,23 +4,61 @@ def test_MRIsExpand_inputs(): input_map = dict( - args=dict(argstr="%s",), - distance=dict(argstr="%g", mandatory=True, position=-2,), - dt=dict(argstr="-T %g",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + distance=dict( + argstr="%g", + mandatory=True, + position=-2, + ), + dt=dict( + argstr="-T %g", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=-3, - ), - nsurfaces=dict(argstr="-N %d",), - out_name=dict(argstr="%s", position=-1, usedefault=True,), - pial=dict(argstr="-pial %s", copyfile=False,), - smooth_averages=dict(argstr="-A %d",), - sphere=dict(copyfile=False, usedefault=True,), - spring=dict(argstr="-S %g",), + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=-3, + ), + nsurfaces=dict( + argstr="-N %d", + ), + out_name=dict( + argstr="%s", + position=-1, + usedefault=True, + ), + pial=dict( + argstr="-pial %s", + copyfile=False, + ), + smooth_averages=dict( + argstr="-A %d", + ), + sphere=dict( + copyfile=False, + usedefault=True, + ), + spring=dict( + argstr="-S %g", + ), subjects_dir=dict(), - thickness=dict(argstr="-thickness",), - thickness_name=dict(argstr="-thickness_name %s", copyfile=False,), - write_iterations=dict(argstr="-W %d",), + thickness=dict( + argstr="-thickness", + ), + thickness_name=dict( + argstr="-thickness_name %s", + copyfile=False, + ), + write_iterations=dict( + argstr="-W %d", + ), ) inputs = MRIsExpand.input_spec() @@ -30,7 +68,11 @@ def test_MRIsExpand_inputs(): def test_MRIsExpand_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRIsExpand.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRIsInflate.py b/nipype/interfaces/freesurfer/tests/test_auto_MRIsInflate.py index aead890eff..9cc45189a0 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MRIsInflate.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRIsInflate.py @@ -4,12 +4,24 @@ def test_MRIsInflate_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=-2, + ), + no_save_sulc=dict( + argstr="-no-save-sulc", + xor=["out_sulc"], ), - no_save_sulc=dict(argstr="-no-save-sulc", xor=["out_sulc"],), out_file=dict( argstr="%s", extensions=None, @@ -19,7 +31,10 @@ def test_MRIsInflate_inputs(): name_template="%s.inflated", position=-1, ), - out_sulc=dict(extensions=None, xor=["no_save_sulc"],), + out_sulc=dict( + extensions=None, + xor=["no_save_sulc"], + ), subjects_dir=dict(), ) inputs = MRIsInflate.input_spec() @@ -30,7 +45,14 @@ def test_MRIsInflate_inputs(): def test_MRIsInflate_outputs(): - output_map = dict(out_file=dict(extensions=None,), out_sulc=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + out_sulc=dict( + extensions=None, + ), + ) outputs = MRIsInflate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRTM1.py b/nipype/interfaces/freesurfer/tests/test_auto_MRTM1.py new file mode 100644 index 0000000000..1637214b9e --- /dev/null +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRTM1.py @@ -0,0 +1,284 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..petsurfer import MRTM1 + + +def test_MRTM1_inputs(): + input_map = dict( + allow_ill_cond=dict( + argstr="--illcond", + ), + allow_repeated_subjects=dict( + argstr="--allowsubjrep", + ), + args=dict( + argstr="%s", + ), + bp_clip_max=dict( + argstr="--bp-clip-max %f", + ), + bp_clip_neg=dict( + argstr="--bp-clip-neg", + ), + calc_AR1=dict( + argstr="--tar1", + ), + check_opts=dict( + argstr="--checkopts", + ), + compute_log_y=dict( + argstr="--logy", + ), + contrast=dict( + argstr="--C %s...", + ), + cortex=dict( + argstr="--cortex", + xor=["label_file"], + ), + debug=dict( + argstr="--debug", + ), + design=dict( + argstr="--X %s", + extensions=None, + xor=("fsgd", "design", "one_sample"), + ), + diag=dict( + argstr="--diag %d", + ), + diag_cluster=dict( + argstr="--diag-cluster", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_fx_dof=dict( + argstr="--ffxdof %d", + xor=["fixed_fx_dof_file"], + ), + fixed_fx_dof_file=dict( + argstr="--ffxdofdat %d", + extensions=None, + xor=["fixed_fx_dof"], + ), + fixed_fx_var=dict( + argstr="--yffxvar %s", + extensions=None, + ), + force_perm=dict( + argstr="--perm-force", + ), + fsgd=dict( + argstr="--fsgd %s %s", + xor=("fsgd", "design", "one_sample"), + ), + fwhm=dict( + argstr="--fwhm %f", + ), + glm_dir=dict( + argstr="--glmdir %s", + genfile=True, + ), + hemi=dict(), + in_file=dict( + argstr="--y %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + invert_mask=dict( + argstr="--mask-inv", + ), + label_file=dict( + argstr="--label %s", + extensions=None, + xor=["cortex"], + ), + logan=dict( + argstr="--logan %s %s %f", + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + mrtm1=dict( + argstr="--mrtm1 %s %s", + mandatory=True, + ), + mrtm2=dict( + argstr="--mrtm2 %s %s %f", + ), + nii=dict( + argstr="--nii", + xor=["nii", "nii_gz"], + ), + nii_gz=dict( + argstr="--nii.gz", + xor=["nii", "nii_gz"], + ), + no_contrast_ok=dict( + argstr="--no-contrasts-ok", + ), + no_est_fwhm=dict( + argstr="--no-est-fwhm", + ), + no_mask_smooth=dict( + argstr="--no-mask-smooth", + ), + no_prune=dict( + argstr="--no-prune", + xor=["prunethresh"], + ), + one_sample=dict( + argstr="--osgm", + xor=("one_sample", "fsgd", "design", "contrast"), + ), + pca=dict( + argstr="--pca", + ), + per_voxel_reg=dict( + argstr="--pvr %s...", + ), + profile=dict( + argstr="--profile %d", + ), + prune=dict( + argstr="--prune", + ), + prune_thresh=dict( + argstr="--prune_thr %f", + xor=["noprune"], + ), + resynth_test=dict( + argstr="--resynthtest %d", + ), + save_cond=dict( + argstr="--save-cond", + ), + save_estimate=dict( + argstr="--yhat-save", + ), + save_res_corr_mtx=dict( + argstr="--eres-scm", + ), + save_residual=dict( + argstr="--eres-save", + ), + seed=dict( + argstr="--seed %d", + ), + self_reg=dict( + argstr="--selfreg %d %d %d", + ), + sim_done_file=dict( + argstr="--sim-done %s", + extensions=None, + ), + sim_sign=dict( + argstr="--sim-sign %s", + ), + simulation=dict( + argstr="--sim %s %d %f %s", + ), + subject_id=dict(), + subjects_dir=dict(), + surf=dict( + argstr="--surf %s %s %s", + requires=["subject_id", "hemi"], + ), + surf_geo=dict( + usedefault=True, + ), + synth=dict( + argstr="--synth", + ), + uniform=dict( + argstr="--uniform %f %f", + ), + var_fwhm=dict( + argstr="--var-fwhm %f", + ), + vox_dump=dict( + argstr="--voxdump %d %d %d", + ), + weight_file=dict( + extensions=None, + xor=["weighted_ls"], + ), + weight_inv=dict( + argstr="--w-inv", + xor=["weighted_ls"], + ), + weight_sqrt=dict( + argstr="--w-sqrt", + xor=["weighted_ls"], + ), + weighted_ls=dict( + argstr="--wls %s", + extensions=None, + xor=("weight_file", "weight_inv", "weight_sqrt"), + ), + ) + inputs = MRTM1.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_MRTM1_outputs(): + output_map = dict( + beta_file=dict( + extensions=None, + ), + bp_file=dict( + extensions=None, + ), + dof_file=dict( + extensions=None, + ), + error_file=dict( + extensions=None, + ), + error_stddev_file=dict( + extensions=None, + ), + error_var_file=dict( + extensions=None, + ), + estimate_file=dict( + extensions=None, + ), + frame_eigenvectors=dict( + extensions=None, + ), + ftest_file=dict(), + fwhm_file=dict( + extensions=None, + ), + gamma_file=dict(), + gamma_var_file=dict(), + glm_dir=dict(), + k2p_file=dict( + extensions=None, + ), + mask_file=dict( + extensions=None, + ), + sig_file=dict(), + singular_values=dict( + extensions=None, + ), + spatial_eigenvectors=dict( + extensions=None, + ), + svd_stats_file=dict( + extensions=None, + ), + ) + outputs = MRTM1.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MRTM2.py b/nipype/interfaces/freesurfer/tests/test_auto_MRTM2.py new file mode 100644 index 0000000000..dea4ca3a92 --- /dev/null +++ b/nipype/interfaces/freesurfer/tests/test_auto_MRTM2.py @@ -0,0 +1,284 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..petsurfer import MRTM2 + + +def test_MRTM2_inputs(): + input_map = dict( + allow_ill_cond=dict( + argstr="--illcond", + ), + allow_repeated_subjects=dict( + argstr="--allowsubjrep", + ), + args=dict( + argstr="%s", + ), + bp_clip_max=dict( + argstr="--bp-clip-max %f", + ), + bp_clip_neg=dict( + argstr="--bp-clip-neg", + ), + calc_AR1=dict( + argstr="--tar1", + ), + check_opts=dict( + argstr="--checkopts", + ), + compute_log_y=dict( + argstr="--logy", + ), + contrast=dict( + argstr="--C %s...", + ), + cortex=dict( + argstr="--cortex", + xor=["label_file"], + ), + debug=dict( + argstr="--debug", + ), + design=dict( + argstr="--X %s", + extensions=None, + xor=("fsgd", "design", "one_sample"), + ), + diag=dict( + argstr="--diag %d", + ), + diag_cluster=dict( + argstr="--diag-cluster", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_fx_dof=dict( + argstr="--ffxdof %d", + xor=["fixed_fx_dof_file"], + ), + fixed_fx_dof_file=dict( + argstr="--ffxdofdat %d", + extensions=None, + xor=["fixed_fx_dof"], + ), + fixed_fx_var=dict( + argstr="--yffxvar %s", + extensions=None, + ), + force_perm=dict( + argstr="--perm-force", + ), + fsgd=dict( + argstr="--fsgd %s %s", + xor=("fsgd", "design", "one_sample"), + ), + fwhm=dict( + argstr="--fwhm %f", + ), + glm_dir=dict( + argstr="--glmdir %s", + genfile=True, + ), + hemi=dict(), + in_file=dict( + argstr="--y %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + invert_mask=dict( + argstr="--mask-inv", + ), + label_file=dict( + argstr="--label %s", + extensions=None, + xor=["cortex"], + ), + logan=dict( + argstr="--logan %s %s %f", + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + mrtm1=dict( + argstr="--mrtm1 %s %s", + ), + mrtm2=dict( + argstr="--mrtm2 %s %s %f", + mandatory=True, + ), + nii=dict( + argstr="--nii", + xor=["nii", "nii_gz"], + ), + nii_gz=dict( + argstr="--nii.gz", + xor=["nii", "nii_gz"], + ), + no_contrast_ok=dict( + argstr="--no-contrasts-ok", + ), + no_est_fwhm=dict( + argstr="--no-est-fwhm", + ), + no_mask_smooth=dict( + argstr="--no-mask-smooth", + ), + no_prune=dict( + argstr="--no-prune", + xor=["prunethresh"], + ), + one_sample=dict( + argstr="--osgm", + xor=("one_sample", "fsgd", "design", "contrast"), + ), + pca=dict( + argstr="--pca", + ), + per_voxel_reg=dict( + argstr="--pvr %s...", + ), + profile=dict( + argstr="--profile %d", + ), + prune=dict( + argstr="--prune", + ), + prune_thresh=dict( + argstr="--prune_thr %f", + xor=["noprune"], + ), + resynth_test=dict( + argstr="--resynthtest %d", + ), + save_cond=dict( + argstr="--save-cond", + ), + save_estimate=dict( + argstr="--yhat-save", + ), + save_res_corr_mtx=dict( + argstr="--eres-scm", + ), + save_residual=dict( + argstr="--eres-save", + ), + seed=dict( + argstr="--seed %d", + ), + self_reg=dict( + argstr="--selfreg %d %d %d", + ), + sim_done_file=dict( + argstr="--sim-done %s", + extensions=None, + ), + sim_sign=dict( + argstr="--sim-sign %s", + ), + simulation=dict( + argstr="--sim %s %d %f %s", + ), + subject_id=dict(), + subjects_dir=dict(), + surf=dict( + argstr="--surf %s %s %s", + requires=["subject_id", "hemi"], + ), + surf_geo=dict( + usedefault=True, + ), + synth=dict( + argstr="--synth", + ), + uniform=dict( + argstr="--uniform %f %f", + ), + var_fwhm=dict( + argstr="--var-fwhm %f", + ), + vox_dump=dict( + argstr="--voxdump %d %d %d", + ), + weight_file=dict( + extensions=None, + xor=["weighted_ls"], + ), + weight_inv=dict( + argstr="--w-inv", + xor=["weighted_ls"], + ), + weight_sqrt=dict( + argstr="--w-sqrt", + xor=["weighted_ls"], + ), + weighted_ls=dict( + argstr="--wls %s", + extensions=None, + xor=("weight_file", "weight_inv", "weight_sqrt"), + ), + ) + inputs = MRTM2.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_MRTM2_outputs(): + output_map = dict( + beta_file=dict( + extensions=None, + ), + bp_file=dict( + extensions=None, + ), + dof_file=dict( + extensions=None, + ), + error_file=dict( + extensions=None, + ), + error_stddev_file=dict( + extensions=None, + ), + error_var_file=dict( + extensions=None, + ), + estimate_file=dict( + extensions=None, + ), + frame_eigenvectors=dict( + extensions=None, + ), + ftest_file=dict(), + fwhm_file=dict( + extensions=None, + ), + gamma_file=dict(), + gamma_var_file=dict(), + glm_dir=dict(), + k2p_file=dict( + extensions=None, + ), + mask_file=dict( + extensions=None, + ), + sig_file=dict(), + singular_values=dict( + extensions=None, + ), + spatial_eigenvectors=dict( + extensions=None, + ), + svd_stats_file=dict( + extensions=None, + ), + ) + outputs = MRTM2.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MS_LDA.py b/nipype/interfaces/freesurfer/tests/test_auto_MS_LDA.py index 47575cf851..093dd3d9b8 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MS_LDA.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MS_LDA.py @@ -4,18 +4,52 @@ def test_MS_LDA_inputs(): input_map = dict( - args=dict(argstr="%s",), - conform=dict(argstr="-conform",), - environ=dict(nohash=True, usedefault=True,), - images=dict(argstr="%s", copyfile=False, mandatory=True, position=-1,), - label_file=dict(argstr="-label %s", extensions=None,), - lda_labels=dict(argstr="-lda %s", mandatory=True, sep=" ",), - mask_file=dict(argstr="-mask %s", extensions=None,), - shift=dict(argstr="-shift %d",), + args=dict( + argstr="%s", + ), + conform=dict( + argstr="-conform", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + images=dict( + argstr="%s", + copyfile=False, + mandatory=True, + position=-1, + ), + label_file=dict( + argstr="-label %s", + extensions=None, + ), + lda_labels=dict( + argstr="-lda %s", + mandatory=True, + sep=" ", + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + shift=dict( + argstr="-shift %d", + ), subjects_dir=dict(), - use_weights=dict(argstr="-W",), - vol_synth_file=dict(argstr="-synth %s", extensions=None, mandatory=True,), - weight_file=dict(argstr="-weight %s", extensions=None, mandatory=True,), + use_weights=dict( + argstr="-W", + ), + vol_synth_file=dict( + argstr="-synth %s", + extensions=None, + mandatory=True, + ), + weight_file=dict( + argstr="-weight %s", + extensions=None, + mandatory=True, + ), ) inputs = MS_LDA.input_spec() @@ -26,7 +60,12 @@ def test_MS_LDA_inputs(): def test_MS_LDA_outputs(): output_map = dict( - vol_synth_file=dict(extensions=None,), weight_file=dict(extensions=None,), + vol_synth_file=dict( + extensions=None, + ), + weight_file=dict( + extensions=None, + ), ) outputs = MS_LDA.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MakeAverageSubject.py b/nipype/interfaces/freesurfer/tests/test_auto_MakeAverageSubject.py index 3f7b6ac9ab..e3778911e6 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MakeAverageSubject.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MakeAverageSubject.py @@ -4,11 +4,24 @@ def test_MakeAverageSubject_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - out_name=dict(argstr="--out %s", extensions=None, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + out_name=dict( + argstr="--out %s", + extensions=None, + usedefault=True, + ), subjects_dir=dict(), - subjects_ids=dict(argstr="--subjects %s", mandatory=True, sep=" ",), + subjects_ids=dict( + argstr="--subjects %s", + mandatory=True, + sep=" ", + ), ) inputs = MakeAverageSubject.input_spec() @@ -18,7 +31,9 @@ def test_MakeAverageSubject_inputs(): def test_MakeAverageSubject_outputs(): - output_map = dict(average_subject_name=dict(),) + output_map = dict( + average_subject_name=dict(), + ) outputs = MakeAverageSubject.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_MakeSurfaces.py b/nipype/interfaces/freesurfer/tests/test_auto_MakeSurfaces.py index 219150aef9..06316d071a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_MakeSurfaces.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_MakeSurfaces.py @@ -4,29 +4,88 @@ def test_MakeSurfaces_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), copy_inputs=dict(), - environ=dict(nohash=True, usedefault=True,), - fix_mtl=dict(argstr="-fix_mtl",), - hemisphere=dict(argstr="%s", mandatory=True, position=-1,), - in_T1=dict(argstr="-T1 %s", extensions=None,), - in_aseg=dict(argstr="-aseg %s", extensions=None,), - in_filled=dict(extensions=None, mandatory=True,), - in_label=dict(extensions=None, xor=["noaparc"],), - in_orig=dict(argstr="-orig %s", extensions=None, mandatory=True,), - in_white=dict(extensions=None,), - in_wm=dict(extensions=None, mandatory=True,), - longitudinal=dict(argstr="-long",), - maximum=dict(argstr="-max %.1f",), - mgz=dict(argstr="-mgz",), - no_white=dict(argstr="-nowhite",), - noaparc=dict(argstr="-noaparc", xor=["in_label"],), - orig_pial=dict(argstr="-orig_pial %s", extensions=None, requires=["in_label"],), - orig_white=dict(argstr="-orig_white %s", extensions=None,), - subject_id=dict(argstr="%s", mandatory=True, position=-2, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), + fix_mtl=dict( + argstr="-fix_mtl", + ), + hemisphere=dict( + argstr="%s", + mandatory=True, + position=-1, + ), + in_T1=dict( + argstr="-T1 %s", + extensions=None, + ), + in_aseg=dict( + argstr="-aseg %s", + extensions=None, + ), + in_filled=dict( + extensions=None, + mandatory=True, + ), + in_label=dict( + extensions=None, + xor=["noaparc"], + ), + in_orig=dict( + argstr="-orig %s", + extensions=None, + mandatory=True, + ), + in_white=dict( + extensions=None, + ), + in_wm=dict( + extensions=None, + mandatory=True, + ), + longitudinal=dict( + argstr="-long", + ), + maximum=dict( + argstr="-max %.1f", + ), + mgz=dict( + argstr="-mgz", + ), + no_white=dict( + argstr="-nowhite", + ), + noaparc=dict( + argstr="-noaparc", + xor=["in_label"], + ), + orig_pial=dict( + argstr="-orig_pial %s", + extensions=None, + requires=["in_label"], + ), + orig_white=dict( + argstr="-orig_white %s", + extensions=None, + ), + subject_id=dict( + argstr="%s", + mandatory=True, + position=-2, + usedefault=True, + ), subjects_dir=dict(), - white=dict(argstr="-white %s",), - white_only=dict(argstr="-whiteonly",), + white=dict( + argstr="-white %s", + ), + white_only=dict( + argstr="-whiteonly", + ), ) inputs = MakeSurfaces.input_spec() @@ -37,12 +96,24 @@ def test_MakeSurfaces_inputs(): def test_MakeSurfaces_outputs(): output_map = dict( - out_area=dict(extensions=None,), - out_cortex=dict(extensions=None,), - out_curv=dict(extensions=None,), - out_pial=dict(extensions=None,), - out_thickness=dict(extensions=None,), - out_white=dict(extensions=None,), + out_area=dict( + extensions=None, + ), + out_cortex=dict( + extensions=None, + ), + out_curv=dict( + extensions=None, + ), + out_pial=dict( + extensions=None, + ), + out_thickness=dict( + extensions=None, + ), + out_white=dict( + extensions=None, + ), ) outputs = MakeSurfaces.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Normalize.py b/nipype/interfaces/freesurfer/tests/test_auto_Normalize.py index f639141960..271f0bb328 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Normalize.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Normalize.py @@ -4,11 +4,26 @@ def test_Normalize_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - gradient=dict(argstr="-g %d",), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - mask=dict(argstr="-mask %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradient=dict( + argstr="-g %d", + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), out_file=dict( argstr="%s", extensions=None, @@ -18,9 +33,14 @@ def test_Normalize_inputs(): name_template="%s_norm", position=-1, ), - segmentation=dict(argstr="-aseg %s", extensions=None,), + segmentation=dict( + argstr="-aseg %s", + extensions=None, + ), subjects_dir=dict(), - transform=dict(extensions=None,), + transform=dict( + extensions=None, + ), ) inputs = Normalize.input_spec() @@ -30,7 +50,11 @@ def test_Normalize_inputs(): def test_Normalize_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Normalize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_OneSampleTTest.py b/nipype/interfaces/freesurfer/tests/test_auto_OneSampleTTest.py index da476e1cb3..51b2f2cd0b 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_OneSampleTTest.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_OneSampleTTest.py @@ -4,68 +4,215 @@ def test_OneSampleTTest_inputs(): input_map = dict( - allow_ill_cond=dict(argstr="--illcond",), - allow_repeated_subjects=dict(argstr="--allowsubjrep",), - args=dict(argstr="%s",), - calc_AR1=dict(argstr="--tar1",), - check_opts=dict(argstr="--checkopts",), - compute_log_y=dict(argstr="--logy",), - contrast=dict(argstr="--C %s...",), - cortex=dict(argstr="--cortex", xor=["label_file"],), - debug=dict(argstr="--debug",), + allow_ill_cond=dict( + argstr="--illcond", + ), + allow_repeated_subjects=dict( + argstr="--allowsubjrep", + ), + args=dict( + argstr="%s", + ), + bp_clip_max=dict( + argstr="--bp-clip-max %f", + ), + bp_clip_neg=dict( + argstr="--bp-clip-neg", + ), + calc_AR1=dict( + argstr="--tar1", + ), + check_opts=dict( + argstr="--checkopts", + ), + compute_log_y=dict( + argstr="--logy", + ), + contrast=dict( + argstr="--C %s...", + ), + cortex=dict( + argstr="--cortex", + xor=["label_file"], + ), + debug=dict( + argstr="--debug", + ), design=dict( - argstr="--X %s", extensions=None, xor=("fsgd", "design", "one_sample"), + argstr="--X %s", + extensions=None, + xor=("fsgd", "design", "one_sample"), + ), + diag=dict( + argstr="--diag %d", + ), + diag_cluster=dict( + argstr="--diag-cluster", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_fx_dof=dict( + argstr="--ffxdof %d", + xor=["fixed_fx_dof_file"], ), - diag=dict(argstr="--diag %d",), - diag_cluster=dict(argstr="--diag-cluster",), - environ=dict(nohash=True, usedefault=True,), - fixed_fx_dof=dict(argstr="--ffxdof %d", xor=["fixed_fx_dof_file"],), fixed_fx_dof_file=dict( - argstr="--ffxdofdat %d", extensions=None, xor=["fixed_fx_dof"], + argstr="--ffxdofdat %d", + extensions=None, + xor=["fixed_fx_dof"], + ), + fixed_fx_var=dict( + argstr="--yffxvar %s", + extensions=None, + ), + force_perm=dict( + argstr="--perm-force", + ), + fsgd=dict( + argstr="--fsgd %s %s", + xor=("fsgd", "design", "one_sample"), + ), + fwhm=dict( + argstr="--fwhm %f", + ), + glm_dir=dict( + argstr="--glmdir %s", + genfile=True, ), - fixed_fx_var=dict(argstr="--yffxvar %s", extensions=None,), - force_perm=dict(argstr="--perm-force",), - fsgd=dict(argstr="--fsgd %s %s", xor=("fsgd", "design", "one_sample"),), - fwhm=dict(argstr="--fwhm %f",), - glm_dir=dict(argstr="--glmdir %s", genfile=True,), hemi=dict(), - in_file=dict(argstr="--y %s", copyfile=False, extensions=None, mandatory=True,), - invert_mask=dict(argstr="--mask-inv",), - label_file=dict(argstr="--label %s", extensions=None, xor=["cortex"],), - mask_file=dict(argstr="--mask %s", extensions=None,), - no_contrast_ok=dict(argstr="--no-contrasts-ok",), - no_est_fwhm=dict(argstr="--no-est-fwhm",), - no_mask_smooth=dict(argstr="--no-mask-smooth",), - no_prune=dict(argstr="--no-prune", xor=["prunethresh"],), + in_file=dict( + argstr="--y %s", + copyfile=False, + extensions=None, + mandatory=True, + ), + invert_mask=dict( + argstr="--mask-inv", + ), + label_file=dict( + argstr="--label %s", + extensions=None, + xor=["cortex"], + ), + logan=dict( + argstr="--logan %s %s %f", + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + mrtm1=dict( + argstr="--mrtm1 %s %s", + ), + mrtm2=dict( + argstr="--mrtm2 %s %s %f", + ), + nii=dict( + argstr="--nii", + xor=["nii", "nii_gz"], + ), + nii_gz=dict( + argstr="--nii.gz", + xor=["nii", "nii_gz"], + ), + no_contrast_ok=dict( + argstr="--no-contrasts-ok", + ), + no_est_fwhm=dict( + argstr="--no-est-fwhm", + ), + no_mask_smooth=dict( + argstr="--no-mask-smooth", + ), + no_prune=dict( + argstr="--no-prune", + xor=["prunethresh"], + ), one_sample=dict( - argstr="--osgm", xor=("one_sample", "fsgd", "design", "contrast"), - ), - pca=dict(argstr="--pca",), - per_voxel_reg=dict(argstr="--pvr %s...",), - profile=dict(argstr="--profile %d",), - prune=dict(argstr="--prune",), - prune_thresh=dict(argstr="--prune_thr %f", xor=["noprune"],), - resynth_test=dict(argstr="--resynthtest %d",), - save_cond=dict(argstr="--save-cond",), - save_estimate=dict(argstr="--yhat-save",), - save_res_corr_mtx=dict(argstr="--eres-scm",), - save_residual=dict(argstr="--eres-save",), - seed=dict(argstr="--seed %d",), - self_reg=dict(argstr="--selfreg %d %d %d",), - sim_done_file=dict(argstr="--sim-done %s", extensions=None,), - sim_sign=dict(argstr="--sim-sign %s",), - simulation=dict(argstr="--sim %s %d %f %s",), + argstr="--osgm", + xor=("one_sample", "fsgd", "design", "contrast"), + ), + pca=dict( + argstr="--pca", + ), + per_voxel_reg=dict( + argstr="--pvr %s...", + ), + profile=dict( + argstr="--profile %d", + ), + prune=dict( + argstr="--prune", + ), + prune_thresh=dict( + argstr="--prune_thr %f", + xor=["noprune"], + ), + resynth_test=dict( + argstr="--resynthtest %d", + ), + save_cond=dict( + argstr="--save-cond", + ), + save_estimate=dict( + argstr="--yhat-save", + ), + save_res_corr_mtx=dict( + argstr="--eres-scm", + ), + save_residual=dict( + argstr="--eres-save", + ), + seed=dict( + argstr="--seed %d", + ), + self_reg=dict( + argstr="--selfreg %d %d %d", + ), + sim_done_file=dict( + argstr="--sim-done %s", + extensions=None, + ), + sim_sign=dict( + argstr="--sim-sign %s", + ), + simulation=dict( + argstr="--sim %s %d %f %s", + ), subject_id=dict(), subjects_dir=dict(), - surf=dict(argstr="--surf %s %s %s", requires=["subject_id", "hemi"],), - surf_geo=dict(usedefault=True,), - synth=dict(argstr="--synth",), - uniform=dict(argstr="--uniform %f %f",), - var_fwhm=dict(argstr="--var-fwhm %f",), - vox_dump=dict(argstr="--voxdump %d %d %d",), - weight_file=dict(extensions=None, xor=["weighted_ls"],), - weight_inv=dict(argstr="--w-inv", xor=["weighted_ls"],), - weight_sqrt=dict(argstr="--w-sqrt", xor=["weighted_ls"],), + surf=dict( + argstr="--surf %s %s %s", + requires=["subject_id", "hemi"], + ), + surf_geo=dict( + usedefault=True, + ), + synth=dict( + argstr="--synth", + ), + uniform=dict( + argstr="--uniform %f %f", + ), + var_fwhm=dict( + argstr="--var-fwhm %f", + ), + vox_dump=dict( + argstr="--voxdump %d %d %d", + ), + weight_file=dict( + extensions=None, + xor=["weighted_ls"], + ), + weight_inv=dict( + argstr="--w-inv", + xor=["weighted_ls"], + ), + weight_sqrt=dict( + argstr="--w-sqrt", + xor=["weighted_ls"], + ), weighted_ls=dict( argstr="--wls %s", extensions=None, @@ -81,23 +228,53 @@ def test_OneSampleTTest_inputs(): def test_OneSampleTTest_outputs(): output_map = dict( - beta_file=dict(extensions=None,), - dof_file=dict(extensions=None,), - error_file=dict(extensions=None,), - error_stddev_file=dict(extensions=None,), - error_var_file=dict(extensions=None,), - estimate_file=dict(extensions=None,), - frame_eigenvectors=dict(extensions=None,), + beta_file=dict( + extensions=None, + ), + bp_file=dict( + extensions=None, + ), + dof_file=dict( + extensions=None, + ), + error_file=dict( + extensions=None, + ), + error_stddev_file=dict( + extensions=None, + ), + error_var_file=dict( + extensions=None, + ), + estimate_file=dict( + extensions=None, + ), + frame_eigenvectors=dict( + extensions=None, + ), ftest_file=dict(), - fwhm_file=dict(extensions=None,), + fwhm_file=dict( + extensions=None, + ), gamma_file=dict(), gamma_var_file=dict(), glm_dir=dict(), - mask_file=dict(extensions=None,), + k2p_file=dict( + extensions=None, + ), + mask_file=dict( + extensions=None, + ), sig_file=dict(), - singular_values=dict(extensions=None,), - spatial_eigenvectors=dict(extensions=None,), - svd_stats_file=dict(extensions=None,), + singular_values=dict( + extensions=None, + ), + spatial_eigenvectors=dict( + extensions=None, + ), + svd_stats_file=dict( + extensions=None, + ), ) outputs = OneSampleTTest.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Paint.py b/nipype/interfaces/freesurfer/tests/test_auto_Paint.py index 0a93abec78..d95c4c9fa3 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Paint.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Paint.py @@ -4,10 +4,22 @@ def test_Paint_inputs(): input_map = dict( - args=dict(argstr="%s",), - averages=dict(argstr="-a %d",), - environ=dict(nohash=True, usedefault=True,), - in_surf=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + averages=dict( + argstr="-a %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_surf=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), out_file=dict( argstr="%s", extensions=None, @@ -18,7 +30,12 @@ def test_Paint_inputs(): position=-1, ), subjects_dir=dict(), - template=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), + template=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), template_param=dict(), ) inputs = Paint.input_spec() @@ -29,7 +46,11 @@ def test_Paint_inputs(): def test_Paint_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Paint.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ParcellationStats.py b/nipype/interfaces/freesurfer/tests/test_auto_ParcellationStats.py index cf42abe8b6..e1632020b5 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ParcellationStats.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ParcellationStats.py @@ -4,38 +4,109 @@ def test_ParcellationStats_inputs(): input_map = dict( - args=dict(argstr="%s",), - aseg=dict(extensions=None, mandatory=True,), - brainmask=dict(extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + aseg=dict( + extensions=None, + mandatory=True, + ), + brainmask=dict( + extensions=None, + mandatory=True, + ), copy_inputs=dict(), - cortex_label=dict(extensions=None,), - environ=dict(nohash=True, usedefault=True,), - hemisphere=dict(argstr="%s", mandatory=True, position=-2,), - in_annotation=dict(argstr="-a %s", extensions=None, xor=["in_label"],), - in_cortex=dict(argstr="-cortex %s", extensions=None,), + cortex_label=dict( + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemisphere=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + in_annotation=dict( + argstr="-a %s", + extensions=None, + xor=["in_label"], + ), + in_cortex=dict( + argstr="-cortex %s", + extensions=None, + ), in_label=dict( - argstr="-l %s", extensions=None, xor=["in_annotatoin", "out_color"], + argstr="-l %s", + extensions=None, + xor=["in_annotatoin", "out_color"], + ), + lh_pial=dict( + extensions=None, + mandatory=True, + ), + lh_white=dict( + extensions=None, + mandatory=True, + ), + mgz=dict( + argstr="-mgz", ), - lh_pial=dict(extensions=None, mandatory=True,), - lh_white=dict(extensions=None, mandatory=True,), - mgz=dict(argstr="-mgz",), out_color=dict( - argstr="-c %s", extensions=None, genfile=True, xor=["in_label"], + argstr="-c %s", + extensions=None, + genfile=True, + xor=["in_label"], ), out_table=dict( - argstr="-f %s", extensions=None, genfile=True, requires=["tabular_output"], + argstr="-f %s", + extensions=None, + genfile=True, + requires=["tabular_output"], + ), + rh_pial=dict( + extensions=None, + mandatory=True, + ), + rh_white=dict( + extensions=None, + mandatory=True, + ), + ribbon=dict( + extensions=None, + mandatory=True, + ), + subject_id=dict( + argstr="%s", + mandatory=True, + position=-3, + usedefault=True, ), - rh_pial=dict(extensions=None, mandatory=True,), - rh_white=dict(extensions=None, mandatory=True,), - ribbon=dict(extensions=None, mandatory=True,), - subject_id=dict(argstr="%s", mandatory=True, position=-3, usedefault=True,), subjects_dir=dict(), - surface=dict(argstr="%s", position=-1,), - tabular_output=dict(argstr="-b",), - th3=dict(argstr="-th3", requires=["cortex_label"],), - thickness=dict(extensions=None, mandatory=True,), - transform=dict(extensions=None, mandatory=True,), - wm=dict(extensions=None, mandatory=True,), + surface=dict( + argstr="%s", + position=-1, + ), + tabular_output=dict( + argstr="-b", + ), + th3=dict( + argstr="-th3", + requires=["cortex_label"], + ), + thickness=dict( + extensions=None, + mandatory=True, + ), + transform=dict( + extensions=None, + mandatory=True, + ), + wm=dict( + extensions=None, + mandatory=True, + ), ) inputs = ParcellationStats.input_spec() @@ -46,7 +117,12 @@ def test_ParcellationStats_inputs(): def test_ParcellationStats_outputs(): output_map = dict( - out_color=dict(extensions=None,), out_table=dict(extensions=None,), + out_color=dict( + extensions=None, + ), + out_table=dict( + extensions=None, + ), ) outputs = ParcellationStats.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ParseDICOMDir.py b/nipype/interfaces/freesurfer/tests/test_auto_ParseDICOMDir.py index 243e769266..3168ac64ec 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ParseDICOMDir.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ParseDICOMDir.py @@ -4,13 +4,29 @@ def test_ParseDICOMDir_inputs(): input_map = dict( - args=dict(argstr="%s",), - dicom_dir=dict(argstr="--d %s", mandatory=True,), - dicom_info_file=dict(argstr="--o %s", extensions=None, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - sortbyrun=dict(argstr="--sortbyrun",), + args=dict( + argstr="%s", + ), + dicom_dir=dict( + argstr="--d %s", + mandatory=True, + ), + dicom_info_file=dict( + argstr="--o %s", + extensions=None, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + sortbyrun=dict( + argstr="--sortbyrun", + ), subjects_dir=dict(), - summarize=dict(argstr="--summarize",), + summarize=dict( + argstr="--summarize", + ), ) inputs = ParseDICOMDir.input_spec() @@ -20,7 +36,11 @@ def test_ParseDICOMDir_inputs(): def test_ParseDICOMDir_outputs(): - output_map = dict(dicom_info_file=dict(extensions=None,),) + output_map = dict( + dicom_info_file=dict( + extensions=None, + ), + ) outputs = ParseDICOMDir.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_ReconAll.py b/nipype/interfaces/freesurfer/tests/test_auto_ReconAll.py index 29a9f0006b..f31bdb89f4 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_ReconAll.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_ReconAll.py @@ -4,58 +4,194 @@ def test_ReconAll_inputs(): input_map = dict( - FLAIR_file=dict(argstr="-FLAIR %s", extensions=None, min_ver="5.3.0",), - T1_files=dict(argstr="-i %s...",), - T2_file=dict(argstr="-T2 %s", extensions=None, min_ver="5.3.0",), - args=dict(argstr="%s",), - big_ventricles=dict(argstr="-bigventricles",), - brainstem=dict(argstr="-brainstem-structures",), - directive=dict(argstr="-%s", position=0, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - expert=dict(argstr="-expert %s", extensions=None,), - flags=dict(argstr="%s",), - hemi=dict(argstr="-hemi %s",), + FLAIR_file=dict( + argstr="-FLAIR %s", + extensions=None, + min_ver="5.3.0", + requires=["subject_id"], + ), + T1_files=dict( + argstr="-i %s...", + requires=["subject_id"], + ), + T2_file=dict( + argstr="-T2 %s", + extensions=None, + min_ver="5.3.0", + requires=["subject_id"], + ), + args=dict( + argstr="%s", + ), + base_template_id=dict( + argstr="-base %s", + requires=["base_timepoint_ids"], + xor=["subject_id", "longitudinal_timepoint_id"], + ), + base_timepoint_ids=dict( + argstr="-base-tp %s...", + ), + big_ventricles=dict( + argstr="-bigventricles", + ), + brainstem=dict( + argstr="-brainstem-structures", + requires=["subject_id"], + ), + directive=dict( + argstr="-%s", + position=0, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expert=dict( + argstr="-expert %s", + extensions=None, + ), + flags=dict( + argstr="%s", + ), + hemi=dict( + argstr="-hemi %s", + requires=["subject_id"], + ), hippocampal_subfields_T1=dict( - argstr="-hippocampal-subfields-T1", min_ver="6.0.0", + argstr="-hippocampal-subfields-T1", + min_ver="6.0.0", + requires=["subject_id"], ), hippocampal_subfields_T2=dict( - argstr="-hippocampal-subfields-T2 %s %s", min_ver="6.0.0", - ), - hires=dict(argstr="-hires", min_ver="6.0.0",), - mprage=dict(argstr="-mprage",), - mri_aparc2aseg=dict(xor=["expert"],), - mri_ca_label=dict(xor=["expert"],), - mri_ca_normalize=dict(xor=["expert"],), - mri_ca_register=dict(xor=["expert"],), - mri_edit_wm_with_aseg=dict(xor=["expert"],), - mri_em_register=dict(xor=["expert"],), - mri_fill=dict(xor=["expert"],), - mri_mask=dict(xor=["expert"],), - mri_normalize=dict(xor=["expert"],), - mri_pretess=dict(xor=["expert"],), - mri_remove_neck=dict(xor=["expert"],), - mri_segment=dict(xor=["expert"],), - mri_segstats=dict(xor=["expert"],), - mri_tessellate=dict(xor=["expert"],), - mri_watershed=dict(xor=["expert"],), - mris_anatomical_stats=dict(xor=["expert"],), - mris_ca_label=dict(xor=["expert"],), - mris_fix_topology=dict(xor=["expert"],), - mris_inflate=dict(xor=["expert"],), - mris_make_surfaces=dict(xor=["expert"],), - mris_register=dict(xor=["expert"],), - mris_smooth=dict(xor=["expert"],), - mris_sphere=dict(xor=["expert"],), - mris_surf2vol=dict(xor=["expert"],), - mrisp_paint=dict(xor=["expert"],), - openmp=dict(argstr="-openmp %d",), - parallel=dict(argstr="-parallel",), - subject_id=dict(argstr="-subjid %s", usedefault=True,), - subjects_dir=dict(argstr="-sd %s", genfile=True, hash_files=False,), - talairach=dict(xor=["expert"],), - use_FLAIR=dict(argstr="-FLAIRpial", min_ver="5.3.0", xor=["use_T2"],), - use_T2=dict(argstr="-T2pial", min_ver="5.3.0", xor=["use_FLAIR"],), - xopts=dict(argstr="-xopts-%s",), + argstr="-hippocampal-subfields-T2 %s %s", + min_ver="6.0.0", + requires=["subject_id"], + ), + hires=dict( + argstr="-hires", + min_ver="6.0.0", + ), + longitudinal_template_id=dict( + argstr="%s", + position=2, + ), + longitudinal_timepoint_id=dict( + argstr="-long %s", + position=1, + requires=["longitudinal_template_id"], + xor=["subject_id", "base_template_id"], + ), + mprage=dict( + argstr="-mprage", + requires=["subject_id"], + ), + mri_aparc2aseg=dict( + xor=["expert"], + ), + mri_ca_label=dict( + xor=["expert"], + ), + mri_ca_normalize=dict( + xor=["expert"], + ), + mri_ca_register=dict( + xor=["expert"], + ), + mri_edit_wm_with_aseg=dict( + xor=["expert"], + ), + mri_em_register=dict( + xor=["expert"], + ), + mri_fill=dict( + xor=["expert"], + ), + mri_mask=dict( + xor=["expert"], + ), + mri_normalize=dict( + xor=["expert"], + ), + mri_pretess=dict( + xor=["expert"], + ), + mri_remove_neck=dict( + xor=["expert"], + ), + mri_segment=dict( + xor=["expert"], + ), + mri_segstats=dict( + xor=["expert"], + ), + mri_tessellate=dict( + xor=["expert"], + ), + mri_watershed=dict( + xor=["expert"], + ), + mris_anatomical_stats=dict( + xor=["expert"], + ), + mris_ca_label=dict( + xor=["expert"], + ), + mris_fix_topology=dict( + xor=["expert"], + ), + mris_inflate=dict( + xor=["expert"], + ), + mris_make_surfaces=dict( + xor=["expert"], + ), + mris_register=dict( + xor=["expert"], + ), + mris_smooth=dict( + xor=["expert"], + ), + mris_sphere=dict( + xor=["expert"], + ), + mris_surf2vol=dict( + xor=["expert"], + ), + mrisp_paint=dict( + xor=["expert"], + ), + openmp=dict( + argstr="-openmp %d", + ), + parallel=dict( + argstr="-parallel", + ), + subject_id=dict( + argstr="-subjid %s", + xor=["base_template_id", "longitudinal_timepoint_id"], + ), + subjects_dir=dict( + argstr="-sd %s", + genfile=True, + hash_files=False, + ), + talairach=dict( + xor=["expert"], + ), + use_FLAIR=dict( + argstr="-FLAIRpial", + min_ver="5.3.0", + xor=["use_T2"], + ), + use_T2=dict( + argstr="-T2pial", + min_ver="5.3.0", + xor=["use_FLAIR"], + ), + xopts=dict( + argstr="-xopts-%s", + ), ) inputs = ReconAll.input_spec() @@ -66,45 +202,145 @@ def test_ReconAll_inputs(): def test_ReconAll_outputs(): output_map = dict( - BA_stats=dict(altkey="BA", loc="stats",), - T1=dict(extensions=None, loc="mri",), - annot=dict(altkey="*annot", loc="label",), - aparc_a2009s_stats=dict(altkey="aparc.a2009s", loc="stats",), - aparc_aseg=dict(altkey="aparc*aseg", loc="mri",), - aparc_stats=dict(altkey="aparc", loc="stats",), - area_pial=dict(altkey="area.pial", loc="surf",), - aseg=dict(extensions=None, loc="mri",), - aseg_stats=dict(altkey="aseg", loc="stats",), - avg_curv=dict(loc="surf",), - brain=dict(extensions=None, loc="mri",), - brainmask=dict(extensions=None, loc="mri",), - curv=dict(loc="surf",), - curv_pial=dict(altkey="curv.pial", loc="surf",), - curv_stats=dict(altkey="curv", loc="stats",), - entorhinal_exvivo_stats=dict(altkey="entorhinal_exvivo", loc="stats",), - filled=dict(extensions=None, loc="mri",), - graymid=dict(altkey=["graymid", "midthickness"], loc="surf",), - inflated=dict(loc="surf",), - jacobian_white=dict(loc="surf",), - label=dict(altkey="*label", loc="label",), - norm=dict(extensions=None, loc="mri",), - nu=dict(extensions=None, loc="mri",), - orig=dict(extensions=None, loc="mri",), - pial=dict(loc="surf",), - rawavg=dict(extensions=None, loc="mri",), - ribbon=dict(altkey="*ribbon", loc="mri",), - smoothwm=dict(loc="surf",), - sphere=dict(loc="surf",), - sphere_reg=dict(altkey="sphere.reg", loc="surf",), + BA_stats=dict( + altkey="BA", + loc="stats", + ), + T1=dict( + extensions=None, + loc="mri", + ), + annot=dict( + altkey="*annot", + loc="label", + ), + aparc_a2009s_stats=dict( + altkey="aparc.a2009s", + loc="stats", + ), + aparc_aseg=dict( + altkey="aparc*aseg", + loc="mri", + ), + aparc_stats=dict( + altkey="aparc", + loc="stats", + ), + area_pial=dict( + altkey="area.pial", + loc="surf", + ), + aseg=dict( + extensions=None, + loc="mri", + ), + aseg_stats=dict( + altkey="aseg", + loc="stats", + ), + avg_curv=dict( + loc="surf", + ), + brain=dict( + extensions=None, + loc="mri", + ), + brainmask=dict( + extensions=None, + loc="mri", + ), + curv=dict( + loc="surf", + ), + curv_pial=dict( + altkey="curv.pial", + loc="surf", + ), + curv_stats=dict( + altkey="curv", + loc="stats", + ), + entorhinal_exvivo_stats=dict( + altkey="entorhinal_exvivo", + loc="stats", + ), + filled=dict( + extensions=None, + loc="mri", + ), + graymid=dict( + altkey=["graymid", "midthickness"], + loc="surf", + ), + inflated=dict( + loc="surf", + ), + jacobian_white=dict( + loc="surf", + ), + label=dict( + altkey="*label", + loc="label", + ), + norm=dict( + extensions=None, + loc="mri", + ), + nu=dict( + extensions=None, + loc="mri", + ), + orig=dict( + extensions=None, + loc="mri", + ), + pial=dict( + loc="surf", + ), + rawavg=dict( + extensions=None, + loc="mri", + ), + ribbon=dict( + altkey="*ribbon", + loc="mri", + ), + smoothwm=dict( + loc="surf", + ), + sphere=dict( + loc="surf", + ), + sphere_reg=dict( + altkey="sphere.reg", + loc="surf", + ), subject_id=dict(), subjects_dir=dict(), - sulc=dict(loc="surf",), - thickness=dict(loc="surf",), - volume=dict(loc="surf",), - white=dict(loc="surf",), - wm=dict(extensions=None, loc="mri",), - wmparc=dict(extensions=None, loc="mri",), - wmparc_stats=dict(altkey="wmparc", loc="stats",), + sulc=dict( + loc="surf", + ), + thickness=dict( + loc="surf", + ), + volume=dict( + loc="surf", + ), + white=dict( + loc="surf", + ), + wm=dict( + extensions=None, + loc="mri", + ), + wmparc=dict( + extensions=None, + loc="mri", + ), + wmparc_stats=dict( + altkey="wmparc", + loc="stats", + ), ) outputs = ReconAll.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Register.py b/nipype/interfaces/freesurfer/tests/test_auto_Register.py index d2add3db5b..c10daabd58 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Register.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Register.py @@ -4,17 +4,46 @@ def test_Register_inputs(): input_map = dict( - args=dict(argstr="%s",), - curv=dict(argstr="-curv", requires=["in_smoothwm"],), - environ=dict(nohash=True, usedefault=True,), - in_smoothwm=dict(copyfile=True, extensions=None,), - in_sulc=dict(copyfile=True, extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + curv=dict( + argstr="-curv", + requires=["in_smoothwm"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_smoothwm=dict( + copyfile=True, + extensions=None, + ), + in_sulc=dict( + copyfile=True, + extensions=None, + mandatory=True, + ), in_surf=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=-3, + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=-3, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, ), - out_file=dict(argstr="%s", extensions=None, genfile=True, position=-1,), subjects_dir=dict(), - target=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + target=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), ) inputs = Register.input_spec() @@ -24,7 +53,11 @@ def test_Register_inputs(): def test_Register_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Register.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RegisterAVItoTalairach.py b/nipype/interfaces/freesurfer/tests/test_auto_RegisterAVItoTalairach.py index 39a7e754bb..f66ac1bda7 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RegisterAVItoTalairach.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RegisterAVItoTalairach.py @@ -4,13 +4,38 @@ def test_RegisterAVItoTalairach_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), - out_file=dict(argstr="%s", extensions=None, position=3, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + out_file=dict( + argstr="%s", + extensions=None, + position=3, + usedefault=True, + ), subjects_dir=dict(), - target=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - vox2vox=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + target=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + vox2vox=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), ) inputs = RegisterAVItoTalairach.input_spec() @@ -21,8 +46,13 @@ def test_RegisterAVItoTalairach_inputs(): def test_RegisterAVItoTalairach_outputs(): output_map = dict( - log_file=dict(extensions=None, usedefault=True,), - out_file=dict(extensions=None,), + log_file=dict( + extensions=None, + usedefault=True, + ), + out_file=dict( + extensions=None, + ), ) outputs = RegisterAVItoTalairach.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RelabelHypointensities.py b/nipype/interfaces/freesurfer/tests/test_auto_RelabelHypointensities.py index fd459f14a7..eeac74f722 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RelabelHypointensities.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RelabelHypointensities.py @@ -4,10 +4,24 @@ def test_RelabelHypointensities_inputs(): input_map = dict( - args=dict(argstr="%s",), - aseg=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - environ=dict(nohash=True, usedefault=True,), - lh_white=dict(copyfile=True, extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + aseg=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + lh_white=dict( + copyfile=True, + extensions=None, + mandatory=True, + ), out_file=dict( argstr="%s", extensions=None, @@ -17,9 +31,17 @@ def test_RelabelHypointensities_inputs(): name_template="%s.hypos.mgz", position=-1, ), - rh_white=dict(copyfile=True, extensions=None, mandatory=True,), + rh_white=dict( + copyfile=True, + extensions=None, + mandatory=True, + ), subjects_dir=dict(), - surf_directory=dict(argstr="%s", position=-2, usedefault=True,), + surf_directory=dict( + argstr="%s", + position=-2, + usedefault=True, + ), ) inputs = RelabelHypointensities.input_spec() @@ -29,7 +51,12 @@ def test_RelabelHypointensities_inputs(): def test_RelabelHypointensities_outputs(): - output_map = dict(out_file=dict(argstr="%s", extensions=None,),) + output_map = dict( + out_file=dict( + argstr="%s", + extensions=None, + ), + ) outputs = RelabelHypointensities.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RemoveIntersection.py b/nipype/interfaces/freesurfer/tests/test_auto_RemoveIntersection.py index d94124a82b..735ea7b84a 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RemoveIntersection.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RemoveIntersection.py @@ -4,10 +4,19 @@ def test_RemoveIntersection_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=-2, ), out_file=dict( argstr="%s", @@ -28,7 +37,11 @@ def test_RemoveIntersection_inputs(): def test_RemoveIntersection_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = RemoveIntersection.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RemoveNeck.py b/nipype/interfaces/freesurfer/tests/test_auto_RemoveNeck.py index 4050db776b..3d2ce30cbd 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RemoveNeck.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RemoveNeck.py @@ -4,9 +4,19 @@ def test_RemoveNeck_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-4,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-4, + ), out_file=dict( argstr="%s", extensions=None, @@ -16,10 +26,22 @@ def test_RemoveNeck_inputs(): name_template="%s_noneck", position=-1, ), - radius=dict(argstr="-radius %d",), + radius=dict( + argstr="-radius %d", + ), subjects_dir=dict(), - template=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - transform=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), + template=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + transform=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), ) inputs = RemoveNeck.input_spec() @@ -29,7 +51,11 @@ def test_RemoveNeck_inputs(): def test_RemoveNeck_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = RemoveNeck.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Resample.py b/nipype/interfaces/freesurfer/tests/test_auto_Resample.py index 0dccad303c..280a8a4cc1 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Resample.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Resample.py @@ -4,14 +4,30 @@ def test_Resample_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=-2, + ), resampled_file=dict( - argstr="-o %s", extensions=None, genfile=True, position=-1, + argstr="-o %s", + extensions=None, + genfile=True, + position=-1, ), subjects_dir=dict(), - voxel_size=dict(argstr="-vs %.2f %.2f %.2f", mandatory=True,), + voxel_size=dict( + argstr="-vs %.2f %.2f %.2f", + mandatory=True, + ), ) inputs = Resample.input_spec() @@ -21,7 +37,11 @@ def test_Resample_inputs(): def test_Resample_outputs(): - output_map = dict(resampled_file=dict(extensions=None,),) + output_map = dict( + resampled_file=dict( + extensions=None, + ), + ) outputs = Resample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RobustRegister.py b/nipype/interfaces/freesurfer/tests/test_auto_RobustRegister.py index 7dde230eb7..3f7e1b96a0 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RobustRegister.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RobustRegister.py @@ -4,38 +4,113 @@ def test_RobustRegister_inputs(): input_map = dict( - args=dict(argstr="%s",), - auto_sens=dict(argstr="--satit", mandatory=True, xor=["outlier_sens"],), - environ=dict(nohash=True, usedefault=True,), - est_int_scale=dict(argstr="--iscale",), - force_double=dict(argstr="--doubleprec",), - force_float=dict(argstr="--floattype",), - half_source=dict(argstr="--halfmov %s",), - half_source_xfm=dict(argstr="--halfmovlta %s",), - half_targ=dict(argstr="--halfdst %s",), - half_targ_xfm=dict(argstr="--halfdstlta %s",), - half_weights=dict(argstr="--halfweights %s",), - high_iterations=dict(argstr="--highit %d",), - in_xfm_file=dict(argstr="--transform", extensions=None,), - init_orient=dict(argstr="--initorient",), - iteration_thresh=dict(argstr="--epsit %.3f",), - least_squares=dict(argstr="--leastsquares",), - mask_source=dict(argstr="--maskmov %s", extensions=None,), - mask_target=dict(argstr="--maskdst %s", extensions=None,), - max_iterations=dict(argstr="--maxit %d",), - no_init=dict(argstr="--noinit",), - no_multi=dict(argstr="--nomulti",), - out_reg_file=dict(argstr="--lta %s", usedefault=True,), - outlier_limit=dict(argstr="--wlimit %.3f",), - outlier_sens=dict(argstr="--sat %.4f", mandatory=True, xor=["auto_sens"],), - registered_file=dict(argstr="--warp %s",), - source_file=dict(argstr="--mov %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + auto_sens=dict( + argstr="--satit", + mandatory=True, + xor=["outlier_sens"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + est_int_scale=dict( + argstr="--iscale", + ), + force_double=dict( + argstr="--doubleprec", + ), + force_float=dict( + argstr="--floattype", + ), + half_source=dict( + argstr="--halfmov %s", + ), + half_source_xfm=dict( + argstr="--halfmovlta %s", + ), + half_targ=dict( + argstr="--halfdst %s", + ), + half_targ_xfm=dict( + argstr="--halfdstlta %s", + ), + half_weights=dict( + argstr="--halfweights %s", + ), + high_iterations=dict( + argstr="--highit %d", + ), + in_xfm_file=dict( + argstr="--transform", + extensions=None, + ), + init_orient=dict( + argstr="--initorient", + ), + iteration_thresh=dict( + argstr="--epsit %.3f", + ), + least_squares=dict( + argstr="--leastsquares", + ), + mask_source=dict( + argstr="--maskmov %s", + extensions=None, + ), + mask_target=dict( + argstr="--maskdst %s", + extensions=None, + ), + max_iterations=dict( + argstr="--maxit %d", + ), + no_init=dict( + argstr="--noinit", + ), + no_multi=dict( + argstr="--nomulti", + ), + out_reg_file=dict( + argstr="--lta %s", + usedefault=True, + ), + outlier_limit=dict( + argstr="--wlimit %.3f", + ), + outlier_sens=dict( + argstr="--sat %.4f", + mandatory=True, + xor=["auto_sens"], + ), + registered_file=dict( + argstr="--warp %s", + ), + source_file=dict( + argstr="--mov %s", + extensions=None, + mandatory=True, + ), subjects_dir=dict(), - subsample_thresh=dict(argstr="--subsample %d",), - target_file=dict(argstr="--dst %s", extensions=None, mandatory=True,), - trans_only=dict(argstr="--transonly",), - weights_file=dict(argstr="--weights %s",), - write_vo2vox=dict(argstr="--vox2vox",), + subsample_thresh=dict( + argstr="--subsample %d", + ), + target_file=dict( + argstr="--dst %s", + extensions=None, + mandatory=True, + ), + trans_only=dict( + argstr="--transonly", + ), + weights_file=dict( + argstr="--weights %s", + ), + write_vo2vox=dict( + argstr="--vox2vox", + ), ) inputs = RobustRegister.input_spec() @@ -46,14 +121,30 @@ def test_RobustRegister_inputs(): def test_RobustRegister_outputs(): output_map = dict( - half_source=dict(extensions=None,), - half_source_xfm=dict(extensions=None,), - half_targ=dict(extensions=None,), - half_targ_xfm=dict(extensions=None,), - half_weights=dict(extensions=None,), - out_reg_file=dict(extensions=None,), - registered_file=dict(extensions=None,), - weights_file=dict(extensions=None,), + half_source=dict( + extensions=None, + ), + half_source_xfm=dict( + extensions=None, + ), + half_targ=dict( + extensions=None, + ), + half_targ_xfm=dict( + extensions=None, + ), + half_weights=dict( + extensions=None, + ), + out_reg_file=dict( + extensions=None, + ), + registered_file=dict( + extensions=None, + ), + weights_file=dict( + extensions=None, + ), ) outputs = RobustRegister.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_RobustTemplate.py b/nipype/interfaces/freesurfer/tests/test_auto_RobustTemplate.py index 3ee33a567e..8c180332db 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_RobustTemplate.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_RobustTemplate.py @@ -4,30 +4,65 @@ def test_RobustTemplate_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), auto_detect_sensitivity=dict( - argstr="--satit", mandatory=True, xor=["outlier_sensitivity"], - ), - average_metric=dict(argstr="--average %d",), - environ=dict(nohash=True, usedefault=True,), - fixed_timepoint=dict(argstr="--fixtp",), - in_files=dict(argstr="--mov %s", mandatory=True,), - in_intensity_scales=dict(argstr="--iscalein %s",), - initial_timepoint=dict(argstr="--inittp %d",), - initial_transforms=dict(argstr="--ixforms %s",), - intensity_scaling=dict(argstr="--iscale",), - no_iteration=dict(argstr="--noit",), + argstr="--satit", + mandatory=True, + xor=["outlier_sensitivity"], + ), + average_metric=dict( + argstr="--average %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_timepoint=dict( + argstr="--fixtp", + ), + in_files=dict( + argstr="--mov %s", + mandatory=True, + ), + in_intensity_scales=dict( + argstr="--iscalein %s", + ), + initial_timepoint=dict( + argstr="--inittp %d", + ), + initial_transforms=dict( + argstr="--ixforms %s", + ), + intensity_scaling=dict( + argstr="--iscale", + ), + no_iteration=dict( + argstr="--noit", + ), num_threads=dict(), out_file=dict( - argstr="--template %s", extensions=None, mandatory=True, usedefault=True, + argstr="--template %s", + extensions=None, + mandatory=True, + usedefault=True, ), outlier_sensitivity=dict( - argstr="--sat %.4f", mandatory=True, xor=["auto_detect_sensitivity"], + argstr="--sat %.4f", + mandatory=True, + xor=["auto_detect_sensitivity"], + ), + scaled_intensity_outputs=dict( + argstr="--iscaleout %s", ), - scaled_intensity_outputs=dict(argstr="--iscaleout %s",), subjects_dir=dict(), - subsample_threshold=dict(argstr="--subsample %d",), - transform_outputs=dict(argstr="--lta %s",), + subsample_threshold=dict( + argstr="--subsample %d", + ), + transform_outputs=dict( + argstr="--lta %s", + ), ) inputs = RobustTemplate.input_spec() @@ -38,7 +73,9 @@ def test_RobustTemplate_inputs(): def test_RobustTemplate_outputs(): output_map = dict( - out_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), scaled_intensity_outputs=dict(), transform_outputs=dict(), ) diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SampleToSurface.py b/nipype/interfaces/freesurfer/tests/test_auto_SampleToSurface.py index 67cc1fd244..de9ffe2485 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SampleToSurface.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SampleToSurface.py @@ -4,31 +4,83 @@ def test_SampleToSurface_inputs(): input_map = dict( - apply_rot=dict(argstr="--rot %.3f %.3f %.3f",), - apply_trans=dict(argstr="--trans %.3f %.3f %.3f",), - args=dict(argstr="%s",), - cortex_mask=dict(argstr="--cortex", xor=["mask_label"],), - environ=dict(nohash=True, usedefault=True,), - fix_tk_reg=dict(argstr="--fixtkreg",), - float2int_method=dict(argstr="--float2int %s",), - frame=dict(argstr="--frame %d",), - hemi=dict(argstr="--hemi %s", mandatory=True,), - hits_file=dict(argstr="--srchit %s",), - hits_type=dict(argstr="--srchit_type",), - ico_order=dict(argstr="--icoorder %d", requires=["target_subject"],), - interp_method=dict(argstr="--interp %s",), - mask_label=dict(argstr="--mask %s", extensions=None, xor=["cortex_mask"],), + apply_rot=dict( + argstr="--rot %.3f %.3f %.3f", + ), + apply_trans=dict( + argstr="--trans %.3f %.3f %.3f", + ), + args=dict( + argstr="%s", + ), + cortex_mask=dict( + argstr="--cortex", + xor=["mask_label"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fix_tk_reg=dict( + argstr="--fixtkreg", + ), + float2int_method=dict( + argstr="--float2int %s", + ), + frame=dict( + argstr="--frame %d", + ), + hemi=dict( + argstr="--hemi %s", + mandatory=True, + ), + hits_file=dict( + argstr="--srchit %s", + ), + hits_type=dict( + argstr="--srchit_type", + ), + ico_order=dict( + argstr="--icoorder %d", + requires=["target_subject"], + ), + interp_method=dict( + argstr="--interp %s", + ), + mask_label=dict( + argstr="--mask %s", + extensions=None, + xor=["cortex_mask"], + ), mni152reg=dict( argstr="--mni152reg", mandatory=True, xor=["reg_file", "reg_header", "mni152reg"], ), - no_reshape=dict(argstr="--noreshape", xor=["reshape"],), - out_file=dict(argstr="--o %s", extensions=None, genfile=True,), - out_type=dict(argstr="--out_type %s",), - override_reg_subj=dict(argstr="--srcsubject %s", requires=["subject_id"],), - projection_stem=dict(mandatory=True, xor=["sampling_method"],), - reference_file=dict(argstr="--ref %s", extensions=None,), + no_reshape=dict( + argstr="--noreshape", + xor=["reshape"], + ), + out_file=dict( + argstr="--o %s", + extensions=None, + genfile=True, + ), + out_type=dict( + argstr="--out_type %s", + ), + override_reg_subj=dict( + argstr="--srcsubject %s", + requires=["subject_id"], + ), + projection_stem=dict( + mandatory=True, + xor=["sampling_method"], + ), + reference_file=dict( + argstr="--ref %s", + extensions=None, + ), reg_file=dict( argstr="--reg %s", extensions=None, @@ -41,8 +93,13 @@ def test_SampleToSurface_inputs(): requires=["subject_id"], xor=["reg_file", "reg_header", "mni152reg"], ), - reshape=dict(argstr="--reshape", xor=["no_reshape"],), - reshape_slices=dict(argstr="--rf %d",), + reshape=dict( + argstr="--reshape", + xor=["no_reshape"], + ), + reshape_slices=dict( + argstr="--rf %d", + ), sampling_method=dict( argstr="%s", mandatory=True, @@ -51,16 +108,35 @@ def test_SampleToSurface_inputs(): ), sampling_range=dict(), sampling_units=dict(), - scale_input=dict(argstr="--scale %.3f",), - smooth_surf=dict(argstr="--surf-fwhm %.3f",), - smooth_vol=dict(argstr="--fwhm %.3f",), - source_file=dict(argstr="--mov %s", extensions=None, mandatory=True,), + scale_input=dict( + argstr="--scale %.3f", + ), + smooth_surf=dict( + argstr="--surf-fwhm %.3f", + ), + smooth_vol=dict( + argstr="--fwhm %.3f", + ), + source_file=dict( + argstr="--mov %s", + extensions=None, + mandatory=True, + ), subject_id=dict(), subjects_dir=dict(), - surf_reg=dict(argstr="--surfreg %s", requires=["target_subject"],), - surface=dict(argstr="--surf %s",), - target_subject=dict(argstr="--trgsubject %s",), - vox_file=dict(argstr="--nvox %s",), + surf_reg=dict( + argstr="--surfreg %s", + requires=["target_subject"], + ), + surface=dict( + argstr="--surf %s", + ), + target_subject=dict( + argstr="--trgsubject %s", + ), + vox_file=dict( + argstr="--nvox %s", + ), ) inputs = SampleToSurface.input_spec() @@ -71,9 +147,15 @@ def test_SampleToSurface_inputs(): def test_SampleToSurface_outputs(): output_map = dict( - hits_file=dict(extensions=None,), - out_file=dict(extensions=None,), - vox_file=dict(extensions=None,), + hits_file=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + vox_file=dict( + extensions=None, + ), ) outputs = SampleToSurface.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SegStats.py b/nipype/interfaces/freesurfer/tests/test_auto_SegStats.py index 5cb7321d50..dfb82e8b85 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SegStats.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SegStats.py @@ -9,72 +9,146 @@ def test_SegStats_inputs(): mandatory=True, xor=("segmentation_file", "annot", "surf_label"), ), - args=dict(argstr="%s",), - avgwf_file=dict(argstr="--avgwfvol %s",), - avgwf_txt_file=dict(argstr="--avgwf %s",), - brain_vol=dict(argstr="--%s",), - brainmask_file=dict(argstr="--brainmask %s", extensions=None,), - calc_power=dict(argstr="--%s",), - calc_snr=dict(argstr="--snr",), + args=dict( + argstr="%s", + ), + avgwf_file=dict( + argstr="--avgwfvol %s", + ), + avgwf_txt_file=dict( + argstr="--avgwf %s", + ), + brain_vol=dict( + argstr="--%s", + ), + brainmask_file=dict( + argstr="--brainmask %s", + extensions=None, + ), + calc_power=dict( + argstr="--%s", + ), + calc_snr=dict( + argstr="--snr", + ), color_table_file=dict( argstr="--ctab %s", extensions=None, xor=("color_table_file", "default_color_table", "gca_color_table"), ), - cortex_vol_from_surf=dict(argstr="--surf-ctx-vol",), + cortex_vol_from_surf=dict( + argstr="--surf-ctx-vol", + ), default_color_table=dict( argstr="--ctab-default", xor=("color_table_file", "default_color_table", "gca_color_table"), ), - empty=dict(argstr="--empty",), - environ=dict(nohash=True, usedefault=True,), - etiv=dict(argstr="--etiv",), + empty=dict( + argstr="--empty", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + etiv=dict( + argstr="--etiv", + ), etiv_only=dict(), - euler=dict(argstr="--euler",), - exclude_ctx_gm_wm=dict(argstr="--excl-ctxgmwm",), - exclude_id=dict(argstr="--excludeid %d",), - frame=dict(argstr="--frame %d",), + euler=dict( + argstr="--euler", + ), + exclude_ctx_gm_wm=dict( + argstr="--excl-ctxgmwm", + ), + exclude_id=dict( + argstr="--excludeid %d", + ), + frame=dict( + argstr="--frame %d", + ), gca_color_table=dict( argstr="--ctab-gca %s", extensions=None, xor=("color_table_file", "default_color_table", "gca_color_table"), ), - in_file=dict(argstr="--i %s", extensions=None,), - in_intensity=dict(argstr="--in %s --in-intensity-name %s", extensions=None,), + in_file=dict( + argstr="--i %s", + extensions=None, + ), + in_intensity=dict( + argstr="--in %s --in-intensity-name %s", + extensions=None, + ), intensity_units=dict( - argstr="--in-intensity-units %s", requires=["in_intensity"], + argstr="--in-intensity-units %s", + requires=["in_intensity"], + ), + mask_erode=dict( + argstr="--maskerode %d", + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + mask_frame=dict( + requires=["mask_file"], + ), + mask_invert=dict( + argstr="--maskinvert", ), - mask_erode=dict(argstr="--maskerode %d",), - mask_file=dict(argstr="--mask %s", extensions=None,), - mask_frame=dict(requires=["mask_file"],), - mask_invert=dict(argstr="--maskinvert",), mask_sign=dict(), - mask_thresh=dict(argstr="--maskthresh %f",), - multiply=dict(argstr="--mul %f",), - non_empty_only=dict(argstr="--nonempty",), - partial_volume_file=dict(argstr="--pv %s", extensions=None,), - segment_id=dict(argstr="--id %s...",), + mask_thresh=dict( + argstr="--maskthresh %f", + ), + multiply=dict( + argstr="--mul %f", + ), + non_empty_only=dict( + argstr="--nonempty", + ), + partial_volume_file=dict( + argstr="--pv %s", + extensions=None, + ), + segment_id=dict( + argstr="--id %s...", + ), segmentation_file=dict( argstr="--seg %s", extensions=None, mandatory=True, xor=("segmentation_file", "annot", "surf_label"), ), - sf_avg_file=dict(argstr="--sfavg %s",), - subcort_gm=dict(argstr="--subcortgray",), + sf_avg_file=dict( + argstr="--sfavg %s", + ), + subcort_gm=dict( + argstr="--subcortgray", + ), subjects_dir=dict(), summary_file=dict( - argstr="--sum %s", extensions=None, genfile=True, position=-1, + argstr="--sum %s", + extensions=None, + genfile=True, + position=-1, + ), + supratent=dict( + argstr="--supratent", ), - supratent=dict(argstr="--supratent",), surf_label=dict( argstr="--slabel %s %s %s", mandatory=True, xor=("segmentation_file", "annot", "surf_label"), ), - total_gray=dict(argstr="--totalgray",), - vox=dict(argstr="--vox %s",), - wm_vol_from_surf=dict(argstr="--surf-wm-vol",), + total_gray=dict( + argstr="--totalgray", + ), + vox=dict( + argstr="--vox %s", + ), + wm_vol_from_surf=dict( + argstr="--surf-wm-vol", + ), ) inputs = SegStats.input_spec() @@ -85,10 +159,18 @@ def test_SegStats_inputs(): def test_SegStats_outputs(): output_map = dict( - avgwf_file=dict(extensions=None,), - avgwf_txt_file=dict(extensions=None,), - sf_avg_file=dict(extensions=None,), - summary_file=dict(extensions=None,), + avgwf_file=dict( + extensions=None, + ), + avgwf_txt_file=dict( + extensions=None, + ), + sf_avg_file=dict( + extensions=None, + ), + summary_file=dict( + extensions=None, + ), ) outputs = SegStats.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SegStatsReconAll.py b/nipype/interfaces/freesurfer/tests/test_auto_SegStatsReconAll.py index 2301087a3b..0121dd7d9e 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SegStatsReconAll.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SegStatsReconAll.py @@ -9,84 +9,190 @@ def test_SegStatsReconAll_inputs(): mandatory=True, xor=("segmentation_file", "annot", "surf_label"), ), - args=dict(argstr="%s",), - aseg=dict(extensions=None,), - avgwf_file=dict(argstr="--avgwfvol %s",), - avgwf_txt_file=dict(argstr="--avgwf %s",), - brain_vol=dict(argstr="--%s",), - brainmask_file=dict(argstr="--brainmask %s", extensions=None,), - calc_power=dict(argstr="--%s",), - calc_snr=dict(argstr="--snr",), + args=dict( + argstr="%s", + ), + aseg=dict( + extensions=None, + ), + avgwf_file=dict( + argstr="--avgwfvol %s", + ), + avgwf_txt_file=dict( + argstr="--avgwf %s", + ), + brain_vol=dict( + argstr="--%s", + ), + brainmask_file=dict( + argstr="--brainmask %s", + extensions=None, + ), + calc_power=dict( + argstr="--%s", + ), + calc_snr=dict( + argstr="--snr", + ), color_table_file=dict( argstr="--ctab %s", extensions=None, xor=("color_table_file", "default_color_table", "gca_color_table"), ), copy_inputs=dict(), - cortex_vol_from_surf=dict(argstr="--surf-ctx-vol",), + cortex_vol_from_surf=dict( + argstr="--surf-ctx-vol", + ), default_color_table=dict( argstr="--ctab-default", xor=("color_table_file", "default_color_table", "gca_color_table"), ), - empty=dict(argstr="--empty",), - environ=dict(nohash=True, usedefault=True,), - etiv=dict(argstr="--etiv",), + empty=dict( + argstr="--empty", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + etiv=dict( + argstr="--etiv", + ), etiv_only=dict(), - euler=dict(argstr="--euler",), - exclude_ctx_gm_wm=dict(argstr="--excl-ctxgmwm",), - exclude_id=dict(argstr="--excludeid %d",), - frame=dict(argstr="--frame %d",), + euler=dict( + argstr="--euler", + ), + exclude_ctx_gm_wm=dict( + argstr="--excl-ctxgmwm", + ), + exclude_id=dict( + argstr="--excludeid %d", + ), + frame=dict( + argstr="--frame %d", + ), gca_color_table=dict( argstr="--ctab-gca %s", extensions=None, xor=("color_table_file", "default_color_table", "gca_color_table"), ), - in_file=dict(argstr="--i %s", extensions=None,), - in_intensity=dict(argstr="--in %s --in-intensity-name %s", extensions=None,), + in_file=dict( + argstr="--i %s", + extensions=None, + ), + in_intensity=dict( + argstr="--in %s --in-intensity-name %s", + extensions=None, + ), intensity_units=dict( - argstr="--in-intensity-units %s", requires=["in_intensity"], - ), - lh_orig_nofix=dict(extensions=None, mandatory=True,), - lh_pial=dict(extensions=None, mandatory=True,), - lh_white=dict(extensions=None, mandatory=True,), - mask_erode=dict(argstr="--maskerode %d",), - mask_file=dict(argstr="--mask %s", extensions=None,), - mask_frame=dict(requires=["mask_file"],), - mask_invert=dict(argstr="--maskinvert",), + argstr="--in-intensity-units %s", + requires=["in_intensity"], + ), + lh_orig_nofix=dict( + extensions=None, + mandatory=True, + ), + lh_pial=dict( + extensions=None, + mandatory=True, + ), + lh_white=dict( + extensions=None, + mandatory=True, + ), + mask_erode=dict( + argstr="--maskerode %d", + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + ), + mask_frame=dict( + requires=["mask_file"], + ), + mask_invert=dict( + argstr="--maskinvert", + ), mask_sign=dict(), - mask_thresh=dict(argstr="--maskthresh %f",), - multiply=dict(argstr="--mul %f",), - non_empty_only=dict(argstr="--nonempty",), - partial_volume_file=dict(argstr="--pv %s", extensions=None,), - presurf_seg=dict(extensions=None,), - rh_orig_nofix=dict(extensions=None, mandatory=True,), - rh_pial=dict(extensions=None, mandatory=True,), - rh_white=dict(extensions=None, mandatory=True,), - ribbon=dict(extensions=None, mandatory=True,), - segment_id=dict(argstr="--id %s...",), + mask_thresh=dict( + argstr="--maskthresh %f", + ), + multiply=dict( + argstr="--mul %f", + ), + non_empty_only=dict( + argstr="--nonempty", + ), + partial_volume_file=dict( + argstr="--pv %s", + extensions=None, + ), + presurf_seg=dict( + extensions=None, + ), + rh_orig_nofix=dict( + extensions=None, + mandatory=True, + ), + rh_pial=dict( + extensions=None, + mandatory=True, + ), + rh_white=dict( + extensions=None, + mandatory=True, + ), + ribbon=dict( + extensions=None, + mandatory=True, + ), + segment_id=dict( + argstr="--id %s...", + ), segmentation_file=dict( argstr="--seg %s", extensions=None, mandatory=True, xor=("segmentation_file", "annot", "surf_label"), ), - sf_avg_file=dict(argstr="--sfavg %s",), - subcort_gm=dict(argstr="--subcortgray",), - subject_id=dict(argstr="--subject %s", mandatory=True, usedefault=True,), + sf_avg_file=dict( + argstr="--sfavg %s", + ), + subcort_gm=dict( + argstr="--subcortgray", + ), + subject_id=dict( + argstr="--subject %s", + mandatory=True, + usedefault=True, + ), subjects_dir=dict(), summary_file=dict( - argstr="--sum %s", extensions=None, genfile=True, position=-1, + argstr="--sum %s", + extensions=None, + genfile=True, + position=-1, + ), + supratent=dict( + argstr="--supratent", ), - supratent=dict(argstr="--supratent",), surf_label=dict( argstr="--slabel %s %s %s", mandatory=True, xor=("segmentation_file", "annot", "surf_label"), ), - total_gray=dict(argstr="--totalgray",), - transform=dict(extensions=None, mandatory=True,), - vox=dict(argstr="--vox %s",), - wm_vol_from_surf=dict(argstr="--surf-wm-vol",), + total_gray=dict( + argstr="--totalgray", + ), + transform=dict( + extensions=None, + mandatory=True, + ), + vox=dict( + argstr="--vox %s", + ), + wm_vol_from_surf=dict( + argstr="--surf-wm-vol", + ), ) inputs = SegStatsReconAll.input_spec() @@ -97,10 +203,18 @@ def test_SegStatsReconAll_inputs(): def test_SegStatsReconAll_outputs(): output_map = dict( - avgwf_file=dict(extensions=None,), - avgwf_txt_file=dict(extensions=None,), - sf_avg_file=dict(extensions=None,), - summary_file=dict(extensions=None,), + avgwf_file=dict( + extensions=None, + ), + avgwf_txt_file=dict( + extensions=None, + ), + sf_avg_file=dict( + extensions=None, + ), + summary_file=dict( + extensions=None, + ), ) outputs = SegStatsReconAll.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SegmentCC.py b/nipype/interfaces/freesurfer/tests/test_auto_SegmentCC.py index 9343177c30..7c16a1f476 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SegmentCC.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SegmentCC.py @@ -4,11 +4,23 @@ def test_SegmentCC_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), copy_inputs=dict(), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-aseg %s", extensions=None, mandatory=True,), - in_norm=dict(extensions=None, mandatory=True,), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-aseg %s", + extensions=None, + mandatory=True, + ), + in_norm=dict( + extensions=None, + mandatory=True, + ), out_file=dict( argstr="-o %s", extensions=None, @@ -17,8 +29,17 @@ def test_SegmentCC_inputs(): name_source=["in_file"], name_template="%s.auto.mgz", ), - out_rotation=dict(argstr="-lta %s", extensions=None, mandatory=True,), - subject_id=dict(argstr="%s", mandatory=True, position=-1, usedefault=True,), + out_rotation=dict( + argstr="-lta %s", + extensions=None, + mandatory=True, + ), + subject_id=dict( + argstr="%s", + mandatory=True, + position=-1, + usedefault=True, + ), subjects_dir=dict(), ) inputs = SegmentCC.input_spec() @@ -30,7 +51,12 @@ def test_SegmentCC_inputs(): def test_SegmentCC_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_rotation=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_rotation=dict( + extensions=None, + ), ) outputs = SegmentCC.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SegmentWM.py b/nipype/interfaces/freesurfer/tests/test_auto_SegmentWM.py index 87f4af54c0..8aac066c26 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SegmentWM.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SegmentWM.py @@ -4,10 +4,25 @@ def test_SegmentWM_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - out_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), subjects_dir=dict(), ) inputs = SegmentWM.input_spec() @@ -18,7 +33,11 @@ def test_SegmentWM_inputs(): def test_SegmentWM_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SegmentWM.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Smooth.py b/nipype/interfaces/freesurfer/tests/test_auto_Smooth.py index bc180a00f6..e20de1c795 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Smooth.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Smooth.py @@ -4,14 +4,41 @@ def test_Smooth_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="--i %s", extensions=None, mandatory=True,), - num_iters=dict(argstr="--niters %d", mandatory=True, xor=["surface_fwhm"],), - proj_frac=dict(argstr="--projfrac %s", xor=["proj_frac_avg"],), - proj_frac_avg=dict(argstr="--projfrac-avg %.2f %.2f %.2f", xor=["proj_frac"],), - reg_file=dict(argstr="--reg %s", extensions=None, mandatory=True,), - smoothed_file=dict(argstr="--o %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="--i %s", + extensions=None, + mandatory=True, + ), + num_iters=dict( + argstr="--niters %d", + mandatory=True, + xor=["surface_fwhm"], + ), + proj_frac=dict( + argstr="--projfrac %s", + xor=["proj_frac_avg"], + ), + proj_frac_avg=dict( + argstr="--projfrac-avg %.2f %.2f %.2f", + xor=["proj_frac"], + ), + reg_file=dict( + argstr="--reg %s", + extensions=None, + mandatory=True, + ), + smoothed_file=dict( + argstr="--o %s", + extensions=None, + genfile=True, + ), subjects_dir=dict(), surface_fwhm=dict( argstr="--fwhm %f", @@ -19,7 +46,9 @@ def test_Smooth_inputs(): requires=["reg_file"], xor=["num_iters"], ), - vol_fwhm=dict(argstr="--vol-fwhm %f",), + vol_fwhm=dict( + argstr="--vol-fwhm %f", + ), ) inputs = Smooth.input_spec() @@ -29,7 +58,11 @@ def test_Smooth_inputs(): def test_Smooth_outputs(): - output_map = dict(smoothed_file=dict(extensions=None,),) + output_map = dict( + smoothed_file=dict( + extensions=None, + ), + ) outputs = Smooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SmoothTessellation.py b/nipype/interfaces/freesurfer/tests/test_auto_SmoothTessellation.py index 517a223432..5f97cc281b 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SmoothTessellation.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SmoothTessellation.py @@ -4,25 +4,65 @@ def test_SmoothTessellation_inputs(): input_map = dict( - args=dict(argstr="%s",), - curvature_averaging_iterations=dict(argstr="-a %d",), - disable_estimates=dict(argstr="-nw",), - environ=dict(nohash=True, usedefault=True,), - gaussian_curvature_norm_steps=dict(argstr="%d",), - gaussian_curvature_smoothing_steps=dict(argstr=" %d",), + args=dict( + argstr="%s", + ), + curvature_averaging_iterations=dict( + argstr="-a %d", + ), + disable_estimates=dict( + argstr="-nw", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gaussian_curvature_norm_steps=dict( + argstr="%d", + ), + gaussian_curvature_smoothing_steps=dict( + argstr=" %d", + ), in_file=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=-2, - ), - normalize_area=dict(argstr="-area",), - out_area_file=dict(argstr="-b %s", extensions=None,), - out_curvature_file=dict(argstr="-c %s", extensions=None,), - out_file=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - seed=dict(argstr="-seed %d",), - smoothing_iterations=dict(argstr="-n %d",), - snapshot_writing_iterations=dict(argstr="-w %d",), + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=-2, + ), + normalize_area=dict( + argstr="-area", + ), + out_area_file=dict( + argstr="-b %s", + extensions=None, + ), + out_curvature_file=dict( + argstr="-c %s", + extensions=None, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + seed=dict( + argstr="-seed %d", + ), + smoothing_iterations=dict( + argstr="-n %d", + ), + snapshot_writing_iterations=dict( + argstr="-w %d", + ), subjects_dir=dict(), - use_gaussian_curvature_smoothing=dict(argstr="-g",), - use_momentum=dict(argstr="-m",), + use_gaussian_curvature_smoothing=dict( + argstr="-g", + ), + use_momentum=dict( + argstr="-m", + ), ) inputs = SmoothTessellation.input_spec() @@ -32,7 +72,11 @@ def test_SmoothTessellation_inputs(): def test_SmoothTessellation_outputs(): - output_map = dict(surface=dict(extensions=None,),) + output_map = dict( + surface=dict( + extensions=None, + ), + ) outputs = SmoothTessellation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Sphere.py b/nipype/interfaces/freesurfer/tests/test_auto_Sphere.py index 407354fbfe..84673e2951 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Sphere.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Sphere.py @@ -4,13 +4,27 @@ def test_Sphere_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=True, extensions=None, mandatory=True, position=-2, + argstr="%s", + copyfile=True, + extensions=None, + mandatory=True, + position=-2, + ), + in_smoothwm=dict( + copyfile=True, + extensions=None, + ), + magic=dict( + argstr="-q", ), - in_smoothwm=dict(copyfile=True, extensions=None,), - magic=dict(argstr="-q",), num_threads=dict(), out_file=dict( argstr="%s", @@ -20,7 +34,9 @@ def test_Sphere_inputs(): name_template="%s.sphere", position=-1, ), - seed=dict(argstr="-seed %d",), + seed=dict( + argstr="-seed %d", + ), subjects_dir=dict(), ) inputs = Sphere.input_spec() @@ -31,7 +47,11 @@ def test_Sphere_inputs(): def test_Sphere_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Sphere.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SphericalAverage.py b/nipype/interfaces/freesurfer/tests/test_auto_SphericalAverage.py index 41c61ea0fa..73f5b3efd7 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SphericalAverage.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SphericalAverage.py @@ -4,19 +4,60 @@ def test_SphericalAverage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - erode=dict(argstr="-erode %d",), - fname=dict(argstr="%s", mandatory=True, position=-5,), - hemisphere=dict(argstr="%s", mandatory=True, position=-4,), - in_average=dict(argstr="%s", genfile=True, position=-2,), - in_orig=dict(argstr="-orig %s", extensions=None,), - in_surf=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - out_file=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - subject_id=dict(argstr="-o %s", mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + erode=dict( + argstr="-erode %d", + ), + fname=dict( + argstr="%s", + mandatory=True, + position=-5, + ), + hemisphere=dict( + argstr="%s", + mandatory=True, + position=-4, + ), + in_average=dict( + argstr="%s", + genfile=True, + position=-2, + ), + in_orig=dict( + argstr="-orig %s", + extensions=None, + ), + in_surf=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + subject_id=dict( + argstr="-o %s", + mandatory=True, + ), subjects_dir=dict(), - threshold=dict(argstr="-t %.1f",), - which=dict(argstr="%s", mandatory=True, position=-6,), + threshold=dict( + argstr="-t %.1f", + ), + which=dict( + argstr="%s", + mandatory=True, + position=-6, + ), ) inputs = SphericalAverage.input_spec() @@ -26,7 +67,11 @@ def test_SphericalAverage_inputs(): def test_SphericalAverage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SphericalAverage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Surface2VolTransform.py b/nipype/interfaces/freesurfer/tests/test_auto_Surface2VolTransform.py index c9e20a00b5..01dc354710 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Surface2VolTransform.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Surface2VolTransform.py @@ -4,13 +4,29 @@ def test_Surface2VolTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - hemi=dict(argstr="--hemi %s", mandatory=True,), - mkmask=dict(argstr="--mkmask", xor=["source_file"],), - projfrac=dict(argstr="--projfrac %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemi=dict( + argstr="--hemi %s", + mandatory=True, + ), + mkmask=dict( + argstr="--mkmask", + xor=["source_file"], + ), + projfrac=dict( + argstr="--projfrac %s", + ), reg_file=dict( - argstr="--volreg %s", extensions=None, mandatory=True, xor=["subject_id"], + argstr="--volreg %s", + extensions=None, + mandatory=True, + xor=["subject_id"], ), source_file=dict( argstr="--surfval %s", @@ -19,10 +35,20 @@ def test_Surface2VolTransform_inputs(): mandatory=True, xor=["mkmask"], ), - subject_id=dict(argstr="--identity %s", xor=["reg_file"],), - subjects_dir=dict(argstr="--sd %s",), - surf_name=dict(argstr="--surf %s",), - template_file=dict(argstr="--template %s", extensions=None,), + subject_id=dict( + argstr="--identity %s", + xor=["reg_file"], + ), + subjects_dir=dict( + argstr="--sd %s", + ), + surf_name=dict( + argstr="--surf %s", + ), + template_file=dict( + argstr="--template %s", + extensions=None, + ), transformed_file=dict( argstr="--outvol %s", extensions=None, @@ -47,7 +73,12 @@ def test_Surface2VolTransform_inputs(): def test_Surface2VolTransform_outputs(): output_map = dict( - transformed_file=dict(extensions=None,), vertexvol_file=dict(extensions=None,), + transformed_file=dict( + extensions=None, + ), + vertexvol_file=dict( + extensions=None, + ), ) outputs = Surface2VolTransform.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSmooth.py b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSmooth.py index 020f7af7a8..7876dfa1cc 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSmooth.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSmooth.py @@ -4,16 +4,46 @@ def test_SurfaceSmooth_inputs(): input_map = dict( - args=dict(argstr="%s",), - cortex=dict(argstr="--cortex", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - fwhm=dict(argstr="--fwhm %.4f", xor=["smooth_iters"],), - hemi=dict(argstr="--hemi %s", mandatory=True,), - in_file=dict(argstr="--sval %s", extensions=None, mandatory=True,), - out_file=dict(argstr="--tval %s", extensions=None, genfile=True,), - reshape=dict(argstr="--reshape",), - smooth_iters=dict(argstr="--smooth %d", xor=["fwhm"],), - subject_id=dict(argstr="--s %s", mandatory=True,), + args=dict( + argstr="%s", + ), + cortex=dict( + argstr="--cortex", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr="--fwhm %.4f", + xor=["smooth_iters"], + ), + hemi=dict( + argstr="--hemi %s", + mandatory=True, + ), + in_file=dict( + argstr="--sval %s", + extensions=None, + mandatory=True, + ), + out_file=dict( + argstr="--tval %s", + extensions=None, + genfile=True, + ), + reshape=dict( + argstr="--reshape", + ), + smooth_iters=dict( + argstr="--smooth %d", + xor=["fwhm"], + ), + subject_id=dict( + argstr="--s %s", + mandatory=True, + ), subjects_dir=dict(), ) inputs = SurfaceSmooth.input_spec() @@ -24,7 +54,11 @@ def test_SurfaceSmooth_inputs(): def test_SurfaceSmooth_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SurfaceSmooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py index b4b3e8a5e2..c778bcc959 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceSnapshots.py @@ -4,51 +4,127 @@ def test_SurfaceSnapshots_inputs(): input_map = dict( - annot_file=dict(argstr="-annotation %s", extensions=None, xor=["annot_name"],), - annot_name=dict(argstr="-annotation %s", xor=["annot_file"],), - args=dict(argstr="%s",), - colortable=dict(argstr="-colortable %s", extensions=None,), - demean_overlay=dict(argstr="-zm",), - environ=dict(nohash=True, usedefault=True,), - hemi=dict(argstr="%s", mandatory=True, position=2,), + annot_file=dict( + argstr="-annotation %s", + extensions=None, + xor=["annot_name"], + ), + annot_name=dict( + argstr="-annotation %s", + xor=["annot_file"], + ), + args=dict( + argstr="%s", + ), + colortable=dict( + argstr="-colortable %s", + extensions=None, + ), + demean_overlay=dict( + argstr="-zm", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemi=dict( + argstr="%s", + mandatory=True, + position=2, + ), identity_reg=dict( argstr="-overlay-reg-identity", xor=["overlay_reg", "identity_reg", "mni152_reg"], ), - invert_overlay=dict(argstr="-invphaseflag 1",), - label_file=dict(argstr="-label %s", extensions=None, xor=["label_name"],), - label_name=dict(argstr="-label %s", xor=["label_file"],), - label_outline=dict(argstr="-label-outline",), - label_under=dict(argstr="-labels-under",), + invert_overlay=dict( + argstr="-invphaseflag 1", + ), + label_file=dict( + argstr="-label %s", + extensions=None, + xor=["label_name"], + ), + label_name=dict( + argstr="-label %s", + xor=["label_file"], + ), + label_outline=dict( + argstr="-label-outline", + ), + label_under=dict( + argstr="-labels-under", + ), mni152_reg=dict( - argstr="-mni152reg", xor=["overlay_reg", "identity_reg", "mni152_reg"], + argstr="-mni152reg", + xor=["overlay_reg", "identity_reg", "mni152_reg"], + ), + orig_suffix=dict( + argstr="-orig %s", ), - orig_suffix=dict(argstr="-orig %s",), overlay=dict( - argstr="-overlay %s", extensions=None, requires=["overlay_range"], + argstr="-overlay %s", + extensions=None, + requires=["overlay_range"], + ), + overlay_range=dict( + argstr="%s", + ), + overlay_range_offset=dict( + argstr="-foffset %.3f", ), - overlay_range=dict(argstr="%s",), - overlay_range_offset=dict(argstr="-foffset %.3f",), overlay_reg=dict( argstr="-overlay-reg %s", extensions=None, xor=["overlay_reg", "identity_reg", "mni152_reg"], ), - patch_file=dict(argstr="-patch %s", extensions=None,), - reverse_overlay=dict(argstr="-revphaseflag 1",), + patch_file=dict( + argstr="-patch %s", + extensions=None, + ), + reverse_overlay=dict( + argstr="-revphaseflag 1", + ), screenshot_stem=dict(), - show_color_scale=dict(argstr="-colscalebarflag 1",), - show_color_text=dict(argstr="-colscaletext 1",), - show_curv=dict(argstr="-curv", xor=["show_gray_curv"],), - show_gray_curv=dict(argstr="-gray", xor=["show_curv"],), + show_color_scale=dict( + argstr="-colscalebarflag 1", + ), + show_color_text=dict( + argstr="-colscaletext 1", + ), + show_curv=dict( + argstr="-curv", + xor=["show_gray_curv"], + ), + show_gray_curv=dict( + argstr="-gray", + xor=["show_curv"], + ), six_images=dict(), - sphere_suffix=dict(argstr="-sphere %s",), - stem_template_args=dict(requires=["screenshot_stem"],), - subject_id=dict(argstr="%s", mandatory=True, position=1,), + sphere_suffix=dict( + argstr="-sphere %s", + ), + stem_template_args=dict( + requires=["screenshot_stem"], + ), + subject_id=dict( + argstr="%s", + mandatory=True, + position=1, + ), subjects_dir=dict(), - surface=dict(argstr="%s", mandatory=True, position=3,), - tcl_script=dict(argstr="%s", extensions=None, genfile=True,), - truncate_overlay=dict(argstr="-truncphaseflag 1",), + surface=dict( + argstr="%s", + mandatory=True, + position=3, + ), + tcl_script=dict( + argstr="%s", + extensions=None, + genfile=True, + ), + truncate_overlay=dict( + argstr="-truncphaseflag 1", + ), ) inputs = SurfaceSnapshots.input_spec() @@ -58,7 +134,9 @@ def test_SurfaceSnapshots_inputs(): def test_SurfaceSnapshots_outputs(): - output_map = dict(snapshots=dict(),) + output_map = dict( + snapshots=dict(), + ) outputs = SurfaceSnapshots.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceTransform.py b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceTransform.py index d8bcf6eb28..88923befd4 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SurfaceTransform.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SurfaceTransform.py @@ -4,12 +4,28 @@ def test_SurfaceTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - hemi=dict(argstr="--hemi %s", mandatory=True,), - out_file=dict(argstr="--tval %s", extensions=None, genfile=True,), - reshape=dict(argstr="--reshape",), - reshape_factor=dict(argstr="--reshape-factor",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hemi=dict( + argstr="--hemi %s", + mandatory=True, + ), + out_file=dict( + argstr="--tval %s", + extensions=None, + genfile=True, + ), + reshape=dict( + argstr="--reshape", + ), + reshape_factor=dict( + argstr="--reshape-factor", + ), source_annot_file=dict( argstr="--sval-annot %s", extensions=None, @@ -22,12 +38,25 @@ def test_SurfaceTransform_inputs(): mandatory=True, xor=["source_annot_file"], ), - source_subject=dict(argstr="--srcsubject %s", mandatory=True,), - source_type=dict(argstr="--sfmt %s", requires=["source_file"],), + source_subject=dict( + argstr="--srcsubject %s", + mandatory=True, + ), + source_type=dict( + argstr="--sfmt %s", + requires=["source_file"], + ), subjects_dir=dict(), - target_ico_order=dict(argstr="--trgicoorder %d",), - target_subject=dict(argstr="--trgsubject %s", mandatory=True,), - target_type=dict(argstr="--tfmt %s",), + target_ico_order=dict( + argstr="--trgicoorder %d", + ), + target_subject=dict( + argstr="--trgsubject %s", + mandatory=True, + ), + target_type=dict( + argstr="--tfmt %s", + ), ) inputs = SurfaceTransform.input_spec() @@ -37,7 +66,11 @@ def test_SurfaceTransform_inputs(): def test_SurfaceTransform_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SurfaceTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_SynthesizeFLASH.py b/nipype/interfaces/freesurfer/tests/test_auto_SynthesizeFLASH.py index 396d46e1a9..7d52c994bc 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_SynthesizeFLASH.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_SynthesizeFLASH.py @@ -4,16 +4,50 @@ def test_SynthesizeFLASH_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixed_weighting=dict(argstr="-w", position=1,), - flip_angle=dict(argstr="%.2f", mandatory=True, position=3,), - out_file=dict(argstr="%s", extensions=None, genfile=True,), - pd_image=dict(argstr="%s", extensions=None, mandatory=True, position=6,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixed_weighting=dict( + argstr="-w", + position=1, + ), + flip_angle=dict( + argstr="%.2f", + mandatory=True, + position=3, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + ), + pd_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=6, + ), subjects_dir=dict(), - t1_image=dict(argstr="%s", extensions=None, mandatory=True, position=5,), - te=dict(argstr="%.3f", mandatory=True, position=4,), - tr=dict(argstr="%.2f", mandatory=True, position=2,), + t1_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=5, + ), + te=dict( + argstr="%.3f", + mandatory=True, + position=4, + ), + tr=dict( + argstr="%.2f", + mandatory=True, + position=2, + ), ) inputs = SynthesizeFLASH.input_spec() @@ -23,7 +57,11 @@ def test_SynthesizeFLASH_inputs(): def test_SynthesizeFLASH_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SynthesizeFLASH.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_TalairachAVI.py b/nipype/interfaces/freesurfer/tests/test_auto_TalairachAVI.py index 41ad7fef4e..384f44edd2 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_TalairachAVI.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_TalairachAVI.py @@ -4,11 +4,26 @@ def test_TalairachAVI_inputs(): input_map = dict( - args=dict(argstr="%s",), - atlas=dict(argstr="--atlas %s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="--i %s", extensions=None, mandatory=True,), - out_file=dict(argstr="--xfm %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + atlas=dict( + argstr="--atlas %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="--i %s", + extensions=None, + mandatory=True, + ), + out_file=dict( + argstr="--xfm %s", + extensions=None, + mandatory=True, + ), subjects_dir=dict(), ) inputs = TalairachAVI.input_spec() @@ -20,9 +35,15 @@ def test_TalairachAVI_inputs(): def test_TalairachAVI_outputs(): output_map = dict( - out_file=dict(extensions=None,), - out_log=dict(extensions=None,), - out_txt=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_log=dict( + extensions=None, + ), + out_txt=dict( + extensions=None, + ), ) outputs = TalairachAVI.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_TalairachQC.py b/nipype/interfaces/freesurfer/tests/test_auto_TalairachQC.py index 52b07074e1..c6536186aa 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_TalairachQC.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_TalairachQC.py @@ -4,9 +4,19 @@ def test_TalairachQC_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - log_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + log_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), subjects_dir=dict(), ) inputs = TalairachQC.input_spec() @@ -17,7 +27,12 @@ def test_TalairachQC_inputs(): def test_TalairachQC_outputs(): - output_map = dict(log_file=dict(extensions=None, usedefault=True,),) + output_map = dict( + log_file=dict( + extensions=None, + usedefault=True, + ), + ) outputs = TalairachQC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_auto_Tkregister2.py b/nipype/interfaces/freesurfer/tests/test_auto_Tkregister2.py index 0e80196220..31cdedb679 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_Tkregister2.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_Tkregister2.py @@ -4,27 +4,76 @@ def test_Tkregister2_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fsl_in_matrix=dict(argstr="--fsl %s", extensions=None,), - fsl_out=dict(argstr="--fslregout %s",), - fstal=dict(argstr="--fstal", xor=["target_image", "moving_image", "reg_file"],), - fstarg=dict(argstr="--fstarg", xor=["target_image"],), - invert_lta_in=dict(requires=["lta_in"],), - invert_lta_out=dict(argstr="--ltaout-inv", requires=["lta_in"],), - lta_in=dict(argstr="--lta %s", extensions=None,), - lta_out=dict(argstr="--ltaout %s",), - moving_image=dict(argstr="--mov %s", extensions=None, mandatory=True,), - movscale=dict(argstr="--movscale %f",), - noedit=dict(argstr="--noedit", usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fsl_in_matrix=dict( + argstr="--fsl %s", + extensions=None, + ), + fsl_out=dict( + argstr="--fslregout %s", + ), + fstal=dict( + argstr="--fstal", + xor=["target_image", "moving_image", "reg_file"], + ), + fstarg=dict( + argstr="--fstarg", + xor=["target_image"], + ), + invert_lta_in=dict( + requires=["lta_in"], + ), + invert_lta_out=dict( + argstr="--ltaout-inv", + requires=["lta_in"], + ), + lta_in=dict( + argstr="--lta %s", + extensions=None, + ), + lta_out=dict( + argstr="--ltaout %s", + ), + moving_image=dict( + argstr="--mov %s", + extensions=None, + mandatory=True, + ), + movscale=dict( + argstr="--movscale %f", + ), + noedit=dict( + argstr="--noedit", + usedefault=True, + ), reg_file=dict( - argstr="--reg %s", extensions=None, mandatory=True, usedefault=True, + argstr="--reg %s", + extensions=None, + mandatory=True, + usedefault=True, + ), + reg_header=dict( + argstr="--regheader", + ), + subject_id=dict( + argstr="--s %s", ), - reg_header=dict(argstr="--regheader",), - subject_id=dict(argstr="--s %s",), subjects_dir=dict(), - target_image=dict(argstr="--targ %s", extensions=None, xor=["fstarg"],), - xfm=dict(argstr="--xfm %s", extensions=None,), + target_image=dict( + argstr="--targ %s", + extensions=None, + xor=["fstarg"], + ), + xfm=dict( + argstr="--xfm %s", + extensions=None, + ), ) inputs = Tkregister2.input_spec() @@ -35,9 +84,15 @@ def test_Tkregister2_inputs(): def test_Tkregister2_outputs(): output_map = dict( - fsl_file=dict(extensions=None,), - lta_file=dict(extensions=None,), - reg_file=dict(extensions=None,), + fsl_file=dict( + extensions=None, + ), + lta_file=dict( + extensions=None, + ), + reg_file=dict( + extensions=None, + ), ) outputs = Tkregister2.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_UnpackSDICOMDir.py b/nipype/interfaces/freesurfer/tests/test_auto_UnpackSDICOMDir.py index b4378f3cac..b6b27e67b8 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_UnpackSDICOMDir.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_UnpackSDICOMDir.py @@ -4,33 +4,57 @@ def test_UnpackSDICOMDir_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), config=dict( argstr="-cfg %s", extensions=None, mandatory=True, xor=("run_info", "config", "seq_config"), ), - dir_structure=dict(argstr="-%s",), - environ=dict(nohash=True, usedefault=True,), - log_file=dict(argstr="-log %s", extensions=None,), - no_info_dump=dict(argstr="-noinfodump",), - no_unpack_err=dict(argstr="-no-unpackerr",), - output_dir=dict(argstr="-targ %s",), + dir_structure=dict( + argstr="-%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + log_file=dict( + argstr="-log %s", + extensions=None, + ), + no_info_dump=dict( + argstr="-noinfodump", + ), + no_unpack_err=dict( + argstr="-no-unpackerr", + ), + output_dir=dict( + argstr="-targ %s", + ), run_info=dict( argstr="-run %d %s %s %s", mandatory=True, xor=("run_info", "config", "seq_config"), ), - scan_only=dict(argstr="-scanonly %s", extensions=None,), + scan_only=dict( + argstr="-scanonly %s", + extensions=None, + ), seq_config=dict( argstr="-seqcfg %s", extensions=None, mandatory=True, xor=("run_info", "config", "seq_config"), ), - source_dir=dict(argstr="-src %s", mandatory=True,), - spm_zeropad=dict(argstr="-nspmzeropad %d",), + source_dir=dict( + argstr="-src %s", + mandatory=True, + ), + spm_zeropad=dict( + argstr="-nspmzeropad %d", + ), subjects_dir=dict(), ) inputs = UnpackSDICOMDir.input_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_VolumeMask.py b/nipype/interfaces/freesurfer/tests/test_auto_VolumeMask.py index cef9ddfedc..152f03eaa8 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_VolumeMask.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_VolumeMask.py @@ -4,21 +4,64 @@ def test_VolumeMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - aseg=dict(extensions=None, xor=["in_aseg"],), + args=dict( + argstr="%s", + ), + aseg=dict( + extensions=None, + xor=["in_aseg"], + ), copy_inputs=dict(), - environ=dict(nohash=True, usedefault=True,), - in_aseg=dict(argstr="--aseg_name %s", extensions=None, xor=["aseg"],), - left_ribbonlabel=dict(argstr="--label_left_ribbon %d", mandatory=True,), - left_whitelabel=dict(argstr="--label_left_white %d", mandatory=True,), - lh_pial=dict(extensions=None, mandatory=True,), - lh_white=dict(extensions=None, mandatory=True,), - rh_pial=dict(extensions=None, mandatory=True,), - rh_white=dict(extensions=None, mandatory=True,), - right_ribbonlabel=dict(argstr="--label_right_ribbon %d", mandatory=True,), - right_whitelabel=dict(argstr="--label_right_white %d", mandatory=True,), - save_ribbon=dict(argstr="--save_ribbon",), - subject_id=dict(argstr="%s", mandatory=True, position=-1, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), + in_aseg=dict( + argstr="--aseg_name %s", + extensions=None, + xor=["aseg"], + ), + left_ribbonlabel=dict( + argstr="--label_left_ribbon %d", + mandatory=True, + ), + left_whitelabel=dict( + argstr="--label_left_white %d", + mandatory=True, + ), + lh_pial=dict( + extensions=None, + mandatory=True, + ), + lh_white=dict( + extensions=None, + mandatory=True, + ), + rh_pial=dict( + extensions=None, + mandatory=True, + ), + rh_white=dict( + extensions=None, + mandatory=True, + ), + right_ribbonlabel=dict( + argstr="--label_right_ribbon %d", + mandatory=True, + ), + right_whitelabel=dict( + argstr="--label_right_white %d", + mandatory=True, + ), + save_ribbon=dict( + argstr="--save_ribbon", + ), + subject_id=dict( + argstr="%s", + mandatory=True, + position=-1, + usedefault=True, + ), subjects_dir=dict(), ) inputs = VolumeMask.input_spec() @@ -30,9 +73,15 @@ def test_VolumeMask_inputs(): def test_VolumeMask_outputs(): output_map = dict( - lh_ribbon=dict(extensions=None,), - out_ribbon=dict(extensions=None,), - rh_ribbon=dict(extensions=None,), + lh_ribbon=dict( + extensions=None, + ), + out_ribbon=dict( + extensions=None, + ), + rh_ribbon=dict( + extensions=None, + ), ) outputs = VolumeMask.output_spec() diff --git a/nipype/interfaces/freesurfer/tests/test_auto_WatershedSkullStrip.py b/nipype/interfaces/freesurfer/tests/test_auto_WatershedSkullStrip.py index 649e4e497b..5e8609c4c6 100644 --- a/nipype/interfaces/freesurfer/tests/test_auto_WatershedSkullStrip.py +++ b/nipype/interfaces/freesurfer/tests/test_auto_WatershedSkullStrip.py @@ -4,16 +4,40 @@ def test_WatershedSkullStrip_inputs(): input_map = dict( - args=dict(argstr="%s",), - brain_atlas=dict(argstr="-brain_atlas %s", extensions=None, position=-4,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + brain_atlas=dict( + argstr="-brain_atlas %s", + extensions=None, + position=-4, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, ), subjects_dir=dict(), - t1=dict(argstr="-T1",), - transform=dict(argstr="%s", extensions=None, position=-3,), + t1=dict( + argstr="-T1", + ), + transform=dict( + argstr="%s", + extensions=None, + position=-3, + ), ) inputs = WatershedSkullStrip.input_spec() @@ -23,7 +47,11 @@ def test_WatershedSkullStrip_inputs(): def test_WatershedSkullStrip_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = WatershedSkullStrip.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/freesurfer/tests/test_model.py b/nipype/interfaces/freesurfer/tests/test_model.py index 8d30ebb5dc..f300edf3a1 100644 --- a/nipype/interfaces/freesurfer/tests/test_model.py +++ b/nipype/interfaces/freesurfer/tests/test_model.py @@ -1,14 +1,11 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -import os import numpy as np import nibabel as nb import pytest -from nipype.utils import NUMPY_MMAP from nipype.interfaces.freesurfer import model, no_freesurfer import nipype.pipeline.engine as pe diff --git a/nipype/interfaces/freesurfer/tests/test_preprocess.py b/nipype/interfaces/freesurfer/tests/test_preprocess.py index 518d60b9a5..a6e2c3cbf9 100644 --- a/nipype/interfaces/freesurfer/tests/test_preprocess.py +++ b/nipype/interfaces/freesurfer/tests/test_preprocess.py @@ -1,14 +1,13 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os import pytest -from nipype.testing.fixtures import create_files_in_directory +from looseversion import LooseVersion +from nipype.testing.fixtures import create_files_in_directory from nipype.interfaces import freesurfer from nipype.interfaces.freesurfer import Info -from nipype import LooseVersion @pytest.mark.skipif(freesurfer.no_freesurfer(), reason="freesurfer is not installed") @@ -66,7 +65,7 @@ def test_fitmsparams(create_files_in_directory): # .inputs based parameters setting fit.inputs.in_files = filelist fit.inputs.out_dir = outdir - assert fit.cmdline == "mri_ms_fitparms %s %s %s" % ( + assert fit.cmdline == "mri_ms_fitparms {} {} {}".format( filelist[0], filelist[1], outdir, @@ -137,7 +136,7 @@ def test_mandatory_outvol(create_files_in_directory): ext = ext2 + ext assert mni.cmdline == ( - "mri_nu_correct.mni --i %s --n 4 --o %s_output%s" % (filelist[0], base, ext) + f"mri_nu_correct.mni --i {filelist[0]} --n 4 --o {base}_output{ext}" ) # test with custom outfile @@ -192,7 +191,6 @@ def test_bbregister(create_files_in_directory): def test_FSVersion(): - """Check that FSVersion is a string that can be compared with LooseVersion - """ + """Check that FSVersion is a string that can be compared with LooseVersion""" assert isinstance(freesurfer.preprocess.FSVersion, str) assert LooseVersion(freesurfer.preprocess.FSVersion) >= LooseVersion("0") diff --git a/nipype/interfaces/freesurfer/tests/test_utils.py b/nipype/interfaces/freesurfer/tests/test_utils.py index 52348bb5e0..323c04166d 100644 --- a/nipype/interfaces/freesurfer/tests/test_utils.py +++ b/nipype/interfaces/freesurfer/tests/test_utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -17,7 +16,6 @@ @pytest.mark.skipif(fs.no_freesurfer(), reason="freesurfer is not installed") def test_sample2surf(create_files_in_directory_plus_dummy_file): - s2s = fs.SampleToSurface() # Test underlying command assert s2s.cmd == "mri_vol2surf" @@ -65,7 +63,6 @@ def set_illegal_range(): @pytest.mark.skipif(fs.no_freesurfer(), reason="freesurfer is not installed") def test_surfsmooth(create_surf_file_in_directory): - smooth = fs.SurfaceSmooth() # Test underlying command @@ -104,7 +101,6 @@ def test_surfsmooth(create_surf_file_in_directory): @pytest.mark.skipif(fs.no_freesurfer(), reason="freesurfer is not installed") def test_surfxfm(create_surf_file_in_directory): - xfm = fs.SurfaceTransform() # Test underlying command @@ -141,7 +137,6 @@ def test_surfxfm(create_surf_file_in_directory): @pytest.mark.skipif(fs.no_freesurfer(), reason="freesurfer is not installed") def test_surfshots(create_files_in_directory_plus_dummy_file): - fotos = fs.SurfaceSnapshots() # Test underlying command @@ -154,7 +149,7 @@ def test_surfshots(create_files_in_directory_plus_dummy_file): # Create testing files files, cwd = create_files_in_directory_plus_dummy_file - # Test input settins + # Test input settings fotos.inputs.subject_id = "fsaverage" fotos.inputs.hemi = "lh" fotos.inputs.surface = "pial" @@ -230,3 +225,19 @@ def test_mrisexpand(tmpdir): assert op.dirname(if_out_file) == op.dirname(fsavginfo["smoothwm"]) # Node places output in working directory assert op.dirname(nd_out_file) == nd_res.runtime.cwd + + +@pytest.mark.skipif(fs.no_freesurfer(), reason="freesurfer is not installed") +def test_eulernumber(tmpdir): + # grab a surface from fsaverage + fssrc = FreeSurferSource( + subjects_dir=fs.Info.subjectsdir(), subject_id="fsaverage", hemi="lh" + ) + pial = fssrc.run().outputs.pial + assert isinstance(pial, str), "Problem when fetching surface file" + + eu = fs.EulerNumber() + eu.inputs.in_file = pial + res = eu.run() + assert res.outputs.defects == 0 + assert res.outputs.euler == 2 diff --git a/nipype/interfaces/freesurfer/utils.py b/nipype/interfaces/freesurfer/utils.py index a2b3b7a47b..2c1cdbcc94 100644 --- a/nipype/interfaces/freesurfer/utils.py +++ b/nipype/interfaces/freesurfer/utils.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Interfaces to assorted Freesurfer utility programs. -""" +"""Interfaces to assorted Freesurfer utility programs.""" import os import re import shutil @@ -14,6 +12,7 @@ Directory, File, traits, + Tuple, OutputMultiPath, isdefined, CommandLine, @@ -116,7 +115,6 @@ def createoutputdirs(outputs): class SampleToSurfaceInputSpec(FSTraitedSpec): - source_file = File( exists=True, mandatory=True, @@ -156,14 +154,14 @@ class SampleToSurfaceInputSpec(FSTraitedSpec): desc="source volume is in MNI152 space", ) - apply_rot = traits.Tuple( + apply_rot = Tuple( traits.Float, traits.Float, traits.Float, argstr="--rot %.3f %.3f %.3f", desc="rotation angles (in degrees) to apply to reg matrix", ) - apply_trans = traits.Tuple( + apply_trans = Tuple( traits.Float, traits.Float, traits.Float, @@ -188,7 +186,7 @@ class SampleToSurfaceInputSpec(FSTraitedSpec): ) sampling_range = traits.Either( traits.Float, - traits.Tuple(traits.Float, traits.Float, traits.Float), + Tuple(traits.Float, traits.Float, traits.Float), desc="sampling range - a point or a tuple of (min, max, step)", ) sampling_units = traits.Enum( @@ -289,7 +287,6 @@ class SampleToSurfaceInputSpec(FSTraitedSpec): class SampleToSurfaceOutputSpec(TraitedSpec): - out_file = File(exists=True, desc="surface file") hits_file = File(exists=True, desc="image with number of hits at each voxel") vox_file = File( @@ -343,7 +340,7 @@ def _format_arg(self, name, spec, value): else: range = "%.3f" % range method = dict(point="", max="-max", average="-avg")[value] - return "--proj%s%s %s" % (units, method, range) + return f"--proj{units}{method} {range}" if name == "reg_header": return spec.argstr % self.inputs.subject_id @@ -375,7 +372,7 @@ def _format_arg(self, name, spec, value): if value is True: return spec.argstr % "sphere.reg" - return super(SampleToSurface, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _get_outfilename(self, opt="out_file"): outfile = getattr(self.inputs, opt) @@ -426,7 +423,6 @@ def _gen_filename(self, name): class SurfaceSmoothInputSpec(FSTraitedSpec): - in_file = File(mandatory=True, argstr="--sval %s", desc="source surface file") subject_id = traits.String( mandatory=True, argstr="--s %s", desc="subject id of surface file" @@ -455,14 +451,13 @@ class SurfaceSmoothInputSpec(FSTraitedSpec): class SurfaceSmoothOutputSpec(TraitedSpec): - out_file = File(exists=True, desc="smoothed surface file") class SurfaceSmooth(FSCommand): """Smooth a surface image with mri_surf2surf. - The surface is smoothed by an interative process of averaging the + The surface is smoothed by an iterative process of averaging the value at each vertex with those of its adjacent neighbors. You may supply either the number of iterations to run or a desired effective FWHM of the smoothing process. If the latter, the underlying program will calculate @@ -544,7 +539,7 @@ class SurfaceTransformInputSpec(FSTraitedSpec): 6, 7, argstr="--trgicoorder %d", - desc=("order of the icosahedron if " "target_subject is 'ico'"), + desc=("order of the icosahedron if target_subject is 'ico'"), ) source_type = traits.Enum( filetypes, @@ -612,7 +607,7 @@ def _format_arg(self, name, spec, value): ) if value in implicit_filetypes: return "" - return super(SurfaceTransform, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -656,7 +651,7 @@ def _list_outputs(self): use_ext = False outputs["out_file"] = fname_presuffix( source, - suffix=".%s%s" % (self.inputs.target_subject, ext), + suffix=f".{self.inputs.target_subject}{ext}", newpath=os.getcwd(), use_ext=use_ext, ) @@ -718,7 +713,7 @@ class Surface2VolTransformInputSpec(FSTraitedSpec): projfrac = traits.Float(argstr="--projfrac %s", desc="thickness fraction") subjects_dir = traits.Str( argstr="--sd %s", - desc=("freesurfer subjects directory defaults to " "$SUBJECTS_DIR"), + desc=("freesurfer subjects directory defaults to $SUBJECTS_DIR"), ) subject_id = traits.Str(argstr="--identity %s", desc="subject id", xor=["reg_file"]) @@ -753,7 +748,6 @@ class Surface2VolTransform(FSCommand): class ApplyMaskInputSpec(FSTraitedSpec): - in_file = File( exists=True, mandatory=True, @@ -803,7 +797,6 @@ class ApplyMaskInputSpec(FSTraitedSpec): class ApplyMaskOutputSpec(TraitedSpec): - out_file = File(exists=True, desc="masked image") @@ -822,7 +815,6 @@ class ApplyMask(FSCommand): class SurfaceSnapshotsInputSpec(FSTraitedSpec): - subject_id = traits.String( position=1, argstr="%s", mandatory=True, desc="subject to visualize" ) @@ -871,14 +863,14 @@ class SurfaceSnapshotsInputSpec(FSTraitedSpec): overlay_range = traits.Either( traits.Float, - traits.Tuple(traits.Float, traits.Float), - traits.Tuple(traits.Float, traits.Float, traits.Float), + Tuple(traits.Float, traits.Float), + Tuple(traits.Float, traits.Float, traits.Float), desc="overlay range--either min, (min, max) or (min, mid, max)", argstr="%s", ) overlay_range_offset = traits.Float( argstr="-foffset %.3f", - desc="overlay range will be symettric around offset value", + desc="overlay range will be symmetric around offset value", ) truncate_overlay = traits.Bool( @@ -956,7 +948,6 @@ class SurfaceSnapshotsInputSpec(FSTraitedSpec): class SurfaceSnapshotsOutputSpec(TraitedSpec): - snapshots = OutputMultiPath( File(exists=True), desc="tiff images of the surface from different perspectives" ) @@ -1006,7 +997,7 @@ def _format_arg(self, name, spec, value): if len(value) == 2: return "-fminmax %.3f %.3f" % value else: - return "-fminmax %.3f %.3f -fmid %.3f" % ( + return "-fminmax {:.3f} {:.3f} -fmid {:.3f}".format( value[0], value[2], value[1], @@ -1019,11 +1010,11 @@ def _format_arg(self, name, spec, value): if re.match(r"%s[\.\-_]" % self.inputs.hemi, value[:3]): value = value[3:] return "-annotation %s" % value - return super(SurfaceSnapshots, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _run_interface(self, runtime): if not isdefined(self.inputs.screenshot_stem): - stem = "%s_%s_%s" % ( + stem = "{}_{}_{}".format( self.inputs.subject_id, self.inputs.hemi, self.inputs.surface, @@ -1032,14 +1023,14 @@ def _run_interface(self, runtime): stem = self.inputs.screenshot_stem stem_args = self.inputs.stem_template_args if isdefined(stem_args): - args = tuple([getattr(self.inputs, arg) for arg in stem_args]) + args = tuple(getattr(self.inputs, arg) for arg in stem_args) stem = stem % args # Check if the DISPLAY variable is set -- should avoid crashes (might not?) if "DISPLAY" not in os.environ: raise RuntimeError("Graphics are not enabled -- cannot run tksurfer") runtime.environ["_SNAPSHOT_STEM"] = stem self._write_tcl_script() - runtime = super(SurfaceSnapshots, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) # If a display window can't be opened, this will crash on # aggregate_outputs. Let's try to parse stderr and raise a # better exception here if that happened. @@ -1093,7 +1084,7 @@ def _write_tcl_script(self): def _list_outputs(self): outputs = self._outputs().get() if not isdefined(self.inputs.screenshot_stem): - stem = "%s_%s_%s" % ( + stem = "{}_{}_{}".format( self.inputs.subject_id, self.inputs.hemi, self.inputs.surface, @@ -1102,7 +1093,7 @@ def _list_outputs(self): stem = self.inputs.screenshot_stem stem_args = self.inputs.stem_template_args if isdefined(stem_args): - args = tuple([getattr(self.inputs, arg) for arg in stem_args]) + args = tuple(getattr(self.inputs, arg) for arg in stem_args) stem = stem % args snapshots = ["%s-lat.tif", "%s-med.tif", "%s-dor.tif", "%s-ven.tif"] if self.inputs.six_images: @@ -1118,12 +1109,10 @@ def _gen_filename(self, name): class ImageInfoInputSpec(FSTraitedSpec): - in_file = File(exists=True, position=1, argstr="%s", desc="image to query") class ImageInfoOutputSpec(TraitedSpec): - info = traits.Any(desc="output of mri_info") out_file = File(exists=True, desc="text file with image information") data_type = traits.String(desc="image data type") @@ -1131,20 +1120,19 @@ class ImageInfoOutputSpec(TraitedSpec): TE = traits.String(desc="echo time (msec)") TR = traits.String(desc="repetition time(msec)") TI = traits.String(desc="inversion time (msec)") - dimensions = traits.Tuple(desc="image dimensions (voxels)") - vox_sizes = traits.Tuple(desc="voxel sizes (mm)") + dimensions = Tuple(desc="image dimensions (voxels)") + vox_sizes = Tuple(desc="voxel sizes (mm)") orientation = traits.String(desc="image orientation") ph_enc_dir = traits.String(desc="phase encode direction") class ImageInfo(FSCommand): - _cmd = "mri_info" input_spec = ImageInfoInputSpec output_spec = ImageInfoOutputSpec def info_regexp(self, info, field, delim="\n"): - m = re.search(r"%s\s*:\s+(.+?)%s" % (field, delim), info) + m = re.search(fr"{field}\s*:\s+(.+?){delim}", info) if m: return m.group(1) else: @@ -1167,7 +1155,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): vox = tuple(vox.split(", ")) outputs.vox_sizes = vox dim = self.info_regexp(info, "dimensions") - dim = tuple([int(d) for d in dim.split(" x ")]) + dim = tuple(int(d) for d in dim.split(" x ")) outputs.dimensions = dim outputs.orientation = self.info_regexp(info, "Orientation") @@ -1310,7 +1298,7 @@ class MRIsConvert(FSCommand): def _format_arg(self, name, spec, value): if name == "out_file" and not os.path.isabs(value): value = os.path.abspath(value) - return super(MRIsConvert, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -1371,7 +1359,7 @@ class MRIsCombineOutputSpec(TraitedSpec): """ out_file = File( - exists=True, desc="Output filename. Combined surfaces from " "in_files." + exists=True, desc="Output filename. Combined surfaces from in_files." ) @@ -1438,13 +1426,13 @@ class MRITessellateInputSpec(FSTraitedSpec): mandatory=True, position=-3, argstr="%s", - desc="Input volume to tesselate voxels from.", + desc="Input volume to tessellate voxels from.", ) label_value = traits.Int( position=-2, argstr="%d", mandatory=True, - desc='Label value which to tesselate from the input volume. (integer, if input is "filled.mgz" volume, 127 is rh, 255 is lh)', + desc='Label value which to tessellate from the input volume. (integer, if input is "filled.mgz" volume, 127 is rh, 255 is lh)', ) out_file = File( argstr="%s", @@ -1546,7 +1534,7 @@ class MRIPretessInputSpec(FSTraitedSpec): nocorners = traits.Bool( False, argstr="-nocorners", - desc=("do not remove corner configurations" " in addition to edge ones."), + desc=("do not remove corner configurations in addition to edge ones."), ) keep = traits.Bool(False, argstr="-keep", desc=("keep WM edits")) test = traits.Bool( @@ -1600,13 +1588,13 @@ class MRIMarchingCubesInputSpec(FSTraitedSpec): mandatory=True, position=1, argstr="%s", - desc="Input volume to tesselate voxels from.", + desc="Input volume to tessellate voxels from.", ) label_value = traits.Int( position=2, argstr="%d", mandatory=True, - desc='Label value which to tesselate from the input volume. (integer, if input is "filled.mgz" volume, 127 is rh, 255 is lh)', + desc='Label value which to tessellate from the input volume. (integer, if input is "filled.mgz" volume, 127 is rh, 255 is lh)', ) connectivity_value = traits.Int( 1, @@ -1676,7 +1664,7 @@ class SmoothTessellationInputSpec(FSTraitedSpec): argstr="%s", position=-2, copyfile=True, - desc="Input volume to tesselate voxels from.", + desc="Input volume to tessellate voxels from.", ) curvature_averaging_iterations = traits.Int( argstr="-a %d", desc="Number of curvature averaging iterations (default=10)" @@ -1775,7 +1763,7 @@ def _run_interface(self, runtime): # The returncode is meaningless in BET. So check the output # in stderr and if it's set, then update the returncode # accordingly. - runtime = super(SmoothTessellation, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if "failed" in runtime.stderr: self.raise_exception(runtime) return runtime @@ -1842,7 +1830,7 @@ class ExtractMainComponentOutputSpec(TraitedSpec): class ExtractMainComponent(CommandLine): - """Extract the main component of a tesselated surface + """Extract the main component of a tessellated surface Examples -------- @@ -1918,7 +1906,7 @@ class Tkregister2InputSpec(FSTraitedSpec): desc="freesurfer-style registration file", ) reg_header = traits.Bool( - False, argstr="--regheader", desc="compute regstration from headers" + False, argstr="--regheader", desc="compute registration from headers" ) fstal = traits.Bool( False, @@ -1978,8 +1966,8 @@ def _format_arg(self, name, spec, value): if name == "lta_in" and self.inputs.invert_lta_in: spec = "--lta-inv %s" if name in ("fsl_out", "lta_out") and value is True: - value = self._list_outputs()[name] - return super(Tkregister2, self)._format_arg(name, spec, value) + value = self._list_outputs()[f'{name[:3]}_file'] + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -2015,7 +2003,6 @@ def _gen_outfilename(self): class AddXFormToHeaderInputSpec(FSTraitedSpec): - # required in_file = File( exists=True, mandatory=True, position=-2, argstr="%s", desc="input volume" @@ -2035,7 +2022,6 @@ class AddXFormToHeaderInputSpec(FSTraitedSpec): class AddXFormToHeaderOutputSpec(TraitedSpec): - out_file = File(exists=True, desc="output volume") @@ -2077,7 +2063,7 @@ def _format_arg(self, name, spec, value): return value # os.path.abspath(value) # if name == 'copy_name' and value: # self.input_spec.transform - return super(AddXFormToHeader, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -2107,7 +2093,7 @@ class CheckTalairachAlignmentInputSpec(FSTraitedSpec): usedefault=True, argstr="-T %.3f", desc="Talairach transforms for subjects with p-values <= T " - + "are considered as very unlikely default=0.010", + "are considered as very unlikely default=0.010", ) @@ -2329,7 +2315,7 @@ class MRIFillOutputSpec(TraitedSpec): class MRIFill(FSCommand): """ This program creates hemispheric cutting planes and fills white matter - with specific values for subsequent surface tesselation. + with specific values for subsequent surface tessellation. Examples ======== @@ -2496,8 +2482,7 @@ class FixTopologyInputSpec(FSTraitedSpec): copy_inputs = traits.Bool( mandatory=True, desc="If running as a node, set this to True " - + "otherwise, the topology fixing will be done " - + "in place.", + "otherwise, the topology fixing will be done in place.", ) # optional @@ -2556,24 +2541,24 @@ def run(self, **inputs): self, self.inputs.in_orig, folder="surf", - basename="{0}.orig".format(hemi), + basename=f"{hemi}.orig", ) copy2subjdir( self, self.inputs.in_inflated, folder="surf", - basename="{0}.inflated".format(hemi), + basename=f"{hemi}.inflated", ) copy2subjdir(self, self.inputs.in_brain, folder="mri", basename="brain.mgz") copy2subjdir(self, self.inputs.in_wm, folder="mri", basename="wm.mgz") - return super(FixTopology, self).run(**inputs) + return super().run(**inputs) def _format_arg(self, name, spec, value): if name == "sphere": # get the basename and take out the hemisphere suffix = os.path.basename(value).split(".", 1)[1] return spec.argstr % suffix - return super(FixTopology, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -2592,7 +2577,11 @@ class EulerNumberInputSpec(FSTraitedSpec): class EulerNumberOutputSpec(TraitedSpec): - out_file = File(exists=False, desc="Output file for EulerNumber") + euler = traits.Int( + desc="Euler number of cortical surface. A value of 2 signals a " + "topologically correct surface model with no holes" + ) + defects = traits.Int(desc="Number of defects") class EulerNumber(FSCommand): @@ -2612,9 +2601,22 @@ class EulerNumber(FSCommand): input_spec = EulerNumberInputSpec output_spec = EulerNumberOutputSpec + def _run_interface(self, runtime): + runtime = super()._run_interface(runtime) + self._parse_output(runtime.stdout, runtime.stderr) + return runtime + + def _parse_output(self, stdout, stderr): + """Parse stdout / stderr and extract defects""" + m = re.search(r"(?<=total defect index = )\d+", stdout or stderr) + if m is None: + raise RuntimeError("Could not fetch defect index") + self._defects = int(m.group()) + def _list_outputs(self): outputs = self._outputs().get() - outputs["out_file"] = os.path.abspath(self.inputs.in_file) + outputs["defects"] = self._defects + outputs["euler"] = 2 - (2 * self._defects) return outputs @@ -2713,7 +2715,7 @@ class MakeSurfacesInputSpec(FSTraitedSpec): ) fix_mtl = traits.Bool(argstr="-fix_mtl", desc="Undocumented flag") no_white = traits.Bool(argstr="-nowhite", desc="Undocumented flag") - white_only = traits.Bool(argstr="-whiteonly", desc="Undocumented flage") + white_only = traits.Bool(argstr="-whiteonly", desc="Undocumented flag") in_aseg = File(argstr="-aseg %s", exists=True, desc="Input segmentation file") in_T1 = File(argstr="-T1 %s", exists=True, desc="Input brain or T1 file") mgz = traits.Bool( @@ -2733,9 +2735,8 @@ class MakeSurfacesInputSpec(FSTraitedSpec): ) white = traits.String(argstr="-white %s", desc="White surface name") copy_inputs = traits.Bool( - desc="If running as a node, set this to True." - + "This will copy the input files to the node " - + "directory." + desc="If running as a node, set this to True. " + "This will copy the input files to the node directory." ) @@ -2789,7 +2790,7 @@ def run(self, **inputs): self, self.inputs.in_white, "surf", - "{0}.white".format(self.inputs.hemisphere), + f"{self.inputs.hemisphere}.white", ) for originalfile in [self.inputs.in_aseg, self.inputs.in_T1]: copy2subjdir(self, originalfile, folder="mri") @@ -2804,7 +2805,7 @@ def run(self, **inputs): self, self.inputs.in_label, "label", - "{0}.aparc.annot".format(self.inputs.hemisphere), + f"{self.inputs.hemisphere}.aparc.annot", ) else: os.makedirs( @@ -2812,13 +2813,13 @@ def run(self, **inputs): self.inputs.subjects_dir, self.inputs.subject_id, "label" ) ) - return super(MakeSurfaces, self).run(**inputs) + return super().run(**inputs) def _format_arg(self, name, spec, value): if name in ["in_T1", "in_aseg"]: # These inputs do not take full paths as inputs or even basenames basename = os.path.basename(value) - # whent the -mgz flag is specified, it assumes the mgz extension + # when the -mgz flag is specified, it assumes the mgz extension if self.inputs.mgz: prefix = os.path.splitext(basename)[0] else: @@ -2832,8 +2833,8 @@ def _format_arg(self, name, spec, value): suffix = basename.split(".")[1] return spec.argstr % suffix elif name == "in_orig": - if value.endswith("lh.orig") or value.endswith("rh.orig"): - # {lh,rh}.orig inputs are not sepcified on command line + if value.endswith(("lh.orig", "rh.orig")): + # {lh,rh}.orig inputs are not specified on command line return else: # if the input orig file is different than lh.orig or rh.orig @@ -2841,7 +2842,7 @@ def _format_arg(self, name, spec, value): basename = os.path.basename(value) suffix = basename.split(".")[1] return spec.argstr % suffix - return super(MakeSurfaces, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -2905,7 +2906,7 @@ class CurvatureInputSpec(FSTraitedSpec): argstr="-w", desc="Save curvature files (will only generate screen output without this option)", ) - distances = traits.Tuple( + distances = Tuple( traits.Int, traits.Int, argstr="-distances %d %d", @@ -2944,7 +2945,7 @@ def _format_arg(self, name, spec, value): if name == "in_file": basename = os.path.basename(value) return spec.argstr % basename - return super(Curvature, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -3008,9 +3009,8 @@ class CurvatureStatsInputSpec(FSTraitedSpec): ) write = traits.Bool(argstr="--writeCurvatureFiles", desc="Write curvature files") copy_inputs = traits.Bool( - desc="If running as a node, set this to True." - + "This will copy the input files to the node " - + "directory." + desc="If running as a node, set this to True. " + "This will copy the input files to the node directory." ) @@ -3065,7 +3065,7 @@ def _format_arg(self, name, spec, value): if name in ["surface", "curvfile1", "curvfile2"]: prefix = os.path.basename(value).split(".")[1] return spec.argstr % prefix - return super(CurvatureStats, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -3080,7 +3080,7 @@ def run(self, **inputs): copy2subjdir(self, self.inputs.surface, "surf") copy2subjdir(self, self.inputs.curvfile1, "surf") copy2subjdir(self, self.inputs.curvfile2, "surf") - return super(CurvatureStats, self).run(**inputs) + return super().run(**inputs) class JacobianInputSpec(FSTraitedSpec): @@ -3233,7 +3233,7 @@ class VolumeMaskInputSpec(FSTraitedSpec): exists=True, xor=["in_aseg"], desc="Implicit aseg.mgz segmentation. " - + "Specify a different aseg by using the 'in_aseg' input.", + "Specify a different aseg by using the 'in_aseg' input.", ) subject_id = traits.String( "subject_id", @@ -3253,12 +3253,11 @@ class VolumeMaskInputSpec(FSTraitedSpec): save_ribbon = traits.Bool( argstr="--save_ribbon", desc="option to save just the ribbon for the " - + "hemispheres in the format ?h.ribbon.mgz", + "hemispheres in the format ?h.ribbon.mgz", ) copy_inputs = traits.Bool( - desc="If running as a node, set this to True." - + "This will copy the implicit input files to the " - + "node directory." + desc="If running as a node, set this to True. " + "This will copy the implicit input files to the node directory." ) @@ -3312,12 +3311,12 @@ def run(self, **inputs): copy2subjdir(self, self.inputs.in_aseg, "mri") copy2subjdir(self, self.inputs.aseg, "mri", "aseg.mgz") - return super(VolumeMask, self).run(**inputs) + return super().run(**inputs) def _format_arg(self, name, spec, value): if name == "in_aseg": return spec.argstr % os.path.basename(value).rstrip(".mgz") - return super(VolumeMask, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -3427,9 +3426,8 @@ class ParcellationStatsInputSpec(FSTraitedSpec): desc="Output annotation files's colortable to text file", ) copy_inputs = traits.Bool( - desc="If running as a node, set this to True." - + "This will copy the input files to the node " - + "directory." + desc="If running as a node, set this to True. " + "This will copy the input files to the node directory." ) th3 = traits.Bool( argstr="-th3", @@ -3500,17 +3498,17 @@ def run(self, **inputs): self, self.inputs.thickness, "surf", - "{0}.thickness".format(self.inputs.hemisphere), + f"{self.inputs.hemisphere}.thickness", ) if isdefined(self.inputs.cortex_label): copy2subjdir( self, self.inputs.cortex_label, "label", - "{0}.cortex.label".format(self.inputs.hemisphere), + f"{self.inputs.hemisphere}.cortex.label", ) createoutputdirs(self._list_outputs()) - return super(ParcellationStats, self).run(**inputs) + return super().run(**inputs) def _gen_filename(self, name): if name in ["out_table", "out_color"]: @@ -3619,9 +3617,8 @@ class ContrastInputSpec(FSTraitedSpec): exists=True, mandatory=True, desc="Implicit input file mri/rawavg.mgz" ) copy_inputs = traits.Bool( - desc="If running as a node, set this to True." - + "This will copy the input files to the node " - + "directory." + desc="If running as a node, set this to True. " + "This will copy the input files to the node directory." ) @@ -3661,21 +3658,15 @@ def run(self, **inputs): if "subjects_dir" in inputs: inputs["subjects_dir"] = self.inputs.subjects_dir hemi = self.inputs.hemisphere - copy2subjdir( - self, self.inputs.annotation, "label", "{0}.aparc.annot".format(hemi) - ) - copy2subjdir( - self, self.inputs.cortex, "label", "{0}.cortex.label".format(hemi) - ) - copy2subjdir(self, self.inputs.white, "surf", "{0}.white".format(hemi)) - copy2subjdir( - self, self.inputs.thickness, "surf", "{0}.thickness".format(hemi) - ) + copy2subjdir(self, self.inputs.annotation, "label", f"{hemi}.aparc.annot") + copy2subjdir(self, self.inputs.cortex, "label", f"{hemi}.cortex.label") + copy2subjdir(self, self.inputs.white, "surf", f"{hemi}.white") + copy2subjdir(self, self.inputs.thickness, "surf", f"{hemi}.thickness") copy2subjdir(self, self.inputs.orig, "mri", "orig.mgz") copy2subjdir(self, self.inputs.rawavg, "mri", "rawavg.mgz") # need to create output directories createoutputdirs(self._list_outputs()) - return super(Contrast, self).run(**inputs) + return super().run(**inputs) def _list_outputs(self): outputs = self._outputs().get() @@ -3903,7 +3894,7 @@ def run(self, **inputs): copy2subjdir(self, self.inputs.lh_annotation, "label") copy2subjdir(self, self.inputs.rh_annotation, "label") - return super(Aparc2Aseg, self).run(**inputs) + return super().run(**inputs) def _format_arg(self, name, spec, value): if name == "aseg": @@ -3913,7 +3904,7 @@ def _format_arg(self, name, spec, value): elif name == "out_file": return spec.argstr % os.path.abspath(value) - return super(Aparc2Aseg, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -4029,12 +4020,12 @@ class MRIsExpandInputSpec(FSTraitedSpec): ) # # Requires dev version - Re-add when min_ver/max_ver support this # # https://github.com/freesurfer/freesurfer/blob/9730cb9/mris_expand/mris_expand.c - # navgs = traits.Tuple( + # navgs = Tuple( # traits.Int, traits.Int, # argstr='-navgs %d %d', # desc=('Tuple of (n_averages, min_averages) parameters ' # '(implicit: (16, 0))')) - # target_intensity = traits.Tuple( + # target_intensity = Tuple( # traits.Float, File(exists=True), # argstr='-intensity %g %s', # desc='Tuple of intensity and brain volume to crop to target intensity') @@ -4197,7 +4188,7 @@ class LTAConvert(CommandLine): def _format_arg(self, name, spec, value): if name.startswith("out_") and value is True: value = self._list_outputs()[name] - return super(LTAConvert, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/fsl/__init__.py b/nipype/interfaces/fsl/__init__.py index 1bf8e0ada7..ffeb9b39fc 100644 --- a/nipype/interfaces/fsl/__init__.py +++ b/nipype/interfaces/fsl/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -69,6 +68,8 @@ RobustFOV, CopyGeom, MotionOutliers, + Text2Vest, + Vest2Text, ) from .epi import ( diff --git a/nipype/interfaces/fsl/aroma.py b/nipype/interfaces/fsl/aroma.py index 4a3eb32034..b699cd47e2 100644 --- a/nipype/interfaces/fsl/aroma.py +++ b/nipype/interfaces/fsl/aroma.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """This commandline module provides classes for interfacing with the @@ -12,7 +11,6 @@ File, Directory, traits, - isdefined, ) import os @@ -43,7 +41,7 @@ class ICA_AROMAInputSpec(CommandLineInputSpec): dim = traits.Int( argstr="-dim %d", desc="Dimensionality reduction when running " - "MELODIC (defualt is automatic estimation)", + "MELODIC (default is automatic estimation)", ) TR = traits.Float( argstr="-tr %.3f", @@ -146,7 +144,7 @@ class ICA_AROMA(CommandLine): def _format_arg(self, name, trait_spec, value): if name == "out_dir": return trait_spec.argstr % os.path.abspath(value) - return super(ICA_AROMA, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/fsl/base.py b/nipype/interfaces/fsl/base.py index 43ad7b9f9c..61010ee9a0 100644 --- a/nipype/interfaces/fsl/base.py +++ b/nipype/interfaces/fsl/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The fsl module provides classes for interfacing with the `FSL @@ -51,7 +50,6 @@ class Info(PackageInfo): >>> Info.version() # doctest: +SKIP >>> Info.output_type() # doctest: +SKIP - """ ftypes = { @@ -59,6 +57,7 @@ class Info(PackageInfo): "NIFTI_PAIR": ".img", "NIFTI_GZ": ".nii.gz", "NIFTI_PAIR_GZ": ".img.gz", + "GIFTI": ".func.gii", } if os.getenv("FSLDIR"): @@ -74,8 +73,8 @@ def output_type_to_ext(cls, output_type): Parameters ---------- - output_type : {'NIFTI', 'NIFTI_GZ', 'NIFTI_PAIR', 'NIFTI_PAIR_GZ'} - String specifying the output type. + output_type : {'NIFTI', 'NIFTI_GZ', 'NIFTI_PAIR', 'NIFTI_PAIR_GZ', 'GIFTI'} + String specifying the output type. Note: limited GIFTI support. Returns ------- @@ -146,14 +145,12 @@ class FSLCommandInputSpec(CommandLineInputSpec): class FSLCommand(CommandLine): - """Base support for FSL commands. - - """ + """Base support for FSL commands.""" input_spec = FSLCommandInputSpec _output_type = None - references_ = [ + _references = [ { "entry": BibTeX( "@article{JenkinsonBeckmannBehrensWoolrichSmith2012," @@ -171,7 +168,7 @@ class FSLCommand(CommandLine): ] def __init__(self, **inputs): - super(FSLCommand, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._output_update, "output_type") if self._output_type is None: @@ -209,8 +206,8 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, ext=None) """Generate a filename based on the given parameters. The filename will take the form: cwd/basename. - If change_ext is True, it will use the extentions specified in - intputs.output_type. + If change_ext is True, it will use the extensions specified in + inputs.output_type. Parameters ---------- @@ -241,7 +238,7 @@ def _gen_fname(self, basename, cwd=None, suffix=None, change_ext=True, ext=None) ext = Info.output_type_to_ext(self.inputs.output_type) if change_ext: if suffix: - suffix = "".join((suffix, ext)) + suffix = f"{suffix}{ext}" else: suffix = ext if suffix is None: @@ -266,10 +263,7 @@ def no_fsl(): used with skipif to skip tests that will fail if FSL is not installed""" - if Info.version() is None: - return True - else: - return False + return Info.version() is None def no_fsl_course_data(): diff --git a/nipype/interfaces/fsl/dti.py b/nipype/interfaces/fsl/dti.py index 90f05e3bab..cd46067daa 100644 --- a/nipype/interfaces/fsl/dti.py +++ b/nipype/interfaces/fsl/dti.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The fsl module provides classes for interfacing with the `FSL @@ -31,7 +30,7 @@ class DTIFitInputSpec(FSLCommandInputSpec): ) base_name = traits.Str( "dtifit_", - desc=("base_name that all output files " "will start with"), + desc=("base_name that all output files will start with"), argstr="-o %s", position=1, usedefault=True, @@ -80,16 +79,14 @@ class DTIFitOutputSpec(TraitedSpec): MO = File(exists=True, desc="path/name of file with the mode of anisotropy") S0 = File( exists=True, - desc=( - "path/name of file with the raw T2 signal with no " "diffusion weighting" - ), + desc=("path/name of file with the raw T2 signal with no diffusion weighting"), ) tensor = File(exists=True, desc="path/name of file with the 4D tensor volume") sse = File(exists=True, desc="path/name of file with the summed squared error") class DTIFit(FSLCommand): - """ Use FSL dtifit command for fitting a diffusion tensor model at each + """Use FSL dtifit command for fitting a diffusion tensor model at each voxel Example @@ -179,14 +176,14 @@ class FSLXCommandInputSpec(FSLCommandInputSpec): value=0, usedefault=True, argstr="--burnin=%d", - desc=("Total num of jumps at start of MCMC to be " "discarded"), + desc=("Total num of jumps at start of MCMC to be discarded"), ) burn_in_no_ard = traits.Range( low=0, value=0, usedefault=True, argstr="--burnin_noard=%d", - desc=("num of burnin jumps before the ard is" " imposed"), + desc=("num of burnin jumps before the ard is imposed"), ) sample_every = traits.Range( low=0, @@ -200,7 +197,7 @@ class FSLXCommandInputSpec(FSLCommandInputSpec): value=40, usedefault=True, argstr="--updateproposalevery=%d", - desc=("Num of jumps for each update " "to the proposal density std " "(MCMC)"), + desc=("Num of jumps for each update to the proposal density std (MCMC)"), ) seed = traits.Int( argstr="--seed=%d", desc="seed for pseudo random number generator" @@ -226,7 +223,7 @@ class FSLXCommandInputSpec(FSLCommandInputSpec): cnlinear = traits.Bool( argstr="--cnonlinear", xor=_xor_inputs2, - desc=("Initialise with constrained nonlinear " "fitting"), + desc=("Initialise with constrained nonlinear fitting"), ) rician = traits.Bool(argstr="--rician", desc=("use Rician noise modeling")) @@ -260,21 +257,21 @@ class FSLXCommandInputSpec(FSLCommandInputSpec): class FSLXCommandOutputSpec(TraitedSpec): dyads = OutputMultiPath( - File(exists=True), desc=("Mean of PDD distribution" " in vector form.") + File(exists=True), desc=("Mean of PDD distribution in vector form.") ) fsamples = OutputMultiPath( - File(exists=True), desc=("Samples from the " "distribution on f " "anisotropy") + File(exists=True), desc=("Samples from the distribution on f anisotropy") ) mean_dsamples = File(exists=True, desc="Mean of distribution on diffusivity d") mean_fsamples = OutputMultiPath( - File(exists=True), desc=("Mean of distribution on f " "anisotropy") + File(exists=True), desc=("Mean of distribution on f anisotropy") ) mean_S0samples = File( - exists=True, desc=("Mean of distribution on T2w" "baseline signal intensity S0") + exists=True, desc=("Mean of distribution on T2w baseline signal intensity S0") ) mean_tausamples = File( exists=True, - desc=("Mean of distribution on " "tau samples (only with rician " "noise)"), + desc=("Mean of distribution on tau samples (only with rician noise)"), ) phsamples = OutputMultiPath(File(exists=True), desc=("phi samples, per fiber")) thsamples = OutputMultiPath(File(exists=True), desc=("theta samples, per fiber")) @@ -290,7 +287,7 @@ class FSLXCommand(FSLCommand): def _run_interface(self, runtime): self._out_dir = os.getcwd() - runtime = super(FSLXCommand, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if runtime.stderr: self.raise_exception(runtime) return runtime @@ -364,7 +361,7 @@ class BEDPOSTX5InputSpec(FSLXCommandInputSpec): value=0, usedefault=True, argstr="-b %d", - desc=("Total num of jumps at start of MCMC to be " "discarded"), + desc=("Total num of jumps at start of MCMC to be discarded"), ) sample_every = traits.Range( low=0, @@ -382,7 +379,7 @@ class BEDPOSTX5InputSpec(FSLXCommandInputSpec): argstr="%s", ) gradnonlin = traits.Bool( - False, argstr="-g", desc=("consider gradient nonlinearities, " "default off") + False, argstr="-g", desc=("consider gradient nonlinearities, default off") ) grad_dev = File(exists=True, desc="grad_dev file, if gradnonlin, -g is True") use_gpu = traits.Bool(False, desc="Use the GPU version of bedpostx") @@ -391,10 +388,10 @@ class BEDPOSTX5InputSpec(FSLXCommandInputSpec): class BEDPOSTX5OutputSpec(TraitedSpec): mean_dsamples = File(exists=True, desc="Mean of distribution on diffusivity d") mean_fsamples = OutputMultiPath( - File(exists=True), desc=("Mean of distribution on f " "anisotropy") + File(exists=True), desc=("Mean of distribution on f anisotropy") ) mean_S0samples = File( - exists=True, desc=("Mean of distribution on T2w" "baseline signal intensity S0") + exists=True, desc=("Mean of distribution on T2w baseline signal intensity S0") ) mean_phsamples = OutputMultiPath( File(exists=True), desc="Mean of distribution on phi" @@ -403,14 +400,14 @@ class BEDPOSTX5OutputSpec(TraitedSpec): File(exists=True), desc="Mean of distribution on theta" ) merged_thsamples = OutputMultiPath( - File(exists=True), desc=("Samples from the distribution " "on theta") + File(exists=True), desc=("Samples from the distribution on theta") ) merged_phsamples = OutputMultiPath( - File(exists=True), desc=("Samples from the distribution " "on phi") + File(exists=True), desc=("Samples from the distribution on phi") ) merged_fsamples = OutputMultiPath( File(exists=True), - desc=("Samples from the distribution on " "anisotropic volume fraction"), + desc=("Samples from the distribution on anisotropic volume fraction"), ) dyads = OutputMultiPath( File(exists=True), desc="Mean of PDD distribution in vector form." @@ -452,7 +449,7 @@ class BEDPOSTX5(FSLXCommand): _can_resume = True def __init__(self, **inputs): - super(BEDPOSTX5, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._cuda_update, "use_gpu") def _cuda_update(self): @@ -462,7 +459,6 @@ def _cuda_update(self): self._cmd = self._default_cmd def _run_interface(self, runtime): - subjectdir = os.path.abspath(self.inputs.out_dir) if not os.path.exists(subjectdir): os.makedirs(subjectdir) @@ -476,7 +472,7 @@ def _run_interface(self, runtime): _, _, ext = split_filename(self.inputs.grad_dev) copyfile(self.inputs.grad_dev, os.path.join(subjectdir, "grad_dev" + ext)) - retval = super(BEDPOSTX5, self)._run_interface(runtime) + retval = super()._run_interface(runtime) self._out_dir = subjectdir + ".bedpostX" return retval @@ -559,7 +555,7 @@ class ProbTrackXBaseInputSpec(FSLCommandInputSpec): fsamples = InputMultiPath(File(exists=True), mandatory=True) samples_base_name = traits.Str( "merged", - desc=("the rootname/base_name for samples " "files"), + desc=("the rootname/base_name for samples files"), argstr="--samples=%s", usedefault=True, ) @@ -573,13 +569,13 @@ class ProbTrackXBaseInputSpec(FSLCommandInputSpec): File(exists=True), traits.List(File(exists=True)), traits.List(traits.List(traits.Int(), minlen=3, maxlen=3)), - desc=("seed volume(s), or voxel(s) or freesurfer " "label file"), + desc=("seed volume(s), or voxel(s) or freesurfer label file"), argstr="--seed=%s", mandatory=True, ) target_masks = InputMultiPath( File(exits=True), - desc=("list of target masks - required for " "seeds_to_targets classification"), + desc=("list of target masks - required for seeds_to_targets classification"), argstr="--targetmasks=%s", ) waypoints = File( @@ -625,7 +621,7 @@ class ProbTrackXBaseInputSpec(FSLCommandInputSpec): True, desc="outputs path distributions", argstr="--opd", usedefault=True ) correct_path_distribution = traits.Bool( - desc=("correct path distribution " "for the length of the " "pathways"), + desc=("correct path distribution for the length of the pathways"), argstr="--pd", ) os2t = traits.Bool(desc="Outputs seeds to targets", argstr="--os2t") @@ -633,7 +629,7 @@ class ProbTrackXBaseInputSpec(FSLCommandInputSpec): # desc='produces an output file (default is fdt_paths)') avoid_mp = File( exists=True, - desc=("reject pathways passing through locations given by " "this mask"), + desc=("reject pathways passing through locations given by this mask"), argstr="--avoid=%s", ) stop_mask = File( @@ -669,13 +665,13 @@ class ProbTrackXBaseInputSpec(FSLCommandInputSpec): ) dist_thresh = traits.Float( argstr="--distthresh=%.3f", - desc=("discards samples shorter than this " "threshold (in mm - default=0)"), + desc=("discards samples shorter than this threshold (in mm - default=0)"), ) c_thresh = traits.Float( argstr="--cthr=%.3f", desc="curvature threshold - default=0.2" ) - sample_random_points = traits.Bool( - argstr="--sampvox", desc=("sample random points within " "seed voxels") + sample_random_points = traits.Float( + argstr="--sampvox=%.3f", desc=("sample random points within seed voxels") ) step_length = traits.Float( argstr="--steplength=%.3f", desc="step_length in mm - default=0.5" @@ -714,7 +710,7 @@ class ProbTrackXBaseInputSpec(FSLCommandInputSpec): ), ) mod_euler = traits.Bool(argstr="--modeuler", desc="use modified euler streamlining") - random_seed = traits.Bool(argstr="--rseed", desc="random seed") + random_seed = traits.Int(argstr="--rseed=%d", desc="random seed") s2tastext = traits.Bool( argstr="--s2tastext", desc=( @@ -726,7 +722,7 @@ class ProbTrackXBaseInputSpec(FSLCommandInputSpec): 0, 1, 2, - desc=("Verbose level, [0-2]. Level 2 is required to " "output particle files."), + desc=("Verbose level, [0-2]. Level 2 is required to output particle files."), argstr="--verbose=%d", ) @@ -746,7 +742,7 @@ class ProbTrackXInputSpec(ProbTrackXBaseInputSpec): ) mask2 = File( exists=True, - desc=("second bet binary mask (in diffusion space) in " "twomask_symm mode"), + desc=("second bet binary mask (in diffusion space) in twomask_symm mode"), argstr="--mask2=%s", ) mesh = File( @@ -778,7 +774,7 @@ class ProbTrackXOutputSpec(TraitedSpec): ), ) targets = traits.List( - File(exists=True), desc=("a list with all generated seeds_to_target " "files") + File(exists=True), desc=("a list with all generated seeds_to_target files") ) particle_files = traits.List( File(exists=True), @@ -814,10 +810,10 @@ class ProbTrackX(FSLCommand): def __init__(self, **inputs): warnings.warn( - ("Deprecated: Please use create_bedpostx_pipeline " "instead"), + ("Deprecated: Please use create_bedpostx_pipeline instead"), DeprecationWarning, ) - return super(ProbTrackX, self).__init__(**inputs) + return super().__init__(**inputs) def _run_interface(self, runtime): for i in range(1, len(self.inputs.thsamples) + 1): @@ -854,7 +850,7 @@ def _run_interface(self, runtime): f.write("%s\n" % seed) f.close() - runtime = super(ProbTrackX, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if runtime.stderr: self.raise_exception(runtime) return runtime @@ -862,12 +858,12 @@ def _run_interface(self, runtime): def _format_arg(self, name, spec, value): if name == "target_masks" and isdefined(value): fname = "targets.txt" - return super(ProbTrackX, self)._format_arg(name, spec, [fname]) + return super()._format_arg(name, spec, [fname]) elif name == "seed" and isinstance(value, list): fname = "seeds.txt" - return super(ProbTrackX, self)._format_arg(name, spec, fname) + return super()._format_arg(name, spec, fname) else: - return super(ProbTrackX, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -877,7 +873,7 @@ def _list_outputs(self): out_dir = self.inputs.out_dir outputs["log"] = os.path.abspath(os.path.join(out_dir, "probtrackx.log")) - # utputs['way_total'] = os.path.abspath(os.path.join(out_dir, + # outputs['way_total'] = os.path.abspath(os.path.join(out_dir, # 'waytotal')) if isdefined(self.inputs.opd is True): if isinstance(self.inputs.seed, list) and isinstance( @@ -933,9 +929,7 @@ def _gen_filename(self, name): class ProbTrackX2InputSpec(ProbTrackXBaseInputSpec): simple = traits.Bool( - desc=( - "rack from a list of voxels (seed must be a " "ASCII list of coordinates)" - ), + desc=("rack from a list of voxels (seed must be a ASCII list of coordinates)"), argstr="--simple", ) fopd = File( @@ -947,7 +941,7 @@ class ProbTrackX2InputSpec(ProbTrackXBaseInputSpec): "OR", "AND", argstr="--waycond=%s", - desc=('Waypoint condition. Either "AND" (default) ' 'or "OR"'), + desc=('Waypoint condition. Either "AND" (default) or "OR"'), ) wayorder = traits.Bool( desc=( @@ -958,7 +952,7 @@ class ProbTrackX2InputSpec(ProbTrackXBaseInputSpec): argstr="--wayorder", ) onewaycondition = traits.Bool( - desc=("Apply waypoint conditions to each " "half tract separately"), + desc=("Apply waypoint conditions to each half tract separately"), argstr="--onewaycondition", ) omatrix1 = traits.Bool( @@ -992,7 +986,7 @@ class ProbTrackX2InputSpec(ProbTrackXBaseInputSpec): ) target3 = File( exists=True, - desc=("Mask used for NxN connectivity matrix (or Nxn if " "lrtarget3 is set)"), + desc=("Mask used for NxN connectivity matrix (or Nxn if lrtarget3 is set)"), argstr="--target3=%s", ) lrtarget3 = File( @@ -1009,7 +1003,7 @@ class ProbTrackX2InputSpec(ProbTrackXBaseInputSpec): ), ) omatrix4 = traits.Bool( - desc=("Output matrix4 - DtiMaskToSeed (special " "Oxford Sparse Format)"), + desc=("Output matrix4 - DtiMaskToSeed (special Oxford Sparse Format)"), argstr="--omatrix4", ) colmask4 = File( @@ -1034,18 +1028,18 @@ class ProbTrackX2InputSpec(ProbTrackXBaseInputSpec): class ProbTrackX2OutputSpec(ProbTrackXOutputSpec): network_matrix = File( - exists=True, desc=("the network matrix generated by --omatrix1 " "option") + exists=True, desc=("the network matrix generated by --omatrix1 option") ) matrix1_dot = File(exists=True, desc="Output matrix1.dot - SeedToSeed Connectivity") lookup_tractspace = File( - exists=True, desc=("lookup_tractspace generated by " "--omatrix2 option") + exists=True, desc=("lookup_tractspace generated by --omatrix2 option") ) matrix2_dot = File(exists=True, desc="Output matrix2.dot - SeedToLowResMask") matrix3_dot = File(exists=True, desc="Output matrix3 - NxN connectivity matrix") class ProbTrackX2(ProbTrackX): - """ Use FSL probtrackx2 for tractography on bedpostx results + """Use FSL probtrackx2 for tractography on bedpostx results Examples -------- @@ -1069,7 +1063,7 @@ class ProbTrackX2(ProbTrackX): output_spec = ProbTrackX2OutputSpec def _list_outputs(self): - outputs = super(ProbTrackX2, self)._list_outputs() + outputs = super()._list_outputs() if not isdefined(self.inputs.out_dir): out_dir = os.getcwd() @@ -1110,7 +1104,7 @@ class VecRegInputSpec(FSLCommandInputSpec): ) out_file = File( argstr="-o %s", - desc=("filename for output registered vector or tensor " "field"), + desc=("filename for output registered vector or tensor field"), genfile=True, hash_files=False, ) @@ -1126,7 +1120,7 @@ class VecRegInputSpec(FSLCommandInputSpec): warp_field = File( exists=True, argstr="-w %s", - desc=("filename for 4D warp field for nonlinear " "registration"), + desc=("filename for 4D warp field for nonlinear registration"), ) rotation_mat = File( exists=True, @@ -1162,14 +1156,14 @@ class VecRegInputSpec(FSLCommandInputSpec): ref_mask = File( exists=True, argstr="--refmask=%s", - desc=("brain mask in output space (useful for speed up of " "nonlinear reg)"), + desc=("brain mask in output space (useful for speed up of nonlinear reg)"), ) class VecRegOutputSpec(TraitedSpec): out_file = File( exists=True, - desc=("path/name of filename for the registered vector or " "tensor field"), + desc=("path/name of filename for the registered vector or tensor field"), ) @@ -1201,7 +1195,7 @@ def _run_interface(self, runtime): self.inputs.out_file = self._gen_fname( base_name, cwd=os.path.abspath(pth), suffix="_vreg" ) - return super(VecReg, self)._run_interface(runtime) + return super()._run_interface(runtime) def _list_outputs(self): outputs = self.output_spec().get() @@ -1242,7 +1236,7 @@ class ProjThreshInputSpec(FSLCommandInputSpec): class ProjThreshOuputSpec(TraitedSpec): out_files = traits.List( - File(exists=True), desc=("path/name of output volume after " "thresholding") + File(exists=True), desc=("path/name of output volume after thresholding") ) @@ -1275,7 +1269,7 @@ def _list_outputs(self): self._gen_fname( base_name, cwd=cwd, - suffix="_proj_seg_thr_{}".format(self.inputs.threshold), + suffix=f"_proj_seg_thr_{self.inputs.threshold}", ) ) return outputs @@ -1285,7 +1279,7 @@ class FindTheBiggestInputSpec(FSLCommandInputSpec): in_files = traits.List( File(exists=True), argstr="%s", - desc=("a list of input volumes or a " "singleMatrixFile"), + desc=("a list of input volumes or a singleMatrixFile"), position=0, mandatory=True, ) @@ -1329,7 +1323,7 @@ class FindTheBiggest(FSLCommand): def _run_interface(self, runtime): if not isdefined(self.inputs.out_file): self.inputs.out_file = self._gen_fname("biggestSegmentation", suffix="") - return super(FindTheBiggest, self)._run_interface(runtime) + return super()._run_interface(runtime) def _list_outputs(self): outputs = self.output_spec().get() @@ -1347,12 +1341,11 @@ def _gen_filename(self, name): class TractSkeletonInputSpec(FSLCommandInputSpec): - in_file = File( exists=True, mandatory=True, argstr="-i %s", - desc="input image (typcially mean FA volume)", + desc="input image (typically mean FA volume)", ) _proj_inputs = ["threshold", "distance_map", "data_file"] project_data = traits.Bool( @@ -1371,7 +1364,7 @@ class TractSkeletonInputSpec(FSLCommandInputSpec): True, usedefault=True, xor=["search_mask_file"], - desc=("perform alternate search using " "built-in cingulum mask"), + desc=("perform alternate search using built-in cingulum mask"), ) data_file = File(exists=True, desc="4D data to project onto skeleton (usually FA)") alt_data_file = File( @@ -1385,7 +1378,6 @@ class TractSkeletonInputSpec(FSLCommandInputSpec): class TractSkeletonOutputSpec(TraitedSpec): - projected_data = File(desc="input data projected onto skeleton") skeleton_file = File(desc="tract skeleton image") @@ -1402,7 +1394,7 @@ class TractSkeleton(FSLCommand): ``search_mask_file`` and ``use_cingulum_mask`` inputs are also used in data projection, but ``use_cingulum_mask`` is set to True by default. This mask controls where the projection algorithm searches within a circular space - around a tract, rather than in a single perpindicular direction. + around a tract, rather than in a single perpendicular direction. Example ------- @@ -1443,7 +1435,7 @@ def _format_arg(self, name, spec, value): return spec.argstr % self._list_outputs()["skeleton_file"] else: return spec.argstr % value - return super(TractSkeleton, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -1468,7 +1460,6 @@ def _list_outputs(self): class DistanceMapInputSpec(FSLCommandInputSpec): - in_file = File( exists=True, mandatory=True, @@ -1476,7 +1467,7 @@ class DistanceMapInputSpec(FSLCommandInputSpec): desc="image to calculate distance values for", ) mask_file = File( - exists=True, argstr="--mask=%s", desc="binary mask to contrain calculations" + exists=True, argstr="--mask=%s", desc="binary mask to constrain calculations" ) invert_input = traits.Bool(argstr="--invert", desc="invert input image") local_max_file = traits.Either( @@ -1492,7 +1483,6 @@ class DistanceMapInputSpec(FSLCommandInputSpec): class DistanceMapOutputSpec(TraitedSpec): - distance_map = File(exists=True, desc="value is distance to nearest nonzero voxels") local_max_file = File(desc="image of local maxima") @@ -1519,7 +1509,7 @@ def _format_arg(self, name, spec, value): if name == "local_max_file": if isinstance(value, bool): return spec.argstr % self._list_outputs()["local_max_file"] - return super(DistanceMap, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/fsl/epi.py b/nipype/interfaces/fsl/epi.py index 88250eb1b2..7dda9a49d7 100644 --- a/nipype/interfaces/fsl/epi.py +++ b/nipype/interfaces/fsl/epi.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The fsl module provides classes for interfacing with the `FSL @@ -11,7 +10,6 @@ import warnings from ...utils.filemanip import split_filename, fname_presuffix -from ...utils import NUMPY_MMAP from ..base import traits, TraitedSpec, InputMultiPath, File, isdefined from .base import FSLCommand, FSLCommandInputSpec, Info @@ -26,9 +24,7 @@ class PrepareFieldmapInputSpec(FSLCommandInputSpec): argstr="%s", position=2, mandatory=True, - desc=( - "Phase difference map, in SIEMENS format range from " "0-4096 or 0-8192)" - ), + desc=("Phase difference map, in SIEMENS format range from 0-4096 or 0-8192)"), ) in_magnitude = File( exists=True, @@ -54,7 +50,7 @@ class PrepareFieldmapInputSpec(FSLCommandInputSpec): position=-1, argstr="--nocheck", usedefault=True, - desc=("do not perform sanity checks for image " "size/range/dimensions"), + desc=("do not perform sanity checks for image size/range/dimensions"), ) out_fieldmap = File( argstr="%s", position=4, desc="output name for prepared fieldmap" @@ -106,7 +102,7 @@ def _parse_inputs(self, skip=None): if not isdefined(self.inputs.nocheck) or not self.inputs.nocheck: skip += ["nocheck"] - return super(PrepareFieldmap, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _list_outputs(self): outputs = self.output_spec().get() @@ -114,11 +110,11 @@ def _list_outputs(self): return outputs def _run_interface(self, runtime): - runtime = super(PrepareFieldmap, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if runtime.returncode == 0: out_file = self.inputs.out_fieldmap - im = nb.load(out_file, mmap=NUMPY_MMAP) + im = nb.load(out_file) dumb_img = nb.Nifti1Image(np.zeros(im.shape), im.affine, im.header) out_nii = nb.funcs.concat_images((im, dumb_img)) nb.save(out_nii, out_file) @@ -146,14 +142,14 @@ class TOPUPInputSpec(FSLCommandInputSpec): xor=["encoding_file"], requires=["readout_times"], argstr="--datain=%s", - desc=("encoding direction for automatic " "generation of encoding_file"), + desc=("encoding direction for automatic generation of encoding_file"), ) readout_times = InputMultiPath( traits.Float, requires=["encoding_direction"], xor=["encoding_file"], mandatory=True, - desc=("readout times (dwell times by # " "phase-encode steps minus 1)"), + desc=("readout times (dwell times by # phase-encode steps minus 1)"), ) out_base = File( desc=( @@ -226,7 +222,7 @@ class TOPUPInputSpec(FSLCommandInputSpec): "b02b0.cnf", argstr="--config=%s", usedefault=True, - desc=("Name of config file specifying command line " "arguments"), + desc=("Name of config file specifying command line arguments"), ) max_iter = traits.Int(argstr="--miter=%d", desc="max # of non-linear iterations") reg_lambda = traits.Float( @@ -272,19 +268,17 @@ class TOPUPInputSpec(FSLCommandInputSpec): 0, 1, argstr="--minmet=%d", - desc=( - "Minimisation method 0=Levenberg-Marquardt, " "1=Scaled Conjugate Gradient" - ), + desc=("Minimisation method 0=Levenberg-Marquardt, 1=Scaled Conjugate Gradient"), ) splineorder = traits.Int( argstr="--splineorder=%d", - desc=("order of spline, 2->Qadratic spline, " "3->Cubic spline"), + desc=("order of spline, 2->Qadratic spline, 3->Cubic spline"), ) numprec = traits.Enum( "double", "float", argstr="--numprec=%s", - desc=("Precision for representing Hessian, double " "or float."), + desc=("Precision for representing Hessian, double or float."), ) interp = traits.Enum( "spline", @@ -296,13 +290,13 @@ class TOPUPInputSpec(FSLCommandInputSpec): 0, 1, argstr="--scale=%d", - desc=("If set (=1), the images are individually scaled" " to a common mean"), + desc=("If set (=1), the images are individually scaled to a common mean"), ) regrid = traits.Enum( 1, 0, argstr="--regrid=%d", - desc=("If set (=1), the calculations are done in a " "different grid"), + desc=("If set (=1), the calculations are done in a different grid"), ) @@ -357,10 +351,10 @@ def _format_arg(self, name, trait_spec, value): if path != "": if not os.path.exists(path): raise ValueError("out_base path must exist if provided") - return super(TOPUP, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _list_outputs(self): - outputs = super(TOPUP, self)._list_outputs() + outputs = super()._list_outputs() del outputs["out_base"] base_path = None if isdefined(self.inputs.out_base): @@ -403,17 +397,14 @@ def _get_encfilename(self): return out_file def _generate_encfile(self): - """Generate a topup compatible encoding file based on given directions - """ + """Generate a topup compatible encoding file based on given directions""" out_file = self._get_encfilename() durations = self.inputs.readout_times if len(self.inputs.encoding_direction) != len(durations): if len(self.inputs.readout_times) != 1: raise ValueError( - ( - "Readout time must be a float or match the" - "length of encoding directions" - ) + "Readout time must be a float or match the" + "length of encoding directions" ) durations = durations * len(self.inputs.encoding_direction) @@ -426,13 +417,13 @@ def _generate_encfile(self): float(val[0] == encdir[0]) * direction for val in ["x", "y", "z"] ] + [durations[idx]] lines.append(line) - np.savetxt(out_file, np.array(lines), fmt=b"%d %d %d %.8f") + np.savetxt(out_file, np.array(lines), fmt="%d %d %d %.8f") return out_file def _overload_extension(self, value, name=None): if name == "out_base": return value - return super(TOPUP, self)._overload_extension(value, name) + return super()._overload_extension(value, name) class ApplyTOPUPInputSpec(FSLCommandInputSpec): @@ -460,7 +451,7 @@ class ApplyTOPUPInputSpec(FSLCommandInputSpec): argstr="--topup=%s", copyfile=False, requires=["in_topup_movpar"], - desc=("topup file containing the field " "coefficients"), + desc=("topup file containing the field coefficients"), ) in_topup_movpar = File( exists=True, @@ -478,7 +469,7 @@ class ApplyTOPUPInputSpec(FSLCommandInputSpec): "jac", "lsr", argstr="--method=%s", - desc=("use jacobian modulation (jac) or least-squares" " resampling (lsr)"), + desc=("use jacobian modulation (jac) or least-squares resampling (lsr)"), ) interp = traits.Enum( "trilinear", "spline", argstr="--interp=%s", desc="interpolation method" @@ -496,7 +487,7 @@ class ApplyTOPUPInputSpec(FSLCommandInputSpec): class ApplyTOPUPOutputSpec(TraitedSpec): out_corrected = File( - exists=True, desc=("name of 4D image file with " "unwarped images") + exists=True, desc=("name of 4D image file with unwarped images") ) @@ -540,12 +531,12 @@ def _parse_inputs(self, skip=None): if not isdefined(self.inputs.in_index): self.inputs.in_index = list(range(1, len(self.inputs.in_files) + 1)) - return super(ApplyTOPUP, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _format_arg(self, name, spec, value): if name == "in_topup_fieldcoef": return spec.argstr % value.split("_fieldcoef")[0] - return super(ApplyTOPUP, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class EddyInputSpec(FSLCommandInputSpec): @@ -606,9 +597,7 @@ class EddyInputSpec(FSLCommandInputSpec): desc="Topup results file containing the movement parameters (movpar.txt)", ) field = File( - exists=True, - argstr="--field=%s", - desc="Non-topup derived fieldmap scaled in Hz", + exists=True, argstr="--field=%s", desc="Non-topup derived fieldmap scaled in Hz" ) field_mat = File( exists=True, @@ -855,12 +844,6 @@ class EddyOutputSpec(TraitedSpec): "between the different shells as estimated by a " "post-hoc mutual information based registration", ) - out_shell_pe_translation_parameters = File( - exists=True, - desc="Text file containing translation along the PE-direction " - "between the different shells as estimated by a " - "post-hoc mutual information based registration", - ) out_outlier_map = File( exists=True, desc="Matrix where rows represent volumes and columns represent " @@ -961,7 +944,7 @@ class Eddy(FSLCommand): _num_threads = 1 def __init__(self, **inputs): - super(Eddy, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change(self._num_threads_update, "num_threads") if not isdefined(self.inputs.num_threads): self.inputs.num_threads = self._num_threads @@ -994,7 +977,7 @@ def _run_interface(self, runtime): ) ): self._cmd = "eddy" - runtime = super(Eddy, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) # Restore command to avoid side-effects self._cmd = cmd @@ -1007,7 +990,7 @@ def _format_arg(self, name, spec, value): return spec.argstr % fname_presuffix(value, use_ext=False) if name == "out_base": return spec.argstr % os.path.abspath(value) - return super(Eddy, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -1076,9 +1059,9 @@ def _list_outputs(self): if os.path.exists(out_shell_alignment_parameters): outputs["out_shell_alignment_parameters"] = out_shell_alignment_parameters if os.path.exists(out_shell_pe_translation_parameters): - outputs[ - "out_shell_pe_translation_parameters" - ] = out_shell_pe_translation_parameters + outputs["out_shell_pe_translation_parameters"] = ( + out_shell_pe_translation_parameters + ) if os.path.exists(out_outlier_map): outputs["out_outlier_map"] = out_outlier_map if os.path.exists(out_outlier_n_stdev_map): @@ -1307,20 +1290,19 @@ def _list_outputs(self): outputs["epi2str_inv"] = os.path.join( os.getcwd(), self.inputs.out_base + "_inv.mat" ) - + if not isdefined(self.inputs.wmseg): + outputs["wmedge"] = os.path.join( + os.getcwd(), self.inputs.out_base + "_fast_wmedge.nii.gz" + ) + outputs["wmseg"] = os.path.join( + os.getcwd(), self.inputs.out_base + "_fast_wmseg.nii.gz" + ) + outputs["seg"] = os.path.join( + os.getcwd(), self.inputs.out_base + "_fast_seg.nii.gz" + ) outputs["epi2str_mat"] = os.path.join( os.getcwd(), self.inputs.out_base + ".mat" ) - outputs["wmedge"] = os.path.join( - os.getcwd(), self.inputs.out_base + "_fast_wmedge.nii.gz" - ) - outputs["wmseg"] = os.path.join( - os.getcwd(), self.inputs.out_base + "_fast_wmseg.nii.gz" - ) - outputs["seg"] = os.path.join( - os.getcwd(), self.inputs.out_base + "_fast_seg.nii.gz" - ) - return outputs @@ -1422,10 +1404,10 @@ def __init__(self, **inputs): ), DeprecationWarning, ) - return super(EPIDeWarp, self).__init__(**inputs) + return super().__init__(**inputs) def _run_interface(self, runtime): - runtime = super(EPIDeWarp, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if runtime.stderr: self.raise_exception(runtime) return runtime @@ -1522,13 +1504,13 @@ class EddyCorrect(FSLCommand): def __init__(self, **inputs): warnings.warn( - ("Deprecated: Please use nipype.interfaces.fsl.epi.Eddy " "instead"), + ("Deprecated: Please use nipype.interfaces.fsl.epi.Eddy instead"), DeprecationWarning, ) - return super(EddyCorrect, self).__init__(**inputs) + return super().__init__(**inputs) def _run_interface(self, runtime): - runtime = super(EddyCorrect, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if runtime.stderr: self.raise_exception(runtime) return runtime @@ -1549,7 +1531,7 @@ class EddyQuadInputSpec(FSLCommandInputSpec): exists=True, mandatory=True, argstr="--eddyIdx %s", - desc=("File containing indices for all volumes into acquisition " "parameters"), + desc=("File containing indices for all volumes into acquisition parameters"), ) param_file = File( exists=True, @@ -1577,21 +1559,19 @@ class EddyQuadInputSpec(FSLCommandInputSpec): argstr="--output-dir %s", desc="Output directory - default = '.qc'", ) - field = File( - exists=True, argstr="--field %s", desc="TOPUP estimated field (in Hz)", - ) + field = File(exists=True, argstr="--field %s", desc="TOPUP estimated field (in Hz)") slice_spec = File( exists=True, argstr="--slspec %s", desc="Text file specifying slice/group acquisition", ) - verbose = traits.Bool(argstr="--verbose", desc="Display debug messages",) + verbose = traits.Bool(argstr="--verbose", desc="Display debug messages") class EddyQuadOutputSpec(TraitedSpec): qc_json = File( exists=True, - desc=("Single subject database containing quality metrics and data " "info."), + desc=("Single subject database containing quality metrics and data info."), ) qc_pdf = File(exists=True, desc="Single subject QC report.") avg_b_png = traits.List( diff --git a/nipype/interfaces/fsl/fix.py b/nipype/interfaces/fsl/fix.py index 769513f8c3..2799c53104 100644 --- a/nipype/interfaces/fsl/fix.py +++ b/nipype/interfaces/fsl/fix.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The fix module provides classes for interfacing with the `FSL FIX @@ -96,7 +95,7 @@ class TrainingSetCreator(BaseInterface): the ones that have a hand_labels_noise.txt file in them. This is outsourced as a separate class, so that the pipeline is - rerun everytime a handlabeled file has been changed, or a new one + rerun every time a handlabeled file has been changed, or a new one created. """ @@ -106,11 +105,11 @@ class TrainingSetCreator(BaseInterface): _always_run = True def _run_interface(self, runtime): - mel_icas = [] - for item in self.inputs.mel_icas_in: - if os.path.exists(os.path.join(item, "hand_labels_noise.txt")): - mel_icas.append(item) - + mel_icas = [ + item + for item in self.inputs.mel_icas_in + if os.path.exists(os.path.join(item, "hand_labels_noise.txt")) + ] if len(mel_icas) == 0: raise Exception( "%s did not find any hand_labels_noise.txt files in the following directories: %s" @@ -120,10 +119,11 @@ def _run_interface(self, runtime): return runtime def _list_outputs(self): - mel_icas = [] - for item in self.inputs.mel_icas_in: - if os.path.exists(os.path.join(item, "hand_labels_noise.txt")): - mel_icas.append(item) + mel_icas = [ + item + for item in self.inputs.mel_icas_in + if os.path.exists(os.path.join(item, "hand_labels_noise.txt")) + ] outputs = self._outputs().get() outputs["mel_icas_out"] = mel_icas return outputs @@ -302,7 +302,6 @@ class Classifier(CommandLine): cmd = "fix -c" def _gen_artifacts_list_file(self, mel_ica, thresh): - _, trained_wts_file = os.path.split(self.inputs.trained_wts_file) trained_wts_filestem = trained_wts_file.split(".")[0] filestem = "fix4melview_" + trained_wts_filestem + "_thr" @@ -375,8 +374,8 @@ class Cleaner(CommandLine): cmd = "fix -a" def _get_cleaned_functional_filename(self, artifacts_list_filename): - """ extract the proper filename from the first line of the artifacts file """ - artifacts_list_file = open(artifacts_list_filename, "r") + """extract the proper filename from the first line of the artifacts file""" + artifacts_list_file = open(artifacts_list_filename) functional_filename, extension = artifacts_list_file.readline().split(".") artifacts_list_file_path, artifacts_list_filename = os.path.split( artifacts_list_filename diff --git a/nipype/interfaces/fsl/maths.py b/nipype/interfaces/fsl/maths.py index 1b64511f9e..7640cf930b 100644 --- a/nipype/interfaces/fsl/maths.py +++ b/nipype/interfaces/fsl/maths.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -13,7 +12,6 @@ class MathsInput(FSLCommandInputSpec): - in_file = File( position=2, argstr="%s", exists=True, mandatory=True, desc="image to operate on" ) @@ -25,13 +23,13 @@ class MathsInput(FSLCommandInputSpec): *_dtypes, position=1, argstr="-dt %s", - desc=("datatype to use for calculations " "(default is float)") + desc=("datatype to use for calculations (default is float)") ) output_datatype = traits.Enum( *_dtypes, position=-1, argstr="-odt %s", - desc=("datatype to use for output (default " "uses input type)") + desc=("datatype to use for output (default uses input type)") ) nan2zeros = traits.Bool( @@ -40,12 +38,10 @@ class MathsInput(FSLCommandInputSpec): class MathsOutput(TraitedSpec): - - out_file = File(exists=True, desc="image written after calculations") + out_file = File(desc="image written after calculations") class MathsCommand(FSLCommand): - _cmd = "fslmaths" input_spec = MathsInput output_spec = MathsOutput @@ -68,7 +64,6 @@ def _gen_filename(self, name): class ChangeDataTypeInput(MathsInput): - _dtypes = ["float", "char", "int", "short", "double", "input"] output_datatype = traits.Enum( *_dtypes, position=-1, argstr="-odt %s", mandatory=True, desc="output data type" @@ -76,16 +71,13 @@ class ChangeDataTypeInput(MathsInput): class ChangeDataType(MathsCommand): - """Use fslmaths to change the datatype of an image. - - """ + """Use fslmaths to change the datatype of an image.""" input_spec = ChangeDataTypeInput _suffix = "_chdt" class ThresholdInputSpec(MathsInput): - thresh = traits.Float( mandatory=True, position=4, argstr="%s", desc="threshold value" ) @@ -105,9 +97,7 @@ class ThresholdInputSpec(MathsInput): class Threshold(MathsCommand): - """Use fslmaths to apply a threshold to an image in a variety of ways. - - """ + """Use fslmaths to apply a threshold to an image in a variety of ways.""" input_spec = ThresholdInputSpec _suffix = "_thresh" @@ -126,11 +116,10 @@ def _format_arg(self, name, spec, value): arg += "p" arg += " %.10f" % value return arg - return super(Threshold, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class StdImageInput(MathsInput): - dimension = traits.Enum( "T", "X", @@ -153,7 +142,6 @@ class StdImage(MathsCommand): class MeanImageInput(MathsInput): - dimension = traits.Enum( "T", "X", @@ -167,16 +155,13 @@ class MeanImageInput(MathsInput): class MeanImage(MathsCommand): - """Use fslmaths to generate a mean image across a given dimension. - - """ + """Use fslmaths to generate a mean image across a given dimension.""" input_spec = MeanImageInput _suffix = "_mean" class MaxImageInput(MathsInput): - dimension = traits.Enum( "T", "X", @@ -208,7 +193,6 @@ class MaxImage(MathsCommand): class PercentileImageInput(MathsInput): - dimension = traits.Enum( "T", "X", @@ -224,7 +208,7 @@ class PercentileImageInput(MathsInput): high=100, argstr="%f", position=5, - desc=("nth percentile (0-100) of FULL RANGE " "across dimension"), + desc=("nth percentile (0-100) of FULL RANGE across dimension"), ) @@ -248,7 +232,6 @@ class PercentileImage(MathsCommand): class MaxnImageInput(MathsInput): - dimension = traits.Enum( "T", "X", @@ -272,7 +255,6 @@ class MaxnImage(MathsCommand): class MinImageInput(MathsInput): - dimension = traits.Enum( "T", "X", @@ -286,16 +268,13 @@ class MinImageInput(MathsInput): class MinImage(MathsCommand): - """Use fslmaths to generate a minimum image across a given dimension. - - """ + """Use fslmaths to generate a minimum image across a given dimension.""" input_spec = MinImageInput _suffix = "_min" class MedianImageInput(MathsInput): - dimension = traits.Enum( "T", "X", @@ -309,16 +288,13 @@ class MedianImageInput(MathsInput): class MedianImage(MathsCommand): - """Use fslmaths to generate a median image across a given dimension. - - """ + """Use fslmaths to generate a median image across a given dimension.""" input_spec = MedianImageInput _suffix = "_median" class AR1ImageInput(MathsInput): - dimension = traits.Enum( "T", "X", @@ -327,7 +303,7 @@ class AR1ImageInput(MathsInput): usedefault=True, argstr="-%sar1", position=4, - desc=("dimension to find AR(1) coefficient" "across"), + desc=("dimension to find AR(1) coefficient across"), ) @@ -342,7 +318,6 @@ class AR1Image(MathsCommand): class IsotropicSmoothInput(MathsInput): - fwhm = traits.Float( mandatory=True, xor=["sigma"], @@ -360,9 +335,7 @@ class IsotropicSmoothInput(MathsInput): class IsotropicSmooth(MathsCommand): - """Use fslmaths to spatially smooth an image with a gaussian kernel. - - """ + """Use fslmaths to spatially smooth an image with a gaussian kernel.""" input_spec = IsotropicSmoothInput _suffix = "_smooth" @@ -371,11 +344,10 @@ def _format_arg(self, name, spec, value): if name == "fwhm": sigma = float(value) / np.sqrt(8 * np.log(2)) return spec.argstr % sigma - return super(IsotropicSmooth, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class ApplyMaskInput(MathsInput): - mask_file = File( exists=True, mandatory=True, @@ -386,16 +358,13 @@ class ApplyMaskInput(MathsInput): class ApplyMask(MathsCommand): - """Use fslmaths to apply a binary mask to another image. - - """ + """Use fslmaths to apply a binary mask to another image.""" input_spec = ApplyMaskInput _suffix = "_masked" class KernelInput(MathsInput): - kernel_shape = traits.Enum( "3D", "2D", @@ -412,9 +381,7 @@ class KernelInput(MathsInput): argstr="%.4f", position=5, xor=["kernel_file"], - desc=( - "kernel size - voxels for box/boxv, mm " "for sphere, mm sigma for gauss" - ), + desc=("kernel size - voxels for box/boxv, mm for sphere, mm sigma for gauss"), ) kernel_file = File( exists=True, @@ -426,7 +393,6 @@ class KernelInput(MathsInput): class DilateInput(KernelInput): - operation = traits.Enum( "mean", "modal", @@ -434,14 +400,12 @@ class DilateInput(KernelInput): argstr="-dil%s", position=6, mandatory=True, - desc="filtering operation to perfoem in dilation", + desc="filtering operation to perform in dilation", ) class DilateImage(MathsCommand): - """Use fslmaths to perform a spatial dilation of an image. - - """ + """Use fslmaths to perform a spatial dilation of an image.""" input_spec = DilateInput _suffix = "_dil" @@ -449,24 +413,21 @@ class DilateImage(MathsCommand): def _format_arg(self, name, spec, value): if name == "operation": return spec.argstr % dict(mean="M", modal="D", max="F")[value] - return super(DilateImage, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class ErodeInput(KernelInput): - minimum_filter = traits.Bool( argstr="%s", position=6, usedefault=True, default_value=False, - desc=("if true, minimum filter rather than " "erosion by zeroing-out"), + desc=("if true, minimum filter rather than erosion by zeroing-out"), ) class ErodeImage(MathsCommand): - """Use fslmaths to perform a spatial erosion of an image. - - """ + """Use fslmaths to perform a spatial erosion of an image.""" input_spec = ErodeInput _suffix = "_ero" @@ -476,11 +437,10 @@ def _format_arg(self, name, spec, value): if value: return "-eroF" return "-ero" - return super(ErodeImage, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class SpatialFilterInput(KernelInput): - operation = traits.Enum( "mean", "median", @@ -493,16 +453,13 @@ class SpatialFilterInput(KernelInput): class SpatialFilter(MathsCommand): - """Use fslmaths to spatially filter an image. - - """ + """Use fslmaths to spatially filter an image.""" input_spec = SpatialFilterInput _suffix = "_filt" class UnaryMathsInput(MathsInput): - operation = traits.Enum( "exp", "log", @@ -535,19 +492,16 @@ class UnaryMathsInput(MathsInput): class UnaryMaths(MathsCommand): - """Use fslmaths to perorm a variety of mathematical operations on an image. - - """ + """Use fslmaths to perorm a variety of mathematical operations on an image.""" input_spec = UnaryMathsInput def _list_outputs(self): self._suffix = "_" + self.inputs.operation - return super(UnaryMaths, self)._list_outputs() + return super()._list_outputs() class BinaryMathsInput(MathsInput): - operation = traits.Enum( "add", "sub", @@ -588,17 +542,16 @@ class BinaryMaths(MathsCommand): class MultiImageMathsInput(MathsInput): - op_string = traits.String( position=4, argstr="%s", mandatory=True, - desc=("python formatted string of operations " "to perform"), + desc=("python formatted string of operations to perform"), ) operand_files = InputMultiPath( File(exists=True), mandatory=True, - desc=("list of file names to plug into op " "string"), + desc=("list of file names to plug into op string"), ) @@ -623,11 +576,10 @@ class MultiImageMaths(MathsCommand): def _format_arg(self, name, spec, value): if name == "op_string": return value % tuple(self.inputs.operand_files) - return super(MultiImageMaths, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class TemporalFilterInput(MathsInput): - lowpass_sigma = traits.Float( -1, argstr="%.6f", diff --git a/nipype/interfaces/fsl/model.py b/nipype/interfaces/fsl/model.py index e06377cb4d..2ada4ab969 100644 --- a/nipype/interfaces/fsl/model.py +++ b/nipype/interfaces/fsl/model.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The fsl module provides classes for interfacing with the `FSL @@ -10,16 +9,18 @@ from shutil import rmtree from string import Template +import acres import numpy as np +from looseversion import LooseVersion from nibabel import load -from ... import LooseVersion from ...utils.filemanip import simplify_list, ensure_list from ...utils.misc import human_order_sorted from ...external.due import BibTeX from ..base import ( File, traits, + Tuple, isdefined, TraitedSpec, BaseInterface, @@ -37,7 +38,7 @@ class Level1DesignInputSpec(BaseInterfaceInputSpec): ) session_info = traits.Any( mandatory=True, - desc=("Session specific information generated " "by ``modelgen.SpecifyModel``"), + desc=("Session specific information generated by ``modelgen.SpecifyModel``"), ) bases = traits.Either( traits.Dict( @@ -53,9 +54,7 @@ class Level1DesignInputSpec(BaseInterfaceInputSpec): traits.Dict(traits.Enum("none"), traits.Dict()), traits.Dict(traits.Enum("none"), traits.Enum(None)), mandatory=True, - desc=( - "name of basis function and options e.g., " "{'dgamma': {'derivs': True}}" - ), + desc=("name of basis function and options e.g., {'dgamma': {'derivs': True}}"), ) orthogonalization = traits.Dict( traits.Int, @@ -76,31 +75,31 @@ class Level1DesignInputSpec(BaseInterfaceInputSpec): ) contrasts = traits.List( traits.Either( - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("F"), traits.List( traits.Either( - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), @@ -144,13 +143,12 @@ class Level1Design(BaseInterface): output_spec = Level1DesignOutputSpec def _create_ev_file(self, evfname, evinfo): - f = open(evfname, "wt") - for i in evinfo: - if len(i) == 3: - f.write("%f %f %f\n" % (i[0], i[1], i[2])) - else: - f.write("%f\n" % i[0]) - f.close() + with open(evfname, "w") as f: + for i in evinfo: + if len(i) == 3: + f.write(f"{i[0]:f} {i[1]:f} {i[2]:f}\n") + else: + f.write("%f\n" % i[0]) def _create_ev_files( self, @@ -165,21 +163,21 @@ def _create_ev_files( ): """Creates EV files from condition and regressor information. - Parameters: - ----------- - - runinfo : dict - Generated by `SpecifyModel` and contains information - about events and other regressors. - runidx : int - Index to run number - ev_parameters : dict - A dictionary containing the model parameters for the - given design type. - orthogonalization : dict - A dictionary of dictionaries specifying orthogonal EVs. - contrasts : list of lists - Information on contrasts to be evaluated + Parameters: + ----------- + + runinfo : dict + Generated by `SpecifyModel` and contains information + about events and other regressors. + runidx : int + Index to run number + ev_parameters : dict + A dictionary containing the model parameters for the + given design type. + orthogonalization : dict + A dictionary of dictionaries specifying orthogonal EVs. + contrasts : list of lists + Information on contrasts to be evaluated """ conds = {} evname = [] @@ -261,7 +259,7 @@ def _create_ev_files( # add ev orthogonalization for i in range(1, num_evs[0] + 1): initial = ev_ortho.substitute(c0=i, c1=0, orthogonal=1) - for j in range(0, num_evs[0] + 1): + for j in range(num_evs[0] + 1): try: orthogonal = int(orthogonalization[i][j]) except (KeyError, TypeError, ValueError, IndexError): @@ -321,7 +319,7 @@ def _create_ev_files( for fconidx in ftest_idx: fval = 0 - if con[0] in con_map.keys() and fconidx in con_map[con[0]]: + if con[0] in con_map and fconidx in con_map[con[0]]: fval = 1 ev_txt += contrast_ftest_element.substitute( cnum=ftest_idx.index(fconidx) + 1, @@ -346,8 +344,7 @@ def _format_session_info(self, session_info): return session_info def _get_func_files(self, session_info): - """Returns functional files in the order of runs - """ + """Returns functional files in the order of runs""" func_files = [] for i, info in enumerate(session_info): func_files.insert(i, info["scans"]) @@ -406,9 +403,8 @@ def _run_interface(self, runtime): fsf_txt += cond_txt fsf_txt += fsf_postscript.substitute(overwrite=1) - f = open(os.path.join(cwd, "run%d.fsf" % i), "w") - f.write(fsf_txt) - f.close() + with open(os.path.join(cwd, "run%d.fsf" % i), "w") as f: + f.write(fsf_txt) return runtime @@ -457,8 +453,7 @@ class FEATOutputSpec(TraitedSpec): class FEAT(FSLCommand): - """Uses FSL feat to calculate first level stats - """ + """Uses FSL feat to calculate first level stats""" _cmd = "feat" input_spec = FEATInputSpec @@ -468,7 +463,7 @@ def _list_outputs(self): outputs = self._outputs().get() is_ica = False outputs["feat_dir"] = None - with open(self.inputs.fsf_file, "rt") as fp: + with open(self.inputs.fsf_file) as fp: text = fp.read() if "set fmri(inmelodic) 1" in text: is_ica = True @@ -486,7 +481,6 @@ def _list_outputs(self): outputs["feat_dir"] = glob(os.path.join(os.getcwd(), "*ica"))[0] else: outputs["feat_dir"] = glob(os.path.join(os.getcwd(), "*feat"))[0] - print("Outputs from FEATmodel:", outputs) return outputs @@ -518,8 +512,7 @@ class FEATModelOutpuSpec(TraitedSpec): class FEATModel(FSLCommand): - """Uses FSL feat_model to generate design.mat files - """ + """Uses FSL feat_model to generate design.mat files""" _cmd = "feat_model" input_spec = FEATModelInputSpec @@ -527,13 +520,11 @@ class FEATModel(FSLCommand): def _format_arg(self, name, trait_spec, value): if name == "fsf_file": - return super(FEATModel, self)._format_arg( - name, trait_spec, self._get_design_root(value) - ) + return super()._format_arg(name, trait_spec, self._get_design_root(value)) elif name == "ev_files": return "" else: - return super(FEATModel, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _get_design_root(self, infile): _, fname = os.path.split(infile) @@ -580,7 +571,7 @@ class FILMGLSInputSpec(FSLCommandInputSpec): brightness_threshold = traits.Range( low=0, argstr="-epith %d", - desc=("susan brightness threshold, " "otherwise it is estimated"), + desc=("susan brightness threshold, otherwise it is estimated"), ) full_data = traits.Bool(argstr="-v", desc="output full data") _estimate_xor = [ @@ -594,7 +585,7 @@ class FILMGLSInputSpec(FSLCommandInputSpec): autocorr_estimate_only = traits.Bool( argstr="-ac", xor=_estimate_xor, - desc=("perform autocorrelation " "estimatation only"), + desc=("perform autocorrelation estimatation only"), ) fit_armodel = traits.Bool( argstr="-ar", @@ -624,7 +615,7 @@ class FILMGLSInputSpec(FSLCommandInputSpec): ) output_pwdata = traits.Bool( argstr="-output_pwdata", - desc=("output prewhitened data and average " "design matrix"), + desc=("output prewhitened data and average design matrix"), ) results_dir = Directory( "results", @@ -658,7 +649,7 @@ class FILMGLSInputSpec505(FSLCommandInputSpec): brightness_threshold = traits.Range( low=0, argstr="--epith=%d", - desc=("susan brightness threshold, " "otherwise it is estimated"), + desc=("susan brightness threshold, otherwise it is estimated"), ) full_data = traits.Bool(argstr="-v", desc="output full data") _estimate_xor = [ @@ -672,7 +663,7 @@ class FILMGLSInputSpec505(FSLCommandInputSpec): autocorr_estimate_only = traits.Bool( argstr="--ac", xor=_estimate_xor, - desc=("perform autocorrelation " "estimation only"), + desc=("perform autocorrelation estimation only"), ) fit_armodel = traits.Bool( argstr="--ar", @@ -702,7 +693,7 @@ class FILMGLSInputSpec505(FSLCommandInputSpec): ) output_pwdata = traits.Bool( argstr="--outputPWdata", - desc=("output prewhitened data and average " "design matrix"), + desc=("output prewhitened data and average design matrix"), ) results_dir = Directory( "results", @@ -732,18 +723,18 @@ class FILMGLSInputSpec507(FILMGLSInputSpec505): surface = File( exists=True, argstr="--in2=%s", - desc=("input surface for autocorr smoothing in " "surface-based analyses"), + desc=("input surface for autocorr smoothing in surface-based analyses"), ) class FILMGLSOutputSpec(TraitedSpec): param_estimates = OutputMultiPath( File(exists=True), - desc=("Parameter estimates for each " "column of the design matrix"), + desc=("Parameter estimates for each column of the design matrix"), ) residual4d = File( exists=True, - desc=("Model fit residual mean-squared error for each " "time point"), + desc=("Model fit residual mean-squared error for each time point"), ) dof_file = File(exists=True, desc="degrees of freedom") sigmasquareds = File( @@ -753,7 +744,7 @@ class FILMGLSOutputSpec(TraitedSpec): exists=True, desc="directory storing model estimation output" ) corrections = File( - exists=True, desc=("statistical corrections used within FILM " "modeling") + exists=True, desc=("statistical corrections used within FILM modeling") ) thresholdac = File(exists=True, desc="The FILM autocorrelation parameters") logfile = File(exists=True, desc="FILM run logfile") @@ -762,11 +753,11 @@ class FILMGLSOutputSpec(TraitedSpec): class FILMGLSOutputSpec507(TraitedSpec): param_estimates = OutputMultiPath( File(exists=True), - desc=("Parameter estimates for each " "column of the design matrix"), + desc=("Parameter estimates for each column of the design matrix"), ) residual4d = File( exists=True, - desc=("Model fit residual mean-squared error for each " "time point"), + desc=("Model fit residual mean-squared error for each time point"), ) dof_file = File(exists=True, desc="degrees of freedom") sigmasquareds = File( @@ -822,43 +813,49 @@ class FILMGLS(FSLCommand): _cmd = "film_gls" input_spec = FILMGLSInputSpec output_spec = FILMGLSOutputSpec + if Info.version() and LooseVersion(Info.version()) > LooseVersion("5.0.6"): input_spec = FILMGLSInputSpec507 output_spec = FILMGLSOutputSpec507 elif Info.version() and LooseVersion(Info.version()) > LooseVersion("5.0.4"): input_spec = FILMGLSInputSpec505 + def __init__(self, **inputs): + super(FILMGLS, self).__init__(**inputs) + if Info.version() and LooseVersion(Info.version()) > LooseVersion("5.0.6"): + if 'output_type' not in inputs: + if isdefined(self.inputs.mode) and self.inputs.mode == 'surface': + self.inputs.output_type = 'GIFTI' + def _get_pe_files(self, cwd): files = None if isdefined(self.inputs.design_file): - fp = open(self.inputs.design_file, "rt") - for line in fp.readlines(): - if line.startswith("/NumWaves"): - numpes = int(line.split()[-1]) - files = [] - for i in range(numpes): - files.append(self._gen_fname("pe%d.nii" % (i + 1), cwd=cwd)) - break - fp.close() + with open(self.inputs.design_file) as fp: + for line in fp: + if line.startswith("/NumWaves"): + numpes = int(line.split()[-1]) + files = [ + self._gen_fname(f"pe{i + 1}.nii", cwd=cwd) + for i in range(numpes) + ] + break return files def _get_numcons(self): numtcons = 0 numfcons = 0 if isdefined(self.inputs.tcon_file): - fp = open(self.inputs.tcon_file, "rt") - for line in fp.readlines(): - if line.startswith("/NumContrasts"): - numtcons = int(line.split()[-1]) - break - fp.close() + with open(self.inputs.tcon_file) as fp: + for line in fp: + if line.startswith("/NumContrasts"): + numtcons = int(line.split()[-1]) + break if isdefined(self.inputs.fcon_file): - fp = open(self.inputs.fcon_file, "rt") - for line in fp.readlines(): - if line.startswith("/NumContrasts"): - numfcons = int(line.split()[-1]) - break - fp.close() + with open(self.inputs.fcon_file) as fp: + for line in fp: + if line.startswith("/NumContrasts"): + numfcons = int(line.split()[-1]) + break return numtcons, numfcons def _list_outputs(self): @@ -937,8 +934,7 @@ class FEATRegisterOutputSpec(TraitedSpec): class FEATRegister(BaseInterface): - """Register feat directories to a specific standard - """ + """Register feat directories to a specific standard""" input_spec = FEATRegisterInputSpec output_spec = FEATRegisterOutputSpec @@ -957,9 +953,8 @@ def _run_interface(self, runtime): for i, rundir in enumerate(ensure_list(self.inputs.feat_dirs)): fsf_txt += fsf_dirs.substitute(runno=i + 1, rundir=os.path.abspath(rundir)) fsf_txt += fsf_footer.substitute() - f = open(os.path.join(os.getcwd(), "register.fsf"), "wt") - f.write(fsf_txt) - f.close() + with open(os.path.join(os.getcwd(), "register.fsf"), "w") as f: + f.write(fsf_txt) return runtime @@ -1017,7 +1012,7 @@ class FLAMEOInputSpec(FSLCommandInputSpec): n_jumps = traits.Int(argstr="--njumps=%d", desc="number of jumps made by mcmc") burnin = traits.Int( argstr="--burnin=%d", - desc=("number of jumps at start of mcmc to be " "discarded"), + desc=("number of jumps at start of mcmc to be discarded"), ) sample_every = traits.Int( argstr="--sampleevery=%d", desc="number of jumps for each sample" @@ -1038,7 +1033,7 @@ class FLAMEOInputSpec(FSLCommandInputSpec): outlier_iter = traits.Int( argstr="--ioni=%d", desc=( - "Number of max iterations to use when " "inferring outliers. Default is 12." + "Number of max iterations to use when inferring outliers. Default is 12." ), ) log_dir = Directory("stats", argstr="--ld=%s", usedefault=True) # ohinds @@ -1049,12 +1044,12 @@ class FLAMEOOutputSpec(TraitedSpec): pes = OutputMultiPath( File(exists=True), desc=( - "Parameter estimates for each column of the " "design matrix for each voxel" + "Parameter estimates for each column of the design matrix for each voxel" ), ) res4d = OutputMultiPath( File(exists=True), - desc=("Model fit residual mean-squared error for " "each time point"), + desc=("Model fit residual mean-squared error for each time point"), ) copes = OutputMultiPath( File(exists=True), desc="Contrast estimates for each contrast" @@ -1067,7 +1062,7 @@ class FLAMEOOutputSpec(TraitedSpec): zfstats = OutputMultiPath(File(exists=True), desc="z stat file for each f contrast") fstats = OutputMultiPath(File(exists=True), desc="f-stat file for each contrast") mrefvars = OutputMultiPath( - File(exists=True), desc=("mean random effect variances for each " "contrast") + File(exists=True), desc=("mean random effect variances for each contrast") ) tdof = OutputMultiPath( File(exists=True), desc="temporal dof file for each contrast" @@ -1104,7 +1099,7 @@ class FLAMEO(FSLCommand): input_spec = FLAMEOInputSpec output_spec = FLAMEOOutputSpec - references_ = [ + _references = [ { "entry": BibTeX( "@article{BeckmannJenkinsonSmith2003," @@ -1141,7 +1136,7 @@ def _run_interface(self, runtime): if os.access(os.path.join(cwd, log_dir), os.F_OK): rmtree(os.path.join(cwd, log_dir)) - return super(FLAMEO, self)._run_interface(runtime) + return super()._run_interface(runtime) # ohinds: 2010-04-06 # made these compatible with flameo @@ -1217,7 +1212,7 @@ class ContrastMgrInputSpec(FSLCommandInputSpec): argstr="", copyfile=False, mandatory=True, - desc=("Parameter estimates for each " "column of the design matrix"), + desc=("Parameter estimates for each column of the design matrix"), ) corrections = File( exists=True, @@ -1238,10 +1233,10 @@ class ContrastMgrInputSpec(FSLCommandInputSpec): position=-2, copyfile=False, mandatory=True, - desc=("summary of residuals, See Woolrich, et. al., " "2001"), + desc=("summary of residuals, See Woolrich, et. al., 2001"), ) contrast_num = traits.Range( - low=1, argstr="-cope", desc=("contrast number to start labeling " "copes from") + low=1, argstr="-cope", desc=("contrast number to start labeling copes from") ) suffix = traits.Str( argstr="-suffix %s", @@ -1285,7 +1280,7 @@ def _run_interface(self, runtime): # The returncode is meaningless in ContrastMgr. So check the output # in stderr and if it's set, then update the returncode # accordingly. - runtime = super(ContrastMgr, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if runtime.stderr: self.raise_exception(runtime) return runtime @@ -1297,7 +1292,7 @@ def _format_arg(self, name, trait_spec, value): path, _ = os.path.split(value) return path else: - return super(ContrastMgr, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _get_design_root(self, infile): _, fname = os.path.split(infile) @@ -1307,19 +1302,17 @@ def _get_numcons(self): numtcons = 0 numfcons = 0 if isdefined(self.inputs.tcon_file): - fp = open(self.inputs.tcon_file, "rt") - for line in fp.readlines(): - if line.startswith("/NumContrasts"): - numtcons = int(line.split()[-1]) - break - fp.close() + with open(self.inputs.tcon_file) as fp: + for line in fp: + if line.startswith("/NumContrasts"): + numtcons = int(line.split()[-1]) + break if isdefined(self.inputs.fcon_file): - fp = open(self.inputs.fcon_file, "rt") - for line in fp.readlines(): - if line.startswith("/NumContrasts"): - numfcons = int(line.split()[-1]) - break - fp.close() + with open(self.inputs.fcon_file) as fp: + for line in fp: + if line.startswith("/NumContrasts"): + numfcons = int(line.split()[-1]) + break return numtcons, numfcons def _list_outputs(self): @@ -1391,7 +1384,7 @@ def _run_interface(self, runtime): cwd = os.getcwd() mat_txt = [ "/NumWaves 1", - "/NumPoints {:d}".format(self.inputs.num_copes), + f"/NumPoints {self.inputs.num_copes:d}", "/PPheights 1", "", "/Matrix", @@ -1415,7 +1408,7 @@ def _run_interface(self, runtime): grp_txt = [ "/NumWaves 1", - "/NumPoints {:d}".format(self.inputs.num_copes), + f"/NumPoints {self.inputs.num_copes:d}", "", "/Matrix", ] @@ -1427,9 +1420,8 @@ def _run_interface(self, runtime): # write design files for i, name in enumerate(["design.mat", "design.con", "design.grp"]): - f = open(os.path.join(cwd, name), "wt") - f.write(txt[name]) - f.close() + with open(os.path.join(cwd, name), "w") as f: + f.write(txt[name]) return runtime @@ -1443,22 +1435,22 @@ def _list_outputs(self): class MultipleRegressDesignInputSpec(BaseInterfaceInputSpec): contrasts = traits.List( traits.Either( - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("F"), traits.List( - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), - ), + ) ), ), ), @@ -1473,10 +1465,10 @@ class MultipleRegressDesignInputSpec(BaseInterfaceInputSpec): traits.Str, traits.List(traits.Float), mandatory=True, - desc=("dictionary containing named lists of " "regressors"), + desc=("dictionary containing named lists of regressors"), ) groups = traits.List( - traits.Int, desc=("list of group identifiers (defaults to single " "group)") + traits.Int, desc=("list of group identifiers (defaults to single group)") ) @@ -1516,8 +1508,8 @@ def _run_interface(self, runtime): regs = sorted(self.inputs.regressors.keys()) nwaves = len(regs) npoints = len(self.inputs.regressors[regs[0]]) - ntcons = sum([1 for con in self.inputs.contrasts if con[1] == "T"]) - nfcons = sum([1 for con in self.inputs.contrasts if con[1] == "F"]) + ntcons = sum(1 for con in self.inputs.contrasts if con[1] == "T") + nfcons = sum(1 for con in self.inputs.contrasts if con[1] == "F") # write mat file mat_txt = ["/NumWaves %d" % nwaves, "/NumPoints %d" % npoints] ppheights = [] @@ -1596,15 +1588,14 @@ def _run_interface(self, runtime): if ("fts" in key) and (nfcons == 0): continue filename = key.replace("_", ".") - f = open(os.path.join(cwd, filename), "wt") - f.write(val) - f.close() + with open(os.path.join(cwd, filename), "w") as f: + f.write(val) return runtime def _list_outputs(self): outputs = self._outputs().get() - nfcons = sum([1 for con in self.inputs.contrasts if con[1] == "F"]) + nfcons = sum(1 for con in self.inputs.contrasts if con[1] == "F") for field in list(outputs.keys()): if ("fts" in field) and (nfcons == 0): continue @@ -1886,11 +1877,13 @@ class SmoothEstimateInputSpec(FSLCommandInputSpec): class SmoothEstimateOutputSpec(TraitedSpec): dlh = traits.Float(desc="smoothness estimate sqrt(det(Lambda))") volume = traits.Int(desc="number of voxels in mask") - resels = traits.Float(desc="number of resels") + resels = traits.Float( + desc="volume of resel, in voxels, defined as FWHM_x * FWHM_y * FWHM_z" + ) class SmoothEstimate(FSLCommand): - """ Estimates the smoothness of an image + """Estimates the smoothness of an image Examples -------- @@ -2029,7 +2022,7 @@ class ClusterInputSpec(FSLCommandInputSpec): argstr="--stdvol=%s", desc="filename for standard-space volume" ) num_maxima = traits.Int(argstr="--num=%d", desc="no of local maxima to report") - warpfield_file = File(argstr="--warpvol=%s", desc="file contining warpfield") + warpfield_file = File(argstr="--warpvol=%s", desc="file containing warpfield") class ClusterOutputSpec(TraitedSpec): @@ -2044,7 +2037,7 @@ class ClusterOutputSpec(TraitedSpec): class Cluster(FSLCommand): - """ Uses FSL cluster to perform clustering on statistical output + """Uses FSL cluster to perform clustering on statistical output Examples -------- @@ -2101,7 +2094,7 @@ def _format_arg(self, name, spec, value): else: fname = value return spec.argstr % fname - return super(Cluster, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class DualRegressionInputSpec(FSLCommandInputSpec): @@ -2132,19 +2125,19 @@ class DualRegressionInputSpec(FSLCommandInputSpec): one_sample_group_mean = traits.Bool( argstr="-1", position=3, - desc="perform 1-sample group-mean test instead of generic " "permutation test", + desc="perform 1-sample group-mean test instead of generic permutation test", ) design_file = File( exists=True, argstr="%s", position=3, - desc="Design matrix for final cross-subject modelling with " "randomise", + desc="Design matrix for final cross-subject modelling with randomise", ) con_file = File( exists=True, argstr="%s", position=4, - desc="Design contrasts for final cross-subject modelling with " "randomise", + desc="Design contrasts for final cross-subject modelling with randomise", ) n_perm = traits.Int( argstr="%i", @@ -2227,13 +2220,11 @@ class RandomiseInputSpec(FSLCommandInputSpec): desc="demean data temporally before model fitting", argstr="-D" ) one_sample_group_mean = traits.Bool( - desc=( - "perform 1-sample group-mean test instead of generic " "permutation test" - ), + desc=("perform 1-sample group-mean test instead of generic permutation test"), argstr="-1", ) show_total_perms = traits.Bool( - desc=("print out how many unique permutations would be generated " "and exit"), + desc=("print out how many unique permutations would be generated and exit"), argstr="-q", ) show_info_parallel_mode = traits.Bool( @@ -2244,10 +2235,10 @@ class RandomiseInputSpec(FSLCommandInputSpec): ) tfce = traits.Bool(desc="carry out Threshold-Free Cluster Enhancement", argstr="-T") tfce2D = traits.Bool( - desc=("carry out Threshold-Free Cluster Enhancement with 2D " "optimisation"), + desc=("carry out Threshold-Free Cluster Enhancement with 2D optimisation"), argstr="--T2", ) - f_only = traits.Bool(desc="calculate f-statistics only", argstr="--f_only") + f_only = traits.Bool(desc="calculate f-statistics only", argstr="--fonly") raw_stats_imgs = traits.Bool( desc="output raw ( unpermuted ) statistic images", argstr="-R" ) @@ -2341,21 +2332,17 @@ def _list_outputs(self): prefix = "clusterm" if prefix: outputs["t_p_files"] = glob( - self._gen_fname("%s_%s_p_tstat*" % (self.inputs.base_name, prefix)) + self._gen_fname(f"{self.inputs.base_name}_{prefix}_p_tstat*") ) outputs["t_corrected_p_files"] = glob( - self._gen_fname( - "%s_%s_corrp_tstat*.nii" % (self.inputs.base_name, prefix) - ) + self._gen_fname(f"{self.inputs.base_name}_{prefix}_corrp_tstat*.nii") ) outputs["f_p_files"] = glob( - self._gen_fname("%s_%s_p_fstat*.nii" % (self.inputs.base_name, prefix)) + self._gen_fname(f"{self.inputs.base_name}_{prefix}_p_fstat*.nii") ) outputs["f_corrected_p_files"] = glob( - self._gen_fname( - "%s_%s_corrp_fstat*.nii" % (self.inputs.base_name, prefix) - ) + self._gen_fname(f"{self.inputs.base_name}_{prefix}_corrp_fstat*.nii") ) return outputs @@ -2383,8 +2370,8 @@ class GLMInputSpec(FSLCommandInputSpec): position=2, desc=( "file name of the GLM design matrix (text time" - + " courses for temporal regression or an image" - + " file for spatial regression)" + " courses for temporal regression or an image" + " file for spatial regression)" ), ) contrasts = File( @@ -2398,14 +2385,12 @@ class GLMInputSpec(FSLCommandInputSpec): argstr="--des_norm", desc=( "switch on normalization of the design" - + " matrix columns to unit std deviation" + " matrix columns to unit std deviation" ), ) dat_norm = traits.Bool( argstr="--dat_norm", - desc=( - "switch on normalization of the data time series to unit std " "deviation" - ), + desc=("switch on normalization of the data time series to unit std deviation"), ) var_norm = traits.Bool( argstr="--vn", desc=("perform MELODIC variance-normalisation on data") @@ -2425,7 +2410,7 @@ class GLMInputSpec(FSLCommandInputSpec): out_p_name = File( argstr="--out_p=%s", desc=( - "output file name for p-values of Z-stats (either as text file " "or image)" + "output file name for p-values of Z-stats (either as text file or image)" ), ) out_f_name = File( @@ -2447,7 +2432,7 @@ class GLMInputSpec(FSLCommandInputSpec): ) out_vnscales_name = File( argstr="--out_vnscales=%s", - desc=("output file name for scaling factors for variance " "normalisation"), + desc=("output file name for scaling factors for variance normalisation"), ) @@ -2468,7 +2453,7 @@ class GLMOutputSpec(TraitedSpec): out_p = OutputMultiPath( File(exists=True), desc=( - "output file name for p-values of Z-stats (either as text file " "or image)" + "output file name for p-values of Z-stats (either as text file or image)" ), ) out_f = OutputMultiPath( @@ -2490,7 +2475,7 @@ class GLMOutputSpec(TraitedSpec): ) out_vnscales = OutputMultiPath( File(exists=True), - desc=("output file name for scaling factors for variance " "normalisation"), + desc=("output file name for scaling factors for variance normalisation"), ) @@ -2512,7 +2497,7 @@ class GLM(FSLCommand): output_spec = GLMOutputSpec def _list_outputs(self): - outputs = super(GLM, self)._list_outputs() + outputs = super()._list_outputs() if isdefined(self.inputs.out_cope): outputs["out_cope"] = os.path.abspath(self.inputs.out_cope) @@ -2563,12 +2548,5 @@ def load_template(name): template : string.Template """ - from pkg_resources import resource_filename as pkgrf - - full_fname = pkgrf( - "nipype", os.path.join("interfaces", "fsl", "model_templates", name) - ) - with open(full_fname) as template_file: - template = Template(template_file.read()) - - return template + loader = acres.Loader('nipype.interfaces.fsl') + return Template(loader.readable('model_templates', name).read_text()) diff --git a/nipype/interfaces/fsl/possum.py b/nipype/interfaces/fsl/possum.py index 88797aaecd..2b09764003 100644 --- a/nipype/interfaces/fsl/possum.py +++ b/nipype/interfaces/fsl/possum.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -11,7 +10,7 @@ """ from .base import FSLCommand, FSLCommandInputSpec -from ..base import TraitedSpec, File, traits +from ..base import TraitedSpec, File, traits, Tuple class B0CalcInputSpec(FSLCommandInputSpec): @@ -72,7 +71,7 @@ class B0CalcInputSpec(FSLCommandInputSpec): desc="Value for zeroth-order b0 field (z-component), in Tesla", ) - xyz_b0 = traits.Tuple( + xyz_b0 = Tuple( traits.Float, traits.Float, traits.Float, diff --git a/nipype/interfaces/fsl/preprocess.py b/nipype/interfaces/fsl/preprocess.py index bf38ff3d1f..e4abd5ce16 100644 --- a/nipype/interfaces/fsl/preprocess.py +++ b/nipype/interfaces/fsl/preprocess.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The fsl module provides classes for interfacing with the `FSL @@ -11,8 +10,8 @@ import numpy as np from nibabel import load +from looseversion import LooseVersion -from ... import LooseVersion from ...utils.filemanip import split_filename from ..base import ( TraitedSpec, @@ -21,6 +20,7 @@ OutputMultiPath, Undefined, traits, + Tuple, isdefined, ) from .base import FSLCommand, FSLCommandInputSpec, Info @@ -35,6 +35,7 @@ class BETInputSpec(FSLCommandInputSpec): argstr="%s", position=0, mandatory=True, + copyfile=False, ) out_file = File( desc="name of output skull stripped image", @@ -159,60 +160,71 @@ def _run_interface(self, runtime): # The returncode is meaningless in BET. So check the output # in stderr and if it's set, then update the returncode # accordingly. - runtime = super(BET, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) if runtime.stderr: self.raise_exception(runtime) return runtime + def _format_arg(self, name, spec, value): + formatted = super()._format_arg(name, spec, value) + if name == "in_file": + # Convert to relative path to prevent BET failure + # with long paths. + return op.relpath(formatted, start=os.getcwd()) + return formatted + def _gen_outfilename(self): out_file = self.inputs.out_file + # Generate default output filename if non specified. if not isdefined(out_file) and isdefined(self.inputs.in_file): out_file = self._gen_fname(self.inputs.in_file, suffix="_brain") - return os.path.abspath(out_file) + # Convert to relative path to prevent BET failure + # with long paths. + return op.relpath(out_file, start=os.getcwd()) + return out_file def _list_outputs(self): outputs = self.output_spec().get() - outputs["out_file"] = self._gen_outfilename() + outputs["out_file"] = os.path.abspath(self._gen_outfilename()) + + basename = os.path.basename(outputs["out_file"]) + cwd = os.path.dirname(outputs["out_file"]) + kwargs = {"basename": basename, "cwd": cwd} + if (isdefined(self.inputs.mesh) and self.inputs.mesh) or ( isdefined(self.inputs.surfaces) and self.inputs.surfaces ): outputs["meshfile"] = self._gen_fname( - outputs["out_file"], suffix="_mesh.vtk", change_ext=False + suffix="_mesh.vtk", change_ext=False, **kwargs ) if (isdefined(self.inputs.mask) and self.inputs.mask) or ( isdefined(self.inputs.reduce_bias) and self.inputs.reduce_bias ): - outputs["mask_file"] = self._gen_fname(outputs["out_file"], suffix="_mask") + outputs["mask_file"] = self._gen_fname(suffix="_mask", **kwargs) if isdefined(self.inputs.outline) and self.inputs.outline: - outputs["outline_file"] = self._gen_fname( - outputs["out_file"], suffix="_overlay" - ) + outputs["outline_file"] = self._gen_fname(suffix="_overlay", **kwargs) if isdefined(self.inputs.surfaces) and self.inputs.surfaces: outputs["inskull_mask_file"] = self._gen_fname( - outputs["out_file"], suffix="_inskull_mask" + suffix="_inskull_mask", **kwargs ) outputs["inskull_mesh_file"] = self._gen_fname( - outputs["out_file"], suffix="_inskull_mesh" + suffix="_inskull_mesh", **kwargs ) outputs["outskull_mask_file"] = self._gen_fname( - outputs["out_file"], suffix="_outskull_mask" + suffix="_outskull_mask", **kwargs ) outputs["outskull_mesh_file"] = self._gen_fname( - outputs["out_file"], suffix="_outskull_mesh" + suffix="_outskull_mesh", **kwargs ) outputs["outskin_mask_file"] = self._gen_fname( - outputs["out_file"], suffix="_outskin_mask" + suffix="_outskin_mask", **kwargs ) outputs["outskin_mesh_file"] = self._gen_fname( - outputs["out_file"], suffix="_outskin_mesh" - ) - outputs["skull_mask_file"] = self._gen_fname( - outputs["out_file"], suffix="_skull_mask" + suffix="_outskin_mesh", **kwargs ) + outputs["skull_mask_file"] = self._gen_fname(suffix="_skull_mask", **kwargs) if isdefined(self.inputs.skull) and self.inputs.skull: - outputs["skull_file"] = self._gen_fname( - outputs["out_file"], suffix="_skull" - ) + outputs["skull_file"] = self._gen_fname(suffix="_skull", **kwargs) if isdefined(self.inputs.no_output) and self.inputs.no_output: outputs["out_file"] = Undefined return outputs @@ -224,12 +236,12 @@ def _gen_filename(self, name): class FASTInputSpec(FSLCommandInputSpec): - """ Defines inputs (trait classes) for FAST """ + """Defines inputs (trait classes) for FAST""" in_files = InputMultiPath( File(exists=True), copyfile=False, - desc="image, or multi-channel set of images, " "to be segmented", + desc="image, or multi-channel set of images, to be segmented", argstr="%s", position=-1, mandatory=True, @@ -252,12 +264,12 @@ class FASTInputSpec(FSLCommandInputSpec): low=1, high=10, argstr="-I %d", - desc="number of main-loop iterations during " "bias-field removal", + desc="number of main-loop iterations during bias-field removal", ) bias_lowpass = traits.Range( low=4, high=40, - desc="bias field smoothing extent (FWHM) " "in mm", + desc="bias field smoothing extent (FWHM) in mm", argstr="-l %d", units="mm", ) @@ -270,11 +282,11 @@ class FASTInputSpec(FSLCommandInputSpec): argstr="-f %.3f", ) segments = traits.Bool( - desc="outputs a separate binary image for each " "tissue type", argstr="-g" + desc="outputs a separate binary image for each tissue type", argstr="-g" ) init_transform = File( exists=True, - desc=" initialise" " using priors", + desc=" initialise using priors", argstr="-a %s", ) other_priors = InputMultiPath( @@ -293,7 +305,7 @@ class FASTInputSpec(FSLCommandInputSpec): segment_iters = traits.Range( low=1, high=50, - desc="number of segmentation-initialisation" " iterations", + desc="number of segmentation-initialisation iterations", argstr="-W %d", ) mixel_smooth = traits.Range( @@ -302,7 +314,7 @@ class FASTInputSpec(FSLCommandInputSpec): iters_afterbias = traits.Range( low=1, high=20, - desc="number of main-loop iterations " "after bias-field removal", + desc="number of main-loop iterations after bias-field removal", argstr="-O %d", ) hyper = traits.Range( @@ -364,12 +376,12 @@ class FAST(FSLCommand): Examples -------- >>> from nipype.interfaces import fsl - >>> fastr = fsl.FAST() - >>> fastr.inputs.in_files = 'structural.nii' - >>> fastr.inputs.out_basename = 'fast_' - >>> fastr.cmdline + >>> fast = fsl.FAST() + >>> fast.inputs.in_files = 'structural.nii' + >>> fast.inputs.out_basename = 'fast_' + >>> fast.cmdline 'fast -o fast_ -S 1 structural.nii' - >>> out = fastr.run() # doctest: +SKIP + >>> out = fast.run() # doctest: +SKIP """ @@ -379,7 +391,7 @@ class FAST(FSLCommand): def _format_arg(self, name, spec, value): # first do what should be done in general - formatted = super(FAST, self)._format_arg(name, spec, value) + formatted = super()._format_arg(name, spec, value) if name == "in_files": # FAST needs the -S parameter value to correspond to the number # of input images, otherwise it will ignore all but the first @@ -583,7 +595,7 @@ class FLIRTInputSpec(FSLCommandInputSpec): padding_size = traits.Int( argstr="-paddingsize %d", units="voxels", - desc="for applyxfm: interpolates outside image " "by size", + desc="for applyxfm: interpolates outside image by size", ) searchr_x = traits.List( traits.Int, @@ -637,7 +649,7 @@ class FLIRTInputSpec(FSLCommandInputSpec): bgvalue = traits.Float( 0, argstr="-setbackground %f", - desc=("use specified background value for points " "outside FOV"), + desc=("use specified background value for points outside FOV"), ) # BBR options @@ -683,7 +695,7 @@ class FLIRTInputSpec(FSLCommandInputSpec): "local_abs", argstr="-bbrtype %s", min_ver="5.0.0", - desc=("type of bbr cost function: signed [default], global_abs, " "local_abs"), + desc=("type of bbr cost function: signed [default], global_abs, local_abs"), ) bbrslope = traits.Float( argstr="-bbrslope %f", min_ver="5.0.0", desc="value of bbr slope" @@ -693,7 +705,7 @@ class FLIRTInputSpec(FSLCommandInputSpec): class FLIRTOutputSpec(TraitedSpec): out_file = File(exists=True, desc="path/name of registered file (if generated)") out_matrix_file = File( - exists=True, desc="path/name of calculated affine transform " "(if generated)" + exists=True, desc="path/name of calculated affine transform (if generated)" ) out_log = File(desc="path/name of output log (if generated)") @@ -727,7 +739,7 @@ class FLIRT(FSLCommand): _log_written = False def aggregate_outputs(self, runtime=None, needed_outputs=None): - outputs = super(FLIRT, self).aggregate_outputs( + outputs = super().aggregate_outputs( runtime=runtime, needed_outputs=needed_outputs ) if self.inputs.save_log and not self._log_written: @@ -749,7 +761,7 @@ def _parse_inputs(self, skip=None): "uses_qform arguments to run" ) skip.append("save_log") - return super(FLIRT, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) class ApplyXFMInputSpec(FLIRTInputSpec): @@ -768,7 +780,7 @@ class ApplyXFM(FLIRT): """Currently just a light wrapper around FLIRT, with no modifications - ApplyXFM is used to apply an existing tranform to an image + ApplyXFM is used to apply an existing transform to an image Examples @@ -824,7 +836,7 @@ class MCFLIRTInputSpec(FSLCommandInputSpec): argstr="-stages %d", desc="stages (if 4, perform final search with sinc interpolation", ) - init = File(exists=True, argstr="-init %s", desc="inital transformation matrix") + init = File(exists=True, argstr="-init %s", desc="initial transformation matrix") interpolation = traits.Enum( "spline", "nn", @@ -889,7 +901,7 @@ def _format_arg(self, name, spec, value): return "" else: return spec.argstr % value - return super(MCFLIRT, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -1071,7 +1083,7 @@ class FNIRTInputSpec(FSLCommandInputSpec): traits.Enum(0, 1), argstr="--applyrefmask=%s", xor=["skip_refmask"], - desc=("list of iterations to use reference mask on (1 to use, 0 to " "skip)"), + desc=("list of iterations to use reference mask on (1 to use, 0 to skip)"), sep=",", ) apply_inmask = traits.List( @@ -1083,11 +1095,11 @@ class FNIRTInputSpec(FSLCommandInputSpec): ) skip_implicit_ref_masking = traits.Bool( argstr="--imprefm=0", - desc=("skip implicit masking based on value in --ref image. " "Default = 0"), + desc=("skip implicit masking based on value in --ref image. Default = 0"), ) skip_implicit_in_masking = traits.Bool( argstr="--impinm=0", - desc=("skip implicit masking based on value in --in image. " "Default = 0"), + desc=("skip implicit masking based on value in --in image. Default = 0"), ) refmask_val = traits.Float( argstr="--imprefval=%f", desc="Value to mask out in --ref image. Default =0.0" @@ -1107,7 +1119,7 @@ class FNIRTInputSpec(FSLCommandInputSpec): desc="sub-sampling scheme, list, default [4, 2, 1, 1]", sep=",", ) - warp_resolution = traits.Tuple( + warp_resolution = Tuple( traits.Int, traits.Int, traits.Int, @@ -1153,7 +1165,7 @@ class FNIRTInputSpec(FSLCommandInputSpec): argstr="--lambda=%s", desc=( "Weight of regularisation, default depending on --ssqlambda and " - "--regmod switches. See user documetation." + "--regmod switches. See user documentation." ), sep=",", ) @@ -1161,7 +1173,7 @@ class FNIRTInputSpec(FSLCommandInputSpec): argstr="--ssqlambda=0", desc="If true, lambda is not weighted by current ssq, default false", ) - jacobian_range = traits.Tuple( + jacobian_range = Tuple( traits.Float, traits.Float, argstr="--jacrange=%f,%f", @@ -1169,7 +1181,7 @@ class FNIRTInputSpec(FSLCommandInputSpec): ) derive_from_ref = traits.Bool( argstr="--refderiv", - desc=("If true, ref image is used to calculate derivatives. " "Default false"), + desc=("If true, ref image is used to calculate derivatives. Default false"), ) intensity_mapping_model = traits.Enum( "none", @@ -1185,7 +1197,7 @@ class FNIRTInputSpec(FSLCommandInputSpec): argstr="--intorder=%d", desc="Order of poynomial for mapping intensities, default 5", ) - biasfield_resolution = traits.Tuple( + biasfield_resolution = Tuple( traits.Int, traits.Int, traits.Int, @@ -1218,7 +1230,7 @@ class FNIRTInputSpec(FSLCommandInputSpec): "double", "float", argstr="--numprec=%s", - desc=("Precision for representing Hessian, double or float. " "Default double"), + desc=("Precision for representing Hessian, double or float. Default double"), ) @@ -1310,10 +1322,7 @@ def _list_outputs(self): if key == "out_intensitymap_file" and isdefined(outputs[key]): basename = FNIRT.intensitymap_file_basename(outputs[key]) - outputs[key] = [ - outputs[key], - "%s.txt" % basename, - ] + outputs[key] = [outputs[key], "%s.txt" % basename] return outputs def _format_arg(self, name, spec, value): @@ -1327,7 +1336,7 @@ def _format_arg(self, name, spec, value): return spec.argstr % value[0] if name in list(self.filemap.keys()): return spec.argstr % self._list_outputs()[name] - return super(FNIRT, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_filename(self, name): if name in ["warped_file", "log_file"]: @@ -1345,7 +1354,7 @@ def write_config(self, configfile): """ try: fid = open(configfile, "w+") - except IOError: + except OSError: print("unable to create config_file %s" % (configfile)) for item in list(self.inputs.get().items()): @@ -1472,7 +1481,7 @@ class ApplyWarp(FSLCommand): def _format_arg(self, name, spec, value): if name == "superlevel": return spec.argstr % str(value) - return super(ApplyWarp, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -1615,7 +1624,7 @@ class SUSANInputSpec(FSLCommandInputSpec): ), ) usans = traits.List( - traits.Tuple(File(exists=True), traits.Float), + Tuple(File(exists=True), traits.Float), maxlen=2, argstr="", position=6, @@ -1672,7 +1681,7 @@ def _format_arg(self, name, spec, value): for filename, thresh in value: arglist.extend([filename, "%.10f" % thresh]) return " ".join(arglist) - return super(SUSAN, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -1775,7 +1784,7 @@ class FUGUEInputSpec(FSLCommandInputSpec): icorr = traits.Bool( argstr="--icorr", requires=["shift_in_file"], - desc=("apply intensity correction to unwarping (pixel shift method " "only)"), + desc=("apply intensity correction to unwarping (pixel shift method only)"), ) icorr_only = traits.Bool( argstr="--icorronly", @@ -1903,10 +1912,7 @@ def _parse_inputs(self, skip=None): if not input_phase and not input_vsm and not input_fmap: raise RuntimeError( - ( - "Either phasemap_in_file, shift_in_file or fmap_in_file must " - "be set." - ) + "Either phasemap_in_file, shift_in_file or fmap_in_file must be set." ) if not isdefined(self.inputs.in_file): @@ -1947,10 +1953,8 @@ def _parse_inputs(self, skip=None): trait_spec.name_source = "shift_in_file" else: raise RuntimeError( - ( - "Either phasemap_in_file, shift_in_file or " - "fmap_in_file must be set." - ) + "Either phasemap_in_file, shift_in_file or " + "fmap_in_file must be set." ) if vsm_save_unmasked: @@ -1982,10 +1986,8 @@ def _parse_inputs(self, skip=None): trait_spec.name_source = "fmap_in_file" else: raise RuntimeError( - ( - "Either phasemap_in_file, shift_in_file or " - "fmap_in_file must be set." - ) + "Either phasemap_in_file, shift_in_file or " + "fmap_in_file must be set." ) if fmap_save_unmasked: @@ -1995,7 +1997,7 @@ def _parse_inputs(self, skip=None): else: skip += ["save_fmap", "save_unmasked_fmap", "fmap_out_file"] - return super(FUGUE, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) class PRELUDEInputSpec(FSLCommandInputSpec): @@ -2087,7 +2089,7 @@ class PRELUDE(FSLCommand): _cmd = "prelude" def __init__(self, **kwargs): - super(PRELUDE, self).__init__(**kwargs) + super().__init__(**kwargs) warn("This has not been fully tested. Please report any failures.") def _list_outputs(self): @@ -2174,9 +2176,7 @@ class FIRSTInputSpec(FSLCommandInputSpec): exists=True, position=6, argstr="-a %s", - desc=( - "Affine matrix to use (e.g. img2std.mat) (does not " "re-run registration)" - ), + desc=("Affine matrix to use (e.g. img2std.mat) (does not re-run registration)"), ) @@ -2194,7 +2194,7 @@ class FIRSTOutputSpec(TraitedSpec): ) segmentation_file = File( exists=True, - desc=("4D image file containing a single volume per " "segmented region"), + desc=("4D image file containing a single volume per segmented region"), ) @@ -2261,9 +2261,9 @@ def _gen_fname(self, basename): method = thres.replace(".", "") if basename == "original_segmentations": - return op.abspath("%s_all_%s_origsegs.nii.gz" % (outname, method)) + return op.abspath(f"{outname}_all_{method}_origsegs.nii.gz") if basename == "segmentation_file": - return op.abspath("%s_all_%s_firstseg.nii.gz" % (outname, method)) + return op.abspath(f"{outname}_all_{method}_firstseg.nii.gz") return None diff --git a/nipype/interfaces/fsl/tests/__init__.py b/nipype/interfaces/fsl/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/fsl/tests/__init__.py +++ b/nipype/interfaces/fsl/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/fsl/tests/test_FILMGLS.py b/nipype/interfaces/fsl/tests/test_FILMGLS.py index b4934f4d7a..ce2cc57ffd 100644 --- a/nipype/interfaces/fsl/tests/test_FILMGLS.py +++ b/nipype/interfaces/fsl/tests/test_FILMGLS.py @@ -1,10 +1,9 @@ -# -*- coding: utf-8 -*- from nipype.interfaces.fsl.model import FILMGLS, FILMGLSInputSpec def test_filmgls(): input_map = dict( - args=dict(argstr="%s",), + args=dict(argstr="%s"), autocorr_estimate_only=dict( xor=[ "autocorr_estimate_only", @@ -27,9 +26,9 @@ def test_filmgls(): ], argstr="-noest", ), - brightness_threshold=dict(argstr="-epith %d",), - design_file=dict(argstr="%s",), - environ=dict(usedefault=True,), + brightness_threshold=dict(argstr="-epith %d"), + design_file=dict(argstr="%s"), + environ=dict(usedefault=True), fit_armodel=dict( xor=[ "autocorr_estimate_only", @@ -41,9 +40,9 @@ def test_filmgls(): ], argstr="-ar", ), - full_data=dict(argstr="-v",), - in_file=dict(mandatory=True, argstr="%s",), - mask_size=dict(argstr="-ms %d",), + full_data=dict(argstr="-v"), + in_file=dict(mandatory=True, argstr="%s"), + mask_size=dict(argstr="-ms %d"), multitaper_product=dict( xor=[ "autocorr_estimate_only", @@ -55,11 +54,11 @@ def test_filmgls(): ], argstr="-mt %d", ), - output_pwdata=dict(argstr="-output_pwdata",), + output_pwdata=dict(argstr="-output_pwdata"), output_type=dict(), - results_dir=dict(usedefault=True, argstr="-rn %s",), - smooth_autocorr=dict(argstr="-sa",), - threshold=dict(argstr="%f",), + results_dir=dict(usedefault=True, argstr="-rn %s"), + smooth_autocorr=dict(argstr="-sa"), + threshold=dict(argstr="%f"), tukey_window=dict( xor=[ "autocorr_estimate_only", @@ -71,10 +70,10 @@ def test_filmgls(): ], argstr="-tukey %d", ), - use_pava=dict(argstr="-pava",), + use_pava=dict(argstr="-pava"), ) input_map2 = dict( - args=dict(argstr="%s",), + args=dict(argstr="%s"), autocorr_estimate_only=dict( xor=[ "autocorr_estimate_only", @@ -97,9 +96,9 @@ def test_filmgls(): ], argstr="--noest", ), - brightness_threshold=dict(argstr="--epith=%d",), - design_file=dict(argstr="--pd=%s",), - environ=dict(usedefault=True,), + brightness_threshold=dict(argstr="--epith=%d"), + design_file=dict(argstr="--pd=%s"), + environ=dict(usedefault=True), fit_armodel=dict( xor=[ "autocorr_estimate_only", @@ -111,9 +110,9 @@ def test_filmgls(): ], argstr="--ar", ), - full_data=dict(argstr="-v",), - in_file=dict(mandatory=True, argstr="--in=%s",), - mask_size=dict(argstr="--ms=%d",), + full_data=dict(argstr="-v"), + in_file=dict(mandatory=True, argstr="--in=%s"), + mask_size=dict(argstr="--ms=%d"), multitaper_product=dict( xor=[ "autocorr_estimate_only", @@ -125,11 +124,11 @@ def test_filmgls(): ], argstr="--mt=%d", ), - output_pwdata=dict(argstr="--outputPWdata",), + output_pwdata=dict(argstr="--outputPWdata"), output_type=dict(), - results_dir=dict(argstr="--rn=%s", usedefault=True,), - smooth_autocorr=dict(argstr="--sa",), - threshold=dict(usedefault=True, argstr="--thr=%f",), + results_dir=dict(argstr="--rn=%s", usedefault=True), + smooth_autocorr=dict(argstr="--sa"), + threshold=dict(usedefault=True, argstr="--thr=%f"), tukey_window=dict( xor=[ "autocorr_estimate_only", @@ -141,7 +140,7 @@ def test_filmgls(): ], argstr="--tukey=%d", ), - use_pava=dict(argstr="--pava",), + use_pava=dict(argstr="--pava"), ) instance = FILMGLS() if isinstance(instance.inputs, FILMGLSInputSpec): diff --git a/nipype/interfaces/fsl/tests/test_Level1Design_functions.py b/nipype/interfaces/fsl/tests/test_Level1Design_functions.py index f13ddfaccf..157a217dbc 100644 --- a/nipype/interfaces/fsl/tests/test_Level1Design_functions.py +++ b/nipype/interfaces/fsl/tests/test_Level1Design_functions.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os from ...base import Undefined from ..model import Level1Design @@ -35,4 +34,4 @@ def test_level1design(tmpdir): do_tempfilter, key, ) - assert "set fmri(convolve1) {0}".format(val) in output_txt + assert f"set fmri(convolve1) {val}" in output_txt diff --git a/nipype/interfaces/fsl/tests/test_auto_AR1Image.py b/nipype/interfaces/fsl/tests/test_auto_AR1Image.py index 23e6a19b6c..0f4cfc2bcc 100644 --- a/nipype/interfaces/fsl/tests/test_auto_AR1Image.py +++ b/nipype/interfaces/fsl/tests/test_auto_AR1Image.py @@ -4,16 +4,43 @@ def test_AR1Image_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%sar1", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%sar1", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = AR1Image.input_spec() @@ -24,7 +51,11 @@ def test_AR1Image_inputs(): def test_AR1Image_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = AR1Image.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_AccuracyTester.py b/nipype/interfaces/fsl/tests/test_auto_AccuracyTester.py index 6faf6d5d27..359a076f2d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_AccuracyTester.py +++ b/nipype/interfaces/fsl/tests/test_auto_AccuracyTester.py @@ -4,12 +4,29 @@ def test_AccuracyTester_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - mel_icas=dict(argstr="%s", copyfile=False, mandatory=True, position=3,), - output_directory=dict(argstr="%s", mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + mel_icas=dict( + argstr="%s", + copyfile=False, + mandatory=True, + position=3, + ), + output_directory=dict( + argstr="%s", + mandatory=True, + position=2, + ), trained_wts_file=dict( - argstr="%s", extensions=None, mandatory=True, position=1, + argstr="%s", + extensions=None, + mandatory=True, + position=1, ), ) inputs = AccuracyTester.input_spec() @@ -20,7 +37,12 @@ def test_AccuracyTester_inputs(): def test_AccuracyTester_outputs(): - output_map = dict(output_directory=dict(argstr="%s", position=1,),) + output_map = dict( + output_directory=dict( + argstr="%s", + position=1, + ), + ) outputs = AccuracyTester.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ApplyMask.py b/nipype/interfaces/fsl/tests/test_auto_ApplyMask.py index dcd7fc6081..f38990e572 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ApplyMask.py +++ b/nipype/interfaces/fsl/tests/test_auto_ApplyMask.py @@ -4,16 +4,44 @@ def test_ApplyMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - mask_file=dict(argstr="-mas %s", extensions=None, mandatory=True, position=4,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + mask_file=dict( + argstr="-mas %s", + extensions=None, + mandatory=True, + position=4, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = ApplyMask.input_spec() @@ -24,7 +52,11 @@ def test_ApplyMask_inputs(): def test_ApplyMask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ApplyMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ApplyTOPUP.py b/nipype/interfaces/fsl/tests/test_auto_ApplyTOPUP.py index a600c425e6..4c5bcc13a7 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ApplyTOPUP.py +++ b/nipype/interfaces/fsl/tests/test_auto_ApplyTOPUP.py @@ -4,12 +4,30 @@ def test_ApplyTOPUP_inputs(): input_map = dict( - args=dict(argstr="%s",), - datatype=dict(argstr="-d=%s",), - encoding_file=dict(argstr="--datain=%s", extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="--imain=%s", mandatory=True, sep=",",), - in_index=dict(argstr="--inindex=%s", sep=",",), + args=dict( + argstr="%s", + ), + datatype=dict( + argstr="-d=%s", + ), + encoding_file=dict( + argstr="--datain=%s", + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="--imain=%s", + mandatory=True, + sep=",", + ), + in_index=dict( + argstr="--inindex=%s", + sep=",", + ), in_topup_fieldcoef=dict( argstr="--topup=%s", copyfile=False, @@ -17,10 +35,16 @@ def test_ApplyTOPUP_inputs(): requires=["in_topup_movpar"], ), in_topup_movpar=dict( - copyfile=False, extensions=None, requires=["in_topup_fieldcoef"], + copyfile=False, + extensions=None, + requires=["in_topup_fieldcoef"], + ), + interp=dict( + argstr="--interp=%s", + ), + method=dict( + argstr="--method=%s", ), - interp=dict(argstr="--interp=%s",), - method=dict(argstr="--method=%s",), out_corrected=dict( argstr="--out=%s", extensions=None, @@ -37,7 +61,11 @@ def test_ApplyTOPUP_inputs(): def test_ApplyTOPUP_outputs(): - output_map = dict(out_corrected=dict(extensions=None,),) + output_map = dict( + out_corrected=dict( + extensions=None, + ), + ) outputs = ApplyTOPUP.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ApplyWarp.py b/nipype/interfaces/fsl/tests/test_auto_ApplyWarp.py index 8deaf747c2..1eaf3eb2e7 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ApplyWarp.py +++ b/nipype/interfaces/fsl/tests/test_auto_ApplyWarp.py @@ -4,14 +4,38 @@ def test_ApplyWarp_inputs(): input_map = dict( - abswarp=dict(argstr="--abs", xor=["relwarp"],), - args=dict(argstr="%s",), - datatype=dict(argstr="--datatype=%s",), - environ=dict(nohash=True, usedefault=True,), - field_file=dict(argstr="--warp=%s", extensions=None,), - in_file=dict(argstr="--in=%s", extensions=None, mandatory=True, position=0,), - interp=dict(argstr="--interp=%s", position=-2,), - mask_file=dict(argstr="--mask=%s", extensions=None,), + abswarp=dict( + argstr="--abs", + xor=["relwarp"], + ), + args=dict( + argstr="%s", + ), + datatype=dict( + argstr="--datatype=%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + field_file=dict( + argstr="--warp=%s", + extensions=None, + ), + in_file=dict( + argstr="--in=%s", + extensions=None, + mandatory=True, + position=0, + ), + interp=dict( + argstr="--interp=%s", + position=-2, + ), + mask_file=dict( + argstr="--mask=%s", + extensions=None, + ), out_file=dict( argstr="--out=%s", extensions=None, @@ -20,12 +44,31 @@ def test_ApplyWarp_inputs(): position=2, ), output_type=dict(), - postmat=dict(argstr="--postmat=%s", extensions=None,), - premat=dict(argstr="--premat=%s", extensions=None,), - ref_file=dict(argstr="--ref=%s", extensions=None, mandatory=True, position=1,), - relwarp=dict(argstr="--rel", position=-1, xor=["abswarp"],), - superlevel=dict(argstr="--superlevel=%s",), - supersample=dict(argstr="--super",), + postmat=dict( + argstr="--postmat=%s", + extensions=None, + ), + premat=dict( + argstr="--premat=%s", + extensions=None, + ), + ref_file=dict( + argstr="--ref=%s", + extensions=None, + mandatory=True, + position=1, + ), + relwarp=dict( + argstr="--rel", + position=-1, + xor=["abswarp"], + ), + superlevel=dict( + argstr="--superlevel=%s", + ), + supersample=dict( + argstr="--super", + ), ) inputs = ApplyWarp.input_spec() @@ -35,7 +78,11 @@ def test_ApplyWarp_inputs(): def test_ApplyWarp_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ApplyWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ApplyXFM.py b/nipype/interfaces/fsl/tests/test_auto_ApplyXFM.py index 116748d4c9..0fc914cdde 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ApplyXFM.py +++ b/nipype/interfaces/fsl/tests/test_auto_ApplyXFM.py @@ -4,35 +4,111 @@ def test_ApplyXFM_inputs(): input_map = dict( - angle_rep=dict(argstr="-anglerep %s",), - apply_isoxfm=dict(argstr="-applyisoxfm %f", xor=["apply_xfm"],), - apply_xfm=dict(argstr="-applyxfm", usedefault=True,), - args=dict(argstr="%s",), - bbrslope=dict(argstr="-bbrslope %f", min_ver="5.0.0",), - bbrtype=dict(argstr="-bbrtype %s", min_ver="5.0.0",), - bgvalue=dict(argstr="-setbackground %f",), - bins=dict(argstr="-bins %d",), - coarse_search=dict(argstr="-coarsesearch %d", units="degrees",), - cost=dict(argstr="-cost %s",), - cost_func=dict(argstr="-searchcost %s",), - datatype=dict(argstr="-datatype %s",), - display_init=dict(argstr="-displayinit",), - dof=dict(argstr="-dof %d",), - echospacing=dict(argstr="-echospacing %f", min_ver="5.0.0",), - environ=dict(nohash=True, usedefault=True,), - fieldmap=dict(argstr="-fieldmap %s", extensions=None, min_ver="5.0.0",), - fieldmapmask=dict(argstr="-fieldmapmask %s", extensions=None, min_ver="5.0.0",), - fine_search=dict(argstr="-finesearch %d", units="degrees",), - force_scaling=dict(argstr="-forcescaling",), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True, position=0,), - in_matrix_file=dict(argstr="-init %s", extensions=None,), - in_weight=dict(argstr="-inweight %s", extensions=None,), - interp=dict(argstr="-interp %s",), - min_sampling=dict(argstr="-minsampling %f", units="mm",), - no_clamp=dict(argstr="-noclamp",), - no_resample=dict(argstr="-noresample",), - no_resample_blur=dict(argstr="-noresampblur",), - no_search=dict(argstr="-nosearch",), + angle_rep=dict( + argstr="-anglerep %s", + ), + apply_isoxfm=dict( + argstr="-applyisoxfm %f", + xor=["apply_xfm"], + ), + apply_xfm=dict( + argstr="-applyxfm", + usedefault=True, + ), + args=dict( + argstr="%s", + ), + bbrslope=dict( + argstr="-bbrslope %f", + min_ver="5.0.0", + ), + bbrtype=dict( + argstr="-bbrtype %s", + min_ver="5.0.0", + ), + bgvalue=dict( + argstr="-setbackground %f", + ), + bins=dict( + argstr="-bins %d", + ), + coarse_search=dict( + argstr="-coarsesearch %d", + units="degrees", + ), + cost=dict( + argstr="-cost %s", + ), + cost_func=dict( + argstr="-searchcost %s", + ), + datatype=dict( + argstr="-datatype %s", + ), + display_init=dict( + argstr="-displayinit", + ), + dof=dict( + argstr="-dof %d", + ), + echospacing=dict( + argstr="-echospacing %f", + min_ver="5.0.0", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fieldmap=dict( + argstr="-fieldmap %s", + extensions=None, + min_ver="5.0.0", + ), + fieldmapmask=dict( + argstr="-fieldmapmask %s", + extensions=None, + min_ver="5.0.0", + ), + fine_search=dict( + argstr="-finesearch %d", + units="degrees", + ), + force_scaling=dict( + argstr="-forcescaling", + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + position=0, + ), + in_matrix_file=dict( + argstr="-init %s", + extensions=None, + ), + in_weight=dict( + argstr="-inweight %s", + extensions=None, + ), + interp=dict( + argstr="-interp %s", + ), + min_sampling=dict( + argstr="-minsampling %f", + units="mm", + ), + no_clamp=dict( + argstr="-noclamp", + ), + no_resample=dict( + argstr="-noresample", + ), + no_resample_blur=dict( + argstr="-noresampblur", + ), + no_search=dict( + argstr="-nosearch", + ), out_file=dict( argstr="-out %s", extensions=None, @@ -58,23 +134,72 @@ def test_ApplyXFM_inputs(): position=3, ), output_type=dict(), - padding_size=dict(argstr="-paddingsize %d", units="voxels",), - pedir=dict(argstr="-pedir %d", min_ver="5.0.0",), - ref_weight=dict(argstr="-refweight %s", extensions=None,), - reference=dict(argstr="-ref %s", extensions=None, mandatory=True, position=1,), - rigid2D=dict(argstr="-2D",), + padding_size=dict( + argstr="-paddingsize %d", + units="voxels", + ), + pedir=dict( + argstr="-pedir %d", + min_ver="5.0.0", + ), + ref_weight=dict( + argstr="-refweight %s", + extensions=None, + ), + reference=dict( + argstr="-ref %s", + extensions=None, + mandatory=True, + position=1, + ), + rigid2D=dict( + argstr="-2D", + ), save_log=dict(), - schedule=dict(argstr="-schedule %s", extensions=None,), - searchr_x=dict(argstr="-searchrx %s", units="degrees",), - searchr_y=dict(argstr="-searchry %s", units="degrees",), - searchr_z=dict(argstr="-searchrz %s", units="degrees",), - sinc_width=dict(argstr="-sincwidth %d", units="voxels",), - sinc_window=dict(argstr="-sincwindow %s",), - uses_qform=dict(argstr="-usesqform",), - verbose=dict(argstr="-verbose %d",), - wm_seg=dict(argstr="-wmseg %s", extensions=None, min_ver="5.0.0",), - wmcoords=dict(argstr="-wmcoords %s", extensions=None, min_ver="5.0.0",), - wmnorms=dict(argstr="-wmnorms %s", extensions=None, min_ver="5.0.0",), + schedule=dict( + argstr="-schedule %s", + extensions=None, + ), + searchr_x=dict( + argstr="-searchrx %s", + units="degrees", + ), + searchr_y=dict( + argstr="-searchry %s", + units="degrees", + ), + searchr_z=dict( + argstr="-searchrz %s", + units="degrees", + ), + sinc_width=dict( + argstr="-sincwidth %d", + units="voxels", + ), + sinc_window=dict( + argstr="-sincwindow %s", + ), + uses_qform=dict( + argstr="-usesqform", + ), + verbose=dict( + argstr="-verbose %d", + ), + wm_seg=dict( + argstr="-wmseg %s", + extensions=None, + min_ver="5.0.0", + ), + wmcoords=dict( + argstr="-wmcoords %s", + extensions=None, + min_ver="5.0.0", + ), + wmnorms=dict( + argstr="-wmnorms %s", + extensions=None, + min_ver="5.0.0", + ), ) inputs = ApplyXFM.input_spec() @@ -85,9 +210,15 @@ def test_ApplyXFM_inputs(): def test_ApplyXFM_outputs(): output_map = dict( - out_file=dict(extensions=None,), - out_log=dict(extensions=None,), - out_matrix_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_log=dict( + extensions=None, + ), + out_matrix_file=dict( + extensions=None, + ), ) outputs = ApplyXFM.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_AvScale.py b/nipype/interfaces/fsl/tests/test_auto_AvScale.py index 5f636ec453..4748d6a9bc 100644 --- a/nipype/interfaces/fsl/tests/test_auto_AvScale.py +++ b/nipype/interfaces/fsl/tests/test_auto_AvScale.py @@ -4,11 +4,26 @@ def test_AvScale_inputs(): input_map = dict( - all_param=dict(argstr="--allparams",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - mat_file=dict(argstr="%s", extensions=None, position=-2,), - ref_file=dict(argstr="%s", extensions=None, position=-1,), + all_param=dict( + argstr="--allparams", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + mat_file=dict( + argstr="%s", + extensions=None, + position=-2, + ), + ref_file=dict( + argstr="%s", + extensions=None, + position=-1, + ), ) inputs = AvScale.input_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_B0Calc.py b/nipype/interfaces/fsl/tests/test_auto_B0Calc.py index 85175fd428..01727179ff 100644 --- a/nipype/interfaces/fsl/tests/test_auto_B0Calc.py +++ b/nipype/interfaces/fsl/tests/test_auto_B0Calc.py @@ -4,14 +4,39 @@ def test_B0Calc_inputs(): input_map = dict( - args=dict(argstr="%s",), - chi_air=dict(argstr="--chi0=%e", usedefault=True,), - compute_xyz=dict(argstr="--xyz", usedefault=True,), - delta=dict(argstr="-d %e", usedefault=True,), - directconv=dict(argstr="--directconv", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - extendboundary=dict(argstr="--extendboundary=%0.2f", usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + chi_air=dict( + argstr="--chi0=%e", + usedefault=True, + ), + compute_xyz=dict( + argstr="--xyz", + usedefault=True, + ), + delta=dict( + argstr="-d %e", + usedefault=True, + ), + directconv=dict( + argstr="--directconv", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extendboundary=dict( + argstr="--extendboundary=%0.2f", + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=0, + ), out_file=dict( argstr="-o %s", extensions=None, @@ -21,15 +46,37 @@ def test_B0Calc_inputs(): position=1, ), output_type=dict(), - x_b0=dict(argstr="--b0x=%0.2f", usedefault=True, xor=["xyz_b0"],), - x_grad=dict(argstr="--gx=%0.4f", usedefault=True,), + x_b0=dict( + argstr="--b0x=%0.2f", + usedefault=True, + xor=["xyz_b0"], + ), + x_grad=dict( + argstr="--gx=%0.4f", + usedefault=True, + ), xyz_b0=dict( - argstr="--b0x=%0.2f --b0y=%0.2f --b0=%0.2f", xor=["x_b0", "y_b0", "z_b0"], + argstr="--b0x=%0.2f --b0y=%0.2f --b0=%0.2f", + xor=["x_b0", "y_b0", "z_b0"], + ), + y_b0=dict( + argstr="--b0y=%0.2f", + usedefault=True, + xor=["xyz_b0"], + ), + y_grad=dict( + argstr="--gy=%0.4f", + usedefault=True, + ), + z_b0=dict( + argstr="--b0=%0.2f", + usedefault=True, + xor=["xyz_b0"], + ), + z_grad=dict( + argstr="--gz=%0.4f", + usedefault=True, ), - y_b0=dict(argstr="--b0y=%0.2f", usedefault=True, xor=["xyz_b0"],), - y_grad=dict(argstr="--gy=%0.4f", usedefault=True,), - z_b0=dict(argstr="--b0=%0.2f", usedefault=True, xor=["xyz_b0"],), - z_grad=dict(argstr="--gz=%0.4f", usedefault=True,), ) inputs = B0Calc.input_spec() @@ -39,7 +86,11 @@ def test_B0Calc_inputs(): def test_B0Calc_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = B0Calc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py b/nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py index 8941e775c6..2424307165 100644 --- a/nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py +++ b/nipype/interfaces/fsl/tests/test_auto_BEDPOSTX5.py @@ -4,39 +4,114 @@ def test_BEDPOSTX5_inputs(): input_map = dict( - all_ard=dict(argstr="--allard", xor=("no_ard", "all_ard"),), - args=dict(argstr="%s",), - burn_in=dict(argstr="-b %d", usedefault=True,), - burn_in_no_ard=dict(argstr="--burnin_noard=%d", usedefault=True,), - bvals=dict(extensions=None, mandatory=True,), - bvecs=dict(extensions=None, mandatory=True,), + all_ard=dict( + argstr="--allard", + xor=("no_ard", "all_ard"), + ), + args=dict( + argstr="%s", + ), + burn_in=dict( + argstr="-b %d", + usedefault=True, + ), + burn_in_no_ard=dict( + argstr="--burnin_noard=%d", + usedefault=True, + ), + bvals=dict( + extensions=None, + mandatory=True, + ), + bvecs=dict( + extensions=None, + mandatory=True, + ), cnlinear=dict( - argstr="--cnonlinear", xor=("no_spat", "non_linear", "cnlinear"), - ), - dwi=dict(extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - f0_ard=dict(argstr="--f0 --ardf0", xor=["f0_noard", "f0_ard", "all_ard"],), - f0_noard=dict(argstr="--f0", xor=["f0_noard", "f0_ard"],), - force_dir=dict(argstr="--forcedir", usedefault=True,), - fudge=dict(argstr="-w %d",), - grad_dev=dict(extensions=None,), - gradnonlin=dict(argstr="-g",), - logdir=dict(argstr="--logdir=%s",), - mask=dict(extensions=None, mandatory=True,), - model=dict(argstr="-model %d",), - n_fibres=dict(argstr="-n %d", mandatory=True, usedefault=True,), - n_jumps=dict(argstr="-j %d", usedefault=True,), - no_ard=dict(argstr="--noard", xor=("no_ard", "all_ard"),), - no_spat=dict(argstr="--nospat", xor=("no_spat", "non_linear", "cnlinear"),), + argstr="--cnonlinear", + xor=("no_spat", "non_linear", "cnlinear"), + ), + dwi=dict( + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + f0_ard=dict( + argstr="--f0 --ardf0", + xor=["f0_noard", "f0_ard", "all_ard"], + ), + f0_noard=dict( + argstr="--f0", + xor=["f0_noard", "f0_ard"], + ), + force_dir=dict( + argstr="--forcedir", + usedefault=True, + ), + fudge=dict( + argstr="-w %d", + ), + grad_dev=dict( + extensions=None, + ), + gradnonlin=dict( + argstr="-g", + ), + logdir=dict( + argstr="--logdir=%s", + ), + mask=dict( + extensions=None, + mandatory=True, + ), + model=dict( + argstr="-model %d", + ), + n_fibres=dict( + argstr="-n %d", + mandatory=True, + usedefault=True, + ), + n_jumps=dict( + argstr="-j %d", + usedefault=True, + ), + no_ard=dict( + argstr="--noard", + xor=("no_ard", "all_ard"), + ), + no_spat=dict( + argstr="--nospat", + xor=("no_spat", "non_linear", "cnlinear"), + ), non_linear=dict( - argstr="--nonlinear", xor=("no_spat", "non_linear", "cnlinear"), + argstr="--nonlinear", + xor=("no_spat", "non_linear", "cnlinear"), + ), + out_dir=dict( + argstr="%s", + mandatory=True, + position=1, + usedefault=True, ), - out_dir=dict(argstr="%s", mandatory=True, position=1, usedefault=True,), output_type=dict(), - rician=dict(argstr="--rician",), - sample_every=dict(argstr="-s %d", usedefault=True,), - seed=dict(argstr="--seed=%d",), - update_proposal_every=dict(argstr="--updateproposalevery=%d", usedefault=True,), + rician=dict( + argstr="--rician", + ), + sample_every=dict( + argstr="-s %d", + usedefault=True, + ), + seed=dict( + argstr="--seed=%d", + ), + update_proposal_every=dict( + argstr="--updateproposalevery=%d", + usedefault=True, + ), use_gpu=dict(), ) inputs = BEDPOSTX5.input_spec() @@ -50,8 +125,12 @@ def test_BEDPOSTX5_outputs(): output_map = dict( dyads=dict(), dyads_dispersion=dict(), - mean_S0samples=dict(extensions=None,), - mean_dsamples=dict(extensions=None,), + mean_S0samples=dict( + extensions=None, + ), + mean_dsamples=dict( + extensions=None, + ), mean_fsamples=dict(), mean_phsamples=dict(), mean_thsamples=dict(), diff --git a/nipype/interfaces/fsl/tests/test_auto_BET.py b/nipype/interfaces/fsl/tests/test_auto_BET.py index 8d06376d94..82757a10a6 100644 --- a/nipype/interfaces/fsl/tests/test_auto_BET.py +++ b/nipype/interfaces/fsl/tests/test_auto_BET.py @@ -4,10 +4,20 @@ def test_BET_inputs(): input_map = dict( - args=dict(argstr="%s",), - center=dict(argstr="-c %s", units="voxels",), - environ=dict(nohash=True, usedefault=True,), - frac=dict(argstr="-f %.2f",), + args=dict( + argstr="%s", + ), + center=dict( + argstr="-c %s", + units="voxels", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + frac=dict( + argstr="-f %.2f", + ), functional=dict( argstr="-F", xor=( @@ -20,14 +30,32 @@ def test_BET_inputs(): "t2_guided", ), ), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), - mask=dict(argstr="-m",), - mesh=dict(argstr="-e",), - no_output=dict(argstr="-n",), + in_file=dict( + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=0, + ), + mask=dict( + argstr="-m", + ), + mesh=dict( + argstr="-e", + ), + no_output=dict( + argstr="-n", + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=1, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=1, + ), + outline=dict( + argstr="-o", ), - outline=dict(argstr="-o",), output_type=dict(), padding=dict( argstr="-Z", @@ -41,7 +69,10 @@ def test_BET_inputs(): "t2_guided", ), ), - radius=dict(argstr="-r %d", units="mm",), + radius=dict( + argstr="-r %d", + units="mm", + ), reduce_bias=dict( argstr="-B", xor=( @@ -78,7 +109,9 @@ def test_BET_inputs(): "t2_guided", ), ), - skull=dict(argstr="-s",), + skull=dict( + argstr="-s", + ), surfaces=dict( argstr="-A", xor=( @@ -104,8 +137,12 @@ def test_BET_inputs(): "t2_guided", ), ), - threshold=dict(argstr="-t",), - vertical_gradient=dict(argstr="-g %.2f",), + threshold=dict( + argstr="-t", + ), + vertical_gradient=dict( + argstr="-g %.2f", + ), ) inputs = BET.input_spec() @@ -116,18 +153,42 @@ def test_BET_inputs(): def test_BET_outputs(): output_map = dict( - inskull_mask_file=dict(extensions=None,), - inskull_mesh_file=dict(extensions=None,), - mask_file=dict(extensions=None,), - meshfile=dict(extensions=None,), - out_file=dict(extensions=None,), - outline_file=dict(extensions=None,), - outskin_mask_file=dict(extensions=None,), - outskin_mesh_file=dict(extensions=None,), - outskull_mask_file=dict(extensions=None,), - outskull_mesh_file=dict(extensions=None,), - skull_file=dict(extensions=None,), - skull_mask_file=dict(extensions=None,), + inskull_mask_file=dict( + extensions=None, + ), + inskull_mesh_file=dict( + extensions=None, + ), + mask_file=dict( + extensions=None, + ), + meshfile=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + outline_file=dict( + extensions=None, + ), + outskin_mask_file=dict( + extensions=None, + ), + outskin_mesh_file=dict( + extensions=None, + ), + outskull_mask_file=dict( + extensions=None, + ), + outskull_mesh_file=dict( + extensions=None, + ), + skull_file=dict( + extensions=None, + ), + skull_mask_file=dict( + extensions=None, + ), ) outputs = BET.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_BinaryMaths.py b/nipype/interfaces/fsl/tests/test_auto_BinaryMaths.py index 685058f2d4..405cd592f6 100644 --- a/nipype/interfaces/fsl/tests/test_auto_BinaryMaths.py +++ b/nipype/interfaces/fsl/tests/test_auto_BinaryMaths.py @@ -4,11 +4,27 @@ def test_BinaryMaths_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), operand_file=dict( argstr="%s", extensions=None, @@ -17,13 +33,27 @@ def test_BinaryMaths_inputs(): xor=["operand_value"], ), operand_value=dict( - argstr="%.8f", mandatory=True, position=5, xor=["operand_file"], + argstr="%.8f", + mandatory=True, + position=5, + xor=["operand_file"], + ), + operation=dict( + argstr="-%s", + mandatory=True, + position=4, ), - operation=dict(argstr="-%s", mandatory=True, position=4,), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = BinaryMaths.input_spec() @@ -34,7 +64,11 @@ def test_BinaryMaths_inputs(): def test_BinaryMaths_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BinaryMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ChangeDataType.py b/nipype/interfaces/fsl/tests/test_auto_ChangeDataType.py index 9dfe5ed83f..61f27be950 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ChangeDataType.py +++ b/nipype/interfaces/fsl/tests/test_auto_ChangeDataType.py @@ -4,15 +4,39 @@ def test_ChangeDataType_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + mandatory=True, + position=-1, ), - output_datatype=dict(argstr="-odt %s", mandatory=True, position=-1,), output_type=dict(), ) inputs = ChangeDataType.input_spec() @@ -23,7 +47,11 @@ def test_ChangeDataType_inputs(): def test_ChangeDataType_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ChangeDataType.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Classifier.py b/nipype/interfaces/fsl/tests/test_auto_Classifier.py index e81bb72096..44fde8ae1a 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Classifier.py +++ b/nipype/interfaces/fsl/tests/test_auto_Classifier.py @@ -4,13 +4,32 @@ def test_Classifier_inputs(): input_map = dict( - args=dict(argstr="%s",), - artifacts_list_file=dict(extensions=None,), - environ=dict(nohash=True, usedefault=True,), - mel_ica=dict(argstr="%s", copyfile=False, position=1,), - thresh=dict(argstr="%d", mandatory=True, position=-1,), + args=dict( + argstr="%s", + ), + artifacts_list_file=dict( + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + mel_ica=dict( + argstr="%s", + copyfile=False, + position=1, + ), + thresh=dict( + argstr="%d", + mandatory=True, + position=-1, + ), trained_wts_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=2, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=2, ), ) inputs = Classifier.input_spec() @@ -21,7 +40,11 @@ def test_Classifier_inputs(): def test_Classifier_outputs(): - output_map = dict(artifacts_list_file=dict(extensions=None,),) + output_map = dict( + artifacts_list_file=dict( + extensions=None, + ), + ) outputs = Classifier.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Cleaner.py b/nipype/interfaces/fsl/tests/test_auto_Cleaner.py index d5462a23d8..55e6851603 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Cleaner.py +++ b/nipype/interfaces/fsl/tests/test_auto_Cleaner.py @@ -4,17 +4,47 @@ def test_Cleaner_inputs(): input_map = dict( - aggressive=dict(argstr="-A", position=3,), - args=dict(argstr="%s",), + aggressive=dict( + argstr="-A", + position=3, + ), + args=dict( + argstr="%s", + ), artifacts_list_file=dict( - argstr="%s", extensions=None, mandatory=True, position=1, - ), - cleanup_motion=dict(argstr="-m", position=2,), - confound_file=dict(argstr="-x %s", extensions=None, position=4,), - confound_file_1=dict(argstr="-x %s", extensions=None, position=5,), - confound_file_2=dict(argstr="-x %s", extensions=None, position=6,), - environ=dict(nohash=True, usedefault=True,), - highpass=dict(argstr="-m -h %f", position=2, usedefault=True,), + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + cleanup_motion=dict( + argstr="-m", + position=2, + ), + confound_file=dict( + argstr="-x %s", + extensions=None, + position=4, + ), + confound_file_1=dict( + argstr="-x %s", + extensions=None, + position=5, + ), + confound_file_2=dict( + argstr="-x %s", + extensions=None, + position=6, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + highpass=dict( + argstr="-m -h %f", + position=2, + usedefault=True, + ), ) inputs = Cleaner.input_spec() @@ -24,7 +54,11 @@ def test_Cleaner_inputs(): def test_Cleaner_outputs(): - output_map = dict(cleaned_functional_file=dict(extensions=None,),) + output_map = dict( + cleaned_functional_file=dict( + extensions=None, + ), + ) outputs = Cleaner.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Cluster.py b/nipype/interfaces/fsl/tests/test_auto_Cluster.py index dee38d4875..ba4dfc8ae3 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Cluster.py +++ b/nipype/interfaces/fsl/tests/test_auto_Cluster.py @@ -4,34 +4,110 @@ def test_Cluster_inputs(): input_map = dict( - args=dict(argstr="%s",), - connectivity=dict(argstr="--connectivity=%d",), - cope_file=dict(argstr="--cope=%s", extensions=None,), - dlh=dict(argstr="--dlh=%.10f",), - environ=dict(nohash=True, usedefault=True,), - find_min=dict(argstr="--min", usedefault=True,), - fractional=dict(argstr="--fractional", usedefault=True,), - in_file=dict(argstr="--in=%s", extensions=None, mandatory=True,), - minclustersize=dict(argstr="--minclustersize", usedefault=True,), - no_table=dict(argstr="--no_table", usedefault=True,), - num_maxima=dict(argstr="--num=%d",), - out_index_file=dict(argstr="--oindex=%s", hash_files=False,), - out_localmax_txt_file=dict(argstr="--olmax=%s", hash_files=False,), - out_localmax_vol_file=dict(argstr="--olmaxim=%s", hash_files=False,), - out_max_file=dict(argstr="--omax=%s", hash_files=False,), - out_mean_file=dict(argstr="--omean=%s", hash_files=False,), - out_pval_file=dict(argstr="--opvals=%s", hash_files=False,), - out_size_file=dict(argstr="--osize=%s", hash_files=False,), - out_threshold_file=dict(argstr="--othresh=%s", hash_files=False,), + args=dict( + argstr="%s", + ), + connectivity=dict( + argstr="--connectivity=%d", + ), + cope_file=dict( + argstr="--cope=%s", + extensions=None, + ), + dlh=dict( + argstr="--dlh=%.10f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + find_min=dict( + argstr="--min", + usedefault=True, + ), + fractional=dict( + argstr="--fractional", + usedefault=True, + ), + in_file=dict( + argstr="--in=%s", + extensions=None, + mandatory=True, + ), + minclustersize=dict( + argstr="--minclustersize", + usedefault=True, + ), + no_table=dict( + argstr="--no_table", + usedefault=True, + ), + num_maxima=dict( + argstr="--num=%d", + ), + out_index_file=dict( + argstr="--oindex=%s", + hash_files=False, + ), + out_localmax_txt_file=dict( + argstr="--olmax=%s", + hash_files=False, + ), + out_localmax_vol_file=dict( + argstr="--olmaxim=%s", + hash_files=False, + ), + out_max_file=dict( + argstr="--omax=%s", + hash_files=False, + ), + out_mean_file=dict( + argstr="--omean=%s", + hash_files=False, + ), + out_pval_file=dict( + argstr="--opvals=%s", + hash_files=False, + ), + out_size_file=dict( + argstr="--osize=%s", + hash_files=False, + ), + out_threshold_file=dict( + argstr="--othresh=%s", + hash_files=False, + ), output_type=dict(), - peak_distance=dict(argstr="--peakdist=%.10f",), - pthreshold=dict(argstr="--pthresh=%.10f", requires=["dlh", "volume"],), - std_space_file=dict(argstr="--stdvol=%s", extensions=None,), - threshold=dict(argstr="--thresh=%.10f", mandatory=True,), - use_mm=dict(argstr="--mm", usedefault=True,), - volume=dict(argstr="--volume=%d",), - warpfield_file=dict(argstr="--warpvol=%s", extensions=None,), - xfm_file=dict(argstr="--xfm=%s", extensions=None,), + peak_distance=dict( + argstr="--peakdist=%.10f", + ), + pthreshold=dict( + argstr="--pthresh=%.10f", + requires=["dlh", "volume"], + ), + std_space_file=dict( + argstr="--stdvol=%s", + extensions=None, + ), + threshold=dict( + argstr="--thresh=%.10f", + mandatory=True, + ), + use_mm=dict( + argstr="--mm", + usedefault=True, + ), + volume=dict( + argstr="--volume=%d", + ), + warpfield_file=dict( + argstr="--warpvol=%s", + extensions=None, + ), + xfm_file=dict( + argstr="--xfm=%s", + extensions=None, + ), ) inputs = Cluster.input_spec() @@ -42,14 +118,30 @@ def test_Cluster_inputs(): def test_Cluster_outputs(): output_map = dict( - index_file=dict(extensions=None,), - localmax_txt_file=dict(extensions=None,), - localmax_vol_file=dict(extensions=None,), - max_file=dict(extensions=None,), - mean_file=dict(extensions=None,), - pval_file=dict(extensions=None,), - size_file=dict(extensions=None,), - threshold_file=dict(extensions=None,), + index_file=dict( + extensions=None, + ), + localmax_txt_file=dict( + extensions=None, + ), + localmax_vol_file=dict( + extensions=None, + ), + max_file=dict( + extensions=None, + ), + mean_file=dict( + extensions=None, + ), + pval_file=dict( + extensions=None, + ), + size_file=dict( + extensions=None, + ), + threshold_file=dict( + extensions=None, + ), ) outputs = Cluster.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Complex.py b/nipype/interfaces/fsl/tests/test_auto_Complex.py index ac631cde80..80d6f20fe6 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Complex.py +++ b/nipype/interfaces/fsl/tests/test_auto_Complex.py @@ -4,7 +4,9 @@ def test_Complex_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), complex_cartesian=dict( argstr="-complex", position=1, @@ -17,8 +19,16 @@ def test_Complex_inputs(): "complex_merge", ], ), - complex_in_file=dict(argstr="%s", extensions=None, position=2,), - complex_in_file2=dict(argstr="%s", extensions=None, position=3,), + complex_in_file=dict( + argstr="%s", + extensions=None, + position=2, + ), + complex_in_file2=dict( + argstr="%s", + extensions=None, + position=3, + ), complex_merge=dict( argstr="-complexmerge", position=1, @@ -72,9 +82,19 @@ def test_Complex_inputs(): "complex_merge", ], ), - end_vol=dict(argstr="%d", position=-1,), - environ=dict(nohash=True, usedefault=True,), - imaginary_in_file=dict(argstr="%s", extensions=None, position=3,), + end_vol=dict( + argstr="%d", + position=-1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + imaginary_in_file=dict( + argstr="%s", + extensions=None, + position=3, + ), imaginary_out_file=dict( argstr="%s", extensions=None, @@ -91,7 +111,11 @@ def test_Complex_inputs(): "complex_merge", ], ), - magnitude_in_file=dict(argstr="%s", extensions=None, position=2,), + magnitude_in_file=dict( + argstr="%s", + extensions=None, + position=2, + ), magnitude_out_file=dict( argstr="%s", extensions=None, @@ -109,7 +133,11 @@ def test_Complex_inputs(): ], ), output_type=dict(), - phase_in_file=dict(argstr="%s", extensions=None, position=3,), + phase_in_file=dict( + argstr="%s", + extensions=None, + position=3, + ), phase_out_file=dict( argstr="%s", extensions=None, @@ -138,7 +166,11 @@ def test_Complex_inputs(): "complex_merge", ], ), - real_in_file=dict(argstr="%s", extensions=None, position=2,), + real_in_file=dict( + argstr="%s", + extensions=None, + position=2, + ), real_out_file=dict( argstr="%s", extensions=None, @@ -167,7 +199,10 @@ def test_Complex_inputs(): "complex_merge", ], ), - start_vol=dict(argstr="%d", position=-2,), + start_vol=dict( + argstr="%d", + position=-2, + ), ) inputs = Complex.input_spec() @@ -178,11 +213,21 @@ def test_Complex_inputs(): def test_Complex_outputs(): output_map = dict( - complex_out_file=dict(extensions=None,), - imaginary_out_file=dict(extensions=None,), - magnitude_out_file=dict(extensions=None,), - phase_out_file=dict(extensions=None,), - real_out_file=dict(extensions=None,), + complex_out_file=dict( + extensions=None, + ), + imaginary_out_file=dict( + extensions=None, + ), + magnitude_out_file=dict( + extensions=None, + ), + phase_out_file=dict( + extensions=None, + ), + real_out_file=dict( + extensions=None, + ), ) outputs = Complex.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ContrastMgr.py b/nipype/interfaces/fsl/tests/test_auto_ContrastMgr.py index 185c089889..35e5bd43a7 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ContrastMgr.py +++ b/nipype/interfaces/fsl/tests/test_auto_ContrastMgr.py @@ -4,19 +4,53 @@ def test_ContrastMgr_inputs(): input_map = dict( - args=dict(argstr="%s",), - contrast_num=dict(argstr="-cope",), - corrections=dict(copyfile=False, extensions=None, mandatory=True,), - dof_file=dict(argstr="", copyfile=False, extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - fcon_file=dict(argstr="-f %s", extensions=None,), + args=dict( + argstr="%s", + ), + contrast_num=dict( + argstr="-cope", + ), + corrections=dict( + copyfile=False, + extensions=None, + mandatory=True, + ), + dof_file=dict( + argstr="", + copyfile=False, + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fcon_file=dict( + argstr="-f %s", + extensions=None, + ), output_type=dict(), - param_estimates=dict(argstr="", copyfile=False, mandatory=True,), + param_estimates=dict( + argstr="", + copyfile=False, + mandatory=True, + ), sigmasquareds=dict( - argstr="", copyfile=False, extensions=None, mandatory=True, position=-2, + argstr="", + copyfile=False, + extensions=None, + mandatory=True, + position=-2, + ), + suffix=dict( + argstr="-suffix %s", + ), + tcon_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, ), - suffix=dict(argstr="-suffix %s",), - tcon_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), ) inputs = ContrastMgr.input_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ConvertWarp.py b/nipype/interfaces/fsl/tests/test_auto_ConvertWarp.py index dcfc562258..7ae7f7471b 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ConvertWarp.py +++ b/nipype/interfaces/fsl/tests/test_auto_ConvertWarp.py @@ -4,14 +4,34 @@ def test_ConvertWarp_inputs(): input_map = dict( - abswarp=dict(argstr="--abs", xor=["relwarp"],), - args=dict(argstr="%s",), - cons_jacobian=dict(argstr="--constrainj",), - environ=dict(nohash=True, usedefault=True,), - jacobian_max=dict(argstr="--jmax=%f",), - jacobian_min=dict(argstr="--jmin=%f",), - midmat=dict(argstr="--midmat=%s", extensions=None,), - out_abswarp=dict(argstr="--absout", xor=["out_relwarp"],), + abswarp=dict( + argstr="--abs", + xor=["relwarp"], + ), + args=dict( + argstr="%s", + ), + cons_jacobian=dict( + argstr="--constrainj", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + jacobian_max=dict( + argstr="--jmax=%f", + ), + jacobian_min=dict( + argstr="--jmin=%f", + ), + midmat=dict( + argstr="--midmat=%s", + extensions=None, + ), + out_abswarp=dict( + argstr="--absout", + xor=["out_relwarp"], + ), out_file=dict( argstr="--out=%s", extensions=None, @@ -20,16 +40,45 @@ def test_ConvertWarp_inputs(): output_name="out_file", position=-1, ), - out_relwarp=dict(argstr="--relout", xor=["out_abswarp"],), + out_relwarp=dict( + argstr="--relout", + xor=["out_abswarp"], + ), output_type=dict(), - postmat=dict(argstr="--postmat=%s", extensions=None,), - premat=dict(argstr="--premat=%s", extensions=None,), - reference=dict(argstr="--ref=%s", extensions=None, mandatory=True, position=1,), - relwarp=dict(argstr="--rel", xor=["abswarp"],), - shift_direction=dict(argstr="--shiftdir=%s", requires=["shift_in_file"],), - shift_in_file=dict(argstr="--shiftmap=%s", extensions=None,), - warp1=dict(argstr="--warp1=%s", extensions=None,), - warp2=dict(argstr="--warp2=%s", extensions=None,), + postmat=dict( + argstr="--postmat=%s", + extensions=None, + ), + premat=dict( + argstr="--premat=%s", + extensions=None, + ), + reference=dict( + argstr="--ref=%s", + extensions=None, + mandatory=True, + position=1, + ), + relwarp=dict( + argstr="--rel", + xor=["abswarp"], + ), + shift_direction=dict( + argstr="--shiftdir=%s", + requires=["shift_in_file"], + ), + shift_in_file=dict( + argstr="--shiftmap=%s", + extensions=None, + ), + warp1=dict( + argstr="--warp1=%s", + extensions=None, + ), + warp2=dict( + argstr="--warp2=%s", + extensions=None, + ), ) inputs = ConvertWarp.input_spec() @@ -39,7 +88,11 @@ def test_ConvertWarp_inputs(): def test_ConvertWarp_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ConvertWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ConvertXFM.py b/nipype/interfaces/fsl/tests/test_auto_ConvertXFM.py index b4311d0d37..60e1d7553b 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ConvertXFM.py +++ b/nipype/interfaces/fsl/tests/test_auto_ConvertXFM.py @@ -4,22 +4,36 @@ def test_ConvertXFM_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), concat_xfm=dict( argstr="-concat", position=-3, requires=["in_file2"], xor=["invert_xfm", "concat_xfm", "fix_scale_skew"], ), - environ=dict(nohash=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), fix_scale_skew=dict( argstr="-fixscaleskew", position=-3, requires=["in_file2"], xor=["invert_xfm", "concat_xfm", "fix_scale_skew"], ), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - in_file2=dict(argstr="%s", extensions=None, position=-2,), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + in_file2=dict( + argstr="%s", + extensions=None, + position=-2, + ), invert_xfm=dict( argstr="-inverse", position=-3, @@ -42,7 +56,11 @@ def test_ConvertXFM_inputs(): def test_ConvertXFM_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ConvertXFM.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_CopyGeom.py b/nipype/interfaces/fsl/tests/test_auto_CopyGeom.py index ade301a00e..6f15d47bfc 100644 --- a/nipype/interfaces/fsl/tests/test_auto_CopyGeom.py +++ b/nipype/interfaces/fsl/tests/test_auto_CopyGeom.py @@ -4,7 +4,9 @@ def test_CopyGeom_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), dest_file=dict( argstr="%s", copyfile=True, @@ -15,9 +17,20 @@ def test_CopyGeom_inputs(): output_name="out_file", position=1, ), - environ=dict(nohash=True, usedefault=True,), - ignore_dims=dict(argstr="-d", position="-1",), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_dims=dict( + argstr="-d", + position="-1", + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), output_type=dict(), ) inputs = CopyGeom.input_spec() @@ -28,7 +41,11 @@ def test_CopyGeom_inputs(): def test_CopyGeom_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = CopyGeom.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_DTIFit.py b/nipype/interfaces/fsl/tests/test_auto_DTIFit.py index a0cf704d87..546ffa6848 100644 --- a/nipype/interfaces/fsl/tests/test_auto_DTIFit.py +++ b/nipype/interfaces/fsl/tests/test_auto_DTIFit.py @@ -4,25 +4,78 @@ def test_DTIFit_inputs(): input_map = dict( - args=dict(argstr="%s",), - base_name=dict(argstr="-o %s", position=1, usedefault=True,), - bvals=dict(argstr="-b %s", extensions=None, mandatory=True, position=4,), - bvecs=dict(argstr="-r %s", extensions=None, mandatory=True, position=3,), - cni=dict(argstr="--cni=%s", extensions=None,), - dwi=dict(argstr="-k %s", extensions=None, mandatory=True, position=0,), - environ=dict(nohash=True, usedefault=True,), - gradnonlin=dict(argstr="--gradnonlin=%s", extensions=None,), - little_bit=dict(argstr="--littlebit",), - mask=dict(argstr="-m %s", extensions=None, mandatory=True, position=2,), - max_x=dict(argstr="-X %d",), - max_y=dict(argstr="-Y %d",), - max_z=dict(argstr="-Z %d",), - min_x=dict(argstr="-x %d",), - min_y=dict(argstr="-y %d",), - min_z=dict(argstr="-z %d",), + args=dict( + argstr="%s", + ), + base_name=dict( + argstr="-o %s", + position=1, + usedefault=True, + ), + bvals=dict( + argstr="-b %s", + extensions=None, + mandatory=True, + position=4, + ), + bvecs=dict( + argstr="-r %s", + extensions=None, + mandatory=True, + position=3, + ), + cni=dict( + argstr="--cni=%s", + extensions=None, + ), + dwi=dict( + argstr="-k %s", + extensions=None, + mandatory=True, + position=0, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradnonlin=dict( + argstr="--gradnonlin=%s", + extensions=None, + ), + little_bit=dict( + argstr="--littlebit", + ), + mask=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + position=2, + ), + max_x=dict( + argstr="-X %d", + ), + max_y=dict( + argstr="-Y %d", + ), + max_z=dict( + argstr="-Z %d", + ), + min_x=dict( + argstr="-x %d", + ), + min_y=dict( + argstr="-y %d", + ), + min_z=dict( + argstr="-z %d", + ), output_type=dict(), - save_tensor=dict(argstr="--save_tensor",), - sse=dict(argstr="--sse",), + save_tensor=dict( + argstr="--save_tensor", + ), + sse=dict( + argstr="--sse", + ), ) inputs = DTIFit.input_spec() @@ -33,18 +86,42 @@ def test_DTIFit_inputs(): def test_DTIFit_outputs(): output_map = dict( - FA=dict(extensions=None,), - L1=dict(extensions=None,), - L2=dict(extensions=None,), - L3=dict(extensions=None,), - MD=dict(extensions=None,), - MO=dict(extensions=None,), - S0=dict(extensions=None,), - V1=dict(extensions=None,), - V2=dict(extensions=None,), - V3=dict(extensions=None,), - sse=dict(extensions=None,), - tensor=dict(extensions=None,), + FA=dict( + extensions=None, + ), + L1=dict( + extensions=None, + ), + L2=dict( + extensions=None, + ), + L3=dict( + extensions=None, + ), + MD=dict( + extensions=None, + ), + MO=dict( + extensions=None, + ), + S0=dict( + extensions=None, + ), + V1=dict( + extensions=None, + ), + V2=dict( + extensions=None, + ), + V3=dict( + extensions=None, + ), + sse=dict( + extensions=None, + ), + tensor=dict( + extensions=None, + ), ) outputs = DTIFit.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_DilateImage.py b/nipype/interfaces/fsl/tests/test_auto_DilateImage.py index 4a9a49eb45..ac204e5a38 100644 --- a/nipype/interfaces/fsl/tests/test_auto_DilateImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_DilateImage.py @@ -4,21 +4,58 @@ def test_DilateImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), kernel_file=dict( - argstr="%s", extensions=None, position=5, xor=["kernel_size"], + argstr="%s", + extensions=None, + position=5, + xor=["kernel_size"], + ), + kernel_shape=dict( + argstr="-kernel %s", + position=4, + ), + kernel_size=dict( + argstr="%.4f", + position=5, + xor=["kernel_file"], + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), + operation=dict( + argstr="-dil%s", + mandatory=True, + position=6, ), - kernel_shape=dict(argstr="-kernel %s", position=4,), - kernel_size=dict(argstr="%.4f", position=5, xor=["kernel_file"],), - nan2zeros=dict(argstr="-nan", position=3,), - operation=dict(argstr="-dil%s", mandatory=True, position=6,), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = DilateImage.input_spec() @@ -29,7 +66,11 @@ def test_DilateImage_inputs(): def test_DilateImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = DilateImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_DistanceMap.py b/nipype/interfaces/fsl/tests/test_auto_DistanceMap.py index bd2134ec5d..74ea024917 100644 --- a/nipype/interfaces/fsl/tests/test_auto_DistanceMap.py +++ b/nipype/interfaces/fsl/tests/test_auto_DistanceMap.py @@ -4,15 +4,35 @@ def test_DistanceMap_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), distance_map=dict( - argstr="--out=%s", extensions=None, genfile=True, hash_files=False, + argstr="--out=%s", + extensions=None, + genfile=True, + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="--in=%s", + extensions=None, + mandatory=True, + ), + invert_input=dict( + argstr="--invert", + ), + local_max_file=dict( + argstr="--localmax=%s", + hash_files=False, + ), + mask_file=dict( + argstr="--mask=%s", + extensions=None, ), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="--in=%s", extensions=None, mandatory=True,), - invert_input=dict(argstr="--invert",), - local_max_file=dict(argstr="--localmax=%s", hash_files=False,), - mask_file=dict(argstr="--mask=%s", extensions=None,), output_type=dict(), ) inputs = DistanceMap.input_spec() @@ -24,7 +44,12 @@ def test_DistanceMap_inputs(): def test_DistanceMap_outputs(): output_map = dict( - distance_map=dict(extensions=None,), local_max_file=dict(extensions=None,), + distance_map=dict( + extensions=None, + ), + local_max_file=dict( + extensions=None, + ), ) outputs = DistanceMap.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_DualRegression.py b/nipype/interfaces/fsl/tests/test_auto_DualRegression.py index 99e6a0f23d..4b3d8f6851 100644 --- a/nipype/interfaces/fsl/tests/test_auto_DualRegression.py +++ b/nipype/interfaces/fsl/tests/test_auto_DualRegression.py @@ -4,18 +4,55 @@ def test_DualRegression_inputs(): input_map = dict( - args=dict(argstr="%s",), - con_file=dict(argstr="%s", extensions=None, position=4,), - des_norm=dict(argstr="%i", position=2, usedefault=True,), - design_file=dict(argstr="%s", extensions=None, position=3,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + con_file=dict( + argstr="%s", + extensions=None, + position=4, + ), + des_norm=dict( + argstr="%i", + position=2, + usedefault=True, + ), + design_file=dict( + argstr="%s", + extensions=None, + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), group_IC_maps_4D=dict( - argstr="%s", extensions=None, mandatory=True, position=1, + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-1, + sep=" ", + ), + n_perm=dict( + argstr="%i", + mandatory=True, + position=5, + ), + one_sample_group_mean=dict( + argstr="-1", + position=3, + ), + out_dir=dict( + argstr="%s", + genfile=True, + position=6, + usedefault=True, ), - in_files=dict(argstr="%s", mandatory=True, position=-1, sep=" ",), - n_perm=dict(argstr="%i", mandatory=True, position=5,), - one_sample_group_mean=dict(argstr="-1", position=3,), - out_dir=dict(argstr="%s", genfile=True, position=6, usedefault=True,), output_type=dict(), ) inputs = DualRegression.input_spec() @@ -26,7 +63,9 @@ def test_DualRegression_inputs(): def test_DualRegression_outputs(): - output_map = dict(out_dir=dict(),) + output_map = dict( + out_dir=dict(), + ) outputs = DualRegression.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py b/nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py index 39476ab324..0462fa9cbe 100644 --- a/nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py +++ b/nipype/interfaces/fsl/tests/test_auto_EPIDeWarp.py @@ -4,22 +4,68 @@ def test_EPIDeWarp_inputs(): input_map = dict( - args=dict(argstr="%s",), - cleanup=dict(argstr="--cleanup",), - dph_file=dict(argstr="--dph %s", extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - epi_file=dict(argstr="--epi %s", extensions=None,), - epidw=dict(argstr="--epidw %s", genfile=False,), - esp=dict(argstr="--esp %s", usedefault=True,), - exf_file=dict(argstr="--exf %s", extensions=None,), - exfdw=dict(argstr="--exfdw %s", genfile=True,), - mag_file=dict(argstr="--mag %s", extensions=None, mandatory=True, position=0,), - nocleanup=dict(argstr="--nocleanup", usedefault=True,), + args=dict( + argstr="%s", + ), + cleanup=dict( + argstr="--cleanup", + ), + dph_file=dict( + argstr="--dph %s", + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi_file=dict( + argstr="--epi %s", + extensions=None, + ), + epidw=dict( + argstr="--epidw %s", + genfile=False, + ), + esp=dict( + argstr="--esp %s", + usedefault=True, + ), + exf_file=dict( + argstr="--exf %s", + extensions=None, + ), + exfdw=dict( + argstr="--exfdw %s", + genfile=True, + ), + mag_file=dict( + argstr="--mag %s", + extensions=None, + mandatory=True, + position=0, + ), + nocleanup=dict( + argstr="--nocleanup", + usedefault=True, + ), output_type=dict(), - sigma=dict(argstr="--sigma %s", usedefault=True,), - tediff=dict(argstr="--tediff %s", usedefault=True,), - tmpdir=dict(argstr="--tmpdir %s", genfile=True,), - vsm=dict(argstr="--vsm %s", genfile=True,), + sigma=dict( + argstr="--sigma %s", + usedefault=True, + ), + tediff=dict( + argstr="--tediff %s", + usedefault=True, + ), + tmpdir=dict( + argstr="--tmpdir %s", + genfile=True, + ), + vsm=dict( + argstr="--vsm %s", + genfile=True, + ), ) inputs = EPIDeWarp.input_spec() @@ -30,10 +76,18 @@ def test_EPIDeWarp_inputs(): def test_EPIDeWarp_outputs(): output_map = dict( - exf_mask=dict(extensions=None,), - exfdw=dict(extensions=None,), - unwarped_file=dict(extensions=None,), - vsm_file=dict(extensions=None,), + exf_mask=dict( + extensions=None, + ), + exfdw=dict( + extensions=None, + ), + unwarped_file=dict( + extensions=None, + ), + vsm_file=dict( + extensions=None, + ), ) outputs = EPIDeWarp.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Eddy.py b/nipype/interfaces/fsl/tests/test_auto_Eddy.py index 4a2d245a23..0005085474 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Eddy.py +++ b/nipype/interfaces/fsl/tests/test_auto_Eddy.py @@ -4,33 +4,99 @@ def test_Eddy_inputs(): input_map = dict( - args=dict(argstr="%s",), - cnr_maps=dict(argstr="--cnr_maps", min_ver="5.0.10",), - dont_peas=dict(argstr="--dont_peas",), - dont_sep_offs_move=dict(argstr="--dont_sep_offs_move",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + cnr_maps=dict( + argstr="--cnr_maps", + min_ver="5.0.10", + ), + dont_peas=dict( + argstr="--dont_peas", + ), + dont_sep_offs_move=dict( + argstr="--dont_sep_offs_move", + ), + environ=dict( + nohash=True, + usedefault=True, + ), estimate_move_by_susceptibility=dict( - argstr="--estimate_move_by_susceptibility", min_ver="6.0.1", - ), - fep=dict(argstr="--fep",), - field=dict(argstr="--field=%s", extensions=None,), - field_mat=dict(argstr="--field_mat=%s", extensions=None,), - flm=dict(argstr="--flm=%s", usedefault=True,), - fudge_factor=dict(argstr="--ff=%s", usedefault=True,), - fwhm=dict(argstr="--fwhm=%s",), - in_acqp=dict(argstr="--acqp=%s", extensions=None, mandatory=True,), - in_bval=dict(argstr="--bvals=%s", extensions=None, mandatory=True,), - in_bvec=dict(argstr="--bvecs=%s", extensions=None, mandatory=True,), - in_file=dict(argstr="--imain=%s", extensions=None, mandatory=True,), - in_index=dict(argstr="--index=%s", extensions=None, mandatory=True,), - in_mask=dict(argstr="--mask=%s", extensions=None, mandatory=True,), + argstr="--estimate_move_by_susceptibility", + min_ver="6.0.1", + ), + fep=dict( + argstr="--fep", + ), + field=dict( + argstr="--field=%s", + extensions=None, + ), + field_mat=dict( + argstr="--field_mat=%s", + extensions=None, + ), + flm=dict( + argstr="--flm=%s", + usedefault=True, + ), + fudge_factor=dict( + argstr="--ff=%s", + usedefault=True, + ), + fwhm=dict( + argstr="--fwhm=%s", + ), + in_acqp=dict( + argstr="--acqp=%s", + extensions=None, + mandatory=True, + ), + in_bval=dict( + argstr="--bvals=%s", + extensions=None, + mandatory=True, + ), + in_bvec=dict( + argstr="--bvecs=%s", + extensions=None, + mandatory=True, + ), + in_file=dict( + argstr="--imain=%s", + extensions=None, + mandatory=True, + ), + in_index=dict( + argstr="--index=%s", + extensions=None, + mandatory=True, + ), + in_mask=dict( + argstr="--mask=%s", + extensions=None, + mandatory=True, + ), in_topup_fieldcoef=dict( - argstr="--topup=%s", extensions=None, requires=["in_topup_movpar"], + argstr="--topup=%s", + extensions=None, + requires=["in_topup_movpar"], + ), + in_topup_movpar=dict( + extensions=None, + requires=["in_topup_fieldcoef"], + ), + initrand=dict( + argstr="--initrand", + min_ver="5.0.10", + ), + interp=dict( + argstr="--interp=%s", + usedefault=True, + ), + is_shelled=dict( + argstr="--data_is_shelled", ), - in_topup_movpar=dict(extensions=None, requires=["in_topup_fieldcoef"],), - initrand=dict(argstr="--initrand", min_ver="5.0.10",), - interp=dict(argstr="--interp=%s", usedefault=True,), - is_shelled=dict(argstr="--data_is_shelled",), json=dict( argstr="--json=%s", min_ver="6.0.1", @@ -52,38 +118,102 @@ def test_Eddy_inputs(): min_ver="6.0.1", requires=["estimate_move_by_susceptibility"], ), - method=dict(argstr="--resamp=%s", usedefault=True,), - mporder=dict(argstr="--mporder=%s", min_ver="5.0.11", requires=["use_cuda"],), - multiband_factor=dict(argstr="--mb=%s", min_ver="5.0.10",), + method=dict( + argstr="--resamp=%s", + usedefault=True, + ), + mporder=dict( + argstr="--mporder=%s", + min_ver="5.0.11", + requires=["use_cuda"], + ), + multiband_factor=dict( + argstr="--mb=%s", + min_ver="5.0.10", + ), multiband_offset=dict( - argstr="--mb_offs=%d", min_ver="5.0.10", requires=["multiband_factor"], - ), - niter=dict(argstr="--niter=%s", usedefault=True,), - num_threads=dict(nohash=True, usedefault=True,), - nvoxhp=dict(argstr="--nvoxhp=%s", usedefault=True,), - out_base=dict(argstr="--out=%s", usedefault=True,), - outlier_nstd=dict(argstr="--ol_nstd", min_ver="5.0.10", requires=["repol"],), - outlier_nvox=dict(argstr="--ol_nvox", min_ver="5.0.10", requires=["repol"],), - outlier_pos=dict(argstr="--ol_pos", min_ver="5.0.10", requires=["repol"],), - outlier_sqr=dict(argstr="--ol_sqr", min_ver="5.0.10", requires=["repol"],), - outlier_type=dict(argstr="--ol_type", min_ver="5.0.10", requires=["repol"],), + argstr="--mb_offs=%d", + min_ver="5.0.10", + requires=["multiband_factor"], + ), + niter=dict( + argstr="--niter=%s", + usedefault=True, + ), + num_threads=dict( + nohash=True, + usedefault=True, + ), + nvoxhp=dict( + argstr="--nvoxhp=%s", + usedefault=True, + ), + out_base=dict( + argstr="--out=%s", + usedefault=True, + ), + outlier_nstd=dict( + argstr="--ol_nstd", + min_ver="5.0.10", + requires=["repol"], + ), + outlier_nvox=dict( + argstr="--ol_nvox", + min_ver="5.0.10", + requires=["repol"], + ), + outlier_pos=dict( + argstr="--ol_pos", + min_ver="5.0.10", + requires=["repol"], + ), + outlier_sqr=dict( + argstr="--ol_sqr", + min_ver="5.0.10", + requires=["repol"], + ), + outlier_type=dict( + argstr="--ol_type", + min_ver="5.0.10", + requires=["repol"], + ), output_type=dict(), - repol=dict(argstr="--repol",), - residuals=dict(argstr="--residuals", min_ver="5.0.10",), - session=dict(argstr="--session=%s", extensions=None,), + repol=dict( + argstr="--repol", + ), + residuals=dict( + argstr="--residuals", + min_ver="5.0.10", + ), + session=dict( + argstr="--session=%s", + extensions=None, + ), slice2vol_interp=dict( - argstr="--s2v_interp=%s", min_ver="5.0.11", requires=["mporder"], + argstr="--s2v_interp=%s", + min_ver="5.0.11", + requires=["mporder"], ), slice2vol_lambda=dict( - argstr="--s2v_lambda=%d", min_ver="5.0.11", requires=["mporder"], + argstr="--s2v_lambda=%d", + min_ver="5.0.11", + requires=["mporder"], ), slice2vol_niter=dict( - argstr="--s2v_niter=%d", min_ver="5.0.11", requires=["mporder"], + argstr="--s2v_niter=%d", + min_ver="5.0.11", + requires=["mporder"], ), slice_order=dict( - argstr="--slspec=%s", min_ver="5.0.11", requires=["mporder"], xor=["json"], + argstr="--slspec=%s", + min_ver="5.0.11", + requires=["mporder"], + xor=["json"], + ), + slm=dict( + argstr="--slm=%s", + usedefault=True, ), - slm=dict(argstr="--slm=%s", usedefault=True,), use_cuda=dict(), ) inputs = Eddy.input_spec() @@ -95,21 +225,51 @@ def test_Eddy_inputs(): def test_Eddy_outputs(): output_map = dict( - out_cnr_maps=dict(extensions=None,), - out_corrected=dict(extensions=None,), - out_movement_over_time=dict(extensions=None,), - out_movement_rms=dict(extensions=None,), - out_outlier_free=dict(extensions=None,), - out_outlier_map=dict(extensions=None,), - out_outlier_n_sqr_stdev_map=dict(extensions=None,), - out_outlier_n_stdev_map=dict(extensions=None,), - out_outlier_report=dict(extensions=None,), - out_parameter=dict(extensions=None,), - out_residuals=dict(extensions=None,), - out_restricted_movement_rms=dict(extensions=None,), - out_rotated_bvecs=dict(extensions=None,), - out_shell_alignment_parameters=dict(extensions=None,), - out_shell_pe_translation_parameters=dict(extensions=None,), + out_cnr_maps=dict( + extensions=None, + ), + out_corrected=dict( + extensions=None, + ), + out_movement_over_time=dict( + extensions=None, + ), + out_movement_rms=dict( + extensions=None, + ), + out_outlier_free=dict( + extensions=None, + ), + out_outlier_map=dict( + extensions=None, + ), + out_outlier_n_sqr_stdev_map=dict( + extensions=None, + ), + out_outlier_n_stdev_map=dict( + extensions=None, + ), + out_outlier_report=dict( + extensions=None, + ), + out_parameter=dict( + extensions=None, + ), + out_residuals=dict( + extensions=None, + ), + out_restricted_movement_rms=dict( + extensions=None, + ), + out_rotated_bvecs=dict( + extensions=None, + ), + out_shell_alignment_parameters=dict( + extensions=None, + ), + out_shell_pe_translation_parameters=dict( + extensions=None, + ), ) outputs = Eddy.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_EddyCorrect.py b/nipype/interfaces/fsl/tests/test_auto_EddyCorrect.py index fbd2af30cb..e2ce1c0a3b 100644 --- a/nipype/interfaces/fsl/tests/test_auto_EddyCorrect.py +++ b/nipype/interfaces/fsl/tests/test_auto_EddyCorrect.py @@ -4,9 +4,19 @@ def test_EddyCorrect_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), out_file=dict( argstr="%s", extensions=None, @@ -16,7 +26,12 @@ def test_EddyCorrect_inputs(): position=1, ), output_type=dict(), - ref_num=dict(argstr="%d", mandatory=True, position=2, usedefault=True,), + ref_num=dict( + argstr="%d", + mandatory=True, + position=2, + usedefault=True, + ), ) inputs = EddyCorrect.input_spec() @@ -26,7 +41,11 @@ def test_EddyCorrect_inputs(): def test_EddyCorrect_outputs(): - output_map = dict(eddy_corrected=dict(extensions=None,),) + output_map = dict( + eddy_corrected=dict( + extensions=None, + ), + ) outputs = EddyCorrect.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_EddyQuad.py b/nipype/interfaces/fsl/tests/test_auto_EddyQuad.py index 14b6ca3a28..3d9756a4be 100644 --- a/nipype/interfaces/fsl/tests/test_auto_EddyQuad.py +++ b/nipype/interfaces/fsl/tests/test_auto_EddyQuad.py @@ -4,21 +4,59 @@ def test_EddyQuad_inputs(): input_map = dict( - args=dict(argstr="%s",), - base_name=dict(argstr="%s", position=0, usedefault=True,), - bval_file=dict(argstr="--bvals %s", extensions=None, mandatory=True,), - bvec_file=dict(argstr="--bvecs %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - field=dict(argstr="--field %s", extensions=None,), - idx_file=dict(argstr="--eddyIdx %s", extensions=None, mandatory=True,), - mask_file=dict(argstr="--mask %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + base_name=dict( + argstr="%s", + position=0, + usedefault=True, + ), + bval_file=dict( + argstr="--bvals %s", + extensions=None, + mandatory=True, + ), + bvec_file=dict( + argstr="--bvecs %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + field=dict( + argstr="--field %s", + extensions=None, + ), + idx_file=dict( + argstr="--eddyIdx %s", + extensions=None, + mandatory=True, + ), + mask_file=dict( + argstr="--mask %s", + extensions=None, + mandatory=True, + ), output_dir=dict( - argstr="--output-dir %s", name_source=["base_name"], name_template="%s.qc", + argstr="--output-dir %s", + name_source=["base_name"], + name_template="%s.qc", ), output_type=dict(), - param_file=dict(argstr="--eddyParams %s", extensions=None, mandatory=True,), - slice_spec=dict(argstr="--slspec %s", extensions=None,), - verbose=dict(argstr="--verbose",), + param_file=dict( + argstr="--eddyParams %s", + extensions=None, + mandatory=True, + ), + slice_spec=dict( + argstr="--slspec %s", + extensions=None, + ), + verbose=dict( + argstr="--verbose", + ), ) inputs = EddyQuad.input_spec() @@ -31,12 +69,22 @@ def test_EddyQuad_outputs(): output_map = dict( avg_b0_pe_png=dict(), avg_b_png=dict(), - clean_volumes=dict(extensions=None,), + clean_volumes=dict( + extensions=None, + ), cnr_png=dict(), - qc_json=dict(extensions=None,), - qc_pdf=dict(extensions=None,), - residuals=dict(extensions=None,), - vdm_png=dict(extensions=None,), + qc_json=dict( + extensions=None, + ), + qc_pdf=dict( + extensions=None, + ), + residuals=dict( + extensions=None, + ), + vdm_png=dict( + extensions=None, + ), ) outputs = EddyQuad.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_EpiReg.py b/nipype/interfaces/fsl/tests/test_auto_EpiReg.py index f1f1482260..242c2e6040 100644 --- a/nipype/interfaces/fsl/tests/test_auto_EpiReg.py +++ b/nipype/interfaces/fsl/tests/test_auto_EpiReg.py @@ -4,24 +4,70 @@ def test_EpiReg_inputs(): input_map = dict( - args=dict(argstr="%s",), - echospacing=dict(argstr="--echospacing=%f",), - environ=dict(nohash=True, usedefault=True,), - epi=dict(argstr="--epi=%s", extensions=None, mandatory=True, position=-4,), - fmap=dict(argstr="--fmap=%s", extensions=None,), - fmapmag=dict(argstr="--fmapmag=%s", extensions=None,), - fmapmagbrain=dict(argstr="--fmapmagbrain=%s", extensions=None,), - no_clean=dict(argstr="--noclean", usedefault=True,), - no_fmapreg=dict(argstr="--nofmapreg",), - out_base=dict(argstr="--out=%s", position=-1, usedefault=True,), + args=dict( + argstr="%s", + ), + echospacing=dict( + argstr="--echospacing=%f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + epi=dict( + argstr="--epi=%s", + extensions=None, + mandatory=True, + position=-4, + ), + fmap=dict( + argstr="--fmap=%s", + extensions=None, + ), + fmapmag=dict( + argstr="--fmapmag=%s", + extensions=None, + ), + fmapmagbrain=dict( + argstr="--fmapmagbrain=%s", + extensions=None, + ), + no_clean=dict( + argstr="--noclean", + usedefault=True, + ), + no_fmapreg=dict( + argstr="--nofmapreg", + ), + out_base=dict( + argstr="--out=%s", + position=-1, + usedefault=True, + ), output_type=dict(), - pedir=dict(argstr="--pedir=%s",), + pedir=dict( + argstr="--pedir=%s", + ), t1_brain=dict( - argstr="--t1brain=%s", extensions=None, mandatory=True, position=-2, + argstr="--t1brain=%s", + extensions=None, + mandatory=True, + position=-2, + ), + t1_head=dict( + argstr="--t1=%s", + extensions=None, + mandatory=True, + position=-3, + ), + weight_image=dict( + argstr="--weight=%s", + extensions=None, + ), + wmseg=dict( + argstr="--wmseg=%s", + extensions=None, ), - t1_head=dict(argstr="--t1=%s", extensions=None, mandatory=True, position=-3,), - weight_image=dict(argstr="--weight=%s", extensions=None,), - wmseg=dict(argstr="--wmseg=%s", extensions=None,), ) inputs = EpiReg.input_spec() @@ -32,20 +78,48 @@ def test_EpiReg_inputs(): def test_EpiReg_outputs(): output_map = dict( - epi2str_inv=dict(extensions=None,), - epi2str_mat=dict(extensions=None,), - fmap2epi_mat=dict(extensions=None,), - fmap2str_mat=dict(extensions=None,), - fmap_epi=dict(extensions=None,), - fmap_str=dict(extensions=None,), - fmapmag_str=dict(extensions=None,), - fullwarp=dict(extensions=None,), - out_1vol=dict(extensions=None,), - out_file=dict(extensions=None,), - seg=dict(extensions=None,), - shiftmap=dict(extensions=None,), - wmedge=dict(extensions=None,), - wmseg=dict(extensions=None,), + epi2str_inv=dict( + extensions=None, + ), + epi2str_mat=dict( + extensions=None, + ), + fmap2epi_mat=dict( + extensions=None, + ), + fmap2str_mat=dict( + extensions=None, + ), + fmap_epi=dict( + extensions=None, + ), + fmap_str=dict( + extensions=None, + ), + fmapmag_str=dict( + extensions=None, + ), + fullwarp=dict( + extensions=None, + ), + out_1vol=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + seg=dict( + extensions=None, + ), + shiftmap=dict( + extensions=None, + ), + wmedge=dict( + extensions=None, + ), + wmseg=dict( + extensions=None, + ), ) outputs = EpiReg.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ErodeImage.py b/nipype/interfaces/fsl/tests/test_auto_ErodeImage.py index 1b813812c3..1aad31cd16 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ErodeImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_ErodeImage.py @@ -4,21 +4,58 @@ def test_ErodeImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), kernel_file=dict( - argstr="%s", extensions=None, position=5, xor=["kernel_size"], + argstr="%s", + extensions=None, + position=5, + xor=["kernel_size"], + ), + kernel_shape=dict( + argstr="-kernel %s", + position=4, + ), + kernel_size=dict( + argstr="%.4f", + position=5, + xor=["kernel_file"], + ), + minimum_filter=dict( + argstr="%s", + position=6, + usedefault=True, + ), + nan2zeros=dict( + argstr="-nan", + position=3, ), - kernel_shape=dict(argstr="-kernel %s", position=4,), - kernel_size=dict(argstr="%.4f", position=5, xor=["kernel_file"],), - minimum_filter=dict(argstr="%s", position=6, usedefault=True,), - nan2zeros=dict(argstr="-nan", position=3,), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = ErodeImage.input_spec() @@ -29,7 +66,11 @@ def test_ErodeImage_inputs(): def test_ErodeImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ErodeImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ExtractROI.py b/nipype/interfaces/fsl/tests/test_auto_ExtractROI.py index 4039eb50a2..bd6acb137c 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ExtractROI.py +++ b/nipype/interfaces/fsl/tests/test_auto_ExtractROI.py @@ -4,7 +4,9 @@ def test_ExtractROI_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), crop_list=dict( argstr="%s", position=2, @@ -19,20 +21,56 @@ def test_ExtractROI_inputs(): "t_size", ], ), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), output_type=dict(), roi_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=1, - ), - t_min=dict(argstr="%d", position=8,), - t_size=dict(argstr="%d", position=9,), - x_min=dict(argstr="%d", position=2,), - x_size=dict(argstr="%d", position=3,), - y_min=dict(argstr="%d", position=4,), - y_size=dict(argstr="%d", position=5,), - z_min=dict(argstr="%d", position=6,), - z_size=dict(argstr="%d", position=7,), + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=1, + ), + t_min=dict( + argstr="%d", + position=8, + ), + t_size=dict( + argstr="%d", + position=9, + ), + x_min=dict( + argstr="%d", + position=2, + ), + x_size=dict( + argstr="%d", + position=3, + ), + y_min=dict( + argstr="%d", + position=4, + ), + y_size=dict( + argstr="%d", + position=5, + ), + z_min=dict( + argstr="%d", + position=6, + ), + z_size=dict( + argstr="%d", + position=7, + ), ) inputs = ExtractROI.input_spec() @@ -42,7 +80,11 @@ def test_ExtractROI_inputs(): def test_ExtractROI_outputs(): - output_map = dict(roi_file=dict(extensions=None,),) + output_map = dict( + roi_file=dict( + extensions=None, + ), + ) outputs = ExtractROI.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FAST.py b/nipype/interfaces/fsl/tests/test_auto_FAST.py index 3c245682a6..e775d97b35 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FAST.py +++ b/nipype/interfaces/fsl/tests/test_auto_FAST.py @@ -4,31 +4,87 @@ def test_FAST_inputs(): input_map = dict( - args=dict(argstr="%s",), - bias_iters=dict(argstr="-I %d",), - bias_lowpass=dict(argstr="-l %d", units="mm",), - environ=dict(nohash=True, usedefault=True,), - hyper=dict(argstr="-H %.2f",), - img_type=dict(argstr="-t %d",), - in_files=dict(argstr="%s", copyfile=False, mandatory=True, position=-1,), - init_seg_smooth=dict(argstr="-f %.3f",), - init_transform=dict(argstr="-a %s", extensions=None,), - iters_afterbias=dict(argstr="-O %d",), - manual_seg=dict(argstr="-s %s", extensions=None,), - mixel_smooth=dict(argstr="-R %.2f",), - no_bias=dict(argstr="-N",), - no_pve=dict(argstr="--nopve",), - number_classes=dict(argstr="-n %d",), - other_priors=dict(argstr="-A %s",), - out_basename=dict(argstr="-o %s", extensions=None,), - output_biascorrected=dict(argstr="-B",), - output_biasfield=dict(argstr="-b",), + args=dict( + argstr="%s", + ), + bias_iters=dict( + argstr="-I %d", + ), + bias_lowpass=dict( + argstr="-l %d", + units="mm", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hyper=dict( + argstr="-H %.2f", + ), + img_type=dict( + argstr="-t %d", + ), + in_files=dict( + argstr="%s", + copyfile=False, + mandatory=True, + position=-1, + ), + init_seg_smooth=dict( + argstr="-f %.3f", + ), + init_transform=dict( + argstr="-a %s", + extensions=None, + ), + iters_afterbias=dict( + argstr="-O %d", + ), + manual_seg=dict( + argstr="-s %s", + extensions=None, + ), + mixel_smooth=dict( + argstr="-R %.2f", + ), + no_bias=dict( + argstr="-N", + ), + no_pve=dict( + argstr="--nopve", + ), + number_classes=dict( + argstr="-n %d", + ), + other_priors=dict( + argstr="-A %s", + ), + out_basename=dict( + argstr="-o %s", + extensions=None, + ), + output_biascorrected=dict( + argstr="-B", + ), + output_biasfield=dict( + argstr="-b", + ), output_type=dict(), - probability_maps=dict(argstr="-p",), - segment_iters=dict(argstr="-W %d",), - segments=dict(argstr="-g",), - use_priors=dict(argstr="-P",), - verbose=dict(argstr="-v",), + probability_maps=dict( + argstr="-p", + ), + segment_iters=dict( + argstr="-W %d", + ), + segments=dict( + argstr="-g", + ), + use_priors=dict( + argstr="-P", + ), + verbose=dict( + argstr="-v", + ), ) inputs = FAST.input_spec() @@ -40,13 +96,19 @@ def test_FAST_inputs(): def test_FAST_outputs(): output_map = dict( bias_field=dict(), - mixeltype=dict(extensions=None,), + mixeltype=dict( + extensions=None, + ), partial_volume_files=dict(), - partial_volume_map=dict(extensions=None,), + partial_volume_map=dict( + extensions=None, + ), probability_maps=dict(), restored_image=dict(), tissue_class_files=dict(), - tissue_class_map=dict(extensions=None,), + tissue_class_map=dict( + extensions=None, + ), ) outputs = FAST.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FEAT.py b/nipype/interfaces/fsl/tests/test_auto_FEAT.py index f2d4e1a90d..b363dd290f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FEAT.py +++ b/nipype/interfaces/fsl/tests/test_auto_FEAT.py @@ -4,9 +4,19 @@ def test_FEAT_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fsf_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fsf_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), output_type=dict(), ) inputs = FEAT.input_spec() @@ -17,7 +27,9 @@ def test_FEAT_inputs(): def test_FEAT_outputs(): - output_map = dict(feat_dir=dict(),) + output_map = dict( + feat_dir=dict(), + ) outputs = FEAT.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FEATModel.py b/nipype/interfaces/fsl/tests/test_auto_FEATModel.py index 46e959a2a0..0e6c2f9e33 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FEATModel.py +++ b/nipype/interfaces/fsl/tests/test_auto_FEATModel.py @@ -4,11 +4,25 @@ def test_FEATModel_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - ev_files=dict(argstr="%s", copyfile=False, mandatory=True, position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ev_files=dict( + argstr="%s", + copyfile=False, + mandatory=True, + position=1, + ), fsf_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=0, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=0, ), output_type=dict(), ) @@ -21,11 +35,21 @@ def test_FEATModel_inputs(): def test_FEATModel_outputs(): output_map = dict( - con_file=dict(extensions=None,), - design_cov=dict(extensions=None,), - design_file=dict(extensions=None,), - design_image=dict(extensions=None,), - fcon_file=dict(extensions=None,), + con_file=dict( + extensions=None, + ), + design_cov=dict( + extensions=None, + ), + design_file=dict( + extensions=None, + ), + design_image=dict( + extensions=None, + ), + fcon_file=dict( + extensions=None, + ), ) outputs = FEATModel.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FEATRegister.py b/nipype/interfaces/fsl/tests/test_auto_FEATRegister.py index bd7ae5f7c3..fe09c468ec 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FEATRegister.py +++ b/nipype/interfaces/fsl/tests/test_auto_FEATRegister.py @@ -4,9 +4,16 @@ def test_FEATRegister_inputs(): input_map = dict( - feat_dirs=dict(mandatory=True,), - reg_dof=dict(usedefault=True,), - reg_image=dict(extensions=None, mandatory=True,), + feat_dirs=dict( + mandatory=True, + ), + reg_dof=dict( + usedefault=True, + ), + reg_image=dict( + extensions=None, + mandatory=True, + ), ) inputs = FEATRegister.input_spec() @@ -16,7 +23,11 @@ def test_FEATRegister_inputs(): def test_FEATRegister_outputs(): - output_map = dict(fsf_file=dict(extensions=None,),) + output_map = dict( + fsf_file=dict( + extensions=None, + ), + ) outputs = FEATRegister.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FIRST.py b/nipype/interfaces/fsl/tests/test_auto_FIRST.py index c34f1737d2..42ba79e799 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FIRST.py +++ b/nipype/interfaces/fsl/tests/test_auto_FIRST.py @@ -4,10 +4,22 @@ def test_FIRST_inputs(): input_map = dict( - affine_file=dict(argstr="-a %s", extensions=None, position=6,), - args=dict(argstr="%s",), - brain_extracted=dict(argstr="-b", position=2,), - environ=dict(nohash=True, usedefault=True,), + affine_file=dict( + argstr="-a %s", + extensions=None, + position=6, + ), + args=dict( + argstr="%s", + ), + brain_extracted=dict( + argstr="-b", + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( argstr="-i %s", copyfile=False, @@ -15,15 +27,25 @@ def test_FIRST_inputs(): mandatory=True, position=-2, ), - list_of_specific_structures=dict(argstr="-s %s", position=5, sep=",",), + list_of_specific_structures=dict( + argstr="-s %s", + position=5, + sep=",", + ), method=dict( argstr="-m %s", position=4, usedefault=True, xor=["method_as_numerical_threshold"], ), - method_as_numerical_threshold=dict(argstr="-m %.4f", position=4,), - no_cleanup=dict(argstr="-d", position=3,), + method_as_numerical_threshold=dict( + argstr="-m %.4f", + position=4, + ), + no_cleanup=dict( + argstr="-d", + position=3, + ), out_file=dict( argstr="-o %s", extensions=None, @@ -33,7 +55,10 @@ def test_FIRST_inputs(): usedefault=True, ), output_type=dict(), - verbose=dict(argstr="-v", position=1,), + verbose=dict( + argstr="-v", + position=1, + ), ) inputs = FIRST.input_spec() @@ -45,8 +70,12 @@ def test_FIRST_inputs(): def test_FIRST_outputs(): output_map = dict( bvars=dict(), - original_segmentations=dict(extensions=None,), - segmentation_file=dict(extensions=None,), + original_segmentations=dict( + extensions=None, + ), + segmentation_file=dict( + extensions=None, + ), vtk_surfaces=dict(), ) outputs = FIRST.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FLAMEO.py b/nipype/interfaces/fsl/tests/test_auto_FLAMEO.py index 13690485a5..f25b225d6e 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FLAMEO.py +++ b/nipype/interfaces/fsl/tests/test_auto_FLAMEO.py @@ -4,29 +4,83 @@ def test_FLAMEO_inputs(): input_map = dict( - args=dict(argstr="%s",), - burnin=dict(argstr="--burnin=%d",), - cope_file=dict(argstr="--copefile=%s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + burnin=dict( + argstr="--burnin=%d", + ), + cope_file=dict( + argstr="--copefile=%s", + extensions=None, + mandatory=True, + ), cov_split_file=dict( - argstr="--covsplitfile=%s", extensions=None, mandatory=True, - ), - design_file=dict(argstr="--designfile=%s", extensions=None, mandatory=True,), - dof_var_cope_file=dict(argstr="--dofvarcopefile=%s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - f_con_file=dict(argstr="--fcontrastsfile=%s", extensions=None,), - fix_mean=dict(argstr="--fixmean",), - infer_outliers=dict(argstr="--inferoutliers",), - log_dir=dict(argstr="--ld=%s", usedefault=True,), - mask_file=dict(argstr="--maskfile=%s", extensions=None, mandatory=True,), - n_jumps=dict(argstr="--njumps=%d",), - no_pe_outputs=dict(argstr="--nopeoutput",), - outlier_iter=dict(argstr="--ioni=%d",), + argstr="--covsplitfile=%s", + extensions=None, + mandatory=True, + ), + design_file=dict( + argstr="--designfile=%s", + extensions=None, + mandatory=True, + ), + dof_var_cope_file=dict( + argstr="--dofvarcopefile=%s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + f_con_file=dict( + argstr="--fcontrastsfile=%s", + extensions=None, + ), + fix_mean=dict( + argstr="--fixmean", + ), + infer_outliers=dict( + argstr="--inferoutliers", + ), + log_dir=dict( + argstr="--ld=%s", + usedefault=True, + ), + mask_file=dict( + argstr="--maskfile=%s", + extensions=None, + mandatory=True, + ), + n_jumps=dict( + argstr="--njumps=%d", + ), + no_pe_outputs=dict( + argstr="--nopeoutput", + ), + outlier_iter=dict( + argstr="--ioni=%d", + ), output_type=dict(), - run_mode=dict(argstr="--runmode=%s", mandatory=True,), - sample_every=dict(argstr="--sampleevery=%d",), - sigma_dofs=dict(argstr="--sigma_dofs=%d",), - t_con_file=dict(argstr="--tcontrastsfile=%s", extensions=None, mandatory=True,), - var_cope_file=dict(argstr="--varcopefile=%s", extensions=None,), + run_mode=dict( + argstr="--runmode=%s", + mandatory=True, + ), + sample_every=dict( + argstr="--sampleevery=%d", + ), + sigma_dofs=dict( + argstr="--sigma_dofs=%d", + ), + t_con_file=dict( + argstr="--tcontrastsfile=%s", + extensions=None, + mandatory=True, + ), + var_cope_file=dict( + argstr="--varcopefile=%s", + extensions=None, + ), ) inputs = FLAMEO.input_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FLIRT.py b/nipype/interfaces/fsl/tests/test_auto_FLIRT.py index ce2fca2486..a9bdc38477 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FLIRT.py +++ b/nipype/interfaces/fsl/tests/test_auto_FLIRT.py @@ -4,35 +4,110 @@ def test_FLIRT_inputs(): input_map = dict( - angle_rep=dict(argstr="-anglerep %s",), - apply_isoxfm=dict(argstr="-applyisoxfm %f", xor=["apply_xfm"],), - apply_xfm=dict(argstr="-applyxfm",), - args=dict(argstr="%s",), - bbrslope=dict(argstr="-bbrslope %f", min_ver="5.0.0",), - bbrtype=dict(argstr="-bbrtype %s", min_ver="5.0.0",), - bgvalue=dict(argstr="-setbackground %f",), - bins=dict(argstr="-bins %d",), - coarse_search=dict(argstr="-coarsesearch %d", units="degrees",), - cost=dict(argstr="-cost %s",), - cost_func=dict(argstr="-searchcost %s",), - datatype=dict(argstr="-datatype %s",), - display_init=dict(argstr="-displayinit",), - dof=dict(argstr="-dof %d",), - echospacing=dict(argstr="-echospacing %f", min_ver="5.0.0",), - environ=dict(nohash=True, usedefault=True,), - fieldmap=dict(argstr="-fieldmap %s", extensions=None, min_ver="5.0.0",), - fieldmapmask=dict(argstr="-fieldmapmask %s", extensions=None, min_ver="5.0.0",), - fine_search=dict(argstr="-finesearch %d", units="degrees",), - force_scaling=dict(argstr="-forcescaling",), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True, position=0,), - in_matrix_file=dict(argstr="-init %s", extensions=None,), - in_weight=dict(argstr="-inweight %s", extensions=None,), - interp=dict(argstr="-interp %s",), - min_sampling=dict(argstr="-minsampling %f", units="mm",), - no_clamp=dict(argstr="-noclamp",), - no_resample=dict(argstr="-noresample",), - no_resample_blur=dict(argstr="-noresampblur",), - no_search=dict(argstr="-nosearch",), + angle_rep=dict( + argstr="-anglerep %s", + ), + apply_isoxfm=dict( + argstr="-applyisoxfm %f", + xor=["apply_xfm"], + ), + apply_xfm=dict( + argstr="-applyxfm", + ), + args=dict( + argstr="%s", + ), + bbrslope=dict( + argstr="-bbrslope %f", + min_ver="5.0.0", + ), + bbrtype=dict( + argstr="-bbrtype %s", + min_ver="5.0.0", + ), + bgvalue=dict( + argstr="-setbackground %f", + ), + bins=dict( + argstr="-bins %d", + ), + coarse_search=dict( + argstr="-coarsesearch %d", + units="degrees", + ), + cost=dict( + argstr="-cost %s", + ), + cost_func=dict( + argstr="-searchcost %s", + ), + datatype=dict( + argstr="-datatype %s", + ), + display_init=dict( + argstr="-displayinit", + ), + dof=dict( + argstr="-dof %d", + ), + echospacing=dict( + argstr="-echospacing %f", + min_ver="5.0.0", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fieldmap=dict( + argstr="-fieldmap %s", + extensions=None, + min_ver="5.0.0", + ), + fieldmapmask=dict( + argstr="-fieldmapmask %s", + extensions=None, + min_ver="5.0.0", + ), + fine_search=dict( + argstr="-finesearch %d", + units="degrees", + ), + force_scaling=dict( + argstr="-forcescaling", + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + position=0, + ), + in_matrix_file=dict( + argstr="-init %s", + extensions=None, + ), + in_weight=dict( + argstr="-inweight %s", + extensions=None, + ), + interp=dict( + argstr="-interp %s", + ), + min_sampling=dict( + argstr="-minsampling %f", + units="mm", + ), + no_clamp=dict( + argstr="-noclamp", + ), + no_resample=dict( + argstr="-noresample", + ), + no_resample_blur=dict( + argstr="-noresampblur", + ), + no_search=dict( + argstr="-nosearch", + ), out_file=dict( argstr="-out %s", extensions=None, @@ -58,23 +133,72 @@ def test_FLIRT_inputs(): position=3, ), output_type=dict(), - padding_size=dict(argstr="-paddingsize %d", units="voxels",), - pedir=dict(argstr="-pedir %d", min_ver="5.0.0",), - ref_weight=dict(argstr="-refweight %s", extensions=None,), - reference=dict(argstr="-ref %s", extensions=None, mandatory=True, position=1,), - rigid2D=dict(argstr="-2D",), + padding_size=dict( + argstr="-paddingsize %d", + units="voxels", + ), + pedir=dict( + argstr="-pedir %d", + min_ver="5.0.0", + ), + ref_weight=dict( + argstr="-refweight %s", + extensions=None, + ), + reference=dict( + argstr="-ref %s", + extensions=None, + mandatory=True, + position=1, + ), + rigid2D=dict( + argstr="-2D", + ), save_log=dict(), - schedule=dict(argstr="-schedule %s", extensions=None,), - searchr_x=dict(argstr="-searchrx %s", units="degrees",), - searchr_y=dict(argstr="-searchry %s", units="degrees",), - searchr_z=dict(argstr="-searchrz %s", units="degrees",), - sinc_width=dict(argstr="-sincwidth %d", units="voxels",), - sinc_window=dict(argstr="-sincwindow %s",), - uses_qform=dict(argstr="-usesqform",), - verbose=dict(argstr="-verbose %d",), - wm_seg=dict(argstr="-wmseg %s", extensions=None, min_ver="5.0.0",), - wmcoords=dict(argstr="-wmcoords %s", extensions=None, min_ver="5.0.0",), - wmnorms=dict(argstr="-wmnorms %s", extensions=None, min_ver="5.0.0",), + schedule=dict( + argstr="-schedule %s", + extensions=None, + ), + searchr_x=dict( + argstr="-searchrx %s", + units="degrees", + ), + searchr_y=dict( + argstr="-searchry %s", + units="degrees", + ), + searchr_z=dict( + argstr="-searchrz %s", + units="degrees", + ), + sinc_width=dict( + argstr="-sincwidth %d", + units="voxels", + ), + sinc_window=dict( + argstr="-sincwindow %s", + ), + uses_qform=dict( + argstr="-usesqform", + ), + verbose=dict( + argstr="-verbose %d", + ), + wm_seg=dict( + argstr="-wmseg %s", + extensions=None, + min_ver="5.0.0", + ), + wmcoords=dict( + argstr="-wmcoords %s", + extensions=None, + min_ver="5.0.0", + ), + wmnorms=dict( + argstr="-wmnorms %s", + extensions=None, + min_ver="5.0.0", + ), ) inputs = FLIRT.input_spec() @@ -85,9 +209,15 @@ def test_FLIRT_inputs(): def test_FLIRT_outputs(): output_map = dict( - out_file=dict(extensions=None,), - out_log=dict(extensions=None,), - out_matrix_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_log=dict( + extensions=None, + ), + out_matrix_file=dict( + extensions=None, + ), ) outputs = FLIRT.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FNIRT.py b/nipype/interfaces/fsl/tests/test_auto_FNIRT.py index 794ae7d5f0..eb6ae1f714 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FNIRT.py +++ b/nipype/interfaces/fsl/tests/test_auto_FNIRT.py @@ -4,57 +4,169 @@ def test_FNIRT_inputs(): input_map = dict( - affine_file=dict(argstr="--aff=%s", extensions=None,), - apply_inmask=dict(argstr="--applyinmask=%s", sep=",", xor=["skip_inmask"],), + affine_file=dict( + argstr="--aff=%s", + extensions=None, + ), + apply_inmask=dict( + argstr="--applyinmask=%s", + sep=",", + xor=["skip_inmask"], + ), apply_intensity_mapping=dict( - argstr="--estint=%s", sep=",", xor=["skip_intensity_mapping"], - ), - apply_refmask=dict(argstr="--applyrefmask=%s", sep=",", xor=["skip_refmask"],), - args=dict(argstr="%s",), - bias_regularization_lambda=dict(argstr="--biaslambda=%f",), - biasfield_resolution=dict(argstr="--biasres=%d,%d,%d",), - config_file=dict(argstr="--config=%s",), - derive_from_ref=dict(argstr="--refderiv",), - environ=dict(nohash=True, usedefault=True,), - field_file=dict(argstr="--fout=%s", hash_files=False,), - fieldcoeff_file=dict(argstr="--cout=%s",), - hessian_precision=dict(argstr="--numprec=%s",), - in_file=dict(argstr="--in=%s", extensions=None, mandatory=True,), - in_fwhm=dict(argstr="--infwhm=%s", sep=",",), - in_intensitymap_file=dict(argstr="--intin=%s", copyfile=False,), - inmask_file=dict(argstr="--inmask=%s", extensions=None,), - inmask_val=dict(argstr="--impinval=%f",), - intensity_mapping_model=dict(argstr="--intmod=%s",), - intensity_mapping_order=dict(argstr="--intorder=%d",), - inwarp_file=dict(argstr="--inwarp=%s", extensions=None,), - jacobian_file=dict(argstr="--jout=%s", hash_files=False,), - jacobian_range=dict(argstr="--jacrange=%f,%f",), + argstr="--estint=%s", + sep=",", + xor=["skip_intensity_mapping"], + ), + apply_refmask=dict( + argstr="--applyrefmask=%s", + sep=",", + xor=["skip_refmask"], + ), + args=dict( + argstr="%s", + ), + bias_regularization_lambda=dict( + argstr="--biaslambda=%f", + ), + biasfield_resolution=dict( + argstr="--biasres=%d,%d,%d", + ), + config_file=dict( + argstr="--config=%s", + ), + derive_from_ref=dict( + argstr="--refderiv", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + field_file=dict( + argstr="--fout=%s", + hash_files=False, + ), + fieldcoeff_file=dict( + argstr="--cout=%s", + ), + hessian_precision=dict( + argstr="--numprec=%s", + ), + in_file=dict( + argstr="--in=%s", + extensions=None, + mandatory=True, + ), + in_fwhm=dict( + argstr="--infwhm=%s", + sep=",", + ), + in_intensitymap_file=dict( + argstr="--intin=%s", + copyfile=False, + ), + inmask_file=dict( + argstr="--inmask=%s", + extensions=None, + ), + inmask_val=dict( + argstr="--impinval=%f", + ), + intensity_mapping_model=dict( + argstr="--intmod=%s", + ), + intensity_mapping_order=dict( + argstr="--intorder=%d", + ), + inwarp_file=dict( + argstr="--inwarp=%s", + extensions=None, + ), + jacobian_file=dict( + argstr="--jout=%s", + hash_files=False, + ), + jacobian_range=dict( + argstr="--jacrange=%f,%f", + ), log_file=dict( - argstr="--logout=%s", extensions=None, genfile=True, hash_files=False, + argstr="--logout=%s", + extensions=None, + genfile=True, + hash_files=False, + ), + max_nonlin_iter=dict( + argstr="--miter=%s", + sep=",", + ), + modulatedref_file=dict( + argstr="--refout=%s", + hash_files=False, + ), + out_intensitymap_file=dict( + argstr="--intout=%s", + hash_files=False, ), - max_nonlin_iter=dict(argstr="--miter=%s", sep=",",), - modulatedref_file=dict(argstr="--refout=%s", hash_files=False,), - out_intensitymap_file=dict(argstr="--intout=%s", hash_files=False,), output_type=dict(), - ref_file=dict(argstr="--ref=%s", extensions=None, mandatory=True,), - ref_fwhm=dict(argstr="--reffwhm=%s", sep=",",), - refmask_file=dict(argstr="--refmask=%s", extensions=None,), - refmask_val=dict(argstr="--imprefval=%f",), - regularization_lambda=dict(argstr="--lambda=%s", sep=",",), - regularization_model=dict(argstr="--regmod=%s",), - skip_implicit_in_masking=dict(argstr="--impinm=0",), - skip_implicit_ref_masking=dict(argstr="--imprefm=0",), - skip_inmask=dict(argstr="--applyinmask=0", xor=["apply_inmask"],), + ref_file=dict( + argstr="--ref=%s", + extensions=None, + mandatory=True, + ), + ref_fwhm=dict( + argstr="--reffwhm=%s", + sep=",", + ), + refmask_file=dict( + argstr="--refmask=%s", + extensions=None, + ), + refmask_val=dict( + argstr="--imprefval=%f", + ), + regularization_lambda=dict( + argstr="--lambda=%s", + sep=",", + ), + regularization_model=dict( + argstr="--regmod=%s", + ), + skip_implicit_in_masking=dict( + argstr="--impinm=0", + ), + skip_implicit_ref_masking=dict( + argstr="--imprefm=0", + ), + skip_inmask=dict( + argstr="--applyinmask=0", + xor=["apply_inmask"], + ), skip_intensity_mapping=dict( - argstr="--estint=0", xor=["apply_intensity_mapping"], + argstr="--estint=0", + xor=["apply_intensity_mapping"], + ), + skip_lambda_ssq=dict( + argstr="--ssqlambda=0", + ), + skip_refmask=dict( + argstr="--applyrefmask=0", + xor=["apply_refmask"], + ), + spline_order=dict( + argstr="--splineorder=%d", + ), + subsampling_scheme=dict( + argstr="--subsamp=%s", + sep=",", + ), + warp_resolution=dict( + argstr="--warpres=%d,%d,%d", ), - skip_lambda_ssq=dict(argstr="--ssqlambda=0",), - skip_refmask=dict(argstr="--applyrefmask=0", xor=["apply_refmask"],), - spline_order=dict(argstr="--splineorder=%d",), - subsampling_scheme=dict(argstr="--subsamp=%s", sep=",",), - warp_resolution=dict(argstr="--warpres=%d,%d,%d",), warped_file=dict( - argstr="--iout=%s", extensions=None, genfile=True, hash_files=False, + argstr="--iout=%s", + extensions=None, + genfile=True, + hash_files=False, ), ) inputs = FNIRT.input_spec() @@ -66,13 +178,25 @@ def test_FNIRT_inputs(): def test_FNIRT_outputs(): output_map = dict( - field_file=dict(extensions=None,), - fieldcoeff_file=dict(extensions=None,), - jacobian_file=dict(extensions=None,), - log_file=dict(extensions=None,), - modulatedref_file=dict(extensions=None,), + field_file=dict( + extensions=None, + ), + fieldcoeff_file=dict( + extensions=None, + ), + jacobian_file=dict( + extensions=None, + ), + log_file=dict( + extensions=None, + ), + modulatedref_file=dict( + extensions=None, + ), out_intensitymap_file=dict(), - warped_file=dict(extensions=None,), + warped_file=dict( + extensions=None, + ), ) outputs = FNIRT.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FSLCommand.py b/nipype/interfaces/fsl/tests/test_auto_FSLCommand.py index bc4c0443ee..1b444c381e 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FSLCommand.py +++ b/nipype/interfaces/fsl/tests/test_auto_FSLCommand.py @@ -4,8 +4,13 @@ def test_FSLCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), output_type=dict(), ) inputs = FSLCommand.input_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FSLXCommand.py b/nipype/interfaces/fsl/tests/test_auto_FSLXCommand.py index d9c30cd262..3948f3d650 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FSLXCommand.py +++ b/nipype/interfaces/fsl/tests/test_auto_FSLXCommand.py @@ -4,36 +4,107 @@ def test_FSLXCommand_inputs(): input_map = dict( - all_ard=dict(argstr="--allard", xor=("no_ard", "all_ard"),), - args=dict(argstr="%s",), - burn_in=dict(argstr="--burnin=%d", usedefault=True,), - burn_in_no_ard=dict(argstr="--burnin_noard=%d", usedefault=True,), - bvals=dict(argstr="--bvals=%s", extensions=None, mandatory=True,), - bvecs=dict(argstr="--bvecs=%s", extensions=None, mandatory=True,), + all_ard=dict( + argstr="--allard", + xor=("no_ard", "all_ard"), + ), + args=dict( + argstr="%s", + ), + burn_in=dict( + argstr="--burnin=%d", + usedefault=True, + ), + burn_in_no_ard=dict( + argstr="--burnin_noard=%d", + usedefault=True, + ), + bvals=dict( + argstr="--bvals=%s", + extensions=None, + mandatory=True, + ), + bvecs=dict( + argstr="--bvecs=%s", + extensions=None, + mandatory=True, + ), cnlinear=dict( - argstr="--cnonlinear", xor=("no_spat", "non_linear", "cnlinear"), - ), - dwi=dict(argstr="--data=%s", extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - f0_ard=dict(argstr="--f0 --ardf0", xor=["f0_noard", "f0_ard", "all_ard"],), - f0_noard=dict(argstr="--f0", xor=["f0_noard", "f0_ard"],), - force_dir=dict(argstr="--forcedir", usedefault=True,), - fudge=dict(argstr="--fudge=%d",), - logdir=dict(argstr="--logdir=%s", usedefault=True,), - mask=dict(argstr="--mask=%s", extensions=None, mandatory=True,), - model=dict(argstr="--model=%d",), - n_fibres=dict(argstr="--nfibres=%d", mandatory=True, usedefault=True,), - n_jumps=dict(argstr="--njumps=%d", usedefault=True,), - no_ard=dict(argstr="--noard", xor=("no_ard", "all_ard"),), - no_spat=dict(argstr="--nospat", xor=("no_spat", "non_linear", "cnlinear"),), + argstr="--cnonlinear", + xor=("no_spat", "non_linear", "cnlinear"), + ), + dwi=dict( + argstr="--data=%s", + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + f0_ard=dict( + argstr="--f0 --ardf0", + xor=["f0_noard", "f0_ard", "all_ard"], + ), + f0_noard=dict( + argstr="--f0", + xor=["f0_noard", "f0_ard"], + ), + force_dir=dict( + argstr="--forcedir", + usedefault=True, + ), + fudge=dict( + argstr="--fudge=%d", + ), + logdir=dict( + argstr="--logdir=%s", + usedefault=True, + ), + mask=dict( + argstr="--mask=%s", + extensions=None, + mandatory=True, + ), + model=dict( + argstr="--model=%d", + ), + n_fibres=dict( + argstr="--nfibres=%d", + mandatory=True, + usedefault=True, + ), + n_jumps=dict( + argstr="--njumps=%d", + usedefault=True, + ), + no_ard=dict( + argstr="--noard", + xor=("no_ard", "all_ard"), + ), + no_spat=dict( + argstr="--nospat", + xor=("no_spat", "non_linear", "cnlinear"), + ), non_linear=dict( - argstr="--nonlinear", xor=("no_spat", "non_linear", "cnlinear"), + argstr="--nonlinear", + xor=("no_spat", "non_linear", "cnlinear"), ), output_type=dict(), - rician=dict(argstr="--rician",), - sample_every=dict(argstr="--sampleevery=%d", usedefault=True,), - seed=dict(argstr="--seed=%d",), - update_proposal_every=dict(argstr="--updateproposalevery=%d", usedefault=True,), + rician=dict( + argstr="--rician", + ), + sample_every=dict( + argstr="--sampleevery=%d", + usedefault=True, + ), + seed=dict( + argstr="--seed=%d", + ), + update_proposal_every=dict( + argstr="--updateproposalevery=%d", + usedefault=True, + ), ) inputs = FSLXCommand.input_spec() @@ -46,10 +117,16 @@ def test_FSLXCommand_outputs(): output_map = dict( dyads=dict(), fsamples=dict(), - mean_S0samples=dict(extensions=None,), - mean_dsamples=dict(extensions=None,), + mean_S0samples=dict( + extensions=None, + ), + mean_dsamples=dict( + extensions=None, + ), mean_fsamples=dict(), - mean_tausamples=dict(extensions=None,), + mean_tausamples=dict( + extensions=None, + ), phsamples=dict(), thsamples=dict(), ) diff --git a/nipype/interfaces/fsl/tests/test_auto_FUGUE.py b/nipype/interfaces/fsl/tests/test_auto_FUGUE.py index a1f6873658..841bb2021f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FUGUE.py +++ b/nipype/interfaces/fsl/tests/test_auto_FUGUE.py @@ -4,39 +4,115 @@ def test_FUGUE_inputs(): input_map = dict( - args=dict(argstr="%s",), - asym_se_time=dict(argstr="--asym=%.10f",), - despike_2dfilter=dict(argstr="--despike",), - despike_threshold=dict(argstr="--despikethreshold=%s",), - dwell_time=dict(argstr="--dwell=%.10f",), - dwell_to_asym_ratio=dict(argstr="--dwelltoasym=%.10f",), - environ=dict(nohash=True, usedefault=True,), - fmap_in_file=dict(argstr="--loadfmap=%s", extensions=None,), - fmap_out_file=dict(argstr="--savefmap=%s", extensions=None,), - forward_warping=dict(usedefault=True,), - fourier_order=dict(argstr="--fourier=%d",), - icorr=dict(argstr="--icorr", requires=["shift_in_file"],), - icorr_only=dict(argstr="--icorronly", requires=["unwarped_file"],), - in_file=dict(argstr="--in=%s", extensions=None,), - mask_file=dict(argstr="--mask=%s", extensions=None,), - median_2dfilter=dict(argstr="--median",), - no_extend=dict(argstr="--noextend",), - no_gap_fill=dict(argstr="--nofill",), - nokspace=dict(argstr="--nokspace",), + args=dict( + argstr="%s", + ), + asym_se_time=dict( + argstr="--asym=%.10f", + ), + despike_2dfilter=dict( + argstr="--despike", + ), + despike_threshold=dict( + argstr="--despikethreshold=%s", + ), + dwell_time=dict( + argstr="--dwell=%.10f", + ), + dwell_to_asym_ratio=dict( + argstr="--dwelltoasym=%.10f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fmap_in_file=dict( + argstr="--loadfmap=%s", + extensions=None, + ), + fmap_out_file=dict( + argstr="--savefmap=%s", + extensions=None, + ), + forward_warping=dict( + usedefault=True, + ), + fourier_order=dict( + argstr="--fourier=%d", + ), + icorr=dict( + argstr="--icorr", + requires=["shift_in_file"], + ), + icorr_only=dict( + argstr="--icorronly", + requires=["unwarped_file"], + ), + in_file=dict( + argstr="--in=%s", + extensions=None, + ), + mask_file=dict( + argstr="--mask=%s", + extensions=None, + ), + median_2dfilter=dict( + argstr="--median", + ), + no_extend=dict( + argstr="--noextend", + ), + no_gap_fill=dict( + argstr="--nofill", + ), + nokspace=dict( + argstr="--nokspace", + ), output_type=dict(), - pava=dict(argstr="--pava",), - phase_conjugate=dict(argstr="--phaseconj",), - phasemap_in_file=dict(argstr="--phasemap=%s", extensions=None,), - poly_order=dict(argstr="--poly=%d",), - save_fmap=dict(xor=["save_unmasked_fmap"],), - save_shift=dict(xor=["save_unmasked_shift"],), - save_unmasked_fmap=dict(argstr="--unmaskfmap", xor=["save_fmap"],), - save_unmasked_shift=dict(argstr="--unmaskshift", xor=["save_shift"],), - shift_in_file=dict(argstr="--loadshift=%s", extensions=None,), - shift_out_file=dict(argstr="--saveshift=%s", extensions=None,), - smooth2d=dict(argstr="--smooth2=%.2f",), - smooth3d=dict(argstr="--smooth3=%.2f",), - unwarp_direction=dict(argstr="--unwarpdir=%s",), + pava=dict( + argstr="--pava", + ), + phase_conjugate=dict( + argstr="--phaseconj", + ), + phasemap_in_file=dict( + argstr="--phasemap=%s", + extensions=None, + ), + poly_order=dict( + argstr="--poly=%d", + ), + save_fmap=dict( + xor=["save_unmasked_fmap"], + ), + save_shift=dict( + xor=["save_unmasked_shift"], + ), + save_unmasked_fmap=dict( + argstr="--unmaskfmap", + xor=["save_fmap"], + ), + save_unmasked_shift=dict( + argstr="--unmaskshift", + xor=["save_shift"], + ), + shift_in_file=dict( + argstr="--loadshift=%s", + extensions=None, + ), + shift_out_file=dict( + argstr="--saveshift=%s", + extensions=None, + ), + smooth2d=dict( + argstr="--smooth2=%.2f", + ), + smooth3d=dict( + argstr="--smooth3=%.2f", + ), + unwarp_direction=dict( + argstr="--unwarpdir=%s", + ), unwarped_file=dict( argstr="--unwarp=%s", extensions=None, @@ -59,10 +135,18 @@ def test_FUGUE_inputs(): def test_FUGUE_outputs(): output_map = dict( - fmap_out_file=dict(extensions=None,), - shift_out_file=dict(extensions=None,), - unwarped_file=dict(extensions=None,), - warped_file=dict(extensions=None,), + fmap_out_file=dict( + extensions=None, + ), + shift_out_file=dict( + extensions=None, + ), + unwarped_file=dict( + extensions=None, + ), + warped_file=dict( + extensions=None, + ), ) outputs = FUGUE.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_FeatureExtractor.py b/nipype/interfaces/fsl/tests/test_auto_FeatureExtractor.py index 03d627a0bf..8531fe17c4 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FeatureExtractor.py +++ b/nipype/interfaces/fsl/tests/test_auto_FeatureExtractor.py @@ -4,9 +4,18 @@ def test_FeatureExtractor_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - mel_ica=dict(argstr="%s", copyfile=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + mel_ica=dict( + argstr="%s", + copyfile=False, + position=-1, + ), ) inputs = FeatureExtractor.input_spec() @@ -16,7 +25,13 @@ def test_FeatureExtractor_inputs(): def test_FeatureExtractor_outputs(): - output_map = dict(mel_ica=dict(argstr="%s", copyfile=False, position=-1,),) + output_map = dict( + mel_ica=dict( + argstr="%s", + copyfile=False, + position=-1, + ), + ) outputs = FeatureExtractor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FilterRegressor.py b/nipype/interfaces/fsl/tests/test_auto_FilterRegressor.py index d63a61ea1c..e4826db355 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FilterRegressor.py +++ b/nipype/interfaces/fsl/tests/test_auto_FilterRegressor.py @@ -4,23 +4,55 @@ def test_FilterRegressor_inputs(): input_map = dict( - args=dict(argstr="%s",), - design_file=dict(argstr="-d %s", extensions=None, mandatory=True, position=3,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + design_file=dict( + argstr="-d %s", + extensions=None, + mandatory=True, + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), filter_all=dict( - argstr="-f '%s'", mandatory=True, position=4, xor=["filter_columns"], + argstr="-f '%s'", + mandatory=True, + position=4, + xor=["filter_columns"], ), filter_columns=dict( - argstr="-f '%s'", mandatory=True, position=4, xor=["filter_all"], + argstr="-f '%s'", + mandatory=True, + position=4, + xor=["filter_all"], + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=1, + ), + mask=dict( + argstr="-m %s", + extensions=None, ), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=1,), - mask=dict(argstr="-m %s", extensions=None,), out_file=dict( - argstr="-o %s", extensions=None, genfile=True, hash_files=False, position=2, + argstr="-o %s", + extensions=None, + genfile=True, + hash_files=False, + position=2, + ), + out_vnscales=dict( + argstr="--out_vnscales", ), - out_vnscales=dict(argstr="--out_vnscales",), output_type=dict(), - var_norm=dict(argstr="--vn",), + var_norm=dict( + argstr="--vn", + ), ) inputs = FilterRegressor.input_spec() @@ -30,7 +62,11 @@ def test_FilterRegressor_inputs(): def test_FilterRegressor_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = FilterRegressor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_FindTheBiggest.py b/nipype/interfaces/fsl/tests/test_auto_FindTheBiggest.py index 0152e34ed0..14b3bbb8da 100644 --- a/nipype/interfaces/fsl/tests/test_auto_FindTheBiggest.py +++ b/nipype/interfaces/fsl/tests/test_auto_FindTheBiggest.py @@ -4,11 +4,24 @@ def test_FindTheBiggest_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="%s", mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=0, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=2, ), output_type=dict(), ) @@ -20,7 +33,12 @@ def test_FindTheBiggest_inputs(): def test_FindTheBiggest_outputs(): - output_map = dict(out_file=dict(argstr="%s", extensions=None,),) + output_map = dict( + out_file=dict( + argstr="%s", + extensions=None, + ), + ) outputs = FindTheBiggest.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_GLM.py b/nipype/interfaces/fsl/tests/test_auto_GLM.py index 61a550884d..63105f128d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_GLM.py +++ b/nipype/interfaces/fsl/tests/test_auto_GLM.py @@ -4,19 +4,57 @@ def test_GLM_inputs(): input_map = dict( - args=dict(argstr="%s",), - contrasts=dict(argstr="-c %s", extensions=None,), - dat_norm=dict(argstr="--dat_norm",), - demean=dict(argstr="--demean",), - des_norm=dict(argstr="--des_norm",), - design=dict(argstr="-d %s", extensions=None, mandatory=True, position=2,), - dof=dict(argstr="--dof=%d",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=1,), - mask=dict(argstr="-m %s", extensions=None,), - out_cope=dict(argstr="--out_cope=%s", extensions=None,), - out_data_name=dict(argstr="--out_data=%s", extensions=None,), - out_f_name=dict(argstr="--out_f=%s", extensions=None,), + args=dict( + argstr="%s", + ), + contrasts=dict( + argstr="-c %s", + extensions=None, + ), + dat_norm=dict( + argstr="--dat_norm", + ), + demean=dict( + argstr="--demean", + ), + des_norm=dict( + argstr="--des_norm", + ), + design=dict( + argstr="-d %s", + extensions=None, + mandatory=True, + position=2, + ), + dof=dict( + argstr="--dof=%d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=1, + ), + mask=dict( + argstr="-m %s", + extensions=None, + ), + out_cope=dict( + argstr="--out_cope=%s", + extensions=None, + ), + out_data_name=dict( + argstr="--out_data=%s", + extensions=None, + ), + out_f_name=dict( + argstr="--out_f=%s", + extensions=None, + ), out_file=dict( argstr="-o %s", extensions=None, @@ -25,16 +63,42 @@ def test_GLM_inputs(): name_template="%s_glm", position=3, ), - out_p_name=dict(argstr="--out_p=%s", extensions=None,), - out_pf_name=dict(argstr="--out_pf=%s", extensions=None,), - out_res_name=dict(argstr="--out_res=%s", extensions=None,), - out_sigsq_name=dict(argstr="--out_sigsq=%s", extensions=None,), - out_t_name=dict(argstr="--out_t=%s", extensions=None,), - out_varcb_name=dict(argstr="--out_varcb=%s", extensions=None,), - out_vnscales_name=dict(argstr="--out_vnscales=%s", extensions=None,), - out_z_name=dict(argstr="--out_z=%s", extensions=None,), + out_p_name=dict( + argstr="--out_p=%s", + extensions=None, + ), + out_pf_name=dict( + argstr="--out_pf=%s", + extensions=None, + ), + out_res_name=dict( + argstr="--out_res=%s", + extensions=None, + ), + out_sigsq_name=dict( + argstr="--out_sigsq=%s", + extensions=None, + ), + out_t_name=dict( + argstr="--out_t=%s", + extensions=None, + ), + out_varcb_name=dict( + argstr="--out_varcb=%s", + extensions=None, + ), + out_vnscales_name=dict( + argstr="--out_vnscales=%s", + extensions=None, + ), + out_z_name=dict( + argstr="--out_z=%s", + extensions=None, + ), output_type=dict(), - var_norm=dict(argstr="--vn",), + var_norm=dict( + argstr="--vn", + ), ) inputs = GLM.input_spec() @@ -48,7 +112,9 @@ def test_GLM_outputs(): out_cope=dict(), out_data=dict(), out_f=dict(), - out_file=dict(extensions=None,), + out_file=dict( + extensions=None, + ), out_p=dict(), out_pf=dict(), out_res=dict(), diff --git a/nipype/interfaces/fsl/tests/test_auto_ICA_AROMA.py b/nipype/interfaces/fsl/tests/test_auto_ICA_AROMA.py index 51975c5bef..b49813e24d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ICA_AROMA.py +++ b/nipype/interfaces/fsl/tests/test_auto_ICA_AROMA.py @@ -4,27 +4,64 @@ def test_ICA_AROMA_inputs(): input_map = dict( - TR=dict(argstr="-tr %.3f",), - args=dict(argstr="%s",), - denoise_type=dict(argstr="-den %s", mandatory=True, usedefault=True,), - dim=dict(argstr="-dim %d",), - environ=dict(nohash=True, usedefault=True,), + TR=dict( + argstr="-tr %.3f", + ), + args=dict( + argstr="%s", + ), + denoise_type=dict( + argstr="-den %s", + mandatory=True, + usedefault=True, + ), + dim=dict( + argstr="-dim %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), feat_dir=dict( argstr="-feat %s", mandatory=True, xor=["in_file", "mat_file", "fnirt_warp_file", "motion_parameters"], ), - fnirt_warp_file=dict(argstr="-warp %s", extensions=None, xor=["feat_dir"],), + fnirt_warp_file=dict( + argstr="-warp %s", + extensions=None, + xor=["feat_dir"], + ), in_file=dict( - argstr="-i %s", extensions=None, mandatory=True, xor=["feat_dir"], + argstr="-i %s", + extensions=None, + mandatory=True, + xor=["feat_dir"], + ), + mask=dict( + argstr="-m %s", + extensions=None, + xor=["feat_dir"], + ), + mat_file=dict( + argstr="-affmat %s", + extensions=None, + xor=["feat_dir"], + ), + melodic_dir=dict( + argstr="-meldir %s", ), - mask=dict(argstr="-m %s", extensions=None, xor=["feat_dir"],), - mat_file=dict(argstr="-affmat %s", extensions=None, xor=["feat_dir"],), - melodic_dir=dict(argstr="-meldir %s",), motion_parameters=dict( - argstr="-mc %s", extensions=None, mandatory=True, xor=["feat_dir"], + argstr="-mc %s", + extensions=None, + mandatory=True, + xor=["feat_dir"], + ), + out_dir=dict( + argstr="-o %s", + mandatory=True, + usedefault=True, ), - out_dir=dict(argstr="-o %s", mandatory=True, usedefault=True,), ) inputs = ICA_AROMA.input_spec() @@ -35,8 +72,12 @@ def test_ICA_AROMA_inputs(): def test_ICA_AROMA_outputs(): output_map = dict( - aggr_denoised_file=dict(extensions=None,), - nonaggr_denoised_file=dict(extensions=None,), + aggr_denoised_file=dict( + extensions=None, + ), + nonaggr_denoised_file=dict( + extensions=None, + ), out_dir=dict(), ) outputs = ICA_AROMA.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ImageMaths.py b/nipype/interfaces/fsl/tests/test_auto_ImageMaths.py index 02a73d2662..d2c4737d65 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ImageMaths.py +++ b/nipype/interfaces/fsl/tests/test_auto_ImageMaths.py @@ -4,15 +4,42 @@ def test_ImageMaths_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - in_file2=dict(argstr="%s", extensions=None, position=3,), - mask_file=dict(argstr="-mas %s", extensions=None,), - op_string=dict(argstr="%s", position=2,), - out_data_type=dict(argstr="-odt %s", position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + in_file2=dict( + argstr="%s", + extensions=None, + position=3, + ), + mask_file=dict( + argstr="-mas %s", + extensions=None, + ), + op_string=dict( + argstr="%s", + position=2, + ), + out_data_type=dict( + argstr="-odt %s", + position=-1, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, ), output_type=dict(), suffix=dict(), @@ -25,7 +52,11 @@ def test_ImageMaths_inputs(): def test_ImageMaths_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ImageMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ImageMeants.py b/nipype/interfaces/fsl/tests/test_auto_ImageMeants.py index 2d53d25c1f..b050d8f50b 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ImageMeants.py +++ b/nipype/interfaces/fsl/tests/test_auto_ImageMeants.py @@ -4,19 +4,52 @@ def test_ImageMeants_inputs(): input_map = dict( - args=dict(argstr="%s",), - eig=dict(argstr="--eig",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=0,), - mask=dict(argstr="-m %s", extensions=None,), - nobin=dict(argstr="--no_bin",), - order=dict(argstr="--order=%d", usedefault=True,), - out_file=dict(argstr="-o %s", extensions=None, genfile=True, hash_files=False,), + args=dict( + argstr="%s", + ), + eig=dict( + argstr="--eig", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=0, + ), + mask=dict( + argstr="-m %s", + extensions=None, + ), + nobin=dict( + argstr="--no_bin", + ), + order=dict( + argstr="--order=%d", + usedefault=True, + ), + out_file=dict( + argstr="-o %s", + extensions=None, + genfile=True, + hash_files=False, + ), output_type=dict(), - show_all=dict(argstr="--showall",), - spatial_coord=dict(argstr="-c %s",), - transpose=dict(argstr="--transpose",), - use_mm=dict(argstr="--usemm",), + show_all=dict( + argstr="--showall", + ), + spatial_coord=dict( + argstr="-c %s", + ), + transpose=dict( + argstr="--transpose", + ), + use_mm=dict( + argstr="--usemm", + ), ) inputs = ImageMeants.input_spec() @@ -26,7 +59,11 @@ def test_ImageMeants_inputs(): def test_ImageMeants_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ImageMeants.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ImageStats.py b/nipype/interfaces/fsl/tests/test_auto_ImageStats.py index 0c309880bb..e4ddf5f06d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ImageStats.py +++ b/nipype/interfaces/fsl/tests/test_auto_ImageStats.py @@ -4,14 +4,38 @@ def test_ImageStats_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=3,), - index_mask_file=dict(argstr="-K %s", extensions=None, position=2,), - mask_file=dict(argstr="", extensions=None,), - op_string=dict(argstr="%s", mandatory=True, position=4,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=3, + ), + index_mask_file=dict( + argstr="-K %s", + extensions=None, + position=2, + ), + mask_file=dict( + argstr="", + extensions=None, + ), + op_string=dict( + argstr="%s", + mandatory=True, + position=4, + ), output_type=dict(), - split_4d=dict(argstr="-t", position=1,), + split_4d=dict( + argstr="-t", + position=1, + ), ) inputs = ImageStats.input_spec() @@ -21,7 +45,9 @@ def test_ImageStats_inputs(): def test_ImageStats_outputs(): - output_map = dict(out_stat=dict(),) + output_map = dict( + out_stat=dict(), + ) outputs = ImageStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_InvWarp.py b/nipype/interfaces/fsl/tests/test_auto_InvWarp.py index b116f19737..1dba5e578a 100644 --- a/nipype/interfaces/fsl/tests/test_auto_InvWarp.py +++ b/nipype/interfaces/fsl/tests/test_auto_InvWarp.py @@ -4,9 +4,17 @@ def test_InvWarp_inputs(): input_map = dict( - absolute=dict(argstr="--abs", xor=["relative"],), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + absolute=dict( + argstr="--abs", + xor=["relative"], + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inverse_warp=dict( argstr="--out=%s", extensions=None, @@ -14,15 +22,36 @@ def test_InvWarp_inputs(): name_source=["warp"], name_template="%s_inverse", ), - jacobian_max=dict(argstr="--jmax=%f",), - jacobian_min=dict(argstr="--jmin=%f",), - niter=dict(argstr="--niter=%d",), - noconstraint=dict(argstr="--noconstraint",), + jacobian_max=dict( + argstr="--jmax=%f", + ), + jacobian_min=dict( + argstr="--jmin=%f", + ), + niter=dict( + argstr="--niter=%d", + ), + noconstraint=dict( + argstr="--noconstraint", + ), output_type=dict(), - reference=dict(argstr="--ref=%s", extensions=None, mandatory=True,), - regularise=dict(argstr="--regularise=%f",), - relative=dict(argstr="--rel", xor=["absolute"],), - warp=dict(argstr="--warp=%s", extensions=None, mandatory=True,), + reference=dict( + argstr="--ref=%s", + extensions=None, + mandatory=True, + ), + regularise=dict( + argstr="--regularise=%f", + ), + relative=dict( + argstr="--rel", + xor=["absolute"], + ), + warp=dict( + argstr="--warp=%s", + extensions=None, + mandatory=True, + ), ) inputs = InvWarp.input_spec() @@ -32,7 +61,11 @@ def test_InvWarp_inputs(): def test_InvWarp_outputs(): - output_map = dict(inverse_warp=dict(extensions=None,),) + output_map = dict( + inverse_warp=dict( + extensions=None, + ), + ) outputs = InvWarp.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_IsotropicSmooth.py b/nipype/interfaces/fsl/tests/test_auto_IsotropicSmooth.py index 58186672ec..f9c5432d40 100644 --- a/nipype/interfaces/fsl/tests/test_auto_IsotropicSmooth.py +++ b/nipype/interfaces/fsl/tests/test_auto_IsotropicSmooth.py @@ -4,18 +4,51 @@ def test_IsotropicSmooth_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fwhm=dict(argstr="-s %.5f", mandatory=True, position=4, xor=["sigma"],), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr="-s %.5f", + mandatory=True, + position=4, + xor=["sigma"], + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), - sigma=dict(argstr="-s %.5f", mandatory=True, position=4, xor=["fwhm"],), + sigma=dict( + argstr="-s %.5f", + mandatory=True, + position=4, + xor=["fwhm"], + ), ) inputs = IsotropicSmooth.input_spec() @@ -25,7 +58,11 @@ def test_IsotropicSmooth_inputs(): def test_IsotropicSmooth_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = IsotropicSmooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_L2Model.py b/nipype/interfaces/fsl/tests/test_auto_L2Model.py index 6d16cc6038..c4547fc7a2 100644 --- a/nipype/interfaces/fsl/tests/test_auto_L2Model.py +++ b/nipype/interfaces/fsl/tests/test_auto_L2Model.py @@ -3,7 +3,11 @@ def test_L2Model_inputs(): - input_map = dict(num_copes=dict(mandatory=True,),) + input_map = dict( + num_copes=dict( + mandatory=True, + ), + ) inputs = L2Model.input_spec() for key, metadata in list(input_map.items()): @@ -13,9 +17,15 @@ def test_L2Model_inputs(): def test_L2Model_outputs(): output_map = dict( - design_con=dict(extensions=None,), - design_grp=dict(extensions=None,), - design_mat=dict(extensions=None,), + design_con=dict( + extensions=None, + ), + design_grp=dict( + extensions=None, + ), + design_mat=dict( + extensions=None, + ), ) outputs = L2Model.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Level1Design.py b/nipype/interfaces/fsl/tests/test_auto_Level1Design.py index f8ed336e43..5a43989601 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Level1Design.py +++ b/nipype/interfaces/fsl/tests/test_auto_Level1Design.py @@ -4,12 +4,22 @@ def test_Level1Design_inputs(): input_map = dict( - bases=dict(mandatory=True,), + bases=dict( + mandatory=True, + ), contrasts=dict(), - interscan_interval=dict(mandatory=True,), - model_serial_correlations=dict(mandatory=True,), - orthogonalization=dict(usedefault=True,), - session_info=dict(mandatory=True,), + interscan_interval=dict( + mandatory=True, + ), + model_serial_correlations=dict( + mandatory=True, + ), + orthogonalization=dict( + usedefault=True, + ), + session_info=dict( + mandatory=True, + ), ) inputs = Level1Design.input_spec() @@ -19,7 +29,10 @@ def test_Level1Design_inputs(): def test_Level1Design_outputs(): - output_map = dict(ev_files=dict(), fsf_files=dict(),) + output_map = dict( + ev_files=dict(), + fsf_files=dict(), + ) outputs = Level1Design.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MCFLIRT.py b/nipype/interfaces/fsl/tests/test_auto_MCFLIRT.py index 8f52f40eb0..768c52a7f4 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MCFLIRT.py +++ b/nipype/interfaces/fsl/tests/test_auto_MCFLIRT.py @@ -4,31 +4,82 @@ def test_MCFLIRT_inputs(): input_map = dict( - args=dict(argstr="%s",), - bins=dict(argstr="-bins %d",), - cost=dict(argstr="-cost %s",), - dof=dict(argstr="-dof %d",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True, position=0,), - init=dict(argstr="-init %s", extensions=None,), - interpolation=dict(argstr="-%s_final",), - mean_vol=dict(argstr="-meanvol",), + args=dict( + argstr="%s", + ), + bins=dict( + argstr="-bins %d", + ), + cost=dict( + argstr="-cost %s", + ), + dof=dict( + argstr="-dof %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + position=0, + ), + init=dict( + argstr="-init %s", + extensions=None, + ), + interpolation=dict( + argstr="-%s_final", + ), + mean_vol=dict( + argstr="-meanvol", + ), out_file=dict( - argstr="-out %s", extensions=None, genfile=True, hash_files=False, + argstr="-out %s", + extensions=None, + genfile=True, + hash_files=False, ), output_type=dict(), - ref_file=dict(argstr="-reffile %s", extensions=None,), - ref_vol=dict(argstr="-refvol %d",), - rotation=dict(argstr="-rotation %d",), - save_mats=dict(argstr="-mats",), - save_plots=dict(argstr="-plots",), - save_rms=dict(argstr="-rmsabs -rmsrel",), - scaling=dict(argstr="-scaling %.2f",), - smooth=dict(argstr="-smooth %.2f",), - stages=dict(argstr="-stages %d",), - stats_imgs=dict(argstr="-stats",), - use_contour=dict(argstr="-edge",), - use_gradient=dict(argstr="-gdt",), + ref_file=dict( + argstr="-reffile %s", + extensions=None, + ), + ref_vol=dict( + argstr="-refvol %d", + ), + rotation=dict( + argstr="-rotation %d", + ), + save_mats=dict( + argstr="-mats", + ), + save_plots=dict( + argstr="-plots", + ), + save_rms=dict( + argstr="-rmsabs -rmsrel", + ), + scaling=dict( + argstr="-scaling %.2f", + ), + smooth=dict( + argstr="-smooth %.2f", + ), + stages=dict( + argstr="-stages %d", + ), + stats_imgs=dict( + argstr="-stats", + ), + use_contour=dict( + argstr="-edge", + ), + use_gradient=dict( + argstr="-gdt", + ), ) inputs = MCFLIRT.input_spec() @@ -40,12 +91,22 @@ def test_MCFLIRT_inputs(): def test_MCFLIRT_outputs(): output_map = dict( mat_file=dict(), - mean_img=dict(extensions=None,), - out_file=dict(extensions=None,), - par_file=dict(extensions=None,), + mean_img=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + par_file=dict( + extensions=None, + ), rms_files=dict(), - std_img=dict(extensions=None,), - variance_img=dict(extensions=None,), + std_img=dict( + extensions=None, + ), + variance_img=dict( + extensions=None, + ), ) outputs = MCFLIRT.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_MELODIC.py b/nipype/interfaces/fsl/tests/test_auto_MELODIC.py index 86e4e0e2a2..db2406e30f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MELODIC.py +++ b/nipype/interfaces/fsl/tests/test_auto_MELODIC.py @@ -4,57 +4,171 @@ def test_MELODIC_inputs(): input_map = dict( - ICs=dict(argstr="--ICs=%s", extensions=None,), - approach=dict(argstr="-a %s",), - args=dict(argstr="%s",), - bg_image=dict(argstr="--bgimage=%s", extensions=None,), - bg_threshold=dict(argstr="--bgthreshold=%f",), - cov_weight=dict(argstr="--covarweight=%f",), - dim=dict(argstr="-d %d",), - dim_est=dict(argstr="--dimest=%s",), - environ=dict(nohash=True, usedefault=True,), - epsilon=dict(argstr="--eps=%f",), - epsilonS=dict(argstr="--epsS=%f",), - in_files=dict(argstr="-i %s", mandatory=True, position=0, sep=",",), - log_power=dict(argstr="--logPower",), - mask=dict(argstr="-m %s", extensions=None,), - max_restart=dict(argstr="--maxrestart=%d",), - maxit=dict(argstr="--maxit=%d",), - migp=dict(argstr="--migp",), - migpN=dict(argstr="--migpN %d",), - migp_factor=dict(argstr="--migp_factor %d",), - migp_shuffle=dict(argstr="--migp_shuffle",), - mix=dict(argstr="--mix=%s", extensions=None,), - mm_thresh=dict(argstr="--mmthresh=%f",), - no_bet=dict(argstr="--nobet",), - no_mask=dict(argstr="--nomask",), - no_mm=dict(argstr="--no_mm",), - non_linearity=dict(argstr="--nl=%s",), - num_ICs=dict(argstr="-n %d",), - out_all=dict(argstr="--Oall",), - out_dir=dict(argstr="-o %s", genfile=True,), - out_mean=dict(argstr="--Omean",), - out_orig=dict(argstr="--Oorig",), - out_pca=dict(argstr="--Opca",), - out_stats=dict(argstr="--Ostats",), - out_unmix=dict(argstr="--Ounmix",), - out_white=dict(argstr="--Owhite",), + ICs=dict( + argstr="--ICs=%s", + extensions=None, + ), + approach=dict( + argstr="-a %s", + ), + args=dict( + argstr="%s", + ), + bg_image=dict( + argstr="--bgimage=%s", + extensions=None, + ), + bg_threshold=dict( + argstr="--bgthreshold=%f", + ), + cov_weight=dict( + argstr="--covarweight=%f", + ), + dim=dict( + argstr="-d %d", + ), + dim_est=dict( + argstr="--dimest=%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + epsilon=dict( + argstr="--eps=%f", + ), + epsilonS=dict( + argstr="--epsS=%f", + ), + in_files=dict( + argstr="-i %s", + mandatory=True, + position=0, + sep=",", + ), + log_power=dict( + argstr="--logPower", + ), + mask=dict( + argstr="-m %s", + extensions=None, + ), + max_restart=dict( + argstr="--maxrestart=%d", + ), + maxit=dict( + argstr="--maxit=%d", + ), + migp=dict( + argstr="--migp", + ), + migpN=dict( + argstr="--migpN %d", + ), + migp_factor=dict( + argstr="--migp_factor %d", + ), + migp_shuffle=dict( + argstr="--migp_shuffle", + ), + mix=dict( + argstr="--mix=%s", + extensions=None, + ), + mm_thresh=dict( + argstr="--mmthresh=%f", + ), + no_bet=dict( + argstr="--nobet", + ), + no_mask=dict( + argstr="--nomask", + ), + no_mm=dict( + argstr="--no_mm", + ), + non_linearity=dict( + argstr="--nl=%s", + ), + num_ICs=dict( + argstr="-n %d", + ), + out_all=dict( + argstr="--Oall", + ), + out_dir=dict( + argstr="-o %s", + genfile=True, + ), + out_mean=dict( + argstr="--Omean", + ), + out_orig=dict( + argstr="--Oorig", + ), + out_pca=dict( + argstr="--Opca", + ), + out_stats=dict( + argstr="--Ostats", + ), + out_unmix=dict( + argstr="--Ounmix", + ), + out_white=dict( + argstr="--Owhite", + ), output_type=dict(), - pbsc=dict(argstr="--pbsc",), - rem_cmp=dict(argstr="-f %d",), - remove_deriv=dict(argstr="--remove_deriv",), - report=dict(argstr="--report",), - report_maps=dict(argstr="--report_maps=%s",), - s_con=dict(argstr="--Scon=%s", extensions=None,), - s_des=dict(argstr="--Sdes=%s", extensions=None,), - sep_vn=dict(argstr="--sep_vn",), - sep_whiten=dict(argstr="--sep_whiten",), - smode=dict(argstr="--smode=%s", extensions=None,), - t_con=dict(argstr="--Tcon=%s", extensions=None,), - t_des=dict(argstr="--Tdes=%s", extensions=None,), - tr_sec=dict(argstr="--tr=%f",), - update_mask=dict(argstr="--update_mask",), - var_norm=dict(argstr="--vn",), + pbsc=dict( + argstr="--pbsc", + ), + rem_cmp=dict( + argstr="-f %d", + ), + remove_deriv=dict( + argstr="--remove_deriv", + ), + report=dict( + argstr="--report", + ), + report_maps=dict( + argstr="--report_maps=%s", + ), + s_con=dict( + argstr="--Scon=%s", + extensions=None, + ), + s_des=dict( + argstr="--Sdes=%s", + extensions=None, + ), + sep_vn=dict( + argstr="--sep_vn", + ), + sep_whiten=dict( + argstr="--sep_whiten", + ), + smode=dict( + argstr="--smode=%s", + extensions=None, + ), + t_con=dict( + argstr="--Tcon=%s", + extensions=None, + ), + t_des=dict( + argstr="--Tdes=%s", + extensions=None, + ), + tr_sec=dict( + argstr="--tr=%f", + ), + update_mask=dict( + argstr="--update_mask", + ), + var_norm=dict( + argstr="--vn", + ), ) inputs = MELODIC.input_spec() @@ -64,7 +178,10 @@ def test_MELODIC_inputs(): def test_MELODIC_outputs(): - output_map = dict(out_dir=dict(), report_dir=dict(),) + output_map = dict( + out_dir=dict(), + report_dir=dict(), + ) outputs = MELODIC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MakeDyadicVectors.py b/nipype/interfaces/fsl/tests/test_auto_MakeDyadicVectors.py index 760072bab9..bfdb32146e 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MakeDyadicVectors.py +++ b/nipype/interfaces/fsl/tests/test_auto_MakeDyadicVectors.py @@ -4,16 +4,42 @@ def test_MakeDyadicVectors_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - mask=dict(argstr="%s", extensions=None, position=2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + mask=dict( + argstr="%s", + extensions=None, + position=2, + ), output=dict( - argstr="%s", extensions=None, hash_files=False, position=3, usedefault=True, + argstr="%s", + extensions=None, + hash_files=False, + position=3, + usedefault=True, ), output_type=dict(), - perc=dict(argstr="%f", position=4,), - phi_vol=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - theta_vol=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + perc=dict( + argstr="%f", + position=4, + ), + phi_vol=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + theta_vol=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), ) inputs = MakeDyadicVectors.input_spec() @@ -23,7 +49,14 @@ def test_MakeDyadicVectors_inputs(): def test_MakeDyadicVectors_outputs(): - output_map = dict(dispersion=dict(extensions=None,), dyads=dict(extensions=None,),) + output_map = dict( + dispersion=dict( + extensions=None, + ), + dyads=dict( + extensions=None, + ), + ) outputs = MakeDyadicVectors.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MathsCommand.py b/nipype/interfaces/fsl/tests/test_auto_MathsCommand.py index ce7f058663..e14e4a4005 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MathsCommand.py +++ b/nipype/interfaces/fsl/tests/test_auto_MathsCommand.py @@ -4,15 +4,38 @@ def test_MathsCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = MathsCommand.input_spec() @@ -23,7 +46,11 @@ def test_MathsCommand_inputs(): def test_MathsCommand_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MathsCommand.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MaxImage.py b/nipype/interfaces/fsl/tests/test_auto_MaxImage.py index 1baa75963b..f96f931fcf 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MaxImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MaxImage.py @@ -4,16 +4,43 @@ def test_MaxImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%smax", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%smax", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = MaxImage.input_spec() @@ -24,7 +51,11 @@ def test_MaxImage_inputs(): def test_MaxImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MaxImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MaxnImage.py b/nipype/interfaces/fsl/tests/test_auto_MaxnImage.py index aa52ba3bb7..30ada25d79 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MaxnImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MaxnImage.py @@ -4,16 +4,43 @@ def test_MaxnImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%smaxn", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%smaxn", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = MaxnImage.input_spec() @@ -24,7 +51,11 @@ def test_MaxnImage_inputs(): def test_MaxnImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MaxnImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MeanImage.py b/nipype/interfaces/fsl/tests/test_auto_MeanImage.py index 076cb08a76..e29104476c 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MeanImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MeanImage.py @@ -4,16 +4,43 @@ def test_MeanImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%smean", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%smean", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = MeanImage.input_spec() @@ -24,7 +51,11 @@ def test_MeanImage_inputs(): def test_MeanImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MeanImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MedianImage.py b/nipype/interfaces/fsl/tests/test_auto_MedianImage.py index a70ff14b2f..7c8052fd31 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MedianImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MedianImage.py @@ -4,16 +4,43 @@ def test_MedianImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%smedian", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%smedian", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = MedianImage.input_spec() @@ -24,7 +51,11 @@ def test_MedianImage_inputs(): def test_MedianImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MedianImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Merge.py b/nipype/interfaces/fsl/tests/test_auto_Merge.py index 45db6482a9..847f9b7bd3 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Merge.py +++ b/nipype/interfaces/fsl/tests/test_auto_Merge.py @@ -4,10 +4,23 @@ def test_Merge_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%s", mandatory=True, position=0,), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="%s", mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%s", + mandatory=True, + position=0, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=2, + ), merged_file=dict( argstr="%s", extensions=None, @@ -17,7 +30,10 @@ def test_Merge_inputs(): position=1, ), output_type=dict(), - tr=dict(argstr="%.2f", position=-1,), + tr=dict( + argstr="%.2f", + position=-1, + ), ) inputs = Merge.input_spec() @@ -27,7 +43,11 @@ def test_Merge_inputs(): def test_Merge_outputs(): - output_map = dict(merged_file=dict(extensions=None,),) + output_map = dict( + merged_file=dict( + extensions=None, + ), + ) outputs = Merge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MinImage.py b/nipype/interfaces/fsl/tests/test_auto_MinImage.py index 9d5416bd15..bde76c1afc 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MinImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_MinImage.py @@ -4,16 +4,43 @@ def test_MinImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%smin", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%smin", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = MinImage.input_spec() @@ -24,7 +51,11 @@ def test_MinImage_inputs(): def test_MinImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MinImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MotionOutliers.py b/nipype/interfaces/fsl/tests/test_auto_MotionOutliers.py index 4c8ce55636..9a5773336f 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MotionOutliers.py +++ b/nipype/interfaces/fsl/tests/test_auto_MotionOutliers.py @@ -4,13 +4,31 @@ def test_MotionOutliers_inputs(): input_map = dict( - args=dict(argstr="%s",), - dummy=dict(argstr="--dummy=%d",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True,), - mask=dict(argstr="-m %s", extensions=None,), - metric=dict(argstr="--%s",), - no_motion_correction=dict(argstr="--nomoco",), + args=dict( + argstr="%s", + ), + dummy=dict( + argstr="--dummy=%d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + mask=dict( + argstr="-m %s", + extensions=None, + ), + metric=dict( + argstr="--%s", + ), + no_motion_correction=dict( + argstr="--nomoco", + ), out_file=dict( argstr="-o %s", extensions=None, @@ -36,7 +54,9 @@ def test_MotionOutliers_inputs(): name_template="%s_metrics.txt", ), output_type=dict(), - threshold=dict(argstr="--thresh=%g",), + threshold=dict( + argstr="--thresh=%g", + ), ) inputs = MotionOutliers.input_spec() @@ -47,9 +67,15 @@ def test_MotionOutliers_inputs(): def test_MotionOutliers_outputs(): output_map = dict( - out_file=dict(extensions=None,), - out_metric_plot=dict(extensions=None,), - out_metric_values=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_metric_plot=dict( + extensions=None, + ), + out_metric_values=dict( + extensions=None, + ), ) outputs = MotionOutliers.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_MultiImageMaths.py b/nipype/interfaces/fsl/tests/test_auto_MultiImageMaths.py index ba96daf994..95de40d023 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MultiImageMaths.py +++ b/nipype/interfaces/fsl/tests/test_auto_MultiImageMaths.py @@ -4,17 +4,46 @@ def test_MultiImageMaths_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), - op_string=dict(argstr="%s", mandatory=True, position=4,), - operand_files=dict(mandatory=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), + op_string=dict( + argstr="%s", + mandatory=True, + position=4, + ), + operand_files=dict( + mandatory=True, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = MultiImageMaths.input_spec() @@ -25,7 +54,11 @@ def test_MultiImageMaths_inputs(): def test_MultiImageMaths_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MultiImageMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_MultipleRegressDesign.py b/nipype/interfaces/fsl/tests/test_auto_MultipleRegressDesign.py index fe3ce1b0b1..cae5e90cd4 100644 --- a/nipype/interfaces/fsl/tests/test_auto_MultipleRegressDesign.py +++ b/nipype/interfaces/fsl/tests/test_auto_MultipleRegressDesign.py @@ -4,9 +4,13 @@ def test_MultipleRegressDesign_inputs(): input_map = dict( - contrasts=dict(mandatory=True,), + contrasts=dict( + mandatory=True, + ), groups=dict(), - regressors=dict(mandatory=True,), + regressors=dict( + mandatory=True, + ), ) inputs = MultipleRegressDesign.input_spec() @@ -17,10 +21,18 @@ def test_MultipleRegressDesign_inputs(): def test_MultipleRegressDesign_outputs(): output_map = dict( - design_con=dict(extensions=None,), - design_fts=dict(extensions=None,), - design_grp=dict(extensions=None,), - design_mat=dict(extensions=None,), + design_con=dict( + extensions=None, + ), + design_fts=dict( + extensions=None, + ), + design_grp=dict( + extensions=None, + ), + design_mat=dict( + extensions=None, + ), ) outputs = MultipleRegressDesign.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Overlay.py b/nipype/interfaces/fsl/tests/test_auto_Overlay.py index e09ef17541..22c4f08a44 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Overlay.py +++ b/nipype/interfaces/fsl/tests/test_auto_Overlay.py @@ -4,7 +4,9 @@ def test_Overlay_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), auto_thresh_bg=dict( argstr="-a", mandatory=True, @@ -12,7 +14,10 @@ def test_Overlay_inputs(): xor=("auto_thresh_bg", "full_bg_range", "bg_thresh"), ), background_image=dict( - argstr="%s", extensions=None, mandatory=True, position=4, + argstr="%s", + extensions=None, + mandatory=True, + position=4, ), bg_thresh=dict( argstr="%.3f %.3f", @@ -20,7 +25,10 @@ def test_Overlay_inputs(): position=5, xor=("auto_thresh_bg", "full_bg_range", "bg_thresh"), ), - environ=dict(nohash=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), full_bg_range=dict( argstr="-A", mandatory=True, @@ -28,19 +36,53 @@ def test_Overlay_inputs(): xor=("auto_thresh_bg", "full_bg_range", "bg_thresh"), ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-1, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-1, + ), + out_type=dict( + argstr="%s", + position=2, + usedefault=True, ), - out_type=dict(argstr="%s", position=2, usedefault=True,), output_type=dict(), - show_negative_stats=dict(argstr="%s", position=8, xor=["stat_image2"],), - stat_image=dict(argstr="%s", extensions=None, mandatory=True, position=6,), + show_negative_stats=dict( + argstr="%s", + position=8, + xor=["stat_image2"], + ), + stat_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=6, + ), stat_image2=dict( - argstr="%s", extensions=None, position=9, xor=["show_negative_stats"], + argstr="%s", + extensions=None, + position=9, + xor=["show_negative_stats"], + ), + stat_thresh=dict( + argstr="%.2f %.2f", + mandatory=True, + position=7, + ), + stat_thresh2=dict( + argstr="%.2f %.2f", + position=10, + ), + transparency=dict( + argstr="%s", + position=1, + usedefault=True, + ), + use_checkerboard=dict( + argstr="-c", + position=3, ), - stat_thresh=dict(argstr="%.2f %.2f", mandatory=True, position=7,), - stat_thresh2=dict(argstr="%.2f %.2f", position=10,), - transparency=dict(argstr="%s", position=1, usedefault=True,), - use_checkerboard=dict(argstr="-c", position=3,), ) inputs = Overlay.input_spec() @@ -50,7 +92,11 @@ def test_Overlay_inputs(): def test_Overlay_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Overlay.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PRELUDE.py b/nipype/interfaces/fsl/tests/test_auto_PRELUDE.py index 2c3623a76a..0194526c70 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PRELUDE.py +++ b/nipype/interfaces/fsl/tests/test_auto_PRELUDE.py @@ -4,25 +4,43 @@ def test_PRELUDE_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), complex_phase_file=dict( argstr="--complex=%s", extensions=None, mandatory=True, xor=["magnitude_file", "phase_file"], ), - end=dict(argstr="--end=%d",), - environ=dict(nohash=True, usedefault=True,), - label_file=dict(argstr="--labels=%s", extensions=None, hash_files=False,), - labelprocess2d=dict(argstr="--labelslices",), + end=dict( + argstr="--end=%d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + label_file=dict( + argstr="--labels=%s", + extensions=None, + hash_files=False, + ), + labelprocess2d=dict( + argstr="--labelslices", + ), magnitude_file=dict( argstr="--abs=%s", extensions=None, mandatory=True, xor=["complex_phase_file"], ), - mask_file=dict(argstr="--mask=%s", extensions=None,), - num_partitions=dict(argstr="--numphasesplit=%d",), + mask_file=dict( + argstr="--mask=%s", + extensions=None, + ), + num_partitions=dict( + argstr="--numphasesplit=%d", + ), output_type=dict(), phase_file=dict( argstr="--phase=%s", @@ -30,15 +48,38 @@ def test_PRELUDE_inputs(): mandatory=True, xor=["complex_phase_file"], ), - process2d=dict(argstr="--slices", xor=["labelprocess2d"],), - process3d=dict(argstr="--force3D", xor=["labelprocess2d", "process2d"],), - rawphase_file=dict(argstr="--rawphase=%s", extensions=None, hash_files=False,), - removeramps=dict(argstr="--removeramps",), - savemask_file=dict(argstr="--savemask=%s", extensions=None, hash_files=False,), - start=dict(argstr="--start=%d",), - threshold=dict(argstr="--thresh=%.10f",), + process2d=dict( + argstr="--slices", + xor=["labelprocess2d"], + ), + process3d=dict( + argstr="--force3D", + xor=["labelprocess2d", "process2d"], + ), + rawphase_file=dict( + argstr="--rawphase=%s", + extensions=None, + hash_files=False, + ), + removeramps=dict( + argstr="--removeramps", + ), + savemask_file=dict( + argstr="--savemask=%s", + extensions=None, + hash_files=False, + ), + start=dict( + argstr="--start=%d", + ), + threshold=dict( + argstr="--thresh=%.10f", + ), unwrapped_phase_file=dict( - argstr="--unwrap=%s", extensions=None, genfile=True, hash_files=False, + argstr="--unwrap=%s", + extensions=None, + genfile=True, + hash_files=False, ), ) inputs = PRELUDE.input_spec() @@ -49,7 +90,11 @@ def test_PRELUDE_inputs(): def test_PRELUDE_outputs(): - output_map = dict(unwrapped_phase_file=dict(extensions=None,),) + output_map = dict( + unwrapped_phase_file=dict( + extensions=None, + ), + ) outputs = PRELUDE.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PercentileImage.py b/nipype/interfaces/fsl/tests/test_auto_PercentileImage.py index 2b272b006c..3a3ae14a78 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PercentileImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_PercentileImage.py @@ -4,18 +4,48 @@ def test_PercentileImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%sperc", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%sperc", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), - perc=dict(argstr="%f", position=5,), + perc=dict( + argstr="%f", + position=5, + ), ) inputs = PercentileImage.input_spec() @@ -25,7 +55,11 @@ def test_PercentileImage_inputs(): def test_PercentileImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = PercentileImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PlotMotionParams.py b/nipype/interfaces/fsl/tests/test_auto_PlotMotionParams.py index c12494e50b..8cf1d2e214 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PlotMotionParams.py +++ b/nipype/interfaces/fsl/tests/test_auto_PlotMotionParams.py @@ -4,14 +4,35 @@ def test_PlotMotionParams_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", mandatory=True, position=1,), - in_source=dict(mandatory=True,), - out_file=dict(argstr="-o %s", extensions=None, genfile=True, hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + mandatory=True, + position=1, + ), + in_source=dict( + mandatory=True, + ), + out_file=dict( + argstr="-o %s", + extensions=None, + genfile=True, + hash_files=False, + ), output_type=dict(), - plot_size=dict(argstr="%s",), - plot_type=dict(argstr="%s", mandatory=True,), + plot_size=dict( + argstr="%s", + ), + plot_type=dict( + argstr="%s", + mandatory=True, + ), ) inputs = PlotMotionParams.input_spec() @@ -21,7 +42,11 @@ def test_PlotMotionParams_inputs(): def test_PlotMotionParams_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = PlotMotionParams.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PlotTimeSeries.py b/nipype/interfaces/fsl/tests/test_auto_PlotTimeSeries.py index 0f3954fcf2..5b4ebc46aa 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PlotTimeSeries.py +++ b/nipype/interfaces/fsl/tests/test_auto_PlotTimeSeries.py @@ -4,24 +4,72 @@ def test_PlotTimeSeries_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", mandatory=True, position=1,), - labels=dict(argstr="%s",), - legend_file=dict(argstr="--legend=%s", extensions=None,), - out_file=dict(argstr="-o %s", extensions=None, genfile=True, hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + mandatory=True, + position=1, + ), + labels=dict( + argstr="%s", + ), + legend_file=dict( + argstr="--legend=%s", + extensions=None, + ), + out_file=dict( + argstr="-o %s", + extensions=None, + genfile=True, + hash_files=False, + ), output_type=dict(), - plot_finish=dict(argstr="--finish=%d", xor=("plot_range",),), - plot_range=dict(argstr="%s", xor=("plot_start", "plot_finish"),), - plot_size=dict(argstr="%s",), - plot_start=dict(argstr="--start=%d", xor=("plot_range",),), - sci_notation=dict(argstr="--sci",), - title=dict(argstr="%s",), - x_precision=dict(argstr="--precision=%d",), - x_units=dict(argstr="-u %d", usedefault=True,), - y_max=dict(argstr="--ymax=%.2f", xor=("y_range",),), - y_min=dict(argstr="--ymin=%.2f", xor=("y_range",),), - y_range=dict(argstr="%s", xor=("y_min", "y_max"),), + plot_finish=dict( + argstr="--finish=%d", + xor=("plot_range",), + ), + plot_range=dict( + argstr="%s", + xor=("plot_start", "plot_finish"), + ), + plot_size=dict( + argstr="%s", + ), + plot_start=dict( + argstr="--start=%d", + xor=("plot_range",), + ), + sci_notation=dict( + argstr="--sci", + ), + title=dict( + argstr="%s", + ), + x_precision=dict( + argstr="--precision=%d", + ), + x_units=dict( + argstr="-u %d", + usedefault=True, + ), + y_max=dict( + argstr="--ymax=%.2f", + xor=("y_range",), + ), + y_min=dict( + argstr="--ymin=%.2f", + xor=("y_range",), + ), + y_range=dict( + argstr="%s", + xor=("y_min", "y_max"), + ), ) inputs = PlotTimeSeries.input_spec() @@ -31,7 +79,11 @@ def test_PlotTimeSeries_inputs(): def test_PlotTimeSeries_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = PlotTimeSeries.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PowerSpectrum.py b/nipype/interfaces/fsl/tests/test_auto_PowerSpectrum.py index 5aa19309fc..874cbcf0e8 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PowerSpectrum.py +++ b/nipype/interfaces/fsl/tests/test_auto_PowerSpectrum.py @@ -4,11 +4,25 @@ def test_PowerSpectrum_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=1, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=1, ), output_type=dict(), ) @@ -20,7 +34,11 @@ def test_PowerSpectrum_inputs(): def test_PowerSpectrum_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = PowerSpectrum.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_PrepareFieldmap.py b/nipype/interfaces/fsl/tests/test_auto_PrepareFieldmap.py index d6d39b595c..2286dad026 100644 --- a/nipype/interfaces/fsl/tests/test_auto_PrepareFieldmap.py +++ b/nipype/interfaces/fsl/tests/test_auto_PrepareFieldmap.py @@ -4,15 +4,47 @@ def test_PrepareFieldmap_inputs(): input_map = dict( - args=dict(argstr="%s",), - delta_TE=dict(argstr="%f", mandatory=True, position=-2, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_magnitude=dict(argstr="%s", extensions=None, mandatory=True, position=3,), - in_phase=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - nocheck=dict(argstr="--nocheck", position=-1, usedefault=True,), - out_fieldmap=dict(argstr="%s", extensions=None, position=4,), + args=dict( + argstr="%s", + ), + delta_TE=dict( + argstr="%f", + mandatory=True, + position=-2, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_magnitude=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=3, + ), + in_phase=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + nocheck=dict( + argstr="--nocheck", + position=-1, + usedefault=True, + ), + out_fieldmap=dict( + argstr="%s", + extensions=None, + position=4, + ), output_type=dict(), - scanner=dict(argstr="%s", position=1, usedefault=True,), + scanner=dict( + argstr="%s", + position=1, + usedefault=True, + ), ) inputs = PrepareFieldmap.input_spec() @@ -22,7 +54,11 @@ def test_PrepareFieldmap_inputs(): def test_PrepareFieldmap_outputs(): - output_map = dict(out_fieldmap=dict(extensions=None,),) + output_map = dict( + out_fieldmap=dict( + extensions=None, + ), + ) outputs = PrepareFieldmap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_ProbTrackX.py b/nipype/interfaces/fsl/tests/test_auto_ProbTrackX.py index 1e2d0f5486..c841391efc 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ProbTrackX.py +++ b/nipype/interfaces/fsl/tests/test_auto_ProbTrackX.py @@ -4,45 +4,139 @@ def test_ProbTrackX_inputs(): input_map = dict( - args=dict(argstr="%s",), - avoid_mp=dict(argstr="--avoid=%s", extensions=None,), - c_thresh=dict(argstr="--cthr=%.3f",), - correct_path_distribution=dict(argstr="--pd",), - dist_thresh=dict(argstr="--distthresh=%.3f",), - environ=dict(nohash=True, usedefault=True,), - fibst=dict(argstr="--fibst=%d",), - force_dir=dict(argstr="--forcedir", usedefault=True,), - fsamples=dict(mandatory=True,), - inv_xfm=dict(argstr="--invxfm=%s", extensions=None,), - loop_check=dict(argstr="--loopcheck",), - mask=dict(argstr="-m %s", extensions=None, mandatory=True,), - mask2=dict(argstr="--mask2=%s", extensions=None,), - mesh=dict(argstr="--mesh=%s", extensions=None,), - mod_euler=dict(argstr="--modeuler",), - mode=dict(argstr="--mode=%s", genfile=True,), - n_samples=dict(argstr="--nsamples=%d", usedefault=True,), - n_steps=dict(argstr="--nsteps=%d",), - network=dict(argstr="--network",), - opd=dict(argstr="--opd", usedefault=True,), - os2t=dict(argstr="--os2t",), - out_dir=dict(argstr="--dir=%s", genfile=True,), + args=dict( + argstr="%s", + ), + avoid_mp=dict( + argstr="--avoid=%s", + extensions=None, + ), + c_thresh=dict( + argstr="--cthr=%.3f", + ), + correct_path_distribution=dict( + argstr="--pd", + ), + dist_thresh=dict( + argstr="--distthresh=%.3f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fibst=dict( + argstr="--fibst=%d", + ), + force_dir=dict( + argstr="--forcedir", + usedefault=True, + ), + fsamples=dict( + mandatory=True, + ), + inv_xfm=dict( + argstr="--invxfm=%s", + extensions=None, + ), + loop_check=dict( + argstr="--loopcheck", + ), + mask=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + ), + mask2=dict( + argstr="--mask2=%s", + extensions=None, + ), + mesh=dict( + argstr="--mesh=%s", + extensions=None, + ), + mod_euler=dict( + argstr="--modeuler", + ), + mode=dict( + argstr="--mode=%s", + genfile=True, + ), + n_samples=dict( + argstr="--nsamples=%d", + usedefault=True, + ), + n_steps=dict( + argstr="--nsteps=%d", + ), + network=dict( + argstr="--network", + ), + opd=dict( + argstr="--opd", + usedefault=True, + ), + os2t=dict( + argstr="--os2t", + ), + out_dir=dict( + argstr="--dir=%s", + genfile=True, + ), output_type=dict(), - phsamples=dict(mandatory=True,), - rand_fib=dict(argstr="--randfib=%d",), - random_seed=dict(argstr="--rseed",), - s2tastext=dict(argstr="--s2tastext",), - sample_random_points=dict(argstr="--sampvox",), - samples_base_name=dict(argstr="--samples=%s", usedefault=True,), - seed=dict(argstr="--seed=%s", mandatory=True,), - seed_ref=dict(argstr="--seedref=%s", extensions=None,), - step_length=dict(argstr="--steplength=%.3f",), - stop_mask=dict(argstr="--stop=%s", extensions=None,), - target_masks=dict(argstr="--targetmasks=%s",), - thsamples=dict(mandatory=True,), - use_anisotropy=dict(argstr="--usef",), - verbose=dict(argstr="--verbose=%d",), - waypoints=dict(argstr="--waypoints=%s", extensions=None,), - xfm=dict(argstr="--xfm=%s", extensions=None,), + phsamples=dict( + mandatory=True, + ), + rand_fib=dict( + argstr="--randfib=%d", + ), + random_seed=dict( + argstr="--rseed=%d", + ), + s2tastext=dict( + argstr="--s2tastext", + ), + sample_random_points=dict( + argstr="--sampvox=%.3f", + ), + samples_base_name=dict( + argstr="--samples=%s", + usedefault=True, + ), + seed=dict( + argstr="--seed=%s", + mandatory=True, + ), + seed_ref=dict( + argstr="--seedref=%s", + extensions=None, + ), + step_length=dict( + argstr="--steplength=%.3f", + ), + stop_mask=dict( + argstr="--stop=%s", + extensions=None, + ), + target_masks=dict( + argstr="--targetmasks=%s", + ), + thsamples=dict( + mandatory=True, + ), + use_anisotropy=dict( + argstr="--usef", + ), + verbose=dict( + argstr="--verbose=%d", + ), + waypoints=dict( + argstr="--waypoints=%s", + extensions=None, + ), + xfm=dict( + argstr="--xfm=%s", + extensions=None, + ), ) inputs = ProbTrackX.input_spec() @@ -54,10 +148,14 @@ def test_ProbTrackX_inputs(): def test_ProbTrackX_outputs(): output_map = dict( fdt_paths=dict(), - log=dict(extensions=None,), + log=dict( + extensions=None, + ), particle_files=dict(), targets=dict(), - way_total=dict(extensions=None,), + way_total=dict( + extensions=None, + ), ) outputs = ProbTrackX.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ProbTrackX2.py b/nipype/interfaces/fsl/tests/test_auto_ProbTrackX2.py index 56bff1e5ac..f1941f036d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ProbTrackX2.py +++ b/nipype/interfaces/fsl/tests/test_auto_ProbTrackX2.py @@ -4,59 +4,186 @@ def test_ProbTrackX2_inputs(): input_map = dict( - args=dict(argstr="%s",), - avoid_mp=dict(argstr="--avoid=%s", extensions=None,), - c_thresh=dict(argstr="--cthr=%.3f",), - colmask4=dict(argstr="--colmask4=%s", extensions=None,), - correct_path_distribution=dict(argstr="--pd",), - dist_thresh=dict(argstr="--distthresh=%.3f",), - distthresh1=dict(argstr="--distthresh1=%.3f",), - distthresh3=dict(argstr="--distthresh3=%.3f",), - environ=dict(nohash=True, usedefault=True,), - fibst=dict(argstr="--fibst=%d",), - fopd=dict(argstr="--fopd=%s", extensions=None,), - force_dir=dict(argstr="--forcedir", usedefault=True,), - fsamples=dict(mandatory=True,), - inv_xfm=dict(argstr="--invxfm=%s", extensions=None,), - loop_check=dict(argstr="--loopcheck",), - lrtarget3=dict(argstr="--lrtarget3=%s", extensions=None,), - mask=dict(argstr="-m %s", extensions=None, mandatory=True,), - meshspace=dict(argstr="--meshspace=%s",), - mod_euler=dict(argstr="--modeuler",), - n_samples=dict(argstr="--nsamples=%d", usedefault=True,), - n_steps=dict(argstr="--nsteps=%d",), - network=dict(argstr="--network",), - omatrix1=dict(argstr="--omatrix1",), - omatrix2=dict(argstr="--omatrix2", requires=["target2"],), - omatrix3=dict(argstr="--omatrix3", requires=["target3", "lrtarget3"],), - omatrix4=dict(argstr="--omatrix4",), - onewaycondition=dict(argstr="--onewaycondition",), - opd=dict(argstr="--opd", usedefault=True,), - os2t=dict(argstr="--os2t",), - out_dir=dict(argstr="--dir=%s", genfile=True,), + args=dict( + argstr="%s", + ), + avoid_mp=dict( + argstr="--avoid=%s", + extensions=None, + ), + c_thresh=dict( + argstr="--cthr=%.3f", + ), + colmask4=dict( + argstr="--colmask4=%s", + extensions=None, + ), + correct_path_distribution=dict( + argstr="--pd", + ), + dist_thresh=dict( + argstr="--distthresh=%.3f", + ), + distthresh1=dict( + argstr="--distthresh1=%.3f", + ), + distthresh3=dict( + argstr="--distthresh3=%.3f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fibst=dict( + argstr="--fibst=%d", + ), + fopd=dict( + argstr="--fopd=%s", + extensions=None, + ), + force_dir=dict( + argstr="--forcedir", + usedefault=True, + ), + fsamples=dict( + mandatory=True, + ), + inv_xfm=dict( + argstr="--invxfm=%s", + extensions=None, + ), + loop_check=dict( + argstr="--loopcheck", + ), + lrtarget3=dict( + argstr="--lrtarget3=%s", + extensions=None, + ), + mask=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + ), + meshspace=dict( + argstr="--meshspace=%s", + ), + mod_euler=dict( + argstr="--modeuler", + ), + n_samples=dict( + argstr="--nsamples=%d", + usedefault=True, + ), + n_steps=dict( + argstr="--nsteps=%d", + ), + network=dict( + argstr="--network", + ), + omatrix1=dict( + argstr="--omatrix1", + ), + omatrix2=dict( + argstr="--omatrix2", + requires=["target2"], + ), + omatrix3=dict( + argstr="--omatrix3", + requires=["target3", "lrtarget3"], + ), + omatrix4=dict( + argstr="--omatrix4", + ), + onewaycondition=dict( + argstr="--onewaycondition", + ), + opd=dict( + argstr="--opd", + usedefault=True, + ), + os2t=dict( + argstr="--os2t", + ), + out_dir=dict( + argstr="--dir=%s", + genfile=True, + ), output_type=dict(), - phsamples=dict(mandatory=True,), - rand_fib=dict(argstr="--randfib=%d",), - random_seed=dict(argstr="--rseed",), - s2tastext=dict(argstr="--s2tastext",), - sample_random_points=dict(argstr="--sampvox",), - samples_base_name=dict(argstr="--samples=%s", usedefault=True,), - seed=dict(argstr="--seed=%s", mandatory=True,), - seed_ref=dict(argstr="--seedref=%s", extensions=None,), - simple=dict(argstr="--simple",), - step_length=dict(argstr="--steplength=%.3f",), - stop_mask=dict(argstr="--stop=%s", extensions=None,), - target2=dict(argstr="--target2=%s", extensions=None,), - target3=dict(argstr="--target3=%s", extensions=None,), - target4=dict(argstr="--target4=%s", extensions=None,), - target_masks=dict(argstr="--targetmasks=%s",), - thsamples=dict(mandatory=True,), - use_anisotropy=dict(argstr="--usef",), - verbose=dict(argstr="--verbose=%d",), - waycond=dict(argstr="--waycond=%s",), - wayorder=dict(argstr="--wayorder",), - waypoints=dict(argstr="--waypoints=%s", extensions=None,), - xfm=dict(argstr="--xfm=%s", extensions=None,), + phsamples=dict( + mandatory=True, + ), + rand_fib=dict( + argstr="--randfib=%d", + ), + random_seed=dict( + argstr="--rseed=%d", + ), + s2tastext=dict( + argstr="--s2tastext", + ), + sample_random_points=dict( + argstr="--sampvox=%.3f", + ), + samples_base_name=dict( + argstr="--samples=%s", + usedefault=True, + ), + seed=dict( + argstr="--seed=%s", + mandatory=True, + ), + seed_ref=dict( + argstr="--seedref=%s", + extensions=None, + ), + simple=dict( + argstr="--simple", + ), + step_length=dict( + argstr="--steplength=%.3f", + ), + stop_mask=dict( + argstr="--stop=%s", + extensions=None, + ), + target2=dict( + argstr="--target2=%s", + extensions=None, + ), + target3=dict( + argstr="--target3=%s", + extensions=None, + ), + target4=dict( + argstr="--target4=%s", + extensions=None, + ), + target_masks=dict( + argstr="--targetmasks=%s", + ), + thsamples=dict( + mandatory=True, + ), + use_anisotropy=dict( + argstr="--usef", + ), + verbose=dict( + argstr="--verbose=%d", + ), + waycond=dict( + argstr="--waycond=%s", + ), + wayorder=dict( + argstr="--wayorder", + ), + waypoints=dict( + argstr="--waypoints=%s", + extensions=None, + ), + xfm=dict( + argstr="--xfm=%s", + extensions=None, + ), ) inputs = ProbTrackX2.input_spec() @@ -68,15 +195,29 @@ def test_ProbTrackX2_inputs(): def test_ProbTrackX2_outputs(): output_map = dict( fdt_paths=dict(), - log=dict(extensions=None,), - lookup_tractspace=dict(extensions=None,), - matrix1_dot=dict(extensions=None,), - matrix2_dot=dict(extensions=None,), - matrix3_dot=dict(extensions=None,), - network_matrix=dict(extensions=None,), + log=dict( + extensions=None, + ), + lookup_tractspace=dict( + extensions=None, + ), + matrix1_dot=dict( + extensions=None, + ), + matrix2_dot=dict( + extensions=None, + ), + matrix3_dot=dict( + extensions=None, + ), + network_matrix=dict( + extensions=None, + ), particle_files=dict(), targets=dict(), - way_total=dict(extensions=None,), + way_total=dict( + extensions=None, + ), ) outputs = ProbTrackX2.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_ProjThresh.py b/nipype/interfaces/fsl/tests/test_auto_ProjThresh.py index cc1a6a03ac..420eacb9c2 100644 --- a/nipype/interfaces/fsl/tests/test_auto_ProjThresh.py +++ b/nipype/interfaces/fsl/tests/test_auto_ProjThresh.py @@ -4,11 +4,24 @@ def test_ProjThresh_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="%s", mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=0, + ), output_type=dict(), - threshold=dict(argstr="%d", mandatory=True, position=1,), + threshold=dict( + argstr="%d", + mandatory=True, + position=1, + ), ) inputs = ProjThresh.input_spec() @@ -18,7 +31,9 @@ def test_ProjThresh_inputs(): def test_ProjThresh_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = ProjThresh.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Randomise.py b/nipype/interfaces/fsl/tests/test_auto_Randomise.py index 95c1cf7d59..9b0b74bf28 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Randomise.py +++ b/nipype/interfaces/fsl/tests/test_auto_Randomise.py @@ -4,36 +4,107 @@ def test_Randomise_inputs(): input_map = dict( - args=dict(argstr="%s",), - base_name=dict(argstr='-o "%s"', position=1, usedefault=True,), - c_thresh=dict(argstr="-c %.1f",), - cm_thresh=dict(argstr="-C %.1f",), - demean=dict(argstr="-D",), - design_mat=dict(argstr="-d %s", extensions=None, position=2,), - environ=dict(nohash=True, usedefault=True,), - f_c_thresh=dict(argstr="-F %.2f",), - f_cm_thresh=dict(argstr="-S %.2f",), - f_only=dict(argstr="--f_only",), - fcon=dict(argstr="-f %s", extensions=None,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=0,), - mask=dict(argstr="-m %s", extensions=None,), - num_perm=dict(argstr="-n %d",), - one_sample_group_mean=dict(argstr="-1",), + args=dict( + argstr="%s", + ), + base_name=dict( + argstr='-o "%s"', + position=1, + usedefault=True, + ), + c_thresh=dict( + argstr="-c %.1f", + ), + cm_thresh=dict( + argstr="-C %.1f", + ), + demean=dict( + argstr="-D", + ), + design_mat=dict( + argstr="-d %s", + extensions=None, + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + f_c_thresh=dict( + argstr="-F %.2f", + ), + f_cm_thresh=dict( + argstr="-S %.2f", + ), + f_only=dict( + argstr="--fonly", + ), + fcon=dict( + argstr="-f %s", + extensions=None, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=0, + ), + mask=dict( + argstr="-m %s", + extensions=None, + ), + num_perm=dict( + argstr="-n %d", + ), + one_sample_group_mean=dict( + argstr="-1", + ), output_type=dict(), - p_vec_n_dist_files=dict(argstr="-P",), - raw_stats_imgs=dict(argstr="-R",), - seed=dict(argstr="--seed=%d",), - show_info_parallel_mode=dict(argstr="-Q",), - show_total_perms=dict(argstr="-q",), - tcon=dict(argstr="-t %s", extensions=None, position=3,), - tfce=dict(argstr="-T",), - tfce2D=dict(argstr="--T2",), - tfce_C=dict(argstr="--tfce_C=%.2f",), - tfce_E=dict(argstr="--tfce_E=%.2f",), - tfce_H=dict(argstr="--tfce_H=%.2f",), - var_smooth=dict(argstr="-v %d",), - vox_p_values=dict(argstr="-x",), - x_block_labels=dict(argstr="-e %s", extensions=None,), + p_vec_n_dist_files=dict( + argstr="-P", + ), + raw_stats_imgs=dict( + argstr="-R", + ), + seed=dict( + argstr="--seed=%d", + ), + show_info_parallel_mode=dict( + argstr="-Q", + ), + show_total_perms=dict( + argstr="-q", + ), + tcon=dict( + argstr="-t %s", + extensions=None, + position=3, + ), + tfce=dict( + argstr="-T", + ), + tfce2D=dict( + argstr="--T2", + ), + tfce_C=dict( + argstr="--tfce_C=%.2f", + ), + tfce_E=dict( + argstr="--tfce_E=%.2f", + ), + tfce_H=dict( + argstr="--tfce_H=%.2f", + ), + var_smooth=dict( + argstr="-v %d", + ), + vox_p_values=dict( + argstr="-x", + ), + x_block_labels=dict( + argstr="-e %s", + extensions=None, + ), ) inputs = Randomise.input_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Reorient2Std.py b/nipype/interfaces/fsl/tests/test_auto_Reorient2Std.py index d81874e76a..e008eb44e6 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Reorient2Std.py +++ b/nipype/interfaces/fsl/tests/test_auto_Reorient2Std.py @@ -4,10 +4,24 @@ def test_Reorient2Std_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True,), - out_file=dict(argstr="%s", extensions=None, genfile=True, hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + ), output_type=dict(), ) inputs = Reorient2Std.input_spec() @@ -18,7 +32,11 @@ def test_Reorient2Std_inputs(): def test_Reorient2Std_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Reorient2Std.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_RobustFOV.py b/nipype/interfaces/fsl/tests/test_auto_RobustFOV.py index fbadb82c99..b5598f0de4 100644 --- a/nipype/interfaces/fsl/tests/test_auto_RobustFOV.py +++ b/nipype/interfaces/fsl/tests/test_auto_RobustFOV.py @@ -4,10 +4,22 @@ def test_RobustFOV_inputs(): input_map = dict( - args=dict(argstr="%s",), - brainsize=dict(argstr="-b %d",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=0,), + args=dict( + argstr="%s", + ), + brainsize=dict( + argstr="-b %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=0, + ), out_roi=dict( argstr="-r %s", extensions=None, @@ -33,7 +45,12 @@ def test_RobustFOV_inputs(): def test_RobustFOV_outputs(): output_map = dict( - out_roi=dict(extensions=None,), out_transform=dict(extensions=None,), + out_roi=dict( + extensions=None, + ), + out_transform=dict( + extensions=None, + ), ) outputs = RobustFOV.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_SMM.py b/nipype/interfaces/fsl/tests/test_auto_SMM.py index 2042d0845f..51777eaed9 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SMM.py +++ b/nipype/interfaces/fsl/tests/test_auto_SMM.py @@ -4,8 +4,13 @@ def test_SMM_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), mask=dict( argstr='--mask="%s"', copyfile=False, @@ -13,7 +18,10 @@ def test_SMM_inputs(): mandatory=True, position=1, ), - no_deactivation_class=dict(argstr="--zfstatmode", position=2,), + no_deactivation_class=dict( + argstr="--zfstatmode", + position=2, + ), output_type=dict(), spatial_data_file=dict( argstr='--sdf="%s"', @@ -32,9 +40,15 @@ def test_SMM_inputs(): def test_SMM_outputs(): output_map = dict( - activation_p_map=dict(extensions=None,), - deactivation_p_map=dict(extensions=None,), - null_p_map=dict(extensions=None,), + activation_p_map=dict( + extensions=None, + ), + deactivation_p_map=dict( + extensions=None, + ), + null_p_map=dict( + extensions=None, + ), ) outputs = SMM.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_SUSAN.py b/nipype/interfaces/fsl/tests/test_auto_SUSAN.py index 7f7f270be1..427b770222 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SUSAN.py +++ b/nipype/interfaces/fsl/tests/test_auto_SUSAN.py @@ -4,18 +4,52 @@ def test_SUSAN_inputs(): input_map = dict( - args=dict(argstr="%s",), - brightness_threshold=dict(argstr="%.10f", mandatory=True, position=2,), - dimension=dict(argstr="%d", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - fwhm=dict(argstr="%.10f", mandatory=True, position=3,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=1,), + args=dict( + argstr="%s", + ), + brightness_threshold=dict( + argstr="%.10f", + mandatory=True, + position=2, + ), + dimension=dict( + argstr="%d", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm=dict( + argstr="%.10f", + mandatory=True, + position=3, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-1, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-1, ), output_type=dict(), - usans=dict(argstr="", position=6, usedefault=True,), - use_median=dict(argstr="%d", position=5, usedefault=True,), + usans=dict( + argstr="", + position=6, + usedefault=True, + ), + use_median=dict( + argstr="%d", + position=5, + usedefault=True, + ), ) inputs = SUSAN.input_spec() @@ -25,7 +59,11 @@ def test_SUSAN_inputs(): def test_SUSAN_outputs(): - output_map = dict(smoothed_file=dict(extensions=None,),) + output_map = dict( + smoothed_file=dict( + extensions=None, + ), + ) outputs = SUSAN.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SigLoss.py b/nipype/interfaces/fsl/tests/test_auto_SigLoss.py index fe63fdce23..11be93c5b9 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SigLoss.py +++ b/nipype/interfaces/fsl/tests/test_auto_SigLoss.py @@ -4,14 +4,34 @@ def test_SigLoss_inputs(): input_map = dict( - args=dict(argstr="%s",), - echo_time=dict(argstr="--te=%f",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True,), - mask_file=dict(argstr="-m %s", extensions=None,), - out_file=dict(argstr="-s %s", extensions=None, genfile=True,), + args=dict( + argstr="%s", + ), + echo_time=dict( + argstr="--te=%f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + mask_file=dict( + argstr="-m %s", + extensions=None, + ), + out_file=dict( + argstr="-s %s", + extensions=None, + genfile=True, + ), output_type=dict(), - slice_direction=dict(argstr="-d %s",), + slice_direction=dict( + argstr="-d %s", + ), ) inputs = SigLoss.input_spec() @@ -21,7 +41,11 @@ def test_SigLoss_inputs(): def test_SigLoss_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SigLoss.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Slice.py b/nipype/interfaces/fsl/tests/test_auto_Slice.py index f96ee854b3..f5360716c6 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Slice.py +++ b/nipype/interfaces/fsl/tests/test_auto_Slice.py @@ -4,12 +4,24 @@ def test_Slice_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), in_file=dict( - argstr="%s", copyfile=False, extensions=None, mandatory=True, position=0, + argstr="%s", + copyfile=False, + extensions=None, + mandatory=True, + position=0, + ), + out_base_name=dict( + argstr="%s", + position=1, ), - out_base_name=dict(argstr="%s", position=1,), output_type=dict(), ) inputs = Slice.input_spec() @@ -20,7 +32,9 @@ def test_Slice_inputs(): def test_Slice_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = Slice.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SliceTimer.py b/nipype/interfaces/fsl/tests/test_auto_SliceTimer.py index 0d0c0fc0f4..acdbd8c2ca 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SliceTimer.py +++ b/nipype/interfaces/fsl/tests/test_auto_SliceTimer.py @@ -4,20 +4,49 @@ def test_SliceTimer_inputs(): input_map = dict( - args=dict(argstr="%s",), - custom_order=dict(argstr="--ocustom=%s", extensions=None,), - custom_timings=dict(argstr="--tcustom=%s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - global_shift=dict(argstr="--tglobal",), - in_file=dict(argstr="--in=%s", extensions=None, mandatory=True, position=0,), - index_dir=dict(argstr="--down",), - interleaved=dict(argstr="--odd",), + args=dict( + argstr="%s", + ), + custom_order=dict( + argstr="--ocustom=%s", + extensions=None, + ), + custom_timings=dict( + argstr="--tcustom=%s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + global_shift=dict( + argstr="--tglobal", + ), + in_file=dict( + argstr="--in=%s", + extensions=None, + mandatory=True, + position=0, + ), + index_dir=dict( + argstr="--down", + ), + interleaved=dict( + argstr="--odd", + ), out_file=dict( - argstr="--out=%s", extensions=None, genfile=True, hash_files=False, + argstr="--out=%s", + extensions=None, + genfile=True, + hash_files=False, ), output_type=dict(), - slice_direction=dict(argstr="--direction=%d",), - time_repetition=dict(argstr="--repeat=%f",), + slice_direction=dict( + argstr="--direction=%d", + ), + time_repetition=dict( + argstr="--repeat=%f", + ), ) inputs = SliceTimer.input_spec() @@ -27,7 +56,11 @@ def test_SliceTimer_inputs(): def test_SliceTimer_outputs(): - output_map = dict(slice_time_corrected_file=dict(extensions=None,),) + output_map = dict( + slice_time_corrected_file=dict( + extensions=None, + ), + ) outputs = SliceTimer.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Slicer.py b/nipype/interfaces/fsl/tests/test_auto_Slicer.py index 205aab061b..8e3195fd39 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Slicer.py +++ b/nipype/interfaces/fsl/tests/test_auto_Slicer.py @@ -10,23 +10,61 @@ def test_Slicer_inputs(): requires=["image_width"], xor=("single_slice", "middle_slices", "all_axial", "sample_axial"), ), - args=dict(argstr="%s",), - colour_map=dict(argstr="-l %s", extensions=None, position=4,), - dither_edges=dict(argstr="-t", position=7,), - environ=dict(nohash=True, usedefault=True,), - image_edges=dict(argstr="%s", extensions=None, position=2,), - image_width=dict(argstr="%d", position=-2,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - intensity_range=dict(argstr="-i %.3f %.3f", position=5,), - label_slices=dict(argstr="-L", position=3, usedefault=True,), + args=dict( + argstr="%s", + ), + colour_map=dict( + argstr="-l %s", + extensions=None, + position=4, + ), + dither_edges=dict( + argstr="-t", + position=7, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + image_edges=dict( + argstr="%s", + extensions=None, + position=2, + ), + image_width=dict( + argstr="%d", + position=-2, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + intensity_range=dict( + argstr="-i %.3f %.3f", + position=5, + ), + label_slices=dict( + argstr="-L", + position=3, + usedefault=True, + ), middle_slices=dict( argstr="-a", position=10, xor=("single_slice", "middle_slices", "all_axial", "sample_axial"), ), - nearest_neighbour=dict(argstr="-n", position=8,), + nearest_neighbour=dict( + argstr="-n", + position=8, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-1, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-1, ), output_type=dict(), sample_axial=dict( @@ -35,16 +73,29 @@ def test_Slicer_inputs(): requires=["image_width"], xor=("single_slice", "middle_slices", "all_axial", "sample_axial"), ), - scaling=dict(argstr="-s %f", position=0,), - show_orientation=dict(argstr="%s", position=9, usedefault=True,), + scaling=dict( + argstr="-s %f", + position=0, + ), + show_orientation=dict( + argstr="%s", + position=9, + usedefault=True, + ), single_slice=dict( argstr="-%s", position=10, requires=["slice_number"], xor=("single_slice", "middle_slices", "all_axial", "sample_axial"), ), - slice_number=dict(argstr="-%d", position=11,), - threshold_edges=dict(argstr="-e %.3f", position=6,), + slice_number=dict( + argstr="-%d", + position=11, + ), + threshold_edges=dict( + argstr="-e %.3f", + position=6, + ), ) inputs = Slicer.input_spec() @@ -54,7 +105,11 @@ def test_Slicer_inputs(): def test_Slicer_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Slicer.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Smooth.py b/nipype/interfaces/fsl/tests/test_auto_Smooth.py index 733f0e83f1..9d9324770b 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Smooth.py +++ b/nipype/interfaces/fsl/tests/test_auto_Smooth.py @@ -4,15 +4,25 @@ def test_Smooth_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), fwhm=dict( argstr="-kernel gauss %.03f -fmean", mandatory=True, position=1, xor=["sigma"], ), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), output_type=dict(), sigma=dict( argstr="-kernel gauss %.03f -fmean", @@ -37,7 +47,11 @@ def test_Smooth_inputs(): def test_Smooth_outputs(): - output_map = dict(smoothed_file=dict(extensions=None,),) + output_map = dict( + smoothed_file=dict( + extensions=None, + ), + ) outputs = Smooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SmoothEstimate.py b/nipype/interfaces/fsl/tests/test_auto_SmoothEstimate.py index b6fac84352..bf21438d1d 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SmoothEstimate.py +++ b/nipype/interfaces/fsl/tests/test_auto_SmoothEstimate.py @@ -4,13 +4,34 @@ def test_SmoothEstimate_inputs(): input_map = dict( - args=dict(argstr="%s",), - dof=dict(argstr="--dof=%d", mandatory=True, xor=["zstat_file"],), - environ=dict(nohash=True, usedefault=True,), - mask_file=dict(argstr="--mask=%s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + dof=dict( + argstr="--dof=%d", + mandatory=True, + xor=["zstat_file"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + mask_file=dict( + argstr="--mask=%s", + extensions=None, + mandatory=True, + ), output_type=dict(), - residual_fit_file=dict(argstr="--res=%s", extensions=None, requires=["dof"],), - zstat_file=dict(argstr="--zstat=%s", extensions=None, xor=["dof"],), + residual_fit_file=dict( + argstr="--res=%s", + extensions=None, + requires=["dof"], + ), + zstat_file=dict( + argstr="--zstat=%s", + extensions=None, + xor=["dof"], + ), ) inputs = SmoothEstimate.input_spec() @@ -20,7 +41,11 @@ def test_SmoothEstimate_inputs(): def test_SmoothEstimate_outputs(): - output_map = dict(dlh=dict(), resels=dict(), volume=dict(),) + output_map = dict( + dlh=dict(), + resels=dict(), + volume=dict(), + ) outputs = SmoothEstimate.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SpatialFilter.py b/nipype/interfaces/fsl/tests/test_auto_SpatialFilter.py index ec2b59ba6d..0d6f68cbea 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SpatialFilter.py +++ b/nipype/interfaces/fsl/tests/test_auto_SpatialFilter.py @@ -4,21 +4,58 @@ def test_SpatialFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), kernel_file=dict( - argstr="%s", extensions=None, position=5, xor=["kernel_size"], + argstr="%s", + extensions=None, + position=5, + xor=["kernel_size"], + ), + kernel_shape=dict( + argstr="-kernel %s", + position=4, + ), + kernel_size=dict( + argstr="%.4f", + position=5, + xor=["kernel_file"], + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), + operation=dict( + argstr="-f%s", + mandatory=True, + position=6, ), - kernel_shape=dict(argstr="-kernel %s", position=4,), - kernel_size=dict(argstr="%.4f", position=5, xor=["kernel_file"],), - nan2zeros=dict(argstr="-nan", position=3,), - operation=dict(argstr="-f%s", mandatory=True, position=6,), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = SpatialFilter.input_spec() @@ -29,7 +66,11 @@ def test_SpatialFilter_inputs(): def test_SpatialFilter_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SpatialFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Split.py b/nipype/interfaces/fsl/tests/test_auto_Split.py index 26b814b9c0..79aa3a7ade 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Split.py +++ b/nipype/interfaces/fsl/tests/test_auto_Split.py @@ -4,11 +4,28 @@ def test_Split_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%s", mandatory=True, position=2,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), - out_base_name=dict(argstr="%s", position=1,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%s", + mandatory=True, + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + out_base_name=dict( + argstr="%s", + position=1, + ), output_type=dict(), ) inputs = Split.input_spec() @@ -19,7 +36,9 @@ def test_Split_inputs(): def test_Split_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = Split.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_StdImage.py b/nipype/interfaces/fsl/tests/test_auto_StdImage.py index 073ebfa7ee..226abb5e5e 100644 --- a/nipype/interfaces/fsl/tests/test_auto_StdImage.py +++ b/nipype/interfaces/fsl/tests/test_auto_StdImage.py @@ -4,16 +4,43 @@ def test_StdImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(argstr="-%sstd", position=4, usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + dimension=dict( + argstr="-%sstd", + position=4, + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = StdImage.input_spec() @@ -24,7 +51,11 @@ def test_StdImage_inputs(): def test_StdImage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = StdImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_SwapDimensions.py b/nipype/interfaces/fsl/tests/test_auto_SwapDimensions.py index ac56fad17e..26b3b3ff54 100644 --- a/nipype/interfaces/fsl/tests/test_auto_SwapDimensions.py +++ b/nipype/interfaces/fsl/tests/test_auto_SwapDimensions.py @@ -4,11 +4,29 @@ def test_SwapDimensions_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position="1",), - new_dims=dict(argstr="%s %s %s", mandatory=True,), - out_file=dict(argstr="%s", extensions=None, genfile=True, hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position="1", + ), + new_dims=dict( + argstr="%s %s %s", + mandatory=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + ), output_type=dict(), ) inputs = SwapDimensions.input_spec() @@ -19,7 +37,11 @@ def test_SwapDimensions_inputs(): def test_SwapDimensions_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SwapDimensions.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_TOPUP.py b/nipype/interfaces/fsl/tests/test_auto_TOPUP.py index f34023f799..3358190dfb 100644 --- a/nipype/interfaces/fsl/tests/test_auto_TOPUP.py +++ b/nipype/interfaces/fsl/tests/test_auto_TOPUP.py @@ -4,8 +4,13 @@ def test_TOPUP_inputs(): input_map = dict( - args=dict(argstr="%s",), - config=dict(argstr="--config=%s", usedefault=True,), + args=dict( + argstr="%s", + ), + config=dict( + argstr="--config=%s", + usedefault=True, + ), encoding_direction=dict( argstr="--datain=%s", mandatory=True, @@ -18,14 +23,33 @@ def test_TOPUP_inputs(): mandatory=True, xor=["encoding_direction"], ), - environ=dict(nohash=True, usedefault=True,), - estmov=dict(argstr="--estmov=%d",), - fwhm=dict(argstr="--fwhm=%f",), - in_file=dict(argstr="--imain=%s", extensions=None, mandatory=True,), - interp=dict(argstr="--interp=%s",), - max_iter=dict(argstr="--miter=%d",), - minmet=dict(argstr="--minmet=%d",), - numprec=dict(argstr="--numprec=%s",), + environ=dict( + nohash=True, + usedefault=True, + ), + estmov=dict( + argstr="--estmov=%d", + ), + fwhm=dict( + argstr="--fwhm=%f", + ), + in_file=dict( + argstr="--imain=%s", + extensions=None, + mandatory=True, + ), + interp=dict( + argstr="--interp=%s", + ), + max_iter=dict( + argstr="--miter=%d", + ), + minmet=dict( + argstr="--minmet=%d", + ), + numprec=dict( + argstr="--numprec=%s", + ), out_base=dict( argstr="--out=%s", extensions=None, @@ -47,7 +71,11 @@ def test_TOPUP_inputs(): name_source=["in_file"], name_template="%s_field", ), - out_jac_prefix=dict(argstr="--jacout=%s", hash_files=False, usedefault=True,), + out_jac_prefix=dict( + argstr="--jacout=%s", + hash_files=False, + usedefault=True, + ), out_logfile=dict( argstr="--logout=%s", extensions=None, @@ -56,20 +84,46 @@ def test_TOPUP_inputs(): name_source=["in_file"], name_template="%s_topup.log", ), - out_mat_prefix=dict(argstr="--rbmout=%s", hash_files=False, usedefault=True,), - out_warp_prefix=dict(argstr="--dfout=%s", hash_files=False, usedefault=True,), + out_mat_prefix=dict( + argstr="--rbmout=%s", + hash_files=False, + usedefault=True, + ), + out_warp_prefix=dict( + argstr="--dfout=%s", + hash_files=False, + usedefault=True, + ), output_type=dict(), readout_times=dict( - mandatory=True, requires=["encoding_direction"], xor=["encoding_file"], - ), - reg_lambda=dict(argstr="--lambda=%0.f",), - regmod=dict(argstr="--regmod=%s",), - regrid=dict(argstr="--regrid=%d",), - scale=dict(argstr="--scale=%d",), - splineorder=dict(argstr="--splineorder=%d",), - ssqlambda=dict(argstr="--ssqlambda=%d",), - subsamp=dict(argstr="--subsamp=%d",), - warp_res=dict(argstr="--warpres=%f",), + mandatory=True, + requires=["encoding_direction"], + xor=["encoding_file"], + ), + reg_lambda=dict( + argstr="--lambda=%0.f", + ), + regmod=dict( + argstr="--regmod=%s", + ), + regrid=dict( + argstr="--regrid=%d", + ), + scale=dict( + argstr="--scale=%d", + ), + splineorder=dict( + argstr="--splineorder=%d", + ), + ssqlambda=dict( + argstr="--ssqlambda=%d", + ), + subsamp=dict( + argstr="--subsamp=%d", + ), + warp_res=dict( + argstr="--warpres=%f", + ), ) inputs = TOPUP.input_spec() @@ -80,14 +134,26 @@ def test_TOPUP_inputs(): def test_TOPUP_outputs(): output_map = dict( - out_corrected=dict(extensions=None,), - out_enc_file=dict(extensions=None,), - out_field=dict(extensions=None,), - out_fieldcoef=dict(extensions=None,), + out_corrected=dict( + extensions=None, + ), + out_enc_file=dict( + extensions=None, + ), + out_field=dict( + extensions=None, + ), + out_fieldcoef=dict( + extensions=None, + ), out_jacs=dict(), - out_logfile=dict(extensions=None,), + out_logfile=dict( + extensions=None, + ), out_mats=dict(), - out_movpar=dict(extensions=None,), + out_movpar=dict( + extensions=None, + ), out_warps=dict(), ) outputs = TOPUP.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_TemporalFilter.py b/nipype/interfaces/fsl/tests/test_auto_TemporalFilter.py index a764c6c1a6..3a825e4e45 100644 --- a/nipype/interfaces/fsl/tests/test_auto_TemporalFilter.py +++ b/nipype/interfaces/fsl/tests/test_auto_TemporalFilter.py @@ -4,17 +4,48 @@ def test_TemporalFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - highpass_sigma=dict(argstr="-bptf %.6f", position=4, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - lowpass_sigma=dict(argstr="%.6f", position=5, usedefault=True,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + highpass_sigma=dict( + argstr="-bptf %.6f", + position=4, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + lowpass_sigma=dict( + argstr="%.6f", + position=5, + usedefault=True, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = TemporalFilter.input_spec() @@ -25,7 +56,11 @@ def test_TemporalFilter_inputs(): def test_TemporalFilter_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TemporalFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Text2Vest.py b/nipype/interfaces/fsl/tests/test_auto_Text2Vest.py new file mode 100644 index 0000000000..fdc39356a9 --- /dev/null +++ b/nipype/interfaces/fsl/tests/test_auto_Text2Vest.py @@ -0,0 +1,45 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import Text2Vest + + +def test_Text2Vest_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + output_type=dict(), + ) + inputs = Text2Vest.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_Text2Vest_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = Text2Vest.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/fsl/tests/test_auto_Threshold.py b/nipype/interfaces/fsl/tests/test_auto_Threshold.py index 4156b8f82b..cc3446bd47 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Threshold.py +++ b/nipype/interfaces/fsl/tests/test_auto_Threshold.py @@ -4,19 +4,50 @@ def test_Threshold_inputs(): input_map = dict( - args=dict(argstr="%s",), - direction=dict(usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), + args=dict( + argstr="%s", + ), + direction=dict( + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), - thresh=dict(argstr="%s", mandatory=True, position=4,), - use_nonzero_voxels=dict(requires=["use_robust_range"],), + thresh=dict( + argstr="%s", + mandatory=True, + position=4, + ), + use_nonzero_voxels=dict( + requires=["use_robust_range"], + ), use_robust_range=dict(), ) inputs = Threshold.input_spec() @@ -27,7 +58,11 @@ def test_Threshold_inputs(): def test_Threshold_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Threshold.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_TractSkeleton.py b/nipype/interfaces/fsl/tests/test_auto_TractSkeleton.py index f5c6c38f35..631741da49 100644 --- a/nipype/interfaces/fsl/tests/test_auto_TractSkeleton.py +++ b/nipype/interfaces/fsl/tests/test_auto_TractSkeleton.py @@ -4,23 +4,52 @@ def test_TractSkeleton_inputs(): input_map = dict( - alt_data_file=dict(argstr="-a %s", extensions=None,), - alt_skeleton=dict(argstr="-s %s", extensions=None,), - args=dict(argstr="%s",), - data_file=dict(extensions=None,), - distance_map=dict(extensions=None,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True,), + alt_data_file=dict( + argstr="-a %s", + extensions=None, + ), + alt_skeleton=dict( + argstr="-s %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + data_file=dict( + extensions=None, + ), + distance_map=dict( + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), output_type=dict(), project_data=dict( argstr="-p %.3f %s %s %s %s", requires=["threshold", "distance_map", "data_file"], ), - projected_data=dict(extensions=None,), - search_mask_file=dict(extensions=None, xor=["use_cingulum_mask"],), - skeleton_file=dict(argstr="-o %s",), + projected_data=dict( + extensions=None, + ), + search_mask_file=dict( + extensions=None, + xor=["use_cingulum_mask"], + ), + skeleton_file=dict( + argstr="-o %s", + ), threshold=dict(), - use_cingulum_mask=dict(usedefault=True, xor=["search_mask_file"],), + use_cingulum_mask=dict( + usedefault=True, + xor=["search_mask_file"], + ), ) inputs = TractSkeleton.input_spec() @@ -31,7 +60,12 @@ def test_TractSkeleton_inputs(): def test_TractSkeleton_outputs(): output_map = dict( - projected_data=dict(extensions=None,), skeleton_file=dict(extensions=None,), + projected_data=dict( + extensions=None, + ), + skeleton_file=dict( + extensions=None, + ), ) outputs = TractSkeleton.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_Training.py b/nipype/interfaces/fsl/tests/test_auto_Training.py index 5626f3e483..82a53d1408 100644 --- a/nipype/interfaces/fsl/tests/test_auto_Training.py +++ b/nipype/interfaces/fsl/tests/test_auto_Training.py @@ -4,11 +4,26 @@ def test_Training_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - loo=dict(argstr="-l", position=2,), - mel_icas=dict(argstr="%s", copyfile=False, position=-1,), - trained_wts_filestem=dict(argstr="%s", position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + loo=dict( + argstr="-l", + position=2, + ), + mel_icas=dict( + argstr="%s", + copyfile=False, + position=-1, + ), + trained_wts_filestem=dict( + argstr="%s", + position=1, + ), ) inputs = Training.input_spec() @@ -18,7 +33,11 @@ def test_Training_inputs(): def test_Training_outputs(): - output_map = dict(trained_wts_file=dict(extensions=None,),) + output_map = dict( + trained_wts_file=dict( + extensions=None, + ), + ) outputs = Training.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_TrainingSetCreator.py b/nipype/interfaces/fsl/tests/test_auto_TrainingSetCreator.py index df4c1c2257..3ab307d6a8 100644 --- a/nipype/interfaces/fsl/tests/test_auto_TrainingSetCreator.py +++ b/nipype/interfaces/fsl/tests/test_auto_TrainingSetCreator.py @@ -3,7 +3,13 @@ def test_TrainingSetCreator_inputs(): - input_map = dict(mel_icas_in=dict(argstr="%s", copyfile=False, position=-1,),) + input_map = dict( + mel_icas_in=dict( + argstr="%s", + copyfile=False, + position=-1, + ), + ) inputs = TrainingSetCreator.input_spec() for key, metadata in list(input_map.items()): @@ -12,7 +18,13 @@ def test_TrainingSetCreator_inputs(): def test_TrainingSetCreator_outputs(): - output_map = dict(mel_icas_out=dict(argstr="%s", copyfile=False, position=-1,),) + output_map = dict( + mel_icas_out=dict( + argstr="%s", + copyfile=False, + position=-1, + ), + ) outputs = TrainingSetCreator.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_UnaryMaths.py b/nipype/interfaces/fsl/tests/test_auto_UnaryMaths.py index 67662a8c7f..cb27a76876 100644 --- a/nipype/interfaces/fsl/tests/test_auto_UnaryMaths.py +++ b/nipype/interfaces/fsl/tests/test_auto_UnaryMaths.py @@ -4,16 +4,43 @@ def test_UnaryMaths_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - internal_datatype=dict(argstr="-dt %s", position=1,), - nan2zeros=dict(argstr="-nan", position=3,), - operation=dict(argstr="-%s", mandatory=True, position=4,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + internal_datatype=dict( + argstr="-dt %s", + position=1, + ), + nan2zeros=dict( + argstr="-nan", + position=3, + ), + operation=dict( + argstr="-%s", + mandatory=True, + position=4, + ), out_file=dict( - argstr="%s", extensions=None, genfile=True, hash_files=False, position=-2, + argstr="%s", + extensions=None, + genfile=True, + hash_files=False, + position=-2, + ), + output_datatype=dict( + argstr="-odt %s", + position=-1, ), - output_datatype=dict(argstr="-odt %s", position=-1,), output_type=dict(), ) inputs = UnaryMaths.input_spec() @@ -24,7 +51,11 @@ def test_UnaryMaths_inputs(): def test_UnaryMaths_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = UnaryMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_VecReg.py b/nipype/interfaces/fsl/tests/test_auto_VecReg.py index 4f802628cd..9564241cc3 100644 --- a/nipype/interfaces/fsl/tests/test_auto_VecReg.py +++ b/nipype/interfaces/fsl/tests/test_auto_VecReg.py @@ -4,19 +4,57 @@ def test_VecReg_inputs(): input_map = dict( - affine_mat=dict(argstr="-t %s", extensions=None,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True,), - interpolation=dict(argstr="--interp=%s",), - mask=dict(argstr="-m %s", extensions=None,), - out_file=dict(argstr="-o %s", extensions=None, genfile=True, hash_files=False,), + affine_mat=dict( + argstr="-t %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + interpolation=dict( + argstr="--interp=%s", + ), + mask=dict( + argstr="-m %s", + extensions=None, + ), + out_file=dict( + argstr="-o %s", + extensions=None, + genfile=True, + hash_files=False, + ), output_type=dict(), - ref_mask=dict(argstr="--refmask=%s", extensions=None,), - ref_vol=dict(argstr="-r %s", extensions=None, mandatory=True,), - rotation_mat=dict(argstr="--rotmat=%s", extensions=None,), - rotation_warp=dict(argstr="--rotwarp=%s", extensions=None,), - warp_field=dict(argstr="-w %s", extensions=None,), + ref_mask=dict( + argstr="--refmask=%s", + extensions=None, + ), + ref_vol=dict( + argstr="-r %s", + extensions=None, + mandatory=True, + ), + rotation_mat=dict( + argstr="--rotmat=%s", + extensions=None, + ), + rotation_warp=dict( + argstr="--rotwarp=%s", + extensions=None, + ), + warp_field=dict( + argstr="-w %s", + extensions=None, + ), ) inputs = VecReg.input_spec() @@ -26,7 +64,11 @@ def test_VecReg_inputs(): def test_VecReg_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = VecReg.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_Vest2Text.py b/nipype/interfaces/fsl/tests/test_auto_Vest2Text.py new file mode 100644 index 0000000000..2732e95d12 --- /dev/null +++ b/nipype/interfaces/fsl/tests/test_auto_Vest2Text.py @@ -0,0 +1,45 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import Vest2Text + + +def test_Vest2Text_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + out_file=dict( + argstr="%s", + extensions=None, + position=1, + usedefault=True, + ), + output_type=dict(), + ) + inputs = Vest2Text.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_Vest2Text_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = Vest2Text.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/fsl/tests/test_auto_WarpPoints.py b/nipype/interfaces/fsl/tests/test_auto_WarpPoints.py index 70980aa1be..b7f7fc7d87 100644 --- a/nipype/interfaces/fsl/tests/test_auto_WarpPoints.py +++ b/nipype/interfaces/fsl/tests/test_auto_WarpPoints.py @@ -4,21 +4,53 @@ def test_WarpPoints_inputs(): input_map = dict( - args=dict(argstr="%s",), - coord_mm=dict(argstr="-mm", xor=["coord_vox"],), - coord_vox=dict(argstr="-vox", xor=["coord_mm"],), - dest_file=dict(argstr="-dest %s", extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - in_coords=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), + args=dict( + argstr="%s", + ), + coord_mm=dict( + argstr="-mm", + xor=["coord_vox"], + ), + coord_vox=dict( + argstr="-vox", + xor=["coord_mm"], + ), + dest_file=dict( + argstr="-dest %s", + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_coords=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), out_file=dict( extensions=None, name_source="in_coords", name_template="%s_warped", output_name="out_file", ), - src_file=dict(argstr="-src %s", extensions=None, mandatory=True,), - warp_file=dict(argstr="-warp %s", extensions=None, xor=["xfm_file"],), - xfm_file=dict(argstr="-xfm %s", extensions=None, xor=["warp_file"],), + src_file=dict( + argstr="-src %s", + extensions=None, + mandatory=True, + ), + warp_file=dict( + argstr="-warp %s", + extensions=None, + xor=["xfm_file"], + ), + xfm_file=dict( + argstr="-xfm %s", + extensions=None, + xor=["warp_file"], + ), ) inputs = WarpPoints.input_spec() @@ -28,7 +60,11 @@ def test_WarpPoints_inputs(): def test_WarpPoints_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = WarpPoints.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_WarpPointsFromStd.py b/nipype/interfaces/fsl/tests/test_auto_WarpPointsFromStd.py index a6fa949890..b8f4cbef97 100644 --- a/nipype/interfaces/fsl/tests/test_auto_WarpPointsFromStd.py +++ b/nipype/interfaces/fsl/tests/test_auto_WarpPointsFromStd.py @@ -4,15 +4,47 @@ def test_WarpPointsFromStd_inputs(): input_map = dict( - args=dict(argstr="%s",), - coord_mm=dict(argstr="-mm", xor=["coord_vox"],), - coord_vox=dict(argstr="-vox", xor=["coord_mm"],), - environ=dict(nohash=True, usedefault=True,), - img_file=dict(argstr="-img %s", extensions=None, mandatory=True,), - in_coords=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - std_file=dict(argstr="-std %s", extensions=None, mandatory=True,), - warp_file=dict(argstr="-warp %s", extensions=None, xor=["xfm_file"],), - xfm_file=dict(argstr="-xfm %s", extensions=None, xor=["warp_file"],), + args=dict( + argstr="%s", + ), + coord_mm=dict( + argstr="-mm", + xor=["coord_vox"], + ), + coord_vox=dict( + argstr="-vox", + xor=["coord_mm"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + img_file=dict( + argstr="-img %s", + extensions=None, + mandatory=True, + ), + in_coords=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + std_file=dict( + argstr="-std %s", + extensions=None, + mandatory=True, + ), + warp_file=dict( + argstr="-warp %s", + extensions=None, + xor=["xfm_file"], + ), + xfm_file=dict( + argstr="-xfm %s", + extensions=None, + xor=["warp_file"], + ), ) inputs = WarpPointsFromStd.input_spec() @@ -22,7 +54,11 @@ def test_WarpPointsFromStd_inputs(): def test_WarpPointsFromStd_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = WarpPointsFromStd.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py b/nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py index 9debbe6a74..0b5881c776 100644 --- a/nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py +++ b/nipype/interfaces/fsl/tests/test_auto_WarpPointsToStd.py @@ -4,22 +4,57 @@ def test_WarpPointsToStd_inputs(): input_map = dict( - args=dict(argstr="%s",), - coord_mm=dict(argstr="-mm", xor=["coord_vox"],), - coord_vox=dict(argstr="-vox", xor=["coord_mm"],), - environ=dict(nohash=True, usedefault=True,), - img_file=dict(argstr="-img %s", extensions=None, mandatory=True,), - in_coords=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), + args=dict( + argstr="%s", + ), + coord_mm=dict( + argstr="-mm", + xor=["coord_vox"], + ), + coord_vox=dict( + argstr="-vox", + xor=["coord_mm"], + ), + environ=dict( + nohash=True, + usedefault=True, + ), + img_file=dict( + argstr="-img %s", + extensions=None, + mandatory=True, + ), + in_coords=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), out_file=dict( extensions=None, name_source="in_coords", name_template="%s_warped", output_name="out_file", ), - premat_file=dict(argstr="-premat %s", extensions=None,), - std_file=dict(argstr="-std %s", extensions=None, mandatory=True,), - warp_file=dict(argstr="-warp %s", extensions=None, xor=["xfm_file"],), - xfm_file=dict(argstr="-xfm %s", extensions=None, xor=["warp_file"],), + premat_file=dict( + argstr="-premat %s", + extensions=None, + ), + std_file=dict( + argstr="-std %s", + extensions=None, + mandatory=True, + ), + warp_file=dict( + argstr="-warp %s", + extensions=None, + xor=["xfm_file"], + ), + xfm_file=dict( + argstr="-xfm %s", + extensions=None, + xor=["warp_file"], + ), ) inputs = WarpPointsToStd.input_spec() @@ -29,7 +64,11 @@ def test_WarpPointsToStd_inputs(): def test_WarpPointsToStd_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = WarpPointsToStd.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/fsl/tests/test_auto_WarpUtils.py b/nipype/interfaces/fsl/tests/test_auto_WarpUtils.py index cdb0e86e64..c8caa8da84 100644 --- a/nipype/interfaces/fsl/tests/test_auto_WarpUtils.py +++ b/nipype/interfaces/fsl/tests/test_auto_WarpUtils.py @@ -4,10 +4,21 @@ def test_WarpUtils_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="--in=%s", extensions=None, mandatory=True,), - knot_space=dict(argstr="--knotspace=%d,%d,%d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="--in=%s", + extensions=None, + mandatory=True, + ), + knot_space=dict( + argstr="--knotspace=%d,%d,%d", + ), out_file=dict( argstr="--out=%s", extensions=None, @@ -15,13 +26,29 @@ def test_WarpUtils_inputs(): output_name="out_file", position=-1, ), - out_format=dict(argstr="--outformat=%s",), - out_jacobian=dict(argstr="--jac=%s", extensions=None,), + out_format=dict( + argstr="--outformat=%s", + ), + out_jacobian=dict( + argstr="--jac=%s", + extensions=None, + ), output_type=dict(), - reference=dict(argstr="--ref=%s", extensions=None, mandatory=True,), - warp_resolution=dict(argstr="--warpres=%0.4f,%0.4f,%0.4f",), - with_affine=dict(argstr="--withaff",), - write_jacobian=dict(mandatory=True, usedefault=True,), + reference=dict( + argstr="--ref=%s", + extensions=None, + mandatory=True, + ), + warp_resolution=dict( + argstr="--warpres=%0.4f,%0.4f,%0.4f", + ), + with_affine=dict( + argstr="--withaff", + ), + write_jacobian=dict( + mandatory=True, + usedefault=True, + ), ) inputs = WarpUtils.input_spec() @@ -32,7 +59,12 @@ def test_WarpUtils_inputs(): def test_WarpUtils_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_jacobian=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_jacobian=dict( + extensions=None, + ), ) outputs = WarpUtils.output_spec() diff --git a/nipype/interfaces/fsl/tests/test_auto_XFibres5.py b/nipype/interfaces/fsl/tests/test_auto_XFibres5.py index 9a4e973569..349b2f52e7 100644 --- a/nipype/interfaces/fsl/tests/test_auto_XFibres5.py +++ b/nipype/interfaces/fsl/tests/test_auto_XFibres5.py @@ -4,37 +4,111 @@ def test_XFibres5_inputs(): input_map = dict( - all_ard=dict(argstr="--allard", xor=("no_ard", "all_ard"),), - args=dict(argstr="%s",), - burn_in=dict(argstr="--burnin=%d", usedefault=True,), - burn_in_no_ard=dict(argstr="--burnin_noard=%d", usedefault=True,), - bvals=dict(argstr="--bvals=%s", extensions=None, mandatory=True,), - bvecs=dict(argstr="--bvecs=%s", extensions=None, mandatory=True,), + all_ard=dict( + argstr="--allard", + xor=("no_ard", "all_ard"), + ), + args=dict( + argstr="%s", + ), + burn_in=dict( + argstr="--burnin=%d", + usedefault=True, + ), + burn_in_no_ard=dict( + argstr="--burnin_noard=%d", + usedefault=True, + ), + bvals=dict( + argstr="--bvals=%s", + extensions=None, + mandatory=True, + ), + bvecs=dict( + argstr="--bvecs=%s", + extensions=None, + mandatory=True, + ), cnlinear=dict( - argstr="--cnonlinear", xor=("no_spat", "non_linear", "cnlinear"), - ), - dwi=dict(argstr="--data=%s", extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - f0_ard=dict(argstr="--f0 --ardf0", xor=["f0_noard", "f0_ard", "all_ard"],), - f0_noard=dict(argstr="--f0", xor=["f0_noard", "f0_ard"],), - force_dir=dict(argstr="--forcedir", usedefault=True,), - fudge=dict(argstr="--fudge=%d",), - gradnonlin=dict(argstr="--gradnonlin=%s", extensions=None,), - logdir=dict(argstr="--logdir=%s", usedefault=True,), - mask=dict(argstr="--mask=%s", extensions=None, mandatory=True,), - model=dict(argstr="--model=%d",), - n_fibres=dict(argstr="--nfibres=%d", mandatory=True, usedefault=True,), - n_jumps=dict(argstr="--njumps=%d", usedefault=True,), - no_ard=dict(argstr="--noard", xor=("no_ard", "all_ard"),), - no_spat=dict(argstr="--nospat", xor=("no_spat", "non_linear", "cnlinear"),), + argstr="--cnonlinear", + xor=("no_spat", "non_linear", "cnlinear"), + ), + dwi=dict( + argstr="--data=%s", + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + f0_ard=dict( + argstr="--f0 --ardf0", + xor=["f0_noard", "f0_ard", "all_ard"], + ), + f0_noard=dict( + argstr="--f0", + xor=["f0_noard", "f0_ard"], + ), + force_dir=dict( + argstr="--forcedir", + usedefault=True, + ), + fudge=dict( + argstr="--fudge=%d", + ), + gradnonlin=dict( + argstr="--gradnonlin=%s", + extensions=None, + ), + logdir=dict( + argstr="--logdir=%s", + usedefault=True, + ), + mask=dict( + argstr="--mask=%s", + extensions=None, + mandatory=True, + ), + model=dict( + argstr="--model=%d", + ), + n_fibres=dict( + argstr="--nfibres=%d", + mandatory=True, + usedefault=True, + ), + n_jumps=dict( + argstr="--njumps=%d", + usedefault=True, + ), + no_ard=dict( + argstr="--noard", + xor=("no_ard", "all_ard"), + ), + no_spat=dict( + argstr="--nospat", + xor=("no_spat", "non_linear", "cnlinear"), + ), non_linear=dict( - argstr="--nonlinear", xor=("no_spat", "non_linear", "cnlinear"), + argstr="--nonlinear", + xor=("no_spat", "non_linear", "cnlinear"), ), output_type=dict(), - rician=dict(argstr="--rician",), - sample_every=dict(argstr="--sampleevery=%d", usedefault=True,), - seed=dict(argstr="--seed=%d",), - update_proposal_every=dict(argstr="--updateproposalevery=%d", usedefault=True,), + rician=dict( + argstr="--rician", + ), + sample_every=dict( + argstr="--sampleevery=%d", + usedefault=True, + ), + seed=dict( + argstr="--seed=%d", + ), + update_proposal_every=dict( + argstr="--updateproposalevery=%d", + usedefault=True, + ), ) inputs = XFibres5.input_spec() @@ -47,10 +121,16 @@ def test_XFibres5_outputs(): output_map = dict( dyads=dict(), fsamples=dict(), - mean_S0samples=dict(extensions=None,), - mean_dsamples=dict(extensions=None,), + mean_S0samples=dict( + extensions=None, + ), + mean_dsamples=dict( + extensions=None, + ), mean_fsamples=dict(), - mean_tausamples=dict(extensions=None,), + mean_tausamples=dict( + extensions=None, + ), phsamples=dict(), thsamples=dict(), ) diff --git a/nipype/interfaces/fsl/tests/test_base.py b/nipype/interfaces/fsl/tests/test_base.py index 52f93b545f..1a76d0f6a5 100644 --- a/nipype/interfaces/fsl/tests/test_base.py +++ b/nipype/interfaces/fsl/tests/test_base.py @@ -1,11 +1,10 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os import nipype.interfaces.fsl as fsl from nipype.interfaces.base import InterfaceResult -from nipype.interfaces.fsl import check_fsl, no_fsl +from nipype.interfaces.fsl import no_fsl import pytest @@ -13,8 +12,7 @@ @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") def test_fslversion(): ver = fsl.Info.version() - ver = ver.split(".") - assert ver[0] in ["4", "5"] + assert ver.split(".", 1)[0].isdigit() @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -39,7 +37,7 @@ def test_FSLCommand(): # testing the one item that is not. cmd = fsl.FSLCommand(command="ls") res = cmd.run() - assert type(res) == InterfaceResult + assert type(res) is InterfaceResult @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") @@ -81,7 +79,7 @@ def test_gen_fname(args, desired_name): cmd = fsl.FSLCommand(command="junk", output_type="NIFTI_GZ") pth = os.getcwd() fname = cmd._gen_fname("foo.nii.gz", **args) - if "dir" in desired_name.keys(): + if "dir" in desired_name: desired = os.path.join(desired_name["dir"], desired_name["file"]) else: desired = os.path.join(pth, desired_name["file"]) diff --git a/nipype/interfaces/fsl/tests/test_dti.py b/nipype/interfaces/fsl/tests/test_dti.py index 8f5abfc662..05b2caa0bb 100644 --- a/nipype/interfaces/fsl/tests/test_dti.py +++ b/nipype/interfaces/fsl/tests/test_dti.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -41,7 +40,6 @@ def test_dtifit2(create_files_in_directory): @pytest.mark.xfail(reason="These tests are skipped until we clean up some of this code") def test_randomise2(): - rand = fsl.Randomise() # make sure command gets called @@ -137,7 +135,7 @@ def test_Randomise_parallel(): rand.inputs.t_contrast = "infile.con" actualCmdline = sorted(rand.cmdline.split()) - cmd = "randomise_parallel -i infile.nii -o outfile -d design.mat -t " "infile.con" + cmd = "randomise_parallel -i infile.nii -o outfile -d design.mat -t infile.con" desiredCmdline = sorted(cmd.split()) assert actualCmdline == desiredCmdline @@ -233,7 +231,6 @@ def test_Proj_thresh(): # test vec_reg @pytest.mark.xfail(reason="These tests are skipped until we clean up some of this code") def test_Vec_reg(): - vrg = fsl.VecReg() # make sure command gets called @@ -373,7 +370,7 @@ def test_tbss_skeleton(create_files_in_directory): bones.inputs.data_file = "b.nii" # Even though that's silly # Now we get a command line - assert bones.cmdline == "tbss_skeleton -i a.nii -p 0.200 b.nii %s b.nii %s" % ( + assert bones.cmdline == "tbss_skeleton -i a.nii -p 0.200 b.nii {} b.nii {}".format( Info.standard_image("LowerCingulum_1mm.nii.gz"), os.path.join(newdir, "b_skeletonised.nii"), ) @@ -411,7 +408,7 @@ def test_distancemap(create_files_in_directory): # And we should be able to write out a maxima map mapper.inputs.local_max_file = True - assert mapper.cmdline == "distancemap --out=%s --in=a.nii --localmax=%s" % ( + assert mapper.cmdline == "distancemap --out={} --in=a.nii --localmax={}".format( os.path.join(newdir, "a_dstmap.nii"), os.path.join(newdir, "a_lclmax.nii"), ) diff --git a/nipype/interfaces/fsl/tests/test_epi.py b/nipype/interfaces/fsl/tests/test_epi.py index e8f408de45..715da57f7d 100644 --- a/nipype/interfaces/fsl/tests/test_epi.py +++ b/nipype/interfaces/fsl/tests/test_epi.py @@ -1,7 +1,5 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -import os import pytest from nipype.testing.fixtures import create_files_in_directory diff --git a/nipype/interfaces/fsl/tests/test_maths.py b/nipype/interfaces/fsl/tests/test_maths.py index 9b05645997..189fff8b3f 100644 --- a/nipype/interfaces/fsl/tests/test_maths.py +++ b/nipype/interfaces/fsl/tests/test_maths.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -28,10 +27,10 @@ def test_maths_base(create_files_in_directory_plus_output_type): # Set an in file maths.inputs.in_file = "a.nii" - out_file = "a_maths{}".format(out_ext) + out_file = f"a_maths{out_ext}" # Now test the most basic command line - assert maths.cmdline == "fslmaths a.nii {}".format(os.path.join(testdir, out_file)) + assert maths.cmdline == f"fslmaths a.nii {os.path.join(testdir, out_file)}" # Now test that we can set the various data types dtypes = ["float", "char", "int", "short", "double", "input"] @@ -103,9 +102,9 @@ def test_threshold(create_files_in_directory_plus_output_type): cmdline = "fslmaths a.nii {} b.nii" for val in [0, 0.0, -1, -1.5, -0.5, 0.5, 3, 400, 400.5]: thresh.inputs.thresh = val - assert thresh.cmdline == cmdline.format("-thr {:.10f}".format(val)) + assert thresh.cmdline == cmdline.format(f"-thr {val:.10f}") - val = "{:.10f}".format(42) + val = f"{42:.10f}" thresh = fsl.Threshold( in_file="a.nii", out_file="b.nii", thresh=42, use_robust_range=True ) @@ -132,7 +131,7 @@ def test_meanimage(create_files_in_directory_plus_output_type): # Test the underlying command assert meaner.cmd == "fslmaths" - # Test the defualt opstring + # Test the default opstring assert meaner.cmdline == "fslmaths a.nii -Tmean b.nii" # Test the other dimensions @@ -144,7 +143,7 @@ def test_meanimage(create_files_in_directory_plus_output_type): # Test the auto naming meaner = fsl.MeanImage(in_file="a.nii") assert meaner.cmdline == "fslmaths a.nii -Tmean {}".format( - os.path.join(testdir, "a_mean{}".format(out_ext)) + os.path.join(testdir, f"a_mean{out_ext}") ) @@ -158,7 +157,7 @@ def test_stdimage(create_files_in_directory_plus_output_type): # Test the underlying command assert stder.cmd == "fslmaths" - # Test the defualt opstring + # Test the default opstring assert stder.cmdline == "fslmaths a.nii -Tstd b.nii" # Test the other dimensions @@ -184,7 +183,7 @@ def test_maximage(create_files_in_directory_plus_output_type): # Test the underlying command assert maxer.cmd == "fslmaths" - # Test the defualt opstring + # Test the default opstring assert maxer.cmdline == "fslmaths a.nii -Tmax b.nii" # Test the other dimensions @@ -196,7 +195,7 @@ def test_maximage(create_files_in_directory_plus_output_type): # Test the auto naming maxer = fsl.MaxImage(in_file="a.nii") assert maxer.cmdline == "fslmaths a.nii -Tmax {}".format( - os.path.join(testdir, "a_max{}".format(out_ext)) + os.path.join(testdir, f"a_max{out_ext}") ) @@ -226,7 +225,7 @@ def test_smooth(create_files_in_directory_plus_output_type): # Test automatic naming smoother = fsl.IsotropicSmooth(in_file="a.nii", sigma=5) assert smoother.cmdline == "fslmaths a.nii -s {:.5f} {}".format( - 5, os.path.join(testdir, "a_smooth{}".format(out_ext)) + 5, os.path.join(testdir, f"a_smooth{out_ext}") ) @@ -251,7 +250,7 @@ def test_mask(create_files_in_directory_plus_output_type): # Test auto name generation masker = fsl.ApplyMask(in_file="a.nii", mask_file="b.nii") assert masker.cmdline == "fslmaths a.nii -mas b.nii " + os.path.join( - testdir, "a_masked{}".format(out_ext) + testdir, f"a_masked{out_ext}" ) @@ -273,7 +272,7 @@ def test_dilation(create_files_in_directory_plus_output_type): for op in ["mean", "modal", "max"]: cv = dict(mean="M", modal="D", max="F") diller.inputs.operation = op - assert diller.cmdline == "fslmaths a.nii -dil{} b.nii".format(cv[op]) + assert diller.cmdline == f"fslmaths a.nii -dil{cv[op]} b.nii" # Now test the different kernel options for k in ["3D", "2D", "box", "boxv", "gauss", "sphere"]: @@ -281,8 +280,7 @@ def test_dilation(create_files_in_directory_plus_output_type): diller.inputs.kernel_shape = k diller.inputs.kernel_size = size assert ( - diller.cmdline - == "fslmaths a.nii -kernel {} {:.4f} -dilF b.nii".format(k, size) + diller.cmdline == f"fslmaths a.nii -kernel {k} {size:.4f} -dilF b.nii" ) # Test that we can use a file kernel @@ -296,7 +294,7 @@ def test_dilation(create_files_in_directory_plus_output_type): # Test that we don't need to request an out name dil = fsl.DilateImage(in_file="a.nii", operation="max") assert dil.cmdline == "fslmaths a.nii -dilF {}".format( - os.path.join(testdir, "a_dil{}".format(out_ext)) + os.path.join(testdir, f"a_dil{out_ext}") ) @@ -320,7 +318,7 @@ def test_erosion(create_files_in_directory_plus_output_type): # Test that we don't need to request an out name erode = fsl.ErodeImage(in_file="a.nii") assert erode.cmdline == "fslmaths a.nii -ero {}".format( - os.path.join(testdir, "a_ero{}".format(out_ext)) + os.path.join(testdir, f"a_ero{out_ext}") ) @@ -341,12 +339,12 @@ def test_spatial_filter(create_files_in_directory_plus_output_type): # Test the different operations for op in ["mean", "meanu", "median"]: filter.inputs.operation = op - assert filter.cmdline == "fslmaths a.nii -f{} b.nii".format(op) + assert filter.cmdline == f"fslmaths a.nii -f{op} b.nii" # Test that we don't need to ask for an out name filter = fsl.SpatialFilter(in_file="a.nii", operation="mean") assert filter.cmdline == "fslmaths a.nii -fmean {}".format( - os.path.join(testdir, "a_filt{}".format(out_ext)) + os.path.join(testdir, f"a_filt{out_ext}") ) @@ -368,13 +366,13 @@ def test_unarymaths(create_files_in_directory_plus_output_type): ops = ["exp", "log", "sin", "cos", "sqr", "sqrt", "recip", "abs", "bin", "index"] for op in ops: maths.inputs.operation = op - assert maths.cmdline == "fslmaths a.nii -{} b.nii".format(op) + assert maths.cmdline == f"fslmaths a.nii -{op} b.nii" # Test that we don't need to ask for an out file for op in ops: maths = fsl.UnaryMaths(in_file="a.nii", operation=op) assert maths.cmdline == "fslmaths a.nii -{} {}".format( - op, os.path.join(testdir, "a_{}{}".format(op, out_ext)) + op, os.path.join(testdir, f"a_{op}{out_ext}") ) @@ -400,7 +398,7 @@ def test_binarymaths(create_files_in_directory_plus_output_type): maths = fsl.BinaryMaths(in_file="a.nii", out_file="c.nii", operation=op) if ent == "b.nii": maths.inputs.operand_file = ent - assert maths.cmdline == "fslmaths a.nii -{} b.nii c.nii".format(op) + assert maths.cmdline == f"fslmaths a.nii -{op} b.nii c.nii" else: maths.inputs.operand_value = ent assert maths.cmdline == "fslmaths a.nii -{} {:.8f} c.nii".format( @@ -411,7 +409,7 @@ def test_binarymaths(create_files_in_directory_plus_output_type): for op in ops: maths = fsl.BinaryMaths(in_file="a.nii", operation=op, operand_file="b.nii") assert maths.cmdline == "fslmaths a.nii -{} b.nii {}".format( - op, os.path.join(testdir, "a_maths{}".format(out_ext)) + op, os.path.join(testdir, f"a_maths{out_ext}") ) @@ -470,5 +468,5 @@ def test_tempfilt(create_files_in_directory_plus_output_type): # Test that we don't need to ask for an out file filt = fsl.TemporalFilter(in_file="a.nii", highpass_sigma=64) assert filt.cmdline == "fslmaths a.nii -bptf 64.000000 -1.000000 {}".format( - os.path.join(testdir, "a_filt{}".format(out_ext)) + os.path.join(testdir, f"a_filt{out_ext}") ) diff --git a/nipype/interfaces/fsl/tests/test_model.py b/nipype/interfaces/fsl/tests/test_model.py index 456e7b6492..5b43850c43 100644 --- a/nipype/interfaces/fsl/tests/test_model.py +++ b/nipype/interfaces/fsl/tests/test_model.py @@ -1,24 +1,29 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -import os import pytest import nipype.interfaces.fsl.model as fsl from nipype.interfaces.fsl import no_fsl from pathlib import Path -from ....pipeline import engine as pe +from ....pipeline import engine as pe @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") def test_MultipleRegressDesign(tmpdir): - designer = pe.Node(fsl.MultipleRegressDesign(), name='designer', base_dir=str(tmpdir)) + designer = pe.Node( + fsl.MultipleRegressDesign(), name="designer", base_dir=str(tmpdir) + ) designer.inputs.regressors = dict( voice_stenght=[1, 1, 1], age=[0.2, 0.4, 0.5], BMI=[1, -1, 2] ) con1 = ["voice_and_age", "T", ["age", "voice_stenght"], [0.5, 0.5]] con2 = ["just_BMI", "T", ["BMI"], [1]] - designer.inputs.contrasts = [con1, con2, ["con3", "F", [con1, con2]], ["con4", "F", [con2]]] + designer.inputs.contrasts = [ + con1, + con2, + ["con3", "F", [con1, con2]], + ["con4", "F", [con2]], + ] res = designer.run() outputs = res.outputs.get_traitsfree() @@ -27,7 +32,9 @@ def test_MultipleRegressDesign(tmpdir): expected_content = {} - expected_content["design_mat"] = """/NumWaves 3 + expected_content[ + "design_mat" + ] = """/NumWaves 3 /NumPoints 3 /PPheights 3.000000e+00 5.000000e-01 1.000000e+00 @@ -37,7 +44,9 @@ def test_MultipleRegressDesign(tmpdir): 2.000000e+00 5.000000e-01 1.000000e+00 """ - expected_content["design_con"] = """/ContrastName1 voice_and_age + expected_content[ + "design_con" + ] = """/ContrastName1 voice_and_age /ContrastName2 just_BMI /NumWaves 3 /NumContrasts 2 @@ -49,7 +58,9 @@ def test_MultipleRegressDesign(tmpdir): 1.000000e+00 0.000000e+00 0.000000e+00 """ - expected_content["design_fts"] = """/NumWaves 2 + expected_content[ + "design_fts" + ] = """/NumWaves 2 /NumContrasts 2 /Matrix @@ -57,7 +68,9 @@ def test_MultipleRegressDesign(tmpdir): 0 1 """ - expected_content["design_grp"] = """/NumWaves 1 + expected_content[ + "design_grp" + ] = """/NumWaves 1 /NumPoints 3 /Matrix diff --git a/nipype/interfaces/fsl/tests/test_preprocess.py b/nipype/interfaces/fsl/tests/test_preprocess.py index 438f3f0ec4..143179a5ec 100644 --- a/nipype/interfaces/fsl/tests/test_preprocess.py +++ b/nipype/interfaces/fsl/tests/test_preprocess.py @@ -1,11 +1,9 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os from copy import deepcopy import pytest -import pdb from nipype.utils.filemanip import split_filename, ensure_list from .. import preprocess as fsl from nipype.interfaces.fsl import Info @@ -14,8 +12,7 @@ def fsl_name(obj, fname): - """Create valid fsl name, including file extension for output type. - """ + """Create valid fsl name, including file extension for output type.""" ext = Info.output_type_to_ext(obj.inputs.output_type) return fname + ext @@ -31,6 +28,9 @@ def setup_infile(tmpdir): @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") def test_bet(setup_infile): tmp_infile, tp_dir = setup_infile + # BET converts the in_file path to be relative to prevent + # failure with long paths. + tmp_infile = os.path.relpath(tmp_infile, start=os.getcwd()) better = fsl.BET() assert better.cmd == "bet" @@ -41,13 +41,12 @@ def test_bet(setup_infile): # Test generated outfile name better.inputs.in_file = tmp_infile outfile = fsl_name(better, "foo_brain") - outpath = os.path.join(os.getcwd(), outfile) - realcmd = "bet %s %s" % (tmp_infile, outpath) + realcmd = f"bet {tmp_infile} {outfile}" assert better.cmdline == realcmd # Test specified outfile name outfile = fsl_name(better, "/newdata/bar") better.inputs.out_file = outfile - realcmd = "bet %s %s" % (tmp_infile, outfile) + realcmd = f"bet {tmp_infile} {outfile}" assert better.cmdline == realcmd # infile foo.nii doesn't exist @@ -70,7 +69,7 @@ def func(): "center": ("-c 54 75 80", [54, 75, 80]), "threshold": ("-t", True), "mesh": ("-e", True), - "surfaces": ("-A", True) + "surfaces": ("-A", True), # 'verbose': ('-v', True), # 'flags': ('--i-made-this-up', '--i-made-this-up'), } @@ -79,12 +78,11 @@ def func(): # test each of our arguments better = fsl.BET() outfile = fsl_name(better, "foo_brain") - outpath = os.path.join(os.getcwd(), outfile) for name, settings in list(opt_map.items()): better = fsl.BET(**{name: settings[1]}) # Add mandatory input better.inputs.in_file = tmp_infile - realcmd = " ".join([better.cmd, tmp_infile, outpath, settings[0]]) + realcmd = " ".join([better.cmd, tmp_infile, outfile, settings[0]]) assert better.cmdline == realcmd @@ -104,13 +102,13 @@ def test_fast(setup_infile): assert faster.inputs.manual_seg == Undefined assert faster.inputs != fasted.inputs assert fasted.cmdline == "fast -v -S 1 %s" % (tmp_infile) - assert fasted2.cmdline == "fast -v -S 2 %s %s" % (tmp_infile, tmp_infile) + assert fasted2.cmdline == f"fast -v -S 2 {tmp_infile} {tmp_infile}" faster = fsl.FAST() faster.inputs.in_files = tmp_infile assert faster.cmdline == "fast -S 1 %s" % (tmp_infile) faster.inputs.in_files = [tmp_infile, tmp_infile] - assert faster.cmdline == "fast -S 2 %s %s" % (tmp_infile, tmp_infile) + assert faster.cmdline == f"fast -S 2 {tmp_infile} {tmp_infile}" # Our options and some test values for them # Should parallel the opt_map structure in the class for clarity @@ -123,7 +121,7 @@ def test_fast(setup_infile): "segments": ("-g", True), "init_transform": ("-a %s" % (tmp_infile), "%s" % (tmp_infile)), "other_priors": ( - "-A %s %s %s" % (tmp_infile, tmp_infile, tmp_infile), + f"-A {tmp_infile} {tmp_infile} {tmp_infile}", (["%s" % (tmp_infile), "%s" % (tmp_infile), "%s" % (tmp_infile)]), ), "no_pve": ("--nopve", True), @@ -151,9 +149,9 @@ def test_fast(setup_infile): @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") def test_fast_list_outputs(setup_infile, tmpdir): - """ By default (no -o), FSL's fast command outputs files into the same + """By default (no -o), FSL's fast command outputs files into the same directory as the input files. If the flag -o is set, it outputs files into - the cwd """ + the cwd""" def _run_and_test(opts, output_base): outputs = fsl.FAST(**opts)._list_outputs() @@ -242,7 +240,7 @@ def test_flirt(setup_flirt): pth, fname, ext = split_filename(infile) outfile = fsl_name(flirter, "%s_flirt" % fname) outmat = "%s_flirt.mat" % fname - realcmd = "flirt -in %s -ref %s -out %s -omat %s" % ( + realcmd = "flirt -in {} -ref {} -out {} -omat {}".format( infile, reffile, outfile, @@ -303,16 +301,16 @@ def test_flirt(setup_flirt): else: value = trait_spec.default param = trait_spec.argstr % value - cmdline = "flirt -in %s -ref %s" % (infile, reffile) + cmdline = f"flirt -in {infile} -ref {reffile}" # Handle autogeneration of outfile pth, fname, ext = split_filename(infile) outfile = fsl_name(fsl.FLIRT(), "%s_flirt" % fname) - outfile = " ".join(["-out", outfile]) + outfile = f"-out {outfile}" # Handle autogeneration of outmatrix outmatrix = "%s_flirt.mat" % fname - outmatrix = " ".join(["-omat", outmatrix]) + outmatrix = f"-omat {outmatrix}" # Build command line - cmdline = " ".join([cmdline, outfile, outmatrix, param]) + cmdline = f"{cmdline} {outfile} {outmatrix} {param}" flirter = fsl.FLIRT(in_file=infile, reference=reffile) setattr(flirter.inputs, key, value) assert flirter.cmdline == cmdline @@ -320,8 +318,8 @@ def test_flirt(setup_flirt): # Test OutputSpec flirter = fsl.FLIRT(in_file=infile, reference=reffile) pth, fname, ext = split_filename(infile) - flirter.inputs.out_file = "".join(["foo", ext]) - flirter.inputs.out_matrix_file = "".join(["bar", ext]) + flirter.inputs.out_file = f"foo{ext}" + flirter.inputs.out_matrix_file = f"bar{ext}" outs = flirter._list_outputs() assert outs["out_file"] == os.path.join(os.getcwd(), flirter.inputs.out_file) assert outs["out_matrix_file"] == os.path.join( @@ -402,7 +400,6 @@ def test_mcflirt_noinput(): @pytest.mark.skipif(no_fsl(), reason="fsl is not installed") def test_fnirt(setup_flirt): - tmpdir, infile, reffile = setup_flirt tmpdir.chdir() fnirt = fsl.FNIRT() @@ -436,7 +433,7 @@ def test_fnirt(setup_flirt): " --iout=%s" % (infile, log, flag, strval, reffile, iout) ) elif item in ("in_fwhm", "intensity_mapping_model"): - cmd = "fnirt --in=%s %s=%s --logout=%s " "--ref=%s --iout=%s" % ( + cmd = "fnirt --in={} {}={} --logout={} --ref={} --iout={}".format( infile, flag, strval, @@ -497,7 +494,7 @@ def test_fnirt(setup_flirt): ("log_file", "--logout=%s" % infile, infile), ] - for (name, settings, arg) in opt_map: + for name, settings, arg in opt_map: fnirt = fsl.FNIRT(in_file=infile, ref_file=reffile, **{name: arg}) if name in ("config_file", "affine_file", "field_file", "fieldcoeff_file"): @@ -581,7 +578,6 @@ def test_applywarp(setup_flirt): def setup_fugue(tmpdir): import nibabel as nb import numpy as np - import os.path as op d = np.ones((80, 80, 80)) infile = tmpdir.join("dumbfile.nii.gz").strpath diff --git a/nipype/interfaces/fsl/tests/test_utils.py b/nipype/interfaces/fsl/tests/test_utils.py index ca52354dd4..bfe895c6ee 100644 --- a/nipype/interfaces/fsl/tests/test_utils.py +++ b/nipype/interfaces/fsl/tests/test_utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -6,10 +5,9 @@ import numpy as np -import nibabel as nb import pytest import nipype.interfaces.fsl.utils as fsl -from nipype.interfaces.fsl import no_fsl, Info +from nipype.interfaces.fsl import no_fsl from nipype.testing.fixtures import create_files_in_directory_plus_output_type @@ -75,7 +73,7 @@ def test_fslmerge(create_files_in_directory_plus_output_type): # verify that providing a tr value updates the dimension to tr merger.inputs.tr = 2.25 - assert merger.cmdline == "fslmerge -tr foo_merged.nii %s %.2f" % ( + assert merger.cmdline == "fslmerge -tr foo_merged.nii {} {:.2f}".format( " ".join(filelist), 2.25, ) @@ -89,7 +87,7 @@ def test_fslmerge(create_files_in_directory_plus_output_type): tr=2.25, ) - assert merger2.cmdline == "fslmerge -tr foo_merged.nii %s %.2f" % ( + assert merger2.cmdline == "fslmerge -tr foo_merged.nii {} {:.2f}".format( " ".join(filelist), 2.25, ) @@ -168,9 +166,12 @@ def test_overlay(create_files_in_directory_plus_output_type): auto_thresh_bg=True, out_file="foo2_overlay.nii", ) - assert overlay2.cmdline == "overlay 1 0 %s -a %s 2.50 10.00 foo2_overlay.nii" % ( - filelist[1], - filelist[0], + assert ( + overlay2.cmdline + == "overlay 1 0 {} -a {} 2.50 10.00 foo2_overlay.nii".format( + filelist[1], + filelist[0], + ) ) @@ -196,9 +197,12 @@ def test_slicer(create_files_in_directory_plus_output_type): slicer.inputs.all_axial = True slicer.inputs.image_width = 750 slicer.inputs.out_file = "foo_bar.png" - assert slicer.cmdline == "slicer %s %s -L -i 10.000 20.000 -A 750 foo_bar.png" % ( - filelist[0], - filelist[1], + assert ( + slicer.cmdline + == "slicer {} {} -L -i 10.000 20.000 -A 750 foo_bar.png".format( + filelist[0], + filelist[1], + ) ) # .run based parameter setting @@ -313,7 +317,7 @@ def test_convertxfm(create_files_in_directory_plus_output_type): cvt2 = fsl.ConvertXFM( in_file=filelist[0], in_file2=filelist[1], concat_xfm=True, out_file="bar.mat" ) - assert cvt2.cmdline == "convert_xfm -omat bar.mat -concat %s %s" % ( + assert cvt2.cmdline == "convert_xfm -omat bar.mat -concat {} {}".format( filelist[1], filelist[0], ) diff --git a/nipype/interfaces/fsl/utils.py b/nipype/interfaces/fsl/utils.py index 6ada44e046..704fb77fef 100644 --- a/nipype/interfaces/fsl/utils.py +++ b/nipype/interfaces/fsl/utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The fsl module provides classes for interfacing with the `FSL @@ -20,6 +19,7 @@ from ...utils.filemanip import load_json, save_json, split_filename, fname_presuffix from ..base import ( traits, + Tuple, TraitedSpec, OutputMultiPath, File, @@ -81,10 +81,10 @@ class RobustFOVInputSpec(FSLCommandInputSpec): name_template="%s_ROI", ) brainsize = traits.Int( - desc=("size of brain in z-dimension (default " "170mm/150mm)"), argstr="-b %d" + desc=("size of brain in z-dimension (default 170mm/150mm)"), argstr="-b %d" ) out_transform = File( - desc=("Transformation matrix in_file to out_roi " "output name"), + desc=("Transformation matrix in_file to out_roi output name"), argstr="-m %s", name_source=["in_file"], hash_files=False, @@ -95,7 +95,7 @@ class RobustFOVInputSpec(FSLCommandInputSpec): class RobustFOVOutputSpec(TraitedSpec): out_roi = File(exists=True, desc="ROI volume output name") out_transform = File( - exists=True, desc=("Transformation matrix in_file to out_roi " "output name") + exists=True, desc=("Transformation matrix in_file to out_roi output name") ) @@ -128,26 +128,26 @@ class ImageMeantsInputSpec(FSLCommandInputSpec): mask = File(exists=True, desc="input 3D mask", argstr="-m %s") spatial_coord = traits.List( traits.Int, - desc=(" requested spatial coordinate " "(instead of mask)"), + desc=(" requested spatial coordinate (instead of mask)"), argstr="-c %s", ) use_mm = traits.Bool( - desc=("use mm instead of voxel coordinates (for -c " "option)"), + desc=("use mm instead of voxel coordinates (for -c option)"), argstr="--usemm", ) show_all = traits.Bool( - desc=("show all voxel time series (within mask) " "instead of averaging"), + desc=("show all voxel time series (within mask) instead of averaging"), argstr="--showall", ) eig = traits.Bool( - desc=("calculate Eigenvariate(s) instead of mean (output will have 0 " "mean)"), + desc=("calculate Eigenvariate(s) instead of mean (output will have 0 mean)"), argstr="--eig", ) order = traits.Int( 1, desc="select number of Eigenvariates", argstr="--order=%d", usedefault=True ) nobin = traits.Bool( - desc=("do not binarise the mask for calculation of " "Eigenvariates"), + desc=("do not binarise the mask for calculation of Eigenvariates"), argstr="--no_bin", ) transpose = traits.Bool( @@ -161,9 +161,9 @@ class ImageMeantsOutputSpec(TraitedSpec): class ImageMeants(FSLCommand): - """ Use fslmeants for printing the average timeseries (intensities) to - the screen (or saves to a file). The average is taken over all voxels - in the mask (or all voxels in the image if no mask is specified) + """Use fslmeants for printing the average timeseries (intensities) to + the screen (or saves to a file). The average is taken over all voxels + in the mask (or all voxels in the image if no mask is specified) """ @@ -201,7 +201,7 @@ class SmoothInputSpec(FSLCommandInputSpec): position=1, xor=["sigma"], mandatory=True, - desc=("gaussian kernel fwhm, will be converted to sigma in mm " "(not voxels)"), + desc=("gaussian kernel fwhm, will be converted to sigma in mm (not voxels)"), ) smoothed_file = File( argstr="%s", @@ -261,8 +261,8 @@ class Smooth(FSLCommand): def _format_arg(self, name, trait_spec, value): if name == "fwhm": sigma = float(value) / np.sqrt(8 * np.log(2)) - return super(Smooth, self)._format_arg(name, trait_spec, sigma) - return super(Smooth, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, sigma) + return super()._format_arg(name, trait_spec, value) class SliceInputSpec(FSLCommandInputSpec): @@ -410,7 +410,7 @@ def _format_arg(self, name, spec, value): if isdefined(self.inputs.tr): return "-tr" return spec.argstr % value - return super(Merge, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class ExtractROIInputSpec(FSLCommandInputSpec): @@ -439,7 +439,7 @@ class ExtractROIInputSpec(FSLCommandInputSpec): "t_size", ] crop_list = traits.List( - traits.Tuple(traits.Int, traits.Int), + Tuple(traits.Int, traits.Int), argstr="%s", position=2, xor=_crop_xor, @@ -482,10 +482,9 @@ class ExtractROI(FSLCommand): output_spec = ExtractROIOutputSpec def _format_arg(self, name, spec, value): - if name == "crop_list": - return " ".join(map(str, sum(list(map(list, value)), []))) - return super(ExtractROI, self)._format_arg(name, spec, value) + return " ".join(str(x) for sublist in value for x in sublist) + return super()._format_arg(name, spec, value) def _list_outputs(self): """Create a Bunch which contains all possible files generated @@ -594,7 +593,7 @@ class ImageMathsInputSpec(FSLCommandInputSpec): "input", argstr="-odt %s", position=-1, - desc=("output datatype, one of (char, short, " "int, float, double, input)"), + desc=("output datatype, one of (char, short, int, float, double, input)"), ) @@ -631,7 +630,7 @@ def _gen_filename(self, name): return None def _parse_inputs(self, skip=None): - return super(ImageMaths, self)._parse_inputs(skip=["suffix"]) + return super()._parse_inputs(skip=["suffix"]) def _list_outputs(self): suffix = "_maths" # ohinds: build suffix @@ -683,13 +682,13 @@ class FilterRegressorInputSpec(FSLCommandInputSpec): argstr="-f '%s'", xor=["filter_columns"], position=4, - desc=("use all columns in the design file in " "denoising"), + desc=("use all columns in the design file in denoising"), ) mask = File(exists=True, argstr="-m %s", desc="mask image file name") var_norm = traits.Bool(argstr="--vn", desc="perform variance-normalization on data") out_vnscales = traits.Bool( argstr="--out_vnscales", - desc=("output scaling factors for variance " "normalization"), + desc=("output scaling factors for variance normalization"), ) @@ -717,7 +716,7 @@ def _format_arg(self, name, trait_spec, value): except IndexError: n_cols = 1 return trait_spec.argstr % ",".join(map(str, list(range(1, n_cols + 1)))) - return super(FilterRegressor, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _list_outputs(self): outputs = self.output_spec().get() @@ -739,7 +738,7 @@ class ImageStatsInputSpec(FSLCommandInputSpec): split_4d = traits.Bool( argstr="-t", position=1, - desc=("give a separate output line for each 3D " "volume of a 4D timeseries"), + desc=("give a separate output line for each 3D volume of a 4D timeseries"), ) in_file = File( exists=True, @@ -764,7 +763,7 @@ class ImageStatsInputSpec(FSLCommandInputSpec): exists=True, argstr="-K %s", position=2, - desc="generate seperate n submasks from indexMask, " + desc="generate separate n submasks from indexMask, " "for indexvalues 1..n where n is the maximum index " "value in indexMask, and generate statistics for each submask", ) @@ -806,7 +805,7 @@ def _format_arg(self, name, trait_spec, value): return self.inputs.op_string % self.inputs.mask_file else: raise ValueError("-k %s option in op_string requires mask_file") - return super(ImageStats, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def aggregate_outputs(self, runtime=None, needed_outputs=None): outputs = self._outputs() @@ -815,7 +814,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): if runtime is None: try: out_stat = load_json(outfile)["stat"] - except IOError: + except OSError: return self.run().outputs else: out_stat = [] @@ -884,7 +883,7 @@ class AvScale(CommandLine): _cmd = "avscale" def _run_interface(self, runtime): - runtime = super(AvScale, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) expr = re.compile( r"Rotation & Translation Matrix:\n(?P[0-9\. \n-]+)[\s\n]*" @@ -930,7 +929,7 @@ def _run_interface(self, runtime): float(r) for r in out["translations"].strip().split(" ") ] - setattr(self, "_results", outputs) + self._results = outputs return runtime def _list_outputs(self): @@ -978,7 +977,7 @@ class OverlayInputSpec(FSLCommandInputSpec): xor=_xor_inputs, mandatory=True, ) - bg_thresh = traits.Tuple( + bg_thresh = Tuple( traits.Float, traits.Float, argstr="%.3f %.3f", @@ -994,16 +993,16 @@ class OverlayInputSpec(FSLCommandInputSpec): argstr="%s", desc="statistical image to overlay in color", ) - stat_thresh = traits.Tuple( + stat_thresh = Tuple( traits.Float, traits.Float, position=7, mandatory=True, argstr="%.2f %.2f", - desc=("min and max values for the statistical " "overlay"), + desc=("min and max values for the statistical overlay"), ) show_negative_stats = traits.Bool( - desc=("display negative statistics in " "overlay"), + desc=("display negative statistics in overlay"), xor=["stat_image2"], argstr="%s", position=8, @@ -1015,11 +1014,11 @@ class OverlayInputSpec(FSLCommandInputSpec): argstr="%s", desc="second statistical image to overlay in color", ) - stat_thresh2 = traits.Tuple( + stat_thresh2 = Tuple( traits.Float, traits.Float, position=10, - desc=("min and max values for second " "statistical overlay"), + desc=("min and max values for second statistical overlay"), argstr="%.2f %.2f", ) out_file = File( @@ -1036,7 +1035,7 @@ class OverlayOutputSpec(TraitedSpec): class Overlay(FSLCommand): - """ Use FSL's overlay command to combine background and statistical images + """Use FSL's overlay command to combine background and statistical images into one volume @@ -1071,12 +1070,12 @@ def _format_arg(self, name, spec, value): else: return "1" if name == "show_negative_stats": - return "%s %.2f %.2f" % ( + return "{} {:.2f} {:.2f}".format( self.inputs.stat_image, self.inputs.stat_thresh[0] * -1, self.inputs.stat_thresh[1] * -1, ) - return super(Overlay, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -1086,7 +1085,7 @@ def _list_outputs(self): not isdefined(self.inputs.show_negative_stats) or not self.inputs.show_negative_stats ): - stem = "%s_and_%s" % ( + stem = "{}_and_{}".format( split_filename(self.inputs.stat_image)[1], split_filename(self.inputs.stat_image2)[1], ) @@ -1110,9 +1109,7 @@ class SlicerInputSpec(FSLCommandInputSpec): exists=True, position=2, argstr="%s", - desc=( - "volume to display edge overlay for (useful for " "checking registration" - ), + desc=("volume to display edge overlay for (useful for checking registration"), ) label_slices = traits.Bool( position=3, @@ -1125,9 +1122,9 @@ class SlicerInputSpec(FSLCommandInputSpec): exists=True, position=4, argstr="-l %s", - desc=("use different colour map from that stored in " "nifti header"), + desc=("use different colour map from that stored in nifti header"), ) - intensity_range = traits.Tuple( + intensity_range = Tuple( traits.Float, traits.Float, position=5, @@ -1138,12 +1135,12 @@ class SlicerInputSpec(FSLCommandInputSpec): position=6, argstr="-e %.3f", desc="use threshold for edges" ) dither_edges = traits.Bool( - position=7, argstr="-t", desc=("produce semi-transparent (dithered) " "edges") + position=7, argstr="-t", desc=("produce semi-transparent (dithered) edges") ) nearest_neighbour = traits.Bool( position=8, argstr="-n", - desc=("use nearest neighbor interpolation " "for output"), + desc=("use nearest neighbor interpolation for output"), ) show_orientation = traits.Bool( position=9, @@ -1170,7 +1167,7 @@ class SlicerInputSpec(FSLCommandInputSpec): position=10, argstr="-a", xor=_xor_options, - desc=("output picture of mid-sagittal, axial, " "and coronal slices"), + desc=("output picture of mid-sagittal, axial, and coronal slices"), ) all_axial = traits.Bool( position=10, @@ -1184,7 +1181,7 @@ class SlicerInputSpec(FSLCommandInputSpec): argstr="-S %d", xor=_xor_options, requires=["image_width"], - desc=("output every n axial slices into one " "picture"), + desc=("output every n axial slices into one picture"), ) image_width = traits.Int(position=-2, argstr="%d", desc="max picture width") out_file = File( @@ -1234,7 +1231,7 @@ def _format_arg(self, name, spec, value): return "-L" else: return "" - return super(Slicer, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -1251,14 +1248,13 @@ def _gen_filename(self, name): class PlotTimeSeriesInputSpec(FSLCommandInputSpec): - in_file = traits.Either( File(exists=True), traits.List(File(exists=True)), mandatory=True, argstr="%s", position=1, - desc=("file or list of files with columns of " "timecourse information"), + desc=("file or list of files with columns of timecourse information"), ) plot_start = traits.Int( argstr="--start=%d", @@ -1270,21 +1266,21 @@ class PlotTimeSeriesInputSpec(FSLCommandInputSpec): xor=("plot_range",), desc="final column from in-file to plot", ) - plot_range = traits.Tuple( + plot_range = Tuple( traits.Int, traits.Int, argstr="%s", xor=("plot_start", "plot_finish"), - desc=("first and last columns from the in-file " "to plot"), + desc=("first and last columns from the in-file to plot"), ) title = traits.Str(argstr="%s", desc="plot title") legend_file = File(exists=True, argstr="--legend=%s", desc="legend file") labels = traits.Either( traits.Str, traits.List(traits.Str), argstr="%s", desc="label or list of labels" ) - y_min = traits.Float(argstr="--ymin=%.2f", desc="minumum y value", xor=("y_range",)) + y_min = traits.Float(argstr="--ymin=%.2f", desc="minimum y value", xor=("y_range",)) y_max = traits.Float(argstr="--ymax=%.2f", desc="maximum y value", xor=("y_range",)) - y_range = traits.Tuple( + y_range = Tuple( traits.Float, traits.Float, argstr="%s", @@ -1297,7 +1293,7 @@ class PlotTimeSeriesInputSpec(FSLCommandInputSpec): default_value=1, desc=("scaling units for x-axis (between 1 and length of in file)"), ) - plot_size = traits.Tuple( + plot_size = Tuple( traits.Int, traits.Int, argstr="%s", desc="plot image height and width" ) x_precision = traits.Int(argstr="--precision=%d", desc="precision of x-axis labels") @@ -1308,7 +1304,6 @@ class PlotTimeSeriesInputSpec(FSLCommandInputSpec): class PlotTimeSeriesOutputSpec(TraitedSpec): - out_file = File(exists=True, desc="image to write") @@ -1353,7 +1348,7 @@ def _format_arg(self, name, spec, value): return "--ymin=%d --ymax=%d" % value elif name == "plot_size": return "-h %d -w %d" % value - return super(PlotTimeSeries, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -1374,7 +1369,6 @@ def _gen_filename(self, name): class PlotMotionParamsInputSpec(FSLCommandInputSpec): - in_file = traits.Either( File(exists=True), traits.List(File(exists=True)), @@ -1387,7 +1381,7 @@ class PlotMotionParamsInputSpec(FSLCommandInputSpec): "spm", "fsl", mandatory=True, - desc=("which program generated the motion " "parameter file - fsl, spm"), + desc=("which program generated the motion parameter file - fsl, spm"), ) plot_type = traits.Enum( "rotations", @@ -1395,9 +1389,9 @@ class PlotMotionParamsInputSpec(FSLCommandInputSpec): "displacement", argstr="%s", mandatory=True, - desc=("which motion type to plot - rotations, " "translations, displacement"), + desc=("which motion type to plot - rotations, translations, displacement"), ) - plot_size = traits.Tuple( + plot_size = Tuple( traits.Int, traits.Int, argstr="%s", desc="plot image height and width" ) out_file = File( @@ -1406,7 +1400,6 @@ class PlotMotionParamsInputSpec(FSLCommandInputSpec): class PlotMotionParamsOutputSpec(TraitedSpec): - out_file = File(exists=True, desc="image to write") @@ -1434,7 +1427,7 @@ class PlotMotionParams(FSLCommand): translations, while SPM prints them in the opposite order. This interface should be able to plot timecourses of motion parameters generated from other sources as long as they fall under one of these two patterns. For - more flexibilty, see the :class:`fsl.PlotTimeSeries` interface. + more flexibility, see the :class:`fsl.PlotTimeSeries` interface. """ @@ -1443,14 +1436,13 @@ class PlotMotionParams(FSLCommand): output_spec = PlotMotionParamsOutputSpec def _format_arg(self, name, spec, value): - if name == "plot_type": source = self.inputs.in_source if self.inputs.plot_type == "displacement": title = "-t 'MCFLIRT estimated mean displacement (mm)'" labels = "-a abs,rel" - return "%s %s" % (title, labels) + return f"{title} {labels}" # Get the right starting and ending position depending on source # package @@ -1459,17 +1451,17 @@ def _format_arg(self, name, spec, value): ) # Format the title properly - sfstr = "--start=%d --finish=%d" % sfdict["%s_%s" % (source, value[:3])] + sfstr = "--start=%d --finish=%d" % sfdict[f"{source}_{value[:3]}"] titledict = dict(fsl="MCFLIRT", spm="Realign") unitdict = dict(rot="radians", tra="mm") - title = "'%s estimated %s (%s)'" % ( + title = "'{} estimated {} ({})'".format( titledict[source], value, unitdict[value[:3]], ) - return "-t %s %s -a x,y,z" % (title, sfstr) + return f"-t {title} {sfstr} -a x,y,z" elif name == "plot_size": return "-h %d -w %d" % value elif name == "in_file": @@ -1479,7 +1471,7 @@ def _format_arg(self, name, spec, value): else: return "-i %s" % value - return super(PlotMotionParams, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _list_outputs(self): outputs = self._outputs().get() @@ -1527,14 +1519,14 @@ class ConvertXFMInputSpec(FSLCommandInputSpec): position=-3, xor=_options, requires=["in_file2"], - desc=("write joint transformation of two input " "matrices"), + desc=("write joint transformation of two input matrices"), ) fix_scale_skew = traits.Bool( argstr="-fixscaleskew", position=-3, xor=_options, requires=["in_file2"], - desc=("use secondary matrix to fix scale and " "skew"), + desc=("use secondary matrix to fix scale and skew"), ) out_file = File( genfile=True, @@ -1583,7 +1575,7 @@ def _list_outputs(self): if self.inputs.concat_xfm: _, infile2, _ = split_filename(self.inputs.in_file2) outfile = fname_presuffix( - "%s_%s" % (infile1, infile2), + f"{infile1}_{infile2}", suffix=".mat", newpath=os.getcwd(), use_ext=False, @@ -1602,12 +1594,11 @@ def _gen_filename(self, name): class SwapDimensionsInputSpec(FSLCommandInputSpec): - in_file = File( exists=True, mandatory=True, argstr="%s", position="1", desc="input image" ) _dims = ["x", "-x", "y", "-y", "z", "-z", "RL", "LR", "AP", "PA", "IS", "SI"] - new_dims = traits.Tuple( + new_dims = Tuple( traits.Enum(_dims), traits.Enum(_dims), traits.Enum(_dims), @@ -1619,7 +1610,6 @@ class SwapDimensionsInputSpec(FSLCommandInputSpec): class SwapDimensionsOutputSpec(TraitedSpec): - out_file = File(exists=True, desc="image with new dimensions") @@ -1873,18 +1863,18 @@ class InvWarpInputSpec(FSLCommandInputSpec): ), ) regularise = traits.Float( - argstr="--regularise=%f", desc="Regularization strength (deafult=1.0)." + argstr="--regularise=%f", desc="Regularization strength (default=1.0)." ) noconstraint = traits.Bool( argstr="--noconstraint", desc="Do not apply Jacobian constraint" ) jacobian_min = traits.Float( argstr="--jmin=%f", - desc=("Minimum acceptable Jacobian value for " "constraint (default 0.01)"), + desc=("Minimum acceptable Jacobian value for constraint (default 0.01)"), ) jacobian_max = traits.Float( argstr="--jmax=%f", - desc=("Maximum acceptable Jacobian value for " "constraint (default 100.0)"), + desc=("Maximum acceptable Jacobian value for constraint (default 100.0)"), ) @@ -1980,19 +1970,19 @@ class ComplexInputSpec(FSLCommandInputSpec): start_vol = traits.Int(position=-2, argstr="%d") end_vol = traits.Int(position=-1, argstr="%d") - real_polar = traits.Bool(argstr="-realpolar", xor=_conversion, position=1,) + real_polar = traits.Bool(argstr="-realpolar", xor=_conversion, position=1) # requires=['complex_in_file','magnitude_out_file','phase_out_file']) - real_cartesian = traits.Bool(argstr="-realcartesian", xor=_conversion, position=1,) + real_cartesian = traits.Bool(argstr="-realcartesian", xor=_conversion, position=1) # requires=['complex_in_file','real_out_file','imaginary_out_file']) - complex_cartesian = traits.Bool(argstr="-complex", xor=_conversion, position=1,) + complex_cartesian = traits.Bool(argstr="-complex", xor=_conversion, position=1) # requires=['real_in_file','imaginary_in_file','complex_out_file']) - complex_polar = traits.Bool(argstr="-complexpolar", xor=_conversion, position=1,) + complex_polar = traits.Bool(argstr="-complexpolar", xor=_conversion, position=1) # requires=['magnitude_in_file','phase_in_file', # 'magnitude_out_file','phase_out_file']) - complex_split = traits.Bool(argstr="-complexsplit", xor=_conversion, position=1,) + complex_split = traits.Bool(argstr="-complexsplit", xor=_conversion, position=1) # requires=['complex_in_file','complex_out_file']) complex_merge = traits.Bool( - argstr="-complexmerge", xor=_conversion + ["start_vol", "end_vol"], position=1, + argstr="-complexmerge", xor=_conversion + ["start_vol", "end_vol"], position=1 ) @@ -2034,7 +2024,7 @@ def _parse_inputs(self, skip=None): skip += self.inputs._ofs[:1] + self.inputs._ofs[3:] else: skip += self.inputs._ofs[1:] - return super(Complex, self)._parse_inputs(skip) + return super()._parse_inputs(skip) def _gen_filename(self, name): if name == "complex_out_file": @@ -2117,7 +2107,7 @@ class WarpUtilsInputSpec(FSLCommandInputSpec): ), ) - warp_resolution = traits.Tuple( + warp_resolution = Tuple( traits.Float, traits.Float, traits.Float, @@ -2135,7 +2125,7 @@ class WarpUtilsInputSpec(FSLCommandInputSpec): ), ) - knot_space = traits.Tuple( + knot_space = Tuple( traits.Int, traits.Int, traits.Int, @@ -2191,7 +2181,7 @@ class WarpUtilsInputSpec(FSLCommandInputSpec): class WarpUtilsOutputSpec(TraitedSpec): out_file = File( - desc=("Name of output file, containing the warp as field or " "coefficients.") + desc=("Name of output file, containing the warp as field or coefficients.") ) out_jacobian = File( desc=( @@ -2249,7 +2239,7 @@ def _parse_inputs(self, skip=None): skip += ["out_jacobian"] skip += ["write_jacobian"] - return super(WarpUtils, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) class ConvertWarpInputSpec(FSLCommandInputSpec): @@ -2348,11 +2338,11 @@ class ConvertWarpInputSpec(FSLCommandInputSpec): jacobian_min = traits.Float( argstr="--jmin=%f", - desc="Minimum acceptable Jacobian value for " "constraint (default 0.01)", + desc="Minimum acceptable Jacobian value for constraint (default 0.01)", ) jacobian_max = traits.Float( argstr="--jmax=%f", - desc="Maximum acceptable Jacobian value for " "constraint (default 100.0)", + desc="Maximum acceptable Jacobian value for constraint (default 100.0)", ) abswarp = traits.Bool( @@ -2393,7 +2383,7 @@ class ConvertWarpInputSpec(FSLCommandInputSpec): class ConvertWarpOutputSpec(TraitedSpec): out_file = File( exists=True, - desc="Name of output file, containing the warp as field or " "coefficients.", + desc="Name of output file, containing the warp as field or coefficients.", ) @@ -2441,7 +2431,7 @@ class WarpPointsBaseInputSpec(CommandLineInputSpec): exists=True, argstr="-warp %s", xor=["xfm_file"], - desc="filename of warpfield (e.g. " "intermediate2dest_warp.nii.gz)", + desc="filename of warpfield (e.g. intermediate2dest_warp.nii.gz)", ) coord_vox = traits.Bool( True, @@ -2475,7 +2465,7 @@ class WarpPointsInputSpec(WarpPointsBaseInputSpec): class WarpPointsOutputSpec(TraitedSpec): out_file = File( exists=True, - desc="Name of output file, containing the warp as field or " "coefficients.", + desc="Name of output file, containing the warp as field or coefficients.", ) @@ -2513,21 +2503,19 @@ def __init__(self, command=None, **inputs): self._in_file = None self._outformat = None - super(WarpPoints, self).__init__(command=command, **inputs) + super().__init__(command=command, **inputs) def _format_arg(self, name, trait_spec, value): if name == "out_file": return "" - return super(WarpPoints, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _parse_inputs(self, skip=None): fname, ext = op.splitext(self.inputs.in_coords) - setattr(self, "_in_file", fname) - setattr(self, "_outformat", ext[1:]) - first_args = super(WarpPoints, self)._parse_inputs( - skip=["in_coords", "out_file"] - ) + self._in_file = fname + self._outformat = ext[1:] + first_args = super()._parse_inputs(skip=["in_coords", "out_file"]) second_args = fname + ".txt" @@ -2584,7 +2572,7 @@ def _trk_to_coords(self, in_file, out_file=None): if out_file is None: out_file, _ = op.splitext(in_file) - np.savetxt(streamlines, out_file + ".txt") + np.savetxt(out_file + ".txt", streamlines) return out_file + ".txt" def _coords_to_trk(self, points, out_file): @@ -2592,11 +2580,11 @@ def _coords_to_trk(self, points, out_file): def _overload_extension(self, value, name): if name == "out_file": - return "%s.%s" % (value, getattr(self, "_outformat")) + return "{}.{}".format(value, self._outformat) def _run_interface(self, runtime): - fname = getattr(self, "_in_file") - outformat = getattr(self, "_outformat") + fname = self._in_file + outformat = self._outformat tmpfile = None if outformat == "vtk": @@ -2606,7 +2594,7 @@ def _run_interface(self, runtime): tmpfile = self._tmpfile self._trk_to_coords(fname, out_file=tmpfile) - runtime = super(WarpPoints, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) newpoints = np.fromstring("\n".join(runtime.stdout.split("\n")[1:]), sep=" ") if tmpfile is not None: @@ -2640,9 +2628,7 @@ class WarpPointsToStdInputSpec(WarpPointsBaseInputSpec): premat_file = File( exists=True, argstr="-premat %s", - desc=( - "filename of pre-warp affine transform " "(e.g. example_func2highres.mat)" - ), + desc=("filename of pre-warp affine transform (e.g. example_func2highres.mat)"), ) @@ -2708,7 +2694,7 @@ class WarpPointsFromStdInputSpec(CommandLineInputSpec): exists=True, argstr="-warp %s", xor=["xfm_file"], - desc="filename of warpfield (e.g. " "intermediate2dest_warp.nii.gz)", + desc="filename of warpfield (e.g. intermediate2dest_warp.nii.gz)", ) coord_vox = traits.Bool( True, @@ -2813,7 +2799,7 @@ class MotionOutliersInputSpec(FSLCommandInputSpec): class MotionOutliersOutputSpec(TraitedSpec): - out_file = File(exists=True) + out_file = File() out_metric_values = File(exists=True) out_metric_plot = File(exists=True) @@ -2834,3 +2820,92 @@ class MotionOutliers(FSLCommand): input_spec = MotionOutliersInputSpec output_spec = MotionOutliersOutputSpec _cmd = "fsl_motion_outliers" + + +class Text2VestInputSpec(FSLCommandInputSpec): + in_file = File( + exists=True, + mandatory=True, + desc="plain text file representing your design, contrast, or f-test matrix", + argstr="%s", + position=0, + ) + + out_file = File( + mandatory=True, + desc=( + "file name to store matrix data in the format used by FSL tools" + " (e.g., design.mat, design.con design.fts)" + ), + argstr="%s", + position=1, + ) + + +class Text2VestOutputSpec(TraitedSpec): + out_file = File(desc="matrix data in the format used by FSL tools") + + +class Text2Vest(FSLCommand): + """ + Use FSL Text2Vest`https://web.mit.edu/fsl_v5.0.10/fsl/doc/wiki/GLM(2f)CreatingDesignMatricesByHand.html`_ + to convert your plain text design matrix data into the format used by the FSL tools. + + Examples + -------- + >>> from nipype.interfaces.fsl import Text2Vest + >>> t2v = Text2Vest() + >>> t2v.inputs.in_file = "design.txt" + >>> t2v.inputs.out_file = "design.mat" + >>> t2v.cmdline + 'Text2Vest design.txt design.mat' + >>> res = t2v.run() # doctest: +SKIP + """ + + input_spec = Text2VestInputSpec + output_spec = Text2VestOutputSpec + + _cmd = "Text2Vest" + + +class Vest2TextInputSpec(FSLCommandInputSpec): + in_file = File( + exists=True, + mandatory=True, + desc="matrix data stored in the format used by FSL tools", + argstr="%s", + position=0, + ) + + out_file = File( + "design.txt", + usedefault=True, + desc="file name to store text output from matrix", + argstr="%s", + position=1, + ) + + +class Vest2TextOutputSpec(TraitedSpec): + out_file = File(desc="plain text representation of FSL matrix") + + +class Vest2Text(FSLCommand): + """ + Use FSL Vest2Text`https://web.mit.edu/fsl_v5.0.10/fsl/doc/wiki/GLM(2f)CreatingDesignMatricesByHand.html`_ + to convert your design.mat design.con and design.fts files into plain text. + + Examples + -------- + >>> from nipype.interfaces.fsl import Vest2Text + >>> v2t = Vest2Text() + >>> v2t.inputs.in_file = "design.mat" + >>> v2t.cmdline + 'Vest2Text design.mat design.txt' + >>> res = v2t.run() # doctest: +SKIP + """ + + input_spec = Vest2TextInputSpec + output_spec = Vest2TextOutputSpec + + _cmd = "Vest2Text" diff --git a/nipype/interfaces/image.py b/nipype/interfaces/image.py index a984efa159..f86ae7ef15 100644 --- a/nipype/interfaces/image.py +++ b/nipype/interfaces/image.py @@ -1,10 +1,10 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from ..utils.filemanip import fname_presuffix from .base import SimpleInterface, TraitedSpec, BaseInterfaceInputSpec, traits, File -from .. import LooseVersion + +from looseversion import LooseVersion class RescaleInputSpec(BaseInterfaceInputSpec): @@ -122,63 +122,62 @@ class ReorientOutputSpec(TraitedSpec): class Reorient(SimpleInterface): """Conform an image to a given orientation -Flips and reorder the image data array so that the axes match the -directions indicated in ``orientation``. -The default ``RAS`` orientation corresponds to the first axis being ordered -from left to right, the second axis from posterior to anterior, and the -third axis from inferior to superior. - -For oblique images, the original orientation is considered to be the -closest plumb orientation. + Flips and reorder the image data array so that the axes match the + directions indicated in ``orientation``. + The default ``RAS`` orientation corresponds to the first axis being ordered + from left to right, the second axis from posterior to anterior, and the + third axis from inferior to superior. -No resampling is performed, and thus the output image is not de-obliqued -or registered to any other image or template. + For oblique images, the original orientation is considered to be the + closest plumb orientation. -The effective transform is calculated from the original affine matrix to -the reoriented affine matrix. + No resampling is performed, and thus the output image is not de-obliqued + or registered to any other image or template. -Examples --------- + The effective transform is calculated from the original affine matrix to + the reoriented affine matrix. -If an image is not reoriented, the original file is not modified + Examples + -------- -.. testsetup:: + If an image is not reoriented, the original file is not modified - >>> def print_affine(matrix): - ... print(str(matrix).replace(']', ' ').replace('[', ' ')) + .. testsetup:: ->>> import numpy as np ->>> from nipype.interfaces.image import Reorient ->>> reorient = Reorient(orientation='LPS') ->>> reorient.inputs.in_file = 'segmentation0.nii.gz' ->>> res = reorient.run() ->>> res.outputs.out_file -'segmentation0.nii.gz' + >>> def print_affine(matrix): + ... print(str(matrix).replace(']', ' ').replace('[', ' ')) ->>> print_affine(np.loadtxt(res.outputs.transform)) -1. 0. 0. 0. -0. 1. 0. 0. -0. 0. 1. 0. -0. 0. 0. 1. + >>> import numpy as np + >>> from nipype.interfaces.image import Reorient + >>> reorient = Reorient(orientation='LPS') + >>> reorient.inputs.in_file = 'segmentation0.nii.gz' + >>> res = reorient.run() + >>> res.outputs.out_file + 'segmentation0.nii.gz' ->>> reorient.inputs.orientation = 'RAS' ->>> res = reorient.run() ->>> res.outputs.out_file # doctest: +ELLIPSIS -'.../segmentation0_ras.nii.gz' + >>> print_affine(np.loadtxt(res.outputs.transform)) + 1. 0. 0. 0. + 0. 1. 0. 0. + 0. 0. 1. 0. + 0. 0. 0. 1. ->>> print_affine(np.loadtxt(res.outputs.transform)) --1. 0. 0. 60. - 0. -1. 0. 72. - 0. 0. 1. 0. - 0. 0. 0. 1. + >>> reorient.inputs.orientation = 'RAS' + >>> res = reorient.run() + >>> res.outputs.out_file # doctest: +ELLIPSIS + '.../segmentation0_ras.nii.gz' -.. testcleanup:: + >>> print_affine(np.loadtxt(res.outputs.transform)) + -1. 0. 0. 60. + 0. -1. 0. 72. + 0. 0. 1. 0. + 0. 0. 0. 1. - >>> import os - >>> os.unlink(res.outputs.out_file) - >>> os.unlink(res.outputs.transform) + .. testcleanup:: -""" + >>> import os + >>> os.unlink(res.outputs.out_file) + >>> os.unlink(res.outputs.transform) + """ input_spec = ReorientInputSpec output_spec = ReorientOutputSpec diff --git a/nipype/interfaces/io.py b/nipype/interfaces/io.py index ee26e94675..d6af1ba073 100644 --- a/nipype/interfaces/io.py +++ b/nipype/interfaces/io.py @@ -1,15 +1,14 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -""" Set of interfaces that allow interaction with data. Currently - available interfaces are: +"""Set of interfaces that allow interaction with data. Currently +available interfaces are: - DataSource: Generic nifti to named Nifti interface - DataSink: Generic named output from interfaces to data store - XNATSource: preliminary interface to XNAT +DataSource: Generic nifti to named Nifti interface +DataSink: Generic named output from interfaces to data store +XNATSource: preliminary interface to XNAT - To come : - XNATSink +To come : +XNATSink """ import glob import fnmatch @@ -37,6 +36,7 @@ from .base import ( TraitedSpec, traits, + Tuple, Str, File, Directory, @@ -85,7 +85,7 @@ def copytree(src, dst, use_hardlink=False): hashmethod="content", use_hardlink=use_hardlink, ) - except (IOError, os.error) as why: + except OSError as why: errors.append((srcname, dstname, str(why))) # catch the Error from the recursive copytree so that we can # continue with other files @@ -96,7 +96,7 @@ def copytree(src, dst, use_hardlink=False): def add_traits(base, names, trait_type=None): - """ Add traits to a traited class. + """Add traits to a traited class. All traits are set to Undefined by default """ @@ -114,7 +114,7 @@ def add_traits(base, names, trait_type=None): def _get_head_bucket(s3_resource, bucket_name): - """ Try to get the header info of a bucket, in order to + """Try to get the header info of a bucket, in order to check if it exists and its permissions """ @@ -135,12 +135,12 @@ def _get_head_bucket(s3_resource, bucket_name): ) raise Exception(err_msg) else: - err_msg = "Unable to connect to bucket: %s. Error message:\n%s" % ( + err_msg = "Unable to connect to bucket: {}. Error message:\n{}".format( bucket_name, exc, ) except Exception as exc: - err_msg = "Unable to connect to bucket: %s. Error message:\n%s" % ( + err_msg = "Unable to connect to bucket: {}. Error message:\n{}".format( bucket_name, exc, ) @@ -155,22 +155,21 @@ def _list_outputs(self): raise NotImplementedError def _outputs(self): - return self._add_output_traits(super(IOBase, self)._outputs()) + return self._add_output_traits(super()._outputs()) def _add_output_traits(self, base): return base # Class to track percentage of S3 file upload -class ProgressPercentage(object): +class ProgressPercentage: """ - Callable class instsance (via __call__ method) that displays + Callable class instance (via __call__ method) that displays upload percentage of a file to S3 """ def __init__(self, filename): - """ - """ + """ """ # Import packages import threading @@ -182,8 +181,7 @@ def __init__(self, filename): self._lock = threading.Lock() def __call__(self, bytes_amount): - """ - """ + """ """ # Import packages import sys @@ -208,8 +206,7 @@ def __call__(self, bytes_amount): # DataSink inputs class DataSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - """ - """ + """ """ # Init inputspec data attributes base_directory = Str(desc="Path to the base directory for storing data.") @@ -219,7 +216,7 @@ class DataSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): ) strip_dir = Str(desc="path to strip out of filename") substitutions = InputMultiPath( - traits.Tuple(Str, Str), + Tuple(Str, Str), desc=( "List of 2-tuples reflecting string " "to substitute and string to replace " @@ -227,7 +224,7 @@ class DataSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): ), ) regexp_substitutions = InputMultiPath( - traits.Tuple(Str, Str), + Tuple(Str, Str), desc=( "List of 2-tuples reflecting a pair of a " "Python regexp pattern and a replacement " @@ -248,7 +245,7 @@ class DataSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): "AWS_SECRET_ACCESS_KEY environment variables" ) encrypt_bucket_keys = traits.Bool( - desc="Flag indicating whether to use S3 " "server-side AES-256 encryption" + desc="Flag indicating whether to use S3 server-side AES-256 encryption" ) # Set this if user wishes to override the bucket with their own bucket = traits.Any(desc="Boto3 S3 bucket for manual override of bucket") @@ -257,20 +254,18 @@ class DataSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): # Set call-able inputs attributes def __setattr__(self, key, value): - if key not in self.copyable_trait_names(): if not isdefined(value): - super(DataSinkInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) self._outputs[key] = value else: if key in self._outputs: self._outputs[key] = value - super(DataSinkInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) # DataSink outputs class DataSinkOutputSpec(TraitedSpec): - # Init out file out_file = traits.Any(desc="datasink output") @@ -351,7 +346,7 @@ def __init__(self, infields=None, force_run=True, **kwargs): Indicates the input fields to be dynamically created """ - super(DataSink, self).__init__(**kwargs) + super().__init__(**kwargs) undefined_traits = {} # used for mandatory inputs check self._infields = infields @@ -450,7 +445,7 @@ def _check_s3_base_dir(self): s3_flag = base_directory.lower().startswith(s3_str) if s3_flag: - bucket_name = base_directory[len(s3_str):].partition('/')[0] + bucket_name = base_directory[len(s3_str) :].partition("/")[0] return s3_flag, bucket_name @@ -481,7 +476,7 @@ def _return_aws_keys(self): # Check if creds exist if creds_path and os.path.exists(creds_path): - with open(creds_path, "r") as creds_in: + with open(creds_path) as creds_in: # Grab csv rows row1 = creds_in.readline() row2 = creds_in.readline() @@ -535,8 +530,8 @@ def _fetch_bucket(self, bucket_name): try: import boto3 import botocore - except ImportError as exc: - err_msg = "Boto3 package is not installed - install boto3 and " "try again." + except ImportError: + err_msg = "Boto3 package is not installed - install boto3 and try again." raise Exception(err_msg) # Init variables @@ -577,8 +572,7 @@ def _fetch_bucket(self, bucket_name): # And try fetch the bucket with the name argument try: _get_head_bucket(s3_resource, bucket_name) - except Exception as exc: - + except Exception: # Try to connect anonymously s3_resource.meta.client.meta.events.register( "choose-signer.s3.*", botocore.handlers.disable_signing @@ -610,7 +604,7 @@ def _upload_to_s3(self, bucket, src, dst): # Explicitly lower-case the "s3" if dst.lower().startswith(s3_str): - dst = s3_str + dst[len(s3_str):] + dst = s3_str + dst[len(s3_str) :] # If src is a directory, collect files (this assumes dst is a dir too) if os.path.isdir(src): @@ -661,8 +655,7 @@ def _upload_to_s3(self, bucket, src, dst): # List outputs, main run routine def _list_outputs(self): - """Execute this module. - """ + """Execute this module.""" # Init variables outputs = self.output_spec().get() @@ -768,7 +761,7 @@ def _list_outputs(self): out_files.append(s3dst) # Otherwise, copy locally src -> dst if not s3_flag or isdefined(self.inputs.local_copy): - # Create output directory if it doesnt exist + # Create output directory if it doesn't exist if not os.path.exists(path): try: os.makedirs(path) @@ -893,7 +886,7 @@ def __init__(self, infields=None, outfields=None, **kwargs): """ if not outfields: outfields = ["outfiles"] - super(S3DataGrabber, self).__init__(**kwargs) + super().__init__(**kwargs) undefined_traits = {} # used for mandatory inputs check self._infields = infields @@ -949,7 +942,7 @@ def _list_outputs(self): # get list of all files in s3 bucket conn = boto.connect_s3(anon=self.inputs.anon) bkt = conn.get_bucket(self.inputs.bucket) - bkt_files = list(k.key for k in bkt.list(prefix=self.inputs.bucket_path)) + bkt_files = [k.key for k in bkt.list(prefix=self.inputs.bucket_path)] # keys are outfields, args are template args for the outfield for key, args in list(self.inputs.template_args.items()): @@ -966,24 +959,21 @@ def _list_outputs(self): if isdefined(self.inputs.bucket_path): template = os.path.join(self.inputs.bucket_path, template) if not args: - filelist = [] - for fname in bkt_files: - if re.match(template, fname): - filelist.append(fname) + filelist = [fname for fname in bkt_files if re.match(template, fname)] if len(filelist) == 0: - msg = "Output key: %s Template: %s returned no files" % ( + msg = "Output key: {} Template: {} returned no files".format( key, template, ) if self.inputs.raise_on_empty: - raise IOError(msg) + raise OSError(msg) else: warn(msg) else: if self.inputs.sort_filelist: filelist = human_order_sorted(filelist) outputs[key] = simplify_list(filelist) - for argnum, arglist in enumerate(args): + for arglist in args: maxlen = 1 for arg in arglist: if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): @@ -1011,21 +1001,20 @@ def _list_outputs(self): filledtemplate = template % tuple(argtuple) except TypeError as e: raise TypeError( - e.message - + ": Template %s failed to convert with args %s" - % (template, str(tuple(argtuple))) + f"{e}: Template {template} failed to convert " + f"with args {tuple(argtuple)}" ) outfiles = [] for fname in bkt_files: if re.match(filledtemplate, fname): outfiles.append(fname) if len(outfiles) == 0: - msg = "Output key: %s Template: %s returned no files" % ( + msg = "Output key: {} Template: {} returned no files".format( key, filledtemplate, ) if self.inputs.raise_on_empty: - raise IOError(msg) + raise OSError(msg) else: warn(msg) outputs[key].append(None) @@ -1033,7 +1022,7 @@ def _list_outputs(self): if self.inputs.sort_filelist: outfiles = human_order_sorted(outfiles) outputs[key].append(simplify_list(outfiles)) - if any([val is None for val in outputs[key]]): + if None in outputs[key]: outputs[key] = [] if len(outputs[key]) == 0: outputs[key] = None @@ -1064,9 +1053,9 @@ def s3tolocal(self, s3path, bkt): local_directory = str(self.inputs.local_directory) bucket_path = str(self.inputs.bucket_path) template = str(self.inputs.template) - if not os.path.basename(local_directory) == "": + if os.path.basename(local_directory) != "": local_directory += "/" - if not os.path.basename(bucket_path) == "": + if os.path.basename(bucket_path) != "": bucket_path += "/" if template[0] == "/": template = template[1:] @@ -1179,7 +1168,7 @@ def __init__(self, infields=None, outfields=None, **kwargs): """ if not outfields: outfields = ["outfiles"] - super(DataGrabber, self).__init__(**kwargs) + super().__init__(**kwargs) undefined_traits = {} # used for mandatory inputs check self._infields = infields @@ -1247,19 +1236,19 @@ def _list_outputs(self): if not args: filelist = glob.glob(template) if len(filelist) == 0: - msg = "Output key: %s Template: %s returned no files" % ( + msg = "Output key: {} Template: {} returned no files".format( key, template, ) if self.inputs.raise_on_empty: - raise IOError(msg) + raise OSError(msg) else: warn(msg) else: if self.inputs.sort_filelist: filelist = human_order_sorted(filelist) outputs[key] = simplify_list(filelist) - for argnum, arglist in enumerate(args): + for arglist in args: maxlen = 1 for arg in arglist: if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): @@ -1287,18 +1276,17 @@ def _list_outputs(self): filledtemplate = template % tuple(argtuple) except TypeError as e: raise TypeError( - e.message - + ": Template %s failed to convert with args %s" - % (template, str(tuple(argtuple))) + f"{e}: Template {template} failed to convert " + f"with args {tuple(argtuple)}" ) outfiles = glob.glob(filledtemplate) if len(outfiles) == 0: - msg = "Output key: %s Template: %s returned no files" % ( + msg = "Output key: {} Template: {} returned no files".format( key, filledtemplate, ) if self.inputs.raise_on_empty: - raise IOError(msg) + raise OSError(msg) else: warn(msg) outputs[key].append(None) @@ -1309,7 +1297,7 @@ def _list_outputs(self): if self.inputs.drop_blank_outputs: outputs[key] = [x for x in outputs[key] if x is not None] else: - if any([val is None for val in outputs[key]]): + if None in outputs[key]: outputs[key] = [] if len(outputs[key]) == 0: outputs[key] = None @@ -1319,17 +1307,16 @@ def _list_outputs(self): class SelectFilesInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - base_directory = Directory(exists=True, desc="Root path common to templates.") sort_filelist = traits.Bool( True, usedefault=True, - desc="When matching mutliple files, return them" " in sorted order.", + desc="When matching multiple files, return them in sorted order.", ) raise_on_empty = traits.Bool( True, usedefault=True, - desc="Raise an exception if a template pattern " "matches no files.", + desc="Raise an exception if a template pattern matches no files.", ) force_lists = traits.Either( traits.Bool(), @@ -1350,31 +1337,35 @@ class SelectFiles(IOBase): """ Flexibly collect data from disk to feed into workflows. - This interface uses the {}-based string formatting syntax to plug + This interface uses Python's {}-based string formatting syntax to plug values (possibly known only at workflow execution time) into string - templates and collect files from persistant storage. These templates - can also be combined with glob wildcards. The field names in the - formatting template (i.e. the terms in braces) will become inputs - fields on the interface, and the keys in the templates dictionary - will form the output fields. + templates and collect files from persistent storage. These templates can + also be combined with glob wildcards (``*``, ``?``) and character ranges (``[...]``). + The field names in the formatting template (i.e. the terms in braces) will + become inputs fields on the interface, and the keys in the templates + dictionary will form the output fields. Examples -------- >>> import pprint >>> from nipype import SelectFiles, Node >>> templates={"T1": "{subject_id}/struct/T1.nii", - ... "epi": "{subject_id}/func/f[0, 1].nii"} + ... "epi": "{subject_id}/func/f[0,1].nii"} >>> dg = Node(SelectFiles(templates), "selectfiles") >>> dg.inputs.subject_id = "subj1" >>> pprint.pprint(dg.outputs.get()) # doctest: {'T1': , 'epi': } - The same thing with dynamic grabbing of specific files: + Note that SelectFiles does not support lists as inputs for the dynamic + fields. Attempts to do so may lead to unexpected results because brackets + also express glob character ranges. For example, - >>> templates["epi"] = "{subject_id}/func/f{run!s}.nii" + >>> templates["epi"] = "{subject_id}/func/f{run}.nii" >>> dg = Node(SelectFiles(templates), "selectfiles") >>> dg.inputs.subject_id = "subj1" - >>> dg.inputs.run = [2, 4] + >>> dg.inputs.run = [10, 11] + + would match f0.nii or f1.nii, not f10.nii or f11.nii. """ @@ -1398,14 +1389,14 @@ def __init__(self, templates, **kwargs): used to select files. """ - super(SelectFiles, self).__init__(**kwargs) + super().__init__(**kwargs) # Infer the infields and outfields from the template infields = [] for name, template in list(templates.items()): for _, field_name, _, _ in string.Formatter().parse(template): if field_name is not None: - field_name = re.match("\w+", field_name).group() + field_name = re.match(r"\w+", field_name).group() if field_name not in infields: infields.append(field_name) @@ -1427,13 +1418,9 @@ def _add_output_traits(self, base): def _list_outputs(self): """Find the files and expose them as interface outputs.""" outputs = {} - info = dict( - [ - (k, v) - for k, v in list(self.inputs.__dict__.items()) - if k in self._infields - ] - ) + info = { + k: v for k, v in list(self.inputs.__dict__.items()) if k in self._infields + } force_lists = self.inputs.force_lists if isinstance(force_lists, bool): @@ -1444,12 +1431,11 @@ def _list_outputs(self): plural = "s" if len(bad_fields) > 1 else "" verb = "were" if len(bad_fields) > 1 else "was" msg = ( - "The field%s '%s' %s set in 'force_lists' and not in " "'templates'." + "The field%s '%s' %s set in 'force_lists' and not in 'templates'." ) % (plural, bad_fields, verb) raise ValueError(msg) for field, template in list(self._templates.items()): - find_dirs = template[-1] == os.sep # Build the full template path @@ -1468,12 +1454,12 @@ def _list_outputs(self): # Handle the case where nothing matched if not filelist: - msg = "No files were found matching %s template: %s" % ( + msg = "No files were found matching {} template: {}".format( field, filled_template, ) if self.inputs.raise_on_empty: - raise IOError(msg) + raise OSError(msg) else: warn(msg) @@ -1491,7 +1477,7 @@ def _list_outputs(self): class DataFinderInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - root_paths = traits.Either(traits.List(), Str(), mandatory=True,) + root_paths = traits.Either(traits.List(), Str(), mandatory=True) match_regex = Str( "(.+)", usedefault=True, desc=("Regular expression for matching paths.") ) @@ -1502,8 +1488,8 @@ class DataFinderInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): "ignored." ) ) - max_depth = traits.Int(desc="The maximum depth to search beneath " "the root_paths") - min_depth = traits.Int(desc="The minimum depth to search beneath " "the root paths") + max_depth = traits.Int(desc="The maximum depth to search beneath the root_paths") + min_depth = traits.Int(desc="The minimum depth to search beneath the root paths") unpack_single = traits.Bool( False, usedefault=True, desc="Unpack single results from list" ) @@ -1515,7 +1501,7 @@ class DataFinder(IOBase): Will recursively search any subdirectories by default. This can be limited with the min/max depth options. Matched paths are available in the output 'out_paths'. Any named groups of - captured text from the regular expression are also available as ouputs of + captured text from the regular expression are also available as outputs of the same name. Examples @@ -1585,7 +1571,7 @@ def _run_interface(self, runtime): ] self.result = None for root_path in self.inputs.root_paths: - # Handle tilda/env variables and remove extra seperators + # Handle tilda/env variables and remove extra separators root_path = os.path.normpath( os.path.expandvars(os.path.expanduser(root_path)) ) @@ -1614,7 +1600,7 @@ def _run_interface(self, runtime): for key, vals in list(self.result.items()): self.result[key] = vals[0] else: - # sort all keys acording to out_paths + # sort all keys according to out_paths for key in list(self.result.keys()): if key == "out_paths": continue @@ -1685,7 +1671,7 @@ class FSSourceOutputSpec(TraitedSpec): File(exists=True), desc="Inflated surface meshes", loc="surf" ) pial = OutputMultiPath( - File(exists=True), desc="Gray matter/pia mater surface meshes", loc="surf" + File(exists=True), desc="Gray matter/pia matter surface meshes", loc="surf" ) area_pial = OutputMultiPath( File(exists=True), @@ -1832,7 +1818,7 @@ def _get_files(self, path, key, dirval, altkey=None): else: globprefix = "*" keys = ensure_list(altkey) if altkey else [key] - globfmt = os.path.join(path, dirval, "".join((globprefix, "{}", globsuffix))) + globfmt = os.path.join(path, dirval, f"{globprefix}{{}}{globsuffix}") return [ os.path.abspath(f) for key in keys for f in glob.glob(globfmt.format(key)) ] @@ -1855,10 +1841,9 @@ def _list_outputs(self): class XNATSourceInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - query_template = Str( mandatory=True, - desc=("Layout used to get files. Relative to base " "directory if defined"), + desc="Layout used to get files. Relative to base directory if defined", ) query_template_args = traits.Dict( @@ -1928,7 +1913,7 @@ def __init__(self, infields=None, outfields=None, **kwargs): See class examples for usage """ - super(XNATSource, self).__init__(**kwargs) + super().__init__(**kwargs) undefined_traits = {} # used for mandatory inputs check self._infields = infields @@ -2000,7 +1985,7 @@ def _list_outputs(self): if not args: file_objects = xnat.select(template).get("obj") if file_objects == []: - raise IOError("Template %s returned no files" % template) + raise OSError("Template %s returned no files" % template) outputs[key] = simplify_list( [ str(file_object.get()) @@ -2008,7 +1993,7 @@ def _list_outputs(self): if file_object.exists() ] ) - for argnum, arglist in enumerate(args): + for arglist in args: maxlen = 1 for arg in arglist: if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): @@ -2016,7 +2001,7 @@ def _list_outputs(self): if isinstance(arg, list): if (maxlen > 1) and (len(arg) != maxlen): raise ValueError( - "incompatible number " "of arguments for %s" % key + "incompatible number of arguments for %s" % key ) if len(arg) > maxlen: maxlen = len(arg) @@ -2035,7 +2020,7 @@ def _list_outputs(self): file_objects = xnat.select(target).get("obj") if file_objects == []: - raise IOError("Template %s " "returned no files" % target) + raise OSError("Template %s returned no files" % target) outfiles = simplify_list( [ @@ -2048,7 +2033,7 @@ def _list_outputs(self): file_objects = xnat.select(template).get("obj") if file_objects == []: - raise IOError("Template %s " "returned no files" % template) + raise OSError("Template %s returned no files" % template) outfiles = simplify_list( [ @@ -2067,7 +2052,6 @@ def _list_outputs(self): class XNATSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): - _outputs = traits.Dict(Str, value={}, usedefault=True) server = Str(mandatory=True, requires=["user", "pwd"], xor=["config"]) @@ -2085,7 +2069,7 @@ class XNATSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): assessor_id = Str( desc=( - "Option to customize ouputs representation in XNAT - " + "Option to customize outputs representation in XNAT - " "assessor level will be used with specified id" ), xor=["reconstruction_id"], @@ -2093,7 +2077,7 @@ class XNATSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): reconstruction_id = Str( desc=( - "Option to customize ouputs representation in XNAT - " + "Option to customize outputs representation in XNAT - " "reconstruction level will be used with specified id" ), xor=["assessor_id"], @@ -2113,21 +2097,20 @@ def __setattr__(self, key, value): if key not in self.copyable_trait_names(): self._outputs[key] = value else: - super(XNATSinkInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) class XNATSink(LibraryBaseInterface, IOBase): - """ Generic datasink module that takes a directory containing a - list of nifti files and provides a set of structured output - fields. + """Generic datasink module that takes a directory containing a + list of nifti files and provides a set of structured output + fields. """ input_spec = XNATSinkInputSpec _pkg = "pyxnat" def _list_outputs(self): - """Execute this module. - """ + """Execute this module.""" import pyxnat # setup XNAT connection @@ -2157,14 +2140,13 @@ def _list_outputs(self): ) if not shared.exists(): # subject not in share project - share_project = xnat.select("/project/%s" % self.inputs.project_id) if not share_project.exists(): # check project exists share_project.insert() subject = xnat.select( - "/project/%(project)s" "/subject/%(subject_id)s" % result + "/project/%(project)s/subject/%(subject_id)s" % result ) subject.share(str(self.inputs.project_id)) @@ -2188,9 +2170,7 @@ def _list_outputs(self): # gather outputs and upload them for key, files in list(self.inputs._outputs.items()): - for name in ensure_list(files): - if isinstance(name, list): for i, file_name in enumerate(name): push_file( @@ -2209,7 +2189,6 @@ def unquote_id(string): def push_file(self, xnat, file_name, out_key, uri_template_args): - # grab info from output file names val_list = [ unquote_id(val) @@ -2246,7 +2225,7 @@ def push_file(self, xnat, file_name, out_key, uri_template_args): uri_template_args["container_id"] += "_results" # define resource level - uri_template_args["resource_label"] = "%s_%s" % ( + uri_template_args["resource_label"] = "{}_{}".format( uri_template_args["container_id"], out_key.split(".")[0], ) @@ -2272,7 +2251,6 @@ def push_file(self, xnat, file_name, out_key, uri_template_args): # shares the experiment back to the original project if relevant if "original_project" in uri_template_args: - experiment_template = ( "/project/%(original_project)s" "/subject/%(subject_id)s/experiment/%(experiment_id)s" @@ -2321,15 +2299,13 @@ class SQLiteSink(LibraryBaseInterface, IOBase): _pkg = "sqlite3" def __init__(self, input_names, **inputs): - - super(SQLiteSink, self).__init__(**inputs) + super().__init__(**inputs) self._input_names = ensure_list(input_names) - add_traits(self.inputs, [name for name in self._input_names]) + add_traits(self.inputs, self._input_names) def _list_outputs(self): - """Execute this module. - """ + """Execute this module.""" import sqlite3 conn = sqlite3.connect(self.inputs.database_file, check_same_thread=False) @@ -2385,15 +2361,13 @@ class MySQLSink(IOBase): input_spec = MySQLSinkInputSpec def __init__(self, input_names, **inputs): - - super(MySQLSink, self).__init__(**inputs) + super().__init__(**inputs) self._input_names = ensure_list(input_names) - add_traits(self.inputs, [name for name in self._input_names]) + add_traits(self.inputs, self._input_names) def _list_outputs(self): - """Execute this module. - """ + """Execute this module.""" import MySQLdb if isdefined(self.inputs.config): @@ -2528,10 +2502,10 @@ def __init__(self, infields=None, outfields=None, **kwargs): kwargs = kwargs.copy() kwargs["infields"] = infields kwargs["outfields"] = outfields - super(SSHDataGrabber, self).__init__(**kwargs) + super().__init__(**kwargs) if None in (self.inputs.username, self.inputs.password): raise ValueError( - "either both username and password " "are provided or none of them" + "either both username and password are provided or none of them" ) if ( @@ -2563,7 +2537,7 @@ def _get_files_over_ssh(self, template): # no files msg = "Output template: %s returned no files" % template if self.inputs.raise_on_empty: - raise IOError(msg) + raise OSError(msg) else: warn(msg) @@ -2594,7 +2568,7 @@ def _get_files_over_ssh(self, template): for f in files_to_download: try: sftp.get(os.path.join(template_dir, f), f) - except IOError: + except OSError: iflogger.info("remote file %s not found" % f) # return value @@ -2633,7 +2607,7 @@ def _list_outputs(self): if not args: outputs[key] = self._get_files_over_ssh(template) - for argnum, arglist in enumerate(args): + for arglist in args: maxlen = 1 for arg in arglist: if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg): @@ -2645,7 +2619,6 @@ def _list_outputs(self): ) if len(arg) > maxlen: maxlen = len(arg) - outfiles = [] for i in range(maxlen): argtuple = [] for arg in arglist: @@ -2661,15 +2634,14 @@ def _list_outputs(self): filledtemplate = template % tuple(argtuple) except TypeError as e: raise TypeError( - e.message - + ": Template %s failed to convert with args %s" - % (template, str(tuple(argtuple))) + f"{e}: Template {template} failed to convert " + f"with args {tuple(argtuple)}" ) outputs[key].append(self._get_files_over_ssh(filledtemplate)) # disclude where there was any invalid matches - if any([val is None for val in outputs[key]]): + if None in outputs[key]: outputs[key] = [] # no outputs is None, not empty list @@ -2744,16 +2716,14 @@ class JSONFileGrabber(IOBase): def _list_outputs(self): import simplejson - outputs = {} if isdefined(self.inputs.in_file): - with open(self.inputs.in_file, "r") as f: - data = simplejson.load(f) + with open(self.inputs.in_file) as f: + outputs = simplejson.load(f) - if not isinstance(data, dict): + if not isinstance(outputs, dict): raise RuntimeError("JSON input has no dictionary structure") - - for key, value in list(data.items()): - outputs[key] = value + else: + outputs = {} if isdefined(self.inputs.defaults): defaults = self.inputs.defaults @@ -2772,12 +2742,12 @@ class JSONFileSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec): def __setattr__(self, key, value): if key not in self.copyable_trait_names(): if not isdefined(value): - super(JSONFileSinkInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) self._outputs[key] = value else: if key in self._outputs: self._outputs[key] = value - super(JSONFileSinkInputSpec, self).__setattr__(key, value) + super().__setattr__(key, value) class JSONFileSinkOutputSpec(TraitedSpec): @@ -2816,7 +2786,7 @@ class JSONFileSink(IOBase): output_spec = JSONFileSinkOutputSpec def __init__(self, infields=[], force_run=True, **inputs): - super(JSONFileSink, self).__init__(**inputs) + super().__init__(**inputs) self._input_names = infields undefined_traits = {} @@ -2872,6 +2842,9 @@ class BIDSDataGrabberInputSpec(DynamicTraitedSpec): output_query = traits.Dict( key_trait=Str, value_trait=traits.Dict, desc="Queries for outfield outputs" ) + load_layout = Directory( + exists=True, desc="Path to load already saved Bidslayout.", mandatory=False + ) raise_on_empty = traits.Bool( True, usedefault=True, @@ -2891,6 +2864,14 @@ class BIDSDataGrabber(LibraryBaseInterface, IOBase): Examples -------- + + .. setup:: + + >>> try: + ... import bids + ... except ImportError: + ... pytest.skip() + By default, the BIDSDataGrabber fetches anatomical and functional images from a project, and makes BIDS entities (e.g. subject) available for filtering outputs. @@ -2926,19 +2907,19 @@ def __init__(self, infields=None, **kwargs): infields : list of str Indicates the input fields to be dynamically created """ - super(BIDSDataGrabber, self).__init__(**kwargs) + super().__init__(**kwargs) if not isdefined(self.inputs.output_query): self.inputs.output_query = { "bold": { "datatype": "func", "suffix": "bold", - "extensions": ["nii", ".nii.gz"], + "extension": ["nii", ".nii.gz"], }, "T1w": { "datatype": "anat", "suffix": "T1w", - "extensions": ["nii", ".nii.gz"], + "extension": ["nii", ".nii.gz"], }, } @@ -2947,7 +2928,7 @@ def __init__(self, infields=None, **kwargs): from bids import layout as bidslayout bids_config = join(dirname(bidslayout.__file__), "config", "bids.json") - bids_config = json.load(open(bids_config, "r")) + bids_config = json.load(open(bids_config)) infields = [i["name"] for i in bids_config["entities"]] self._infields = infields or [] @@ -2956,16 +2937,20 @@ def __init__(self, infields=None, **kwargs): undefined_traits = {} for key in self._infields: self.inputs.add_trait(key, traits.Any) - undefined_traits[key] = kwargs[key] if key in kwargs else Undefined + undefined_traits[key] = kwargs.get(key, Undefined) self.inputs.trait_set(trait_change_notify=False, **undefined_traits) def _list_outputs(self): from bids import BIDSLayout - layout = BIDSLayout( - self.inputs.base_dir, derivatives=self.inputs.index_derivatives - ) + # if load_layout is given load layout which is on some datasets much faster + if isdefined(self.inputs.load_layout): + layout = BIDSLayout.load(self.inputs.load_layout) + else: + layout = BIDSLayout( + self.inputs.base_dir, derivatives=self.inputs.index_derivatives + ) if isdefined(self.inputs.extra_derivatives): layout.add_derivatives(self.inputs.extra_derivatives) @@ -2985,7 +2970,7 @@ def _list_outputs(self): if len(filelist) == 0: msg = "Output key: %s returned no files" % key if self.inputs.raise_on_empty: - raise IOError(msg) + raise OSError(msg) else: iflogger.warning(msg) filelist = Undefined @@ -3001,7 +2986,9 @@ class ExportFileInputSpec(BaseInterfaceInputSpec): in_file = File(exists=True, mandatory=True, desc="Input file name") out_file = File(mandatory=True, desc="Output file name") check_extension = traits.Bool( - True, desc="Ensure that the input and output file extensions match" + True, + usedefault=True, + desc="Ensure that the input and output file extensions match", ) clobber = traits.Bool(desc="Permit overwriting existing files") diff --git a/nipype/interfaces/matlab.py b/nipype/interfaces/matlab.py index 59c36eb478..de959988f4 100644 --- a/nipype/interfaces/matlab.py +++ b/nipype/interfaces/matlab.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Interfaces to run MATLAB scripts.""" @@ -17,32 +16,18 @@ def get_matlab_command(): - if "NIPYPE_NO_MATLAB" in os.environ: - return None - - try: - matlab_cmd = os.environ["MATLABCMD"] - except: - matlab_cmd = "matlab" - - try: - res = CommandLine( - command="which", - args=matlab_cmd, - resource_monitor=False, - terminal_output="allatonce", - ).run() - matlab_path = res.runtime.stdout.strip() - except Exception: - return None - return matlab_cmd + """Determine whether Matlab is installed and can be executed.""" + if "NIPYPE_NO_MATLAB" not in os.environ: + from nipype.utils.filemanip import which + + return which(os.getenv("MATLABCMD", "matlab")) no_matlab = get_matlab_command() is None class MatlabInputSpec(CommandLineInputSpec): - """ Basic expected inputs to Matlab interface """ + """Basic expected inputs to Matlab interface""" script = traits.Str( argstr='-r "%s;exit"', desc="m-code to run", mandatory=True, position=-1 @@ -111,7 +96,7 @@ def __init__(self, matlab_cmd=None, **inputs): """initializes interface to matlab (default 'matlab -nodesktop -nosplash') """ - super(MatlabCommand, self).__init__(**inputs) + super().__init__(**inputs) if matlab_cmd and isdefined(matlab_cmd): self._cmd = matlab_cmd elif self._default_matlab_cmd: @@ -167,7 +152,7 @@ def set_default_paths(cls, paths): def _run_interface(self, runtime): self.terminal_output = "allatonce" - runtime = super(MatlabCommand, self)._run_interface(runtime) + runtime = super()._run_interface(runtime) try: # Matlab can leave the terminal in a barbbled state os.system("stty sane") @@ -184,10 +169,10 @@ def _format_arg(self, name, trait_spec, value): if self.inputs.uses_mcr: argstr = "%s" return self._gen_matlab_command(argstr, value) - return super(MatlabCommand, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _gen_matlab_command(self, argstr, script_lines): - """ Generates commands and, if mfile specified, writes it to disk.""" + """Generates commands and, if mfile specified, writes it to disk.""" cwd = os.getcwd() mfile = self.inputs.mfile or self.inputs.uses_mcr paths = [] @@ -205,7 +190,10 @@ def _gen_matlab_command(self, argstr, script_lines): else: prescript.insert(0, "fprintf(1,'Executing code at %s:\\n',datestr(now));") for path in paths: - prescript.append("addpath('%s');\n" % path) + # addpath() is not available after compilation + # https://www.mathworks.com/help/compiler/ismcc.html + # https://www.mathworks.com/help/compiler/isdeployed.html + prescript.append("if ~(ismcc || isdeployed), addpath('%s'); end;\n" % path) if not mfile: # clean up the code of comments and replace newlines with commas @@ -219,12 +207,12 @@ def _gen_matlab_command(self, argstr, script_lines): script_lines = "\n".join(prescript) + script_lines + "\n".join(postscript) if mfile: - with open(os.path.join(cwd, self.inputs.script_file), "wt") as mfile: + with open(os.path.join(cwd, self.inputs.script_file), "w") as mfile: mfile.write(script_lines) if self.inputs.uses_mcr: script = "%s" % (os.path.join(cwd, self.inputs.script_file)) else: - script = "addpath('%s');%s" % ( + script = "addpath('{}');{}".format( cwd, self.inputs.script_file.split(".")[0], ) diff --git a/nipype/interfaces/meshfix.py b/nipype/interfaces/meshfix.py index 505426bfe2..097fdf4010 100644 --- a/nipype/interfaces/meshfix.py +++ b/nipype/interfaces/meshfix.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """MeshFix corrects topological errors in polygonal meshes.""" diff --git a/nipype/interfaces/minc/__init__.py b/nipype/interfaces/minc/__init__.py index a69e38eeb2..b05ef82b5d 100644 --- a/nipype/interfaces/minc/__init__.py +++ b/nipype/interfaces/minc/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The MINC (McConnell Brain Imaging Centre, Montreal Neurological Institute) toolkit. diff --git a/nipype/interfaces/minc/base.py b/nipype/interfaces/minc/base.py index 5aca3e434e..8731627693 100644 --- a/nipype/interfaces/minc/base.py +++ b/nipype/interfaces/minc/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The minc module provides classes for interfacing with the `MINC @@ -18,19 +17,17 @@ def check_minc(): - """Returns True if and only if MINC is installed.' - """ + """Returns True if and only if MINC is installed.'""" return Info.version() is not None def no_minc(): - """Returns True if and only if MINC is *not* installed. - """ + """Returns True if and only if MINC is *not* installed.""" return not check_minc() -class Info(object): +class Info: """Handle MINC version information. version refers to the version of MINC on the system @@ -54,7 +51,7 @@ def version(): clout = CommandLine( command="mincinfo", args="-version", terminal_output="allatonce" ).run() - except IOError: + except OSError: return None out = clout.runtime.stdout @@ -79,15 +76,10 @@ def read_hdf5_version(s): return s.split(":")[1].strip() return None - versions = { - "minc": None, - "libminc": None, - "netcdf": None, - "hdf5": None, - } + versions = {"minc": None, "libminc": None, "netcdf": None, "hdf5": None} for l in out.split("\n"): - for (name, f) in [ + for name, f in [ ("minc", read_program_version), ("libminc", read_libminc_version), ("netcdf", read_netcdf_version), diff --git a/nipype/interfaces/minc/minc.py b/nipype/interfaces/minc/minc.py index 14c29f7b1b..bf80e23732 100644 --- a/nipype/interfaces/minc/minc.py +++ b/nipype/interfaces/minc/minc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The minc module provides classes for interfacing with the `MINC @@ -24,6 +23,7 @@ InputMultiPath, OutputMultiPath, traits, + Tuple, isdefined, ) from .base import aggregate_filename @@ -33,7 +33,7 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): input_file = File( - desc="input file", exists=True, mandatory=True, argstr="%s", position=-2, + desc="input file", exists=True, mandatory=True, argstr="%s", position=-2 ) output_file = File( @@ -102,17 +102,14 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): desc="Write out unsigned data.", argstr="-unsigned", xor=_xor_signed ) - write_range = traits.Tuple( + write_range = Tuple( traits.Float, traits.Float, argstr="-range %s %s", desc="Specify the range of output values\nDefault value: 1.79769e+308 1.79769e+308.", ) - _xor_normalize = ( - "normalize", - "nonormalize", - ) + _xor_normalize = ("normalize", "nonormalize") normalize = traits.Bool( desc="Normalize integer pixel values to file max and min.", @@ -124,7 +121,7 @@ class ExtractInputSpec(StdOutCommandLineInputSpec): desc="Turn off pixel normalization.", argstr="-nonormalize", xor=_xor_normalize ) - image_range = traits.Tuple( + image_range = Tuple( traits.Float, traits.Float, desc="Specify the range of real image values for normalization.", @@ -265,7 +262,7 @@ class Extract(StdOutCommandLine): class ToRawInputSpec(StdOutCommandLineInputSpec): input_file = File( - desc="input file", exists=True, mandatory=True, argstr="%s", position=-2, + desc="input file", exists=True, mandatory=True, argstr="%s", position=-2 ) output_file = File( @@ -324,7 +321,7 @@ class ToRawInputSpec(StdOutCommandLineInputSpec): desc="Write out unsigned data.", argstr="-unsigned", xor=_xor_signed ) - write_range = traits.Tuple( + write_range = Tuple( traits.Float, traits.Float, argstr="-range %s %s", @@ -334,10 +331,7 @@ class ToRawInputSpec(StdOutCommandLineInputSpec): ), ) - _xor_normalize = ( - "normalize", - "nonormalize", - ) + _xor_normalize = ("normalize", "nonormalize") normalize = traits.Bool( desc="Normalize integer pixel values to file max and min.", @@ -356,7 +350,7 @@ class ToRawOutputSpec(TraitedSpec): class ToRaw(StdOutCommandLine): """Dump a chunk of MINC file data. This program is largely - superceded by mincextract (see Extract). + superseded by mincextract (see Extract). Examples -------- @@ -456,11 +450,7 @@ class Convert(CommandLine): class CopyInputSpec(CommandLineInputSpec): input_file = File( - desc="input file to copy", - exists=True, - mandatory=True, - argstr="%s", - position=-2, + desc="input file to copy", exists=True, mandatory=True, argstr="%s", position=-2 ) output_file = File( @@ -528,38 +518,37 @@ class ToEcatInputSpec(CommandLineInputSpec): ) ignore_patient_variable = traits.Bool( - desc="Ignore informations from the minc patient variable.", + desc="Ignore information from the minc patient variable.", argstr="-ignore_patient_variable", ) ignore_study_variable = traits.Bool( - desc="Ignore informations from the minc study variable.", + desc="Ignore information from the minc study variable.", argstr="-ignore_study_variable", ) ignore_acquisition_variable = traits.Bool( - desc="Ignore informations from the minc acquisition variable.", + desc="Ignore information from the minc acquisition variable.", argstr="-ignore_acquisition_variable", ) ignore_ecat_acquisition_variable = traits.Bool( - desc="Ignore informations from the minc ecat_acquisition variable.", + desc="Ignore information from the minc ecat_acquisition variable.", argstr="-ignore_ecat_acquisition_variable", ) ignore_ecat_main = traits.Bool( - desc="Ignore informations from the minc ecat-main variable.", + desc="Ignore information from the minc ecat-main variable.", argstr="-ignore_ecat_main", ) ignore_ecat_subheader_variable = traits.Bool( - desc="Ignore informations from the minc ecat-subhdr variable.", + desc="Ignore information from the minc ecat-subhdr variable.", argstr="-ignore_ecat_subheader_variable", ) no_decay_corr_fctr = traits.Bool( - desc="Do not compute the decay correction factors", - argstr="-no_decay_corr_fctr", + desc="Do not compute the decay correction factors", argstr="-no_decay_corr_fctr" ) voxels_as_integers = traits.Bool( @@ -600,7 +589,7 @@ class ToEcat(CommandLine): class DumpInputSpec(StdOutCommandLineInputSpec): input_file = File( - desc="input file", exists=True, mandatory=True, argstr="%s", position=-2, + desc="input file", exists=True, mandatory=True, argstr="%s", position=-2 ) output_file = File( @@ -612,10 +601,7 @@ class DumpInputSpec(StdOutCommandLineInputSpec): keep_extension=False, ) - _xor_coords_or_header = ( - "coordinate_data", - "header_data", - ) + _xor_coords_or_header = ("coordinate_data", "header_data") coordinate_data = traits.Bool( desc="Coordinate variable data and header information.", @@ -627,10 +613,7 @@ class DumpInputSpec(StdOutCommandLineInputSpec): desc="Header information only, no data.", argstr="-h", xor=_xor_coords_or_header ) - _xor_annotations = ( - "annotations_brief", - "annotations_full", - ) + _xor_annotations = ("annotations_brief", "annotations_full") annotations_brief = traits.Enum( "c", @@ -665,7 +648,7 @@ class DumpInputSpec(StdOutCommandLineInputSpec): precision = traits.Either( traits.Int(), - traits.Tuple(traits.Int, traits.Int), + Tuple(traits.Int, traits.Int), desc="Display floating-point values with less precision", argstr="%s", ) # See _format_arg in Dump for actual formatting. @@ -705,10 +688,10 @@ def _format_arg(self, name, spec, value): and isinstance(value[0], int) and isinstance(value[1], int) ): - return "-p %d,%d" % (value[0], value[1],) + return "-p %d,%d" % (value[0], value[1]) else: raise ValueError("Invalid precision argument: " + str(value)) - return super(Dump, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class AverageInputSpec(CommandLineInputSpec): @@ -751,10 +734,7 @@ class AverageInputSpec(CommandLineInputSpec): default_value=True, ) - _xor_verbose = ( - "verbose", - "quiet", - ) + _xor_verbose = ("verbose", "quiet") verbose = traits.Bool( desc="Print out log messages (default).", argstr="-verbose", xor=_xor_verbose @@ -765,10 +745,7 @@ class AverageInputSpec(CommandLineInputSpec): debug = traits.Bool(desc="Print out debugging messages.", argstr="-debug") - _xor_check_dimensions = ( - "check_dimensions", - "no_check_dimensions", - ) + _xor_check_dimensions = ("check_dimensions", "no_check_dimensions") check_dimensions = traits.Bool( desc="Check that dimension info matches across files (default).", @@ -837,10 +814,7 @@ class AverageInputSpec(CommandLineInputSpec): argstr="-max_buffer_size_in_kb %d", ) - _xor_normalize = ( - "normalize", - "nonormalize", - ) + _xor_normalize = ("normalize", "nonormalize") normalize = traits.Bool( desc="Normalize data sets for mean intensity.", @@ -853,7 +827,7 @@ class AverageInputSpec(CommandLineInputSpec): xor=_xor_normalize, ) - voxel_range = traits.Tuple( + voxel_range = Tuple( traits.Int, traits.Int, argstr="-range %d %d", @@ -884,7 +858,7 @@ class AverageInputSpec(CommandLineInputSpec): argstr="-binarize", ) - binrange = traits.Tuple( + binrange = Tuple( traits.Float, traits.Float, argstr="-binrange %s %s", @@ -939,11 +913,7 @@ class Average(CommandLine): class BlobInputSpec(CommandLineInputSpec): input_file = File( - desc="input file to blob", - exists=True, - mandatory=True, - argstr="%s", - position=-2, + desc="input file to blob", exists=True, mandatory=True, argstr="%s", position=-2 ) output_file = File( @@ -1025,10 +995,7 @@ class CalcInputSpec(CommandLineInputSpec): default_value=True, ) - _xor_verbose = ( - "verbose", - "quiet", - ) + _xor_verbose = ("verbose", "quiet") verbose = traits.Bool( desc="Print out log messages (default).", argstr="-verbose", xor=_xor_verbose @@ -1107,7 +1074,7 @@ class CalcInputSpec(CommandLineInputSpec): xor=_xor_format, ) - voxel_range = traits.Tuple( + voxel_range = Tuple( traits.Int, traits.Int, argstr="-range %d %d", @@ -1120,10 +1087,7 @@ class CalcInputSpec(CommandLineInputSpec): argstr="-max_buffer_size_in_kb %d", ) - _xor_check_dimensions = ( - "check_dimensions", - "no_check_dimensions", - ) + _xor_check_dimensions = ("check_dimensions", "no_check_dimensions") check_dimensions = traits.Bool( desc="Check that files have matching dimensions (default).", @@ -1183,7 +1147,7 @@ class CalcInputSpec(CommandLineInputSpec): # FIXME test this one, the argstr will probably need tweaking, see # _format_arg. outfiles = traits.List( - traits.Tuple( + Tuple( traits.Str, File, argstr="-outfile %s %s", @@ -1236,7 +1200,7 @@ class Calc(CommandLine): class BBoxInputSpec(StdOutCommandLineInputSpec): input_file = File( - desc="input file", exists=True, mandatory=True, argstr="%s", position=-2, + desc="input file", exists=True, mandatory=True, argstr="%s", position=-2 ) output_file = File( @@ -1321,13 +1285,13 @@ class BeastInputSpec(CommandLineInputSpec): -positive: Specify mask of positive segmentation (inside mask) instead of the default mask. -output_selection: Specify file to output selected files. -count: Specify file to output the patch count. - -mask: Specify a segmentation mask instead of the the default mask. + -mask: Specify a segmentation mask instead of the default mask. -no_mask: Do not apply a segmentation mask. Perform the segmentation over the entire image. -no_positive: Do not apply a positive mask. Generic options for all commands: -help: Print summary of command-line options and abort -version: Print version number of program and exit - Copyright (C) 2011 Simon Fristed Eskildsen, Vladimir Fonov, + Copyright (C) 2011 Simon Fristed Eskildsen, Vladimir Fonov, Pierrick Coupe, Jose V. Manjon This program comes with ABSOLUTELY NO WARRANTY; for details type 'cat COPYING'. @@ -1493,7 +1457,7 @@ class Beast(CommandLine): class PikInputSpec(CommandLineInputSpec): input_file = File( - desc="input file", exists=True, mandatory=True, argstr="%s", position=-2, + desc="input file", exists=True, mandatory=True, argstr="%s", position=-2 ) _xor_image_type = ("jpg", "png") @@ -1565,7 +1529,7 @@ class PikInputSpec(CommandLineInputSpec): ) # FIXME tuple of floats? Not voxel values? Man page doesn't specify. - minc_range = traits.Tuple( + minc_range = Tuple( traits.Float, traits.Float, desc="Valid range of values for MINC file.", @@ -1574,7 +1538,7 @@ class PikInputSpec(CommandLineInputSpec): _xor_image_range = ("image_range", "auto_range") - image_range = traits.Tuple( + image_range = Tuple( traits.Float, traits.Float, desc="Range of image values to use for pixel intensity.", @@ -1589,7 +1553,7 @@ class PikInputSpec(CommandLineInputSpec): ) start = traits.Int( - desc="Slice number to get. (note this is in voxel co-ordinates).", + desc="Slice number to get. (note this is in voxel coordinates).", argstr="--slice %s", ) # FIXME Int is correct? @@ -1601,7 +1565,7 @@ class PikInputSpec(CommandLineInputSpec): slice_y = traits.Bool(desc="Get a coronal (y) slice.", argstr="-y", xor=_xor_slice) slice_x = traits.Bool( desc="Get a sagittal (x) slice.", argstr="-x", xor=_xor_slice - ) # FIXME typo in man page? sagital? + ) # FIXME typo in man page? sagittal? triplanar = traits.Bool( desc="Create a triplanar view of the input file.", argstr="--triplanar" @@ -1669,15 +1633,15 @@ def _format_arg(self, name, spec, value): if isinstance(value, bool) and value: return "--title" elif isinstance(value, str): - return "--title --title_text %s" % (value,) + return f"--title --title_text {value}" else: raise ValueError('Unknown value for "title" argument: ' + str(value)) - return super(Pik, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class BlurInputSpec(CommandLineInputSpec): input_file = File( - desc="input file", exists=True, mandatory=True, argstr="%s", position=-2, + desc="input file", exists=True, mandatory=True, argstr="%s", position=-2 ) output_file_base = File(desc="output file base", argstr="%s", position=-1) @@ -1730,7 +1694,7 @@ class BlurInputSpec(CommandLineInputSpec): mandatory=True, ) - fwhm3d = traits.Tuple( + fwhm3d = Tuple( traits.Float, traits.Float, traits.Float, @@ -1839,7 +1803,7 @@ def _list_outputs(self): @property def cmdline(self): output_file_base = self.inputs.output_file_base - orig_cmdline = super(Blur, self).cmdline + orig_cmdline = super().cmdline if isdefined(output_file_base): return orig_cmdline @@ -1847,7 +1811,7 @@ def cmdline(self): # FIXME this seems like a bit of a hack. Can we force output_file # to show up in cmdline by default, even if it isn't specified in # the instantiation of Pik? - return "%s %s" % (orig_cmdline, self._gen_output_base()) + return f"{orig_cmdline} {self._gen_output_base()}" class MathInputSpec(CommandLineInputSpec): @@ -1951,7 +1915,7 @@ class MathInputSpec(CommandLineInputSpec): xor=_xor_format, ) - voxel_range = traits.Tuple( + voxel_range = Tuple( traits.Int, traits.Int, argstr="-range %d %d", @@ -1966,10 +1930,7 @@ class MathInputSpec(CommandLineInputSpec): argstr="-max_buffer_size_in_kb %d", ) - _xor_check_dimensions = ( - "check_dimensions", - "no_check_dimensions", - ) + _xor_check_dimensions = ("check_dimensions", "no_check_dimensions") check_dimensions = traits.Bool( desc="Check that dimension info matches across files (default).", @@ -2131,42 +2092,42 @@ class MathInputSpec(CommandLineInputSpec): square = traits.Bool(desc="Take square of a volume.", argstr="-square") abs = traits.Bool(desc="Take absolute value of a volume.", argstr="-abs") - exp = traits.Tuple( + exp = Tuple( traits.Float, traits.Float, argstr="-exp -const2 %s %s", desc="Calculate c2*exp(c1*x). Both constants must be specified.", ) - log = traits.Tuple( + log = Tuple( traits.Float, traits.Float, argstr="-log -const2 %s %s", desc="Calculate log(x/c2)/c1. The constants c1 and c2 default to 1.", ) - scale = traits.Tuple( + scale = Tuple( traits.Float, traits.Float, argstr="-scale -const2 %s %s", desc="Scale a volume: volume * c1 + c2.", ) - clamp = traits.Tuple( + clamp = Tuple( traits.Float, traits.Float, argstr="-clamp -const2 %s %s", desc="Clamp a volume to lie between two values.", ) - segment = traits.Tuple( + segment = Tuple( traits.Float, traits.Float, argstr="-segment -const2 %s %s", desc="Segment a volume using range of -const2: within range = 1, outside range = 0.", ) - nsegment = traits.Tuple( + nsegment = Tuple( traits.Float, traits.Float, argstr="-nsegment -const2 %s %s", @@ -2244,17 +2205,16 @@ def _format_arg(self, name, spec, value): if isinstance(value, bool) and value: return spec.argstr elif isinstance(value, bool) and not value: - raise ValueError("Does not make sense to specify %s=False" % (name,)) + raise ValueError(f"Does not make sense to specify {name}=False") elif isinstance(value, float): - return "%s -const %s" % (spec.argstr, value,) + return f"{spec.argstr} -const {value}" else: - raise ValueError("Invalid %s argument: %s" % (name, value,)) + raise ValueError(f"Invalid {name} argument: {value}") - return super(Math, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _parse_inputs(self): - """A number of the command line options expect precisely one or two files. - """ + """A number of the command line options expect precisely one or two files.""" nr_input_files = len(self.inputs.input_files) @@ -2266,13 +2226,13 @@ def _parse_inputs(self): if nr_input_files != 2: raise ValueError( "Due to the %s option we expected 2 files but input_files is of length %d" - % (n, nr_input_files,) + % (n, nr_input_files) ) elif isinstance(t, float): if nr_input_files != 1: raise ValueError( "Due to the %s option we expected 1 file but input_files is of length %d" - % (n, nr_input_files,) + % (n, nr_input_files) ) else: raise ValueError( @@ -2286,7 +2246,7 @@ def _parse_inputs(self): if nr_input_files != 1: raise ValueError( "Due to the %s option we expected 1 file but input_files is of length %d" - % (n, nr_input_files,) + % (n, nr_input_files) ) for n in self.input_spec.two_volume_traits: @@ -2296,7 +2256,7 @@ def _parse_inputs(self): if nr_input_files != 2: raise ValueError( "Due to the %s option we expected 2 files but input_files is of length %d" - % (n, nr_input_files,) + % (n, nr_input_files) ) for n in self.input_spec.n_volume_traits: @@ -2306,10 +2266,10 @@ def _parse_inputs(self): if not nr_input_files >= 1: raise ValueError( "Due to the %s option we expected at least one file but input_files is of length %d" - % (n, nr_input_files,) + % (n, nr_input_files) ) - return super(Math, self)._parse_inputs() + return super()._parse_inputs() class ResampleInputSpec(CommandLineInputSpec): @@ -2341,7 +2301,7 @@ class ResampleInputSpec(CommandLineInputSpec): ) # This is a dummy input. - input_grid_files = InputMultiPath(File, desc="input grid file(s)",) + input_grid_files = InputMultiPath(File, desc="input grid file(s)") two = traits.Bool(desc="Create a MINC 2 output file.", argstr="-2") @@ -2481,7 +2441,7 @@ class ResampleInputSpec(CommandLineInputSpec): xor=_xor_format, ) - output_range = traits.Tuple( + output_range = Tuple( traits.Float, traits.Float, argstr="-range %s %s", @@ -2546,7 +2506,7 @@ class ResampleInputSpec(CommandLineInputSpec): ) talairach = traits.Bool(desc="Output is in Talairach space.", argstr="-talairach") - origin = traits.Tuple( + origin = Tuple( traits.Float, traits.Float, traits.Float, @@ -2571,7 +2531,7 @@ class ResampleInputSpec(CommandLineInputSpec): _xor_nelements = ("nelements", "nelements_x_y_or_z") # nr elements along each dimension - nelements = traits.Tuple( + nelements = Tuple( traits.Int, traits.Int, traits.Int, @@ -2606,7 +2566,7 @@ class ResampleInputSpec(CommandLineInputSpec): # step size along each dimension _xor_step = ("step", "step_x_y_or_z") - step = traits.Tuple( + step = Tuple( traits.Int, traits.Int, traits.Int, @@ -2640,7 +2600,7 @@ class ResampleInputSpec(CommandLineInputSpec): # start point along each dimension _xor_start = ("start", "start_x_y_or_z") - start = traits.Tuple( + start = Tuple( traits.Float, traits.Float, traits.Float, @@ -2677,7 +2637,7 @@ class ResampleInputSpec(CommandLineInputSpec): # dircos along each dimension _xor_dircos = ("dircos", "dircos_x_y_or_z") - dircos = traits.Tuple( + dircos = Tuple( traits.Float, traits.Float, traits.Float, @@ -2799,7 +2759,7 @@ class NormInputSpec(CommandLineInputSpec): exists=True, ) clamp = traits.Bool( - desc="Force the ouput range between limits [default].", + desc="Force the output range between limits [default].", argstr="-clamp", usedefault=True, default_value=True, @@ -2939,7 +2899,7 @@ class VolcentreInputSpec(CommandLineInputSpec): argstr="-com", ) - centre = traits.Tuple( + centre = Tuple( traits.Float, traits.Float, traits.Float, @@ -3071,7 +3031,6 @@ class Volpad(CommandLine): class VolisoInputSpec(CommandLineInputSpec): - input_file = File( desc="input file to convert to isotropic sampling", exists=True, @@ -3164,9 +3123,7 @@ class GennlxfmInputSpec(CommandLineInputSpec): ) step = traits.Int(desc="Output ident xfm step [default: 1].", argstr="-step %s") - like = File( - desc="Generate a nlxfm like this file.", exists=True, argstr="-like %s", - ) + like = File(desc="Generate a nlxfm like this file.", exists=True, argstr="-like %s") class GennlxfmOutputSpec(TraitedSpec): @@ -3197,7 +3154,7 @@ class Gennlxfm(CommandLine): _cmd = "gennlxfm" def _list_outputs(self): - outputs = super(Gennlxfm, self)._list_outputs() + outputs = super()._list_outputs() outputs["output_grid"] = re.sub( ".(nlxfm|xfm)$", "_grid_0.mnc", outputs["output_file"] ) @@ -3215,7 +3172,7 @@ class XfmConcatInputSpec(CommandLineInputSpec): ) # This is a dummy input. - input_grid_files = InputMultiPath(File, desc="input grid file(s)",) + input_grid_files = InputMultiPath(File, desc="input grid file(s)") output_file = File( desc="output file", @@ -3262,10 +3219,10 @@ class XfmConcat(CommandLine): _cmd = "xfmconcat" def _list_outputs(self): - outputs = super(XfmConcat, self)._list_outputs() + outputs = super()._list_outputs() if os.path.exists(outputs["output_file"]): - if "grid" in open(outputs["output_file"], "r").read(): + if "grid" in open(outputs["output_file"]).read(): outputs["output_grids"] = glob.glob( re.sub(".(nlxfm|xfm)$", "_grid_*.mnc", outputs["output_file"]) ) @@ -3275,11 +3232,11 @@ def _list_outputs(self): class BestLinRegInputSpec(CommandLineInputSpec): source = File( - desc="source Minc file", exists=True, mandatory=True, argstr="%s", position=-4, + desc="source Minc file", exists=True, mandatory=True, argstr="%s", position=-4 ) target = File( - desc="target Minc file", exists=True, mandatory=True, argstr="%s", position=-3, + desc="target Minc file", exists=True, mandatory=True, argstr="%s", position=-3 ) output_xfm = File( @@ -3356,17 +3313,17 @@ class BestLinReg(CommandLine): class NlpFitInputSpec(CommandLineInputSpec): source = File( - desc="source Minc file", exists=True, mandatory=True, argstr="%s", position=-3, + desc="source Minc file", exists=True, mandatory=True, argstr="%s", position=-3 ) target = File( - desc="target Minc file", exists=True, mandatory=True, argstr="%s", position=-2, + desc="target Minc file", exists=True, mandatory=True, argstr="%s", position=-2 ) - output_xfm = File(desc="output xfm file", genfile=True, argstr="%s", position=-1,) + output_xfm = File(desc="output xfm file", genfile=True, argstr="%s", position=-1) # This is a dummy input. - input_grid_files = InputMultiPath(File, desc="input grid file(s)",) + input_grid_files = InputMultiPath(File, desc="input grid file(s)") config_file = File( desc="File containing the fitting configuration use.", @@ -3446,14 +3403,14 @@ def _gen_filename(self, name): + ".xfm" ) else: - raise NotImplemented + raise NotImplementedError def _list_outputs(self): outputs = self.output_spec().get() outputs["output_xfm"] = os.path.abspath(self._gen_filename("output_xfm")) assert os.path.exists(outputs["output_xfm"]) - if "grid" in open(outputs["output_xfm"], "r").read(): + if "grid" in open(outputs["output_xfm"]).read(): outputs["output_grid"] = re.sub( ".(nlxfm|xfm)$", "_grid_0.mnc", outputs["output_xfm"] ) @@ -3472,9 +3429,9 @@ class XfmAvgInputSpec(CommandLineInputSpec): ) # This is a dummy input. - input_grid_files = InputMultiPath(File, desc="input grid file(s)",) + input_grid_files = InputMultiPath(File, desc="input grid file(s)") - output_file = File(desc="output file", genfile=True, argstr="%s", position=-1,) + output_file = File(desc="output file", genfile=True, argstr="%s", position=-1) verbose = traits.Bool( desc="Print out log messages. Default: False.", argstr="-verbose" @@ -3545,7 +3502,7 @@ def _gen_filename(self, name): + ".xfm" ) else: - raise NotImplemented + raise NotImplementedError def _gen_outfilename(self): return self._gen_filename("output_file") @@ -3555,7 +3512,7 @@ def _list_outputs(self): outputs["output_file"] = os.path.abspath(self._gen_outfilename()) assert os.path.exists(outputs["output_file"]) - if "grid" in open(outputs["output_file"], "r").read(): + if "grid" in open(outputs["output_file"]).read(): outputs["output_grid"] = re.sub( ".(nlxfm|xfm)$", "_grid_0.mnc", outputs["output_file"] ) @@ -3568,7 +3525,7 @@ class XfmInvertInputSpec(CommandLineInputSpec): desc="input file", exists=True, mandatory=True, argstr="%s", position=-2 ) - output_file = File(desc="output file", genfile=True, argstr="%s", position=-1,) + output_file = File(desc="output file", genfile=True, argstr="%s", position=-1) verbose = traits.Bool( desc="Print out log messages. Default: False.", argstr="-verbose" @@ -3616,7 +3573,7 @@ def _gen_filename(self, name): + ".xfm" ) else: - raise NotImplemented + raise NotImplementedError def _gen_outfilename(self): return self._gen_filename("output_file") @@ -3626,7 +3583,7 @@ def _list_outputs(self): outputs["output_file"] = os.path.abspath(self._gen_outfilename()) assert os.path.exists(outputs["output_file"]) - if "grid" in open(outputs["output_file"], "r").read(): + if "grid" in open(outputs["output_file"]).read(): outputs["output_grid"] = re.sub( ".(nlxfm|xfm)$", "_grid_0.mnc", outputs["output_file"] ) @@ -3818,7 +3775,7 @@ class VolSymmInputSpec(CommandLineInputSpec): ) # This is a dummy input. - input_grid_files = InputMultiPath(File, desc="input grid file(s)",) + input_grid_files = InputMultiPath(File, desc="input grid file(s)") verbose = traits.Bool( desc="Print out log messages. Default: False.", argstr="-verbose" @@ -3886,11 +3843,11 @@ class VolSymm(CommandLine): _cmd = "volsymm" def _list_outputs(self): - outputs = super(VolSymm, self)._list_outputs() + outputs = super()._list_outputs() # Have to manually check for the grid files. if os.path.exists(outputs["trans_file"]): - if "grid" in open(outputs["trans_file"], "r").read(): + if "grid" in open(outputs["trans_file"]).read(): outputs["output_grid"] = re.sub( ".(nlxfm|xfm)$", "_grid_0.mnc", outputs["trans_file"] ) diff --git a/nipype/interfaces/minc/testdata.py b/nipype/interfaces/minc/testdata.py index f4e2836d65..1d2ff36d6f 100644 --- a/nipype/interfaces/minc/testdata.py +++ b/nipype/interfaces/minc/testdata.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - -import os from ...testing import example_data minc2Dfile = example_data("minc_test_2D_00.mnc") @@ -10,4 +7,4 @@ def nonempty_minc_data(i, shape="2D"): - return example_data("minc_test_%s_%.2d.mnc" % (shape, i,)) + return example_data("minc_test_%s_%.2d.mnc" % (shape, i)) diff --git a/nipype/interfaces/minc/tests/__init__.py b/nipype/interfaces/minc/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/minc/tests/__init__.py +++ b/nipype/interfaces/minc/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/minc/tests/test_auto_Average.py b/nipype/interfaces/minc/tests/test_auto_Average.py index c9066611dd..7017967d61 100644 --- a/nipype/interfaces/minc/tests/test_auto_Average.py +++ b/nipype/interfaces/minc/tests/test_auto_Average.py @@ -4,18 +4,40 @@ def test_Average_inputs(): input_map = dict( - args=dict(argstr="%s",), - avgdim=dict(argstr="-avgdim %s",), - binarize=dict(argstr="-binarize",), - binrange=dict(argstr="-binrange %s %s",), - binvalue=dict(argstr="-binvalue %s",), + args=dict( + argstr="%s", + ), + avgdim=dict( + argstr="-avgdim %s", + ), + binarize=dict( + argstr="-binarize", + ), + binrange=dict( + argstr="-binrange %s %s", + ), + binvalue=dict( + argstr="-binvalue %s", + ), check_dimensions=dict( - argstr="-check_dimensions", xor=("check_dimensions", "no_check_dimensions"), + argstr="-check_dimensions", + xor=("check_dimensions", "no_check_dimensions"), + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + copy_header=dict( + argstr="-copy_header", + xor=("copy_header", "no_copy_header"), + ), + debug=dict( + argstr="-debug", + ), + environ=dict( + nohash=True, + usedefault=True, ), - clobber=dict(argstr="-clobber", usedefault=True,), - copy_header=dict(argstr="-copy_header", xor=("copy_header", "no_copy_header"),), - debug=dict(argstr="-debug",), - environ=dict(nohash=True, usedefault=True,), filelist=dict( argstr="-filelist %s", extensions=None, @@ -156,17 +178,25 @@ def test_Average_inputs(): xor=("input_files", "filelist"), ), max_buffer_size_in_kb=dict( - argstr="-max_buffer_size_in_kb %d", usedefault=True, + argstr="-max_buffer_size_in_kb %d", + usedefault=True, ), no_check_dimensions=dict( argstr="-nocheck_dimensions", xor=("check_dimensions", "no_check_dimensions"), ), no_copy_header=dict( - argstr="-nocopy_header", xor=("copy_header", "no_copy_header"), + argstr="-nocopy_header", + xor=("copy_header", "no_copy_header"), + ), + nonormalize=dict( + argstr="-nonormalize", + xor=("normalize", "nonormalize"), + ), + normalize=dict( + argstr="-normalize", + xor=("normalize", "nonormalize"), ), - nonormalize=dict(argstr="-nonormalize", xor=("normalize", "nonormalize"),), - normalize=dict(argstr="-normalize", xor=("normalize", "nonormalize"),), output_file=dict( argstr="%s", extensions=None, @@ -176,13 +206,32 @@ def test_Average_inputs(): name_template="%s_averaged.mnc", position=-1, ), - quiet=dict(argstr="-quiet", xor=("verbose", "quiet"),), - sdfile=dict(argstr="-sdfile %s", extensions=None,), - two=dict(argstr="-2",), - verbose=dict(argstr="-verbose", xor=("verbose", "quiet"),), - voxel_range=dict(argstr="-range %d %d",), - weights=dict(argstr="-weights %s", sep=",",), - width_weighted=dict(argstr="-width_weighted", requires=("avgdim",),), + quiet=dict( + argstr="-quiet", + xor=("verbose", "quiet"), + ), + sdfile=dict( + argstr="-sdfile %s", + extensions=None, + ), + two=dict( + argstr="-2", + ), + verbose=dict( + argstr="-verbose", + xor=("verbose", "quiet"), + ), + voxel_range=dict( + argstr="-range %d %d", + ), + weights=dict( + argstr="-weights %s", + sep=",", + ), + width_weighted=dict( + argstr="-width_weighted", + requires=("avgdim",), + ), ) inputs = Average.input_spec() @@ -192,7 +241,11 @@ def test_Average_inputs(): def test_Average_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Average.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_BBox.py b/nipype/interfaces/minc/tests/test_auto_BBox.py index c1dfbb370a..532cb14d5f 100644 --- a/nipype/interfaces/minc/tests/test_auto_BBox.py +++ b/nipype/interfaces/minc/tests/test_auto_BBox.py @@ -4,14 +4,38 @@ def test_BBox_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - format_minccrop=dict(argstr="-minccrop",), - format_mincresample=dict(argstr="-mincresample",), - format_mincreshape=dict(argstr="-mincreshape",), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - one_line=dict(argstr="-one_line", xor=("one_line", "two_lines"),), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + format_minccrop=dict( + argstr="-minccrop", + ), + format_mincresample=dict( + argstr="-mincresample", + ), + format_mincreshape=dict( + argstr="-mincreshape", + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + one_line=dict( + argstr="-one_line", + xor=("one_line", "two_lines"), + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), output_file=dict( extensions=None, hash_files=False, @@ -20,8 +44,13 @@ def test_BBox_inputs(): name_template="%s_bbox.txt", position=-1, ), - threshold=dict(argstr="-threshold",), - two_lines=dict(argstr="-two_lines", xor=("one_line", "two_lines"),), + threshold=dict( + argstr="-threshold", + ), + two_lines=dict( + argstr="-two_lines", + xor=("one_line", "two_lines"), + ), ) inputs = BBox.input_spec() @@ -31,7 +60,11 @@ def test_BBox_inputs(): def test_BBox_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = BBox.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Beast.py b/nipype/interfaces/minc/tests/test_auto_Beast.py index 5aed48440f..487550a33a 100644 --- a/nipype/interfaces/minc/tests/test_auto_Beast.py +++ b/nipype/interfaces/minc/tests/test_auto_Beast.py @@ -4,20 +4,59 @@ def test_Beast_inputs(): input_map = dict( - abspath=dict(argstr="-abspath", usedefault=True,), - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - confidence_level_alpha=dict(argstr="-alpha %s", usedefault=True,), - configuration_file=dict(argstr="-configuration %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - fill_holes=dict(argstr="-fill",), - flip_images=dict(argstr="-flip",), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - library_dir=dict(argstr="%s", mandatory=True, position=-3,), - load_moments=dict(argstr="-load_moments",), - median_filter=dict(argstr="-median",), - nlm_filter=dict(argstr="-nlm_filter",), - number_selected_images=dict(argstr="-selection_num %s", usedefault=True,), + abspath=dict( + argstr="-abspath", + usedefault=True, + ), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + confidence_level_alpha=dict( + argstr="-alpha %s", + usedefault=True, + ), + configuration_file=dict( + argstr="-configuration %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill_holes=dict( + argstr="-fill", + ), + flip_images=dict( + argstr="-flip", + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + library_dir=dict( + argstr="%s", + mandatory=True, + position=-3, + ), + load_moments=dict( + argstr="-load_moments", + ), + median_filter=dict( + argstr="-median", + ), + nlm_filter=dict( + argstr="-nlm_filter", + ), + number_selected_images=dict( + argstr="-selection_num %s", + usedefault=True, + ), output_file=dict( argstr="%s", extensions=None, @@ -26,13 +65,32 @@ def test_Beast_inputs(): name_template="%s_beast_mask.mnc", position=-1, ), - patch_size=dict(argstr="-patch_size %s", usedefault=True,), - probability_map=dict(argstr="-probability",), - same_resolution=dict(argstr="-same_resolution",), - search_area=dict(argstr="-search_area %s", usedefault=True,), - smoothness_factor_beta=dict(argstr="-beta %s", usedefault=True,), - threshold_patch_selection=dict(argstr="-threshold %s", usedefault=True,), - voxel_size=dict(argstr="-voxel_size %s", usedefault=True,), + patch_size=dict( + argstr="-patch_size %s", + usedefault=True, + ), + probability_map=dict( + argstr="-probability", + ), + same_resolution=dict( + argstr="-same_resolution", + ), + search_area=dict( + argstr="-search_area %s", + usedefault=True, + ), + smoothness_factor_beta=dict( + argstr="-beta %s", + usedefault=True, + ), + threshold_patch_selection=dict( + argstr="-threshold %s", + usedefault=True, + ), + voxel_size=dict( + argstr="-voxel_size %s", + usedefault=True, + ), ) inputs = Beast.input_spec() @@ -42,7 +100,11 @@ def test_Beast_inputs(): def test_Beast_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Beast.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_BestLinReg.py b/nipype/interfaces/minc/tests/test_auto_BestLinReg.py index 3e765b0e52..57a8929878 100644 --- a/nipype/interfaces/minc/tests/test_auto_BestLinReg.py +++ b/nipype/interfaces/minc/tests/test_auto_BestLinReg.py @@ -4,9 +4,17 @@ def test_BestLinReg_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), output_mnc=dict( argstr="%s", extensions=None, @@ -27,9 +35,21 @@ def test_BestLinReg_inputs(): name_template="%s_bestlinreg.xfm", position=-2, ), - source=dict(argstr="%s", extensions=None, mandatory=True, position=-4,), - target=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - verbose=dict(argstr="-verbose",), + source=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-4, + ), + target=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + verbose=dict( + argstr="-verbose", + ), ) inputs = BestLinReg.input_spec() @@ -40,7 +60,12 @@ def test_BestLinReg_inputs(): def test_BestLinReg_outputs(): output_map = dict( - output_mnc=dict(extensions=None,), output_xfm=dict(extensions=None,), + output_mnc=dict( + extensions=None, + ), + output_xfm=dict( + extensions=None, + ), ) outputs = BestLinReg.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_BigAverage.py b/nipype/interfaces/minc/tests/test_auto_BigAverage.py index 539ae73488..1eefb273d6 100644 --- a/nipype/interfaces/minc/tests/test_auto_BigAverage.py +++ b/nipype/interfaces/minc/tests/test_auto_BigAverage.py @@ -4,10 +4,23 @@ def test_BigAverage_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="--clobber", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - input_files=dict(argstr="%s", mandatory=True, position=-2, sep=" ",), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="--clobber", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_files=dict( + argstr="%s", + mandatory=True, + position=-2, + sep=" ", + ), output_file=dict( argstr="%s", extensions=None, @@ -17,8 +30,12 @@ def test_BigAverage_inputs(): name_template="%s_bigaverage.mnc", position=-1, ), - output_float=dict(argstr="--float",), - robust=dict(argstr="-robust",), + output_float=dict( + argstr="--float", + ), + robust=dict( + argstr="-robust", + ), sd_file=dict( argstr="--sdfile %s", extensions=None, @@ -26,8 +43,12 @@ def test_BigAverage_inputs(): name_source=["input_files"], name_template="%s_bigaverage_stdev.mnc", ), - tmpdir=dict(argstr="-tmpdir %s",), - verbose=dict(argstr="--verbose",), + tmpdir=dict( + argstr="-tmpdir %s", + ), + verbose=dict( + argstr="--verbose", + ), ) inputs = BigAverage.input_spec() @@ -38,7 +59,12 @@ def test_BigAverage_inputs(): def test_BigAverage_outputs(): output_map = dict( - output_file=dict(extensions=None,), sd_file=dict(extensions=None,), + output_file=dict( + extensions=None, + ), + sd_file=dict( + extensions=None, + ), ) outputs = BigAverage.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Blob.py b/nipype/interfaces/minc/tests/test_auto_Blob.py index f51c3693f6..ae2b445c73 100644 --- a/nipype/interfaces/minc/tests/test_auto_Blob.py +++ b/nipype/interfaces/minc/tests/test_auto_Blob.py @@ -4,11 +4,25 @@ def test_Blob_inputs(): input_map = dict( - args=dict(argstr="%s",), - determinant=dict(argstr="-determinant",), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - magnitude=dict(argstr="-magnitude",), + args=dict( + argstr="%s", + ), + determinant=dict( + argstr="-determinant", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + magnitude=dict( + argstr="-magnitude", + ), output_file=dict( argstr="%s", extensions=None, @@ -18,8 +32,12 @@ def test_Blob_inputs(): name_template="%s_blob.mnc", position=-1, ), - trace=dict(argstr="-trace",), - translation=dict(argstr="-translation",), + trace=dict( + argstr="-trace", + ), + translation=dict( + argstr="-translation", + ), ) inputs = Blob.input_spec() @@ -29,7 +47,11 @@ def test_Blob_inputs(): def test_Blob_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Blob.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Blur.py b/nipype/interfaces/minc/tests/test_auto_Blur.py index b37942f768..87647b5f62 100644 --- a/nipype/interfaces/minc/tests/test_auto_Blur.py +++ b/nipype/interfaces/minc/tests/test_auto_Blur.py @@ -4,25 +4,58 @@ def test_Blur_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - dimensions=dict(argstr="-dimensions %s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + dimensions=dict( + argstr="-dimensions %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), fwhm=dict( - argstr="-fwhm %s", mandatory=True, xor=("fwhm", "fwhm3d", "standard_dev"), + argstr="-fwhm %s", + mandatory=True, + xor=("fwhm", "fwhm3d", "standard_dev"), ), fwhm3d=dict( argstr="-3dfwhm %s %s %s", mandatory=True, xor=("fwhm", "fwhm3d", "standard_dev"), ), - gaussian=dict(argstr="-gaussian", xor=("gaussian", "rect"),), - gradient=dict(argstr="-gradient",), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - no_apodize=dict(argstr="-no_apodize",), - output_file_base=dict(argstr="%s", extensions=None, position=-1,), - partial=dict(argstr="-partial",), - rect=dict(argstr="-rect", xor=("gaussian", "rect"),), + gaussian=dict( + argstr="-gaussian", + xor=("gaussian", "rect"), + ), + gradient=dict( + argstr="-gradient", + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + no_apodize=dict( + argstr="-no_apodize", + ), + output_file_base=dict( + argstr="%s", + extensions=None, + position=-1, + ), + partial=dict( + argstr="-partial", + ), + rect=dict( + argstr="-rect", + xor=("gaussian", "rect"), + ), standard_dev=dict( argstr="-standarddev %s", mandatory=True, @@ -38,12 +71,24 @@ def test_Blur_inputs(): def test_Blur_outputs(): output_map = dict( - gradient_dxyz=dict(extensions=None,), - output_file=dict(extensions=None,), - partial_dx=dict(extensions=None,), - partial_dxyz=dict(extensions=None,), - partial_dy=dict(extensions=None,), - partial_dz=dict(extensions=None,), + gradient_dxyz=dict( + extensions=None, + ), + output_file=dict( + extensions=None, + ), + partial_dx=dict( + extensions=None, + ), + partial_dxyz=dict( + extensions=None, + ), + partial_dy=dict( + extensions=None, + ), + partial_dz=dict( + extensions=None, + ), ) outputs = Blur.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Calc.py b/nipype/interfaces/minc/tests/test_auto_Calc.py index 670278dfa9..d0d4f61fbe 100644 --- a/nipype/interfaces/minc/tests/test_auto_Calc.py +++ b/nipype/interfaces/minc/tests/test_auto_Calc.py @@ -4,15 +4,31 @@ def test_Calc_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), check_dimensions=dict( - argstr="-check_dimensions", xor=("check_dimensions", "no_check_dimensions"), + argstr="-check_dimensions", + xor=("check_dimensions", "no_check_dimensions"), + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + copy_header=dict( + argstr="-copy_header", + xor=("copy_header", "no_copy_header"), + ), + debug=dict( + argstr="-debug", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + eval_width=dict( + argstr="-eval_width %s", ), - clobber=dict(argstr="-clobber", usedefault=True,), - copy_header=dict(argstr="-copy_header", xor=("copy_header", "no_copy_header"),), - debug=dict(argstr="-debug",), - environ=dict(nohash=True, usedefault=True,), - eval_width=dict(argstr="-eval_width %s",), expfile=dict( argstr="-expfile %s", extensions=None, @@ -20,7 +36,9 @@ def test_Calc_inputs(): xor=("expression", "expfile"), ), expression=dict( - argstr="-expression '%s'", mandatory=True, xor=("expression", "expfile"), + argstr="-expression '%s'", + mandatory=True, + xor=("expression", "expfile"), ), filelist=dict( argstr="-filelist %s", @@ -154,15 +172,25 @@ def test_Calc_inputs(): "format_unsigned", ), ), - ignore_nan=dict(argstr="-ignore_nan",), - input_files=dict(argstr="%s", mandatory=True, position=-2, sep=" ",), - max_buffer_size_in_kb=dict(argstr="-max_buffer_size_in_kb %d",), + ignore_nan=dict( + argstr="-ignore_nan", + ), + input_files=dict( + argstr="%s", + mandatory=True, + position=-2, + sep=" ", + ), + max_buffer_size_in_kb=dict( + argstr="-max_buffer_size_in_kb %d", + ), no_check_dimensions=dict( argstr="-nocheck_dimensions", xor=("check_dimensions", "no_check_dimensions"), ), no_copy_header=dict( - argstr="-nocopy_header", xor=("copy_header", "no_copy_header"), + argstr="-nocopy_header", + xor=("copy_header", "no_copy_header"), ), outfiles=dict(), output_file=dict( @@ -179,16 +207,30 @@ def test_Calc_inputs(): xor=("output_nan", "output_zero", "output_illegal_value"), ), output_nan=dict( - argstr="-nan", xor=("output_nan", "output_zero", "output_illegal_value"), + argstr="-nan", + xor=("output_nan", "output_zero", "output_illegal_value"), ), output_zero=dict( - argstr="-zero", xor=("output_nan", "output_zero", "output_illegal_value"), + argstr="-zero", + xor=("output_nan", "output_zero", "output_illegal_value"), + ), + propagate_nan=dict( + argstr="-propagate_nan", + ), + quiet=dict( + argstr="-quiet", + xor=("verbose", "quiet"), + ), + two=dict( + argstr="-2", + ), + verbose=dict( + argstr="-verbose", + xor=("verbose", "quiet"), + ), + voxel_range=dict( + argstr="-range %d %d", ), - propagate_nan=dict(argstr="-propagate_nan",), - quiet=dict(argstr="-quiet", xor=("verbose", "quiet"),), - two=dict(argstr="-2",), - verbose=dict(argstr="-verbose", xor=("verbose", "quiet"),), - voxel_range=dict(argstr="-range %d %d",), ) inputs = Calc.input_spec() @@ -198,7 +240,11 @@ def test_Calc_inputs(): def test_Calc_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Calc.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Convert.py b/nipype/interfaces/minc/tests/test_auto_Convert.py index 695d371b47..57963b9b81 100644 --- a/nipype/interfaces/minc/tests/test_auto_Convert.py +++ b/nipype/interfaces/minc/tests/test_auto_Convert.py @@ -4,12 +4,29 @@ def test_Convert_inputs(): input_map = dict( - args=dict(argstr="%s",), - chunk=dict(argstr="-chunk %d",), - clobber=dict(argstr="-clobber", usedefault=True,), - compression=dict(argstr="-compress %s",), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + chunk=dict( + argstr="-chunk %d", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + compression=dict( + argstr="-compress %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), output_file=dict( argstr="%s", extensions=None, @@ -19,8 +36,12 @@ def test_Convert_inputs(): name_template="%s_convert_output.mnc", position=-1, ), - template=dict(argstr="-template",), - two=dict(argstr="-2",), + template=dict( + argstr="-template", + ), + two=dict( + argstr="-2", + ), ) inputs = Convert.input_spec() @@ -30,7 +51,11 @@ def test_Convert_inputs(): def test_Convert_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Convert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Copy.py b/nipype/interfaces/minc/tests/test_auto_Copy.py index 91736a67b3..a6bb527e7a 100644 --- a/nipype/interfaces/minc/tests/test_auto_Copy.py +++ b/nipype/interfaces/minc/tests/test_auto_Copy.py @@ -4,9 +4,19 @@ def test_Copy_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), output_file=dict( argstr="%s", extensions=None, @@ -16,8 +26,14 @@ def test_Copy_inputs(): name_template="%s_copy.mnc", position=-1, ), - pixel_values=dict(argstr="-pixel_values", xor=("pixel_values", "real_values"),), - real_values=dict(argstr="-real_values", xor=("pixel_values", "real_values"),), + pixel_values=dict( + argstr="-pixel_values", + xor=("pixel_values", "real_values"), + ), + real_values=dict( + argstr="-real_values", + xor=("pixel_values", "real_values"), + ), ) inputs = Copy.input_spec() @@ -27,7 +43,11 @@ def test_Copy_inputs(): def test_Copy_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Copy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Dump.py b/nipype/interfaces/minc/tests/test_auto_Dump.py index eb1fe2c6a7..4253bc20cc 100644 --- a/nipype/interfaces/minc/tests/test_auto_Dump.py +++ b/nipype/interfaces/minc/tests/test_auto_Dump.py @@ -5,19 +5,46 @@ def test_Dump_inputs(): input_map = dict( annotations_brief=dict( - argstr="-b %s", xor=("annotations_brief", "annotations_full"), + argstr="-b %s", + xor=("annotations_brief", "annotations_full"), ), annotations_full=dict( - argstr="-f %s", xor=("annotations_brief", "annotations_full"), - ), - args=dict(argstr="%s",), - coordinate_data=dict(argstr="-c", xor=("coordinate_data", "header_data"),), - environ=dict(nohash=True, usedefault=True,), - header_data=dict(argstr="-h", xor=("coordinate_data", "header_data"),), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - line_length=dict(argstr="-l %d",), - netcdf_name=dict(argstr="-n %s",), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), + argstr="-f %s", + xor=("annotations_brief", "annotations_full"), + ), + args=dict( + argstr="%s", + ), + coordinate_data=dict( + argstr="-c", + xor=("coordinate_data", "header_data"), + ), + environ=dict( + nohash=True, + usedefault=True, + ), + header_data=dict( + argstr="-h", + xor=("coordinate_data", "header_data"), + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + line_length=dict( + argstr="-l %d", + ), + netcdf_name=dict( + argstr="-n %s", + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), output_file=dict( extensions=None, hash_files=False, @@ -26,8 +53,13 @@ def test_Dump_inputs(): name_template="%s_dump.txt", position=-1, ), - precision=dict(argstr="%s",), - variables=dict(argstr="-v %s", sep=",",), + precision=dict( + argstr="%s", + ), + variables=dict( + argstr="-v %s", + sep=",", + ), ) inputs = Dump.input_spec() @@ -37,7 +69,11 @@ def test_Dump_inputs(): def test_Dump_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Dump.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Extract.py b/nipype/interfaces/minc/tests/test_auto_Extract.py index 0c05d4ab5f..6c34b443f0 100644 --- a/nipype/interfaces/minc/tests/test_auto_Extract.py +++ b/nipype/interfaces/minc/tests/test_auto_Extract.py @@ -4,9 +4,17 @@ def test_Extract_inputs(): input_map = dict( - args=dict(argstr="%s",), - count=dict(argstr="-count %s", sep=",",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + count=dict( + argstr="-count %s", + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), flip_any_direction=dict( argstr="-any_direction", xor=( @@ -67,13 +75,35 @@ def test_Extract_inputs(): argstr="+zdirection", xor=("flip_z_positive", "flip_z_negative", "flip_z_any"), ), - image_maximum=dict(argstr="-image_maximum %s",), - image_minimum=dict(argstr="-image_minimum %s",), - image_range=dict(argstr="-image_range %s %s",), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - nonormalize=dict(argstr="-nonormalize", xor=("normalize", "nonormalize"),), - normalize=dict(argstr="-normalize", xor=("normalize", "nonormalize"),), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), + image_maximum=dict( + argstr="-image_maximum %s", + ), + image_minimum=dict( + argstr="-image_minimum %s", + ), + image_range=dict( + argstr="-image_range %s %s", + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + nonormalize=dict( + argstr="-nonormalize", + xor=("normalize", "nonormalize"), + ), + normalize=dict( + argstr="-normalize", + xor=("normalize", "nonormalize"), + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), output_file=dict( extensions=None, hash_files=False, @@ -82,7 +112,10 @@ def test_Extract_inputs(): name_template="%s.raw", position=-1, ), - start=dict(argstr="-start %s", sep=",",), + start=dict( + argstr="-start %s", + sep=",", + ), write_ascii=dict( argstr="-ascii", xor=( @@ -173,7 +206,9 @@ def test_Extract_inputs(): "write_unsigned", ), ), - write_range=dict(argstr="-range %s %s",), + write_range=dict( + argstr="-range %s %s", + ), write_short=dict( argstr="-short", xor=( @@ -189,9 +224,13 @@ def test_Extract_inputs(): "write_unsigned", ), ), - write_signed=dict(argstr="-signed", xor=("write_signed", "write_unsigned"),), + write_signed=dict( + argstr="-signed", + xor=("write_signed", "write_unsigned"), + ), write_unsigned=dict( - argstr="-unsigned", xor=("write_signed", "write_unsigned"), + argstr="-unsigned", + xor=("write_signed", "write_unsigned"), ), ) inputs = Extract.input_spec() @@ -202,7 +241,11 @@ def test_Extract_inputs(): def test_Extract_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Extract.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Gennlxfm.py b/nipype/interfaces/minc/tests/test_auto_Gennlxfm.py index deb6449d3d..91bcc57e3c 100644 --- a/nipype/interfaces/minc/tests/test_auto_Gennlxfm.py +++ b/nipype/interfaces/minc/tests/test_auto_Gennlxfm.py @@ -4,11 +4,24 @@ def test_Gennlxfm_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - ident=dict(argstr="-ident",), - like=dict(argstr="-like %s", extensions=None,), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ident=dict( + argstr="-ident", + ), + like=dict( + argstr="-like %s", + extensions=None, + ), output_file=dict( argstr="%s", extensions=None, @@ -18,8 +31,12 @@ def test_Gennlxfm_inputs(): name_template="%s_gennlxfm.xfm", position=-1, ), - step=dict(argstr="-step %s",), - verbose=dict(argstr="-verbose",), + step=dict( + argstr="-step %s", + ), + verbose=dict( + argstr="-verbose", + ), ) inputs = Gennlxfm.input_spec() @@ -30,7 +47,12 @@ def test_Gennlxfm_inputs(): def test_Gennlxfm_outputs(): output_map = dict( - output_file=dict(extensions=None,), output_grid=dict(extensions=None,), + output_file=dict( + extensions=None, + ), + output_grid=dict( + extensions=None, + ), ) outputs = Gennlxfm.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Math.py b/nipype/interfaces/minc/tests/test_auto_Math.py index 32a5f68d66..86858235cd 100644 --- a/nipype/interfaces/minc/tests/test_auto_Math.py +++ b/nipype/interfaces/minc/tests/test_auto_Math.py @@ -4,25 +4,61 @@ def test_Math_inputs(): input_map = dict( - abs=dict(argstr="-abs",), - args=dict(argstr="%s",), - calc_add=dict(argstr="-add",), - calc_and=dict(argstr="-and",), - calc_div=dict(argstr="-div",), - calc_mul=dict(argstr="-mult",), - calc_not=dict(argstr="-not",), - calc_or=dict(argstr="-or",), - calc_sub=dict(argstr="-sub",), + abs=dict( + argstr="-abs", + ), + args=dict( + argstr="%s", + ), + calc_add=dict( + argstr="-add", + ), + calc_and=dict( + argstr="-and", + ), + calc_div=dict( + argstr="-div", + ), + calc_mul=dict( + argstr="-mult", + ), + calc_not=dict( + argstr="-not", + ), + calc_or=dict( + argstr="-or", + ), + calc_sub=dict( + argstr="-sub", + ), check_dimensions=dict( - argstr="-check_dimensions", xor=("check_dimensions", "no_check_dimensions"), - ), - clamp=dict(argstr="-clamp -const2 %s %s",), - clobber=dict(argstr="-clobber", usedefault=True,), - copy_header=dict(argstr="-copy_header", xor=("copy_header", "no_copy_header"),), - count_valid=dict(argstr="-count_valid",), - dimension=dict(argstr="-dimension %s",), - environ=dict(nohash=True, usedefault=True,), - exp=dict(argstr="-exp -const2 %s %s",), + argstr="-check_dimensions", + xor=("check_dimensions", "no_check_dimensions"), + ), + clamp=dict( + argstr="-clamp -const2 %s %s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + copy_header=dict( + argstr="-copy_header", + xor=("copy_header", "no_copy_header"), + ), + count_valid=dict( + argstr="-count_valid", + ), + dimension=dict( + argstr="-dimension %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + exp=dict( + argstr="-exp -const2 %s %s", + ), filelist=dict( argstr="-filelist %s", extensions=None, @@ -155,7 +191,9 @@ def test_Math_inputs(): "format_unsigned", ), ), - ignore_nan=dict(argstr="-ignore_nan",), + ignore_nan=dict( + argstr="-ignore_nan", + ), input_files=dict( argstr="%s", mandatory=True, @@ -163,23 +201,39 @@ def test_Math_inputs(): sep=" ", xor=("input_files", "filelist"), ), - invert=dict(argstr="-invert -const %s",), - isnan=dict(argstr="-isnan",), - log=dict(argstr="-log -const2 %s %s",), + invert=dict( + argstr="-invert -const %s", + ), + isnan=dict( + argstr="-isnan", + ), + log=dict( + argstr="-log -const2 %s %s", + ), max_buffer_size_in_kb=dict( - argstr="-max_buffer_size_in_kb %d", usedefault=True, + argstr="-max_buffer_size_in_kb %d", + usedefault=True, + ), + maximum=dict( + argstr="-maximum", + ), + minimum=dict( + argstr="-minimum", + ), + nisnan=dict( + argstr="-nisnan", ), - maximum=dict(argstr="-maximum",), - minimum=dict(argstr="-minimum",), - nisnan=dict(argstr="-nisnan",), no_check_dimensions=dict( argstr="-nocheck_dimensions", xor=("check_dimensions", "no_check_dimensions"), ), no_copy_header=dict( - argstr="-nocopy_header", xor=("copy_header", "no_copy_header"), + argstr="-nocopy_header", + xor=("copy_header", "no_copy_header"), + ), + nsegment=dict( + argstr="-nsegment -const2 %s %s", ), - nsegment=dict(argstr="-nsegment -const2 %s %s",), output_file=dict( argstr="%s", extensions=None, @@ -194,25 +248,55 @@ def test_Math_inputs(): xor=("output_nan", "output_zero", "output_illegal_value"), ), output_nan=dict( - argstr="-nan", xor=("output_nan", "output_zero", "output_illegal_value"), + argstr="-nan", + xor=("output_nan", "output_zero", "output_illegal_value"), ), output_zero=dict( - argstr="-zero", xor=("output_nan", "output_zero", "output_illegal_value"), - ), - percentdiff=dict(argstr="-percentdiff",), - propagate_nan=dict(argstr="-propagate_nan",), - scale=dict(argstr="-scale -const2 %s %s",), - segment=dict(argstr="-segment -const2 %s %s",), - sqrt=dict(argstr="-sqrt",), - square=dict(argstr="-square",), - test_eq=dict(argstr="-eq",), - test_ge=dict(argstr="-ge",), - test_gt=dict(argstr="-gt",), - test_le=dict(argstr="-le",), - test_lt=dict(argstr="-lt",), - test_ne=dict(argstr="-ne",), - two=dict(argstr="-2",), - voxel_range=dict(argstr="-range %d %d",), + argstr="-zero", + xor=("output_nan", "output_zero", "output_illegal_value"), + ), + percentdiff=dict( + argstr="-percentdiff", + ), + propagate_nan=dict( + argstr="-propagate_nan", + ), + scale=dict( + argstr="-scale -const2 %s %s", + ), + segment=dict( + argstr="-segment -const2 %s %s", + ), + sqrt=dict( + argstr="-sqrt", + ), + square=dict( + argstr="-square", + ), + test_eq=dict( + argstr="-eq", + ), + test_ge=dict( + argstr="-ge", + ), + test_gt=dict( + argstr="-gt", + ), + test_le=dict( + argstr="-le", + ), + test_lt=dict( + argstr="-lt", + ), + test_ne=dict( + argstr="-ne", + ), + two=dict( + argstr="-2", + ), + voxel_range=dict( + argstr="-range %d %d", + ), ) inputs = Math.input_spec() @@ -222,7 +306,11 @@ def test_Math_inputs(): def test_Math_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Math.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_NlpFit.py b/nipype/interfaces/minc/tests/test_auto_NlpFit.py index 58e9e985db..39b1df4743 100644 --- a/nipype/interfaces/minc/tests/test_auto_NlpFit.py +++ b/nipype/interfaces/minc/tests/test_auto_NlpFit.py @@ -4,17 +4,54 @@ def test_NlpFit_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - config_file=dict(argstr="-config_file %s", extensions=None, mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - init_xfm=dict(argstr="-init_xfm %s", extensions=None, mandatory=True,), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + config_file=dict( + argstr="-config_file %s", + extensions=None, + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + init_xfm=dict( + argstr="-init_xfm %s", + extensions=None, + mandatory=True, + ), input_grid_files=dict(), - output_xfm=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - source=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - source_mask=dict(argstr="-source_mask %s", extensions=None, mandatory=True,), - target=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - verbose=dict(argstr="-verbose",), + output_xfm=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + source=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + source_mask=dict( + argstr="-source_mask %s", + extensions=None, + mandatory=True, + ), + target=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + verbose=dict( + argstr="-verbose", + ), ) inputs = NlpFit.input_spec() @@ -25,7 +62,12 @@ def test_NlpFit_inputs(): def test_NlpFit_outputs(): output_map = dict( - output_grid=dict(extensions=None,), output_xfm=dict(extensions=None,), + output_grid=dict( + extensions=None, + ), + output_xfm=dict( + extensions=None, + ), ) outputs = NlpFit.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Norm.py b/nipype/interfaces/minc/tests/test_auto_Norm.py index 462b61459f..f8c2060250 100644 --- a/nipype/interfaces/minc/tests/test_auto_Norm.py +++ b/nipype/interfaces/minc/tests/test_auto_Norm.py @@ -4,16 +4,43 @@ def test_Norm_inputs(): input_map = dict( - args=dict(argstr="%s",), - clamp=dict(argstr="-clamp", usedefault=True,), - clobber=dict(argstr="-clobber", usedefault=True,), - cutoff=dict(argstr="-cutoff %s",), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - lower=dict(argstr="-lower %s",), - mask=dict(argstr="-mask %s", extensions=None,), - out_ceil=dict(argstr="-out_ceil %s",), - out_floor=dict(argstr="-out_floor %s",), + args=dict( + argstr="%s", + ), + clamp=dict( + argstr="-clamp", + usedefault=True, + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + cutoff=dict( + argstr="-cutoff %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + lower=dict( + argstr="-lower %s", + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), + out_ceil=dict( + argstr="-out_ceil %s", + ), + out_floor=dict( + argstr="-out_floor %s", + ), output_file=dict( argstr="%s", extensions=None, @@ -30,11 +57,21 @@ def test_Norm_inputs(): name_source=["input_file"], name_template="%s_norm_threshold_mask.mnc", ), - threshold=dict(argstr="-threshold",), - threshold_blur=dict(argstr="-threshold_blur %s",), - threshold_bmt=dict(argstr="-threshold_bmt",), - threshold_perc=dict(argstr="-threshold_perc %s",), - upper=dict(argstr="-upper %s",), + threshold=dict( + argstr="-threshold", + ), + threshold_blur=dict( + argstr="-threshold_blur %s", + ), + threshold_bmt=dict( + argstr="-threshold_bmt", + ), + threshold_perc=dict( + argstr="-threshold_perc %s", + ), + upper=dict( + argstr="-upper %s", + ), ) inputs = Norm.input_spec() @@ -45,8 +82,12 @@ def test_Norm_inputs(): def test_Norm_outputs(): output_map = dict( - output_file=dict(extensions=None,), - output_threshold_mask=dict(extensions=None,), + output_file=dict( + extensions=None, + ), + output_threshold_mask=dict( + extensions=None, + ), ) outputs = Norm.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Pik.py b/nipype/interfaces/minc/tests/test_auto_Pik.py index 530ead0317..3323ef74a1 100644 --- a/nipype/interfaces/minc/tests/test_auto_Pik.py +++ b/nipype/interfaces/minc/tests/test_auto_Pik.py @@ -4,23 +4,50 @@ def test_Pik_inputs(): input_map = dict( - annotated_bar=dict(argstr="--anot_bar",), - args=dict(argstr="%s",), - auto_range=dict(argstr="--auto_range", xor=("image_range", "auto_range"),), - clobber=dict(argstr="-clobber", usedefault=True,), - depth=dict(argstr="--depth %s",), - environ=dict(nohash=True, usedefault=True,), + annotated_bar=dict( + argstr="--anot_bar", + ), + args=dict( + argstr="%s", + ), + auto_range=dict( + argstr="--auto_range", + xor=("image_range", "auto_range"), + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + depth=dict( + argstr="--depth %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), horizontal_triplanar_view=dict( argstr="--horizontal", xor=("vertical_triplanar_view", "horizontal_triplanar_view"), ), image_range=dict( - argstr="--image_range %s %s", xor=("image_range", "auto_range"), + argstr="--image_range %s %s", + xor=("image_range", "auto_range"), + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + jpg=dict( + xor=("jpg", "png"), + ), + lookup=dict( + argstr="--lookup %s", + ), + minc_range=dict( + argstr="--range %s %s", ), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - jpg=dict(xor=("jpg", "png"),), - lookup=dict(argstr="--lookup %s",), - minc_range=dict(argstr="--range %s %s",), output_file=dict( argstr="%s", extensions=None, @@ -31,23 +58,54 @@ def test_Pik_inputs(): name_template="%s.png", position=-1, ), - png=dict(xor=("jpg", "png"),), - sagittal_offset=dict(argstr="--sagittal_offset %s",), - sagittal_offset_perc=dict(argstr="--sagittal_offset_perc %d",), - scale=dict(argstr="--scale %s", usedefault=True,), - slice_x=dict(argstr="-x", xor=("slice_z", "slice_y", "slice_x"),), - slice_y=dict(argstr="-y", xor=("slice_z", "slice_y", "slice_x"),), - slice_z=dict(argstr="-z", xor=("slice_z", "slice_y", "slice_x"),), - start=dict(argstr="--slice %s",), - tile_size=dict(argstr="--tilesize %s",), - title=dict(argstr="%s",), - title_size=dict(argstr="--title_size %s", requires=["title"],), - triplanar=dict(argstr="--triplanar",), + png=dict( + xor=("jpg", "png"), + ), + sagittal_offset=dict( + argstr="--sagittal_offset %s", + ), + sagittal_offset_perc=dict( + argstr="--sagittal_offset_perc %d", + ), + scale=dict( + argstr="--scale %s", + usedefault=True, + ), + slice_x=dict( + argstr="-x", + xor=("slice_z", "slice_y", "slice_x"), + ), + slice_y=dict( + argstr="-y", + xor=("slice_z", "slice_y", "slice_x"), + ), + slice_z=dict( + argstr="-z", + xor=("slice_z", "slice_y", "slice_x"), + ), + start=dict( + argstr="--slice %s", + ), + tile_size=dict( + argstr="--tilesize %s", + ), + title=dict( + argstr="%s", + ), + title_size=dict( + argstr="--title_size %s", + requires=["title"], + ), + triplanar=dict( + argstr="--triplanar", + ), vertical_triplanar_view=dict( argstr="--vertical", xor=("vertical_triplanar_view", "horizontal_triplanar_view"), ), - width=dict(argstr="--width %s",), + width=dict( + argstr="--width %s", + ), ) inputs = Pik.input_spec() @@ -57,7 +115,11 @@ def test_Pik_inputs(): def test_Pik_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Pik.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Resample.py b/nipype/interfaces/minc/tests/test_auto_Resample.py index 32385be6c9..59f2ae180d 100644 --- a/nipype/interfaces/minc/tests/test_auto_Resample.py +++ b/nipype/interfaces/minc/tests/test_auto_Resample.py @@ -4,17 +4,33 @@ def test_Resample_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), coronal_slices=dict( - argstr="-coronal", xor=("transverse", "sagittal", "coronal"), + argstr="-coronal", + xor=("transverse", "sagittal", "coronal"), ), dircos=dict( - argstr="-dircos %s %s %s", xor=("nelements", "nelements_x_y_or_z"), + argstr="-dircos %s %s %s", + xor=("nelements", "nelements_x_y_or_z"), + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fill=dict( + argstr="-fill", + xor=("nofill", "fill"), + ), + fill_value=dict( + argstr="-fillvalue %s", + requires=["fill"], ), - environ=dict(nohash=True, usedefault=True,), - fill=dict(argstr="-fill", xor=("nofill", "fill"),), - fill_value=dict(argstr="-fillvalue %s", requires=["fill"],), format_byte=dict( argstr="-byte", xor=( @@ -120,15 +136,27 @@ def test_Resample_inputs(): ), ), half_width_sinc_window=dict( - argstr="-width %s", requires=["sinc_interpolation"], + argstr="-width %s", + requires=["sinc_interpolation"], + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, ), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), input_grid_files=dict(), - invert_transformation=dict(argstr="-invert_transformation",), + invert_transformation=dict( + argstr="-invert_transformation", + ), keep_real_range=dict( - argstr="-keep_real_range", xor=("keep_real_range", "nokeep_real_range"), + argstr="-keep_real_range", + xor=("keep_real_range", "nokeep_real_range"), + ), + like=dict( + argstr="-like %s", + extensions=None, ), - like=dict(argstr="-like %s", extensions=None,), nearest_neighbour_interpolation=dict( argstr="-nearest_neighbour", xor=( @@ -139,16 +167,24 @@ def test_Resample_inputs(): ), ), nelements=dict( - argstr="-nelements %s %s %s", xor=("nelements", "nelements_x_y_or_z"), + argstr="-nelements %s %s %s", + xor=("nelements", "nelements_x_y_or_z"), + ), + no_fill=dict( + argstr="-nofill", + xor=("nofill", "fill"), ), - no_fill=dict(argstr="-nofill", xor=("nofill", "fill"),), no_input_sampling=dict( - argstr="-use_input_sampling", xor=("vio_transform", "no_input_sampling"), + argstr="-use_input_sampling", + xor=("vio_transform", "no_input_sampling"), ), nokeep_real_range=dict( - argstr="-nokeep_real_range", xor=("keep_real_range", "nokeep_real_range"), + argstr="-nokeep_real_range", + xor=("keep_real_range", "nokeep_real_range"), + ), + origin=dict( + argstr="-origin %s %s %s", ), - origin=dict(argstr="-origin %s %s %s",), output_file=dict( argstr="%s", extensions=None, @@ -158,9 +194,12 @@ def test_Resample_inputs(): name_template="%s_resample.mnc", position=-1, ), - output_range=dict(argstr="-range %s %s",), + output_range=dict( + argstr="-range %s %s", + ), sagittal_slices=dict( - argstr="-sagittal", xor=("transverse", "sagittal", "coronal"), + argstr="-sagittal", + xor=("transverse", "sagittal", "coronal"), ), sinc_interpolation=dict( argstr="-sinc", @@ -181,14 +220,30 @@ def test_Resample_inputs(): requires=["sinc_interpolation"], xor=("sinc_window_hanning", "sinc_window_hamming"), ), - spacetype=dict(argstr="-spacetype %s",), - standard_sampling=dict(argstr="-standard_sampling",), - start=dict(argstr="-start %s %s %s", xor=("nelements", "nelements_x_y_or_z"),), - step=dict(argstr="-step %s %s %s", xor=("nelements", "nelements_x_y_or_z"),), - talairach=dict(argstr="-talairach",), - transformation=dict(argstr="-transformation %s", extensions=None,), + spacetype=dict( + argstr="-spacetype %s", + ), + standard_sampling=dict( + argstr="-standard_sampling", + ), + start=dict( + argstr="-start %s %s %s", + xor=("nelements", "nelements_x_y_or_z"), + ), + step=dict( + argstr="-step %s %s %s", + xor=("nelements", "nelements_x_y_or_z"), + ), + talairach=dict( + argstr="-talairach", + ), + transformation=dict( + argstr="-transformation %s", + extensions=None, + ), transverse_slices=dict( - argstr="-transverse", xor=("transverse", "sagittal", "coronal"), + argstr="-transverse", + xor=("transverse", "sagittal", "coronal"), ), tricubic_interpolation=dict( argstr="-tricubic", @@ -208,10 +263,15 @@ def test_Resample_inputs(): "sinc_interpolation", ), ), - two=dict(argstr="-2",), - units=dict(argstr="-units %s",), + two=dict( + argstr="-2", + ), + units=dict( + argstr="-units %s", + ), vio_transform=dict( - argstr="-tfm_input_sampling", xor=("vio_transform", "no_input_sampling"), + argstr="-tfm_input_sampling", + xor=("vio_transform", "no_input_sampling"), ), xdircos=dict( argstr="-xdircos %s", @@ -282,7 +342,11 @@ def test_Resample_inputs(): def test_Resample_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Resample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Reshape.py b/nipype/interfaces/minc/tests/test_auto_Reshape.py index 92b0e5862e..50286b41e5 100644 --- a/nipype/interfaces/minc/tests/test_auto_Reshape.py +++ b/nipype/interfaces/minc/tests/test_auto_Reshape.py @@ -4,10 +4,23 @@ def test_Reshape_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), output_file=dict( argstr="%s", extensions=None, @@ -17,8 +30,12 @@ def test_Reshape_inputs(): name_template="%s_reshape.mnc", position=-1, ), - verbose=dict(argstr="-verbose",), - write_short=dict(argstr="-short",), + verbose=dict( + argstr="-verbose", + ), + write_short=dict( + argstr="-short", + ), ) inputs = Reshape.input_spec() @@ -28,7 +45,11 @@ def test_Reshape_inputs(): def test_Reshape_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Reshape.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_ToEcat.py b/nipype/interfaces/minc/tests/test_auto_ToEcat.py index 02936ae4f4..f6ce521232 100644 --- a/nipype/interfaces/minc/tests/test_auto_ToEcat.py +++ b/nipype/interfaces/minc/tests/test_auto_ToEcat.py @@ -4,18 +4,40 @@ def test_ToEcat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - ignore_acquisition_variable=dict(argstr="-ignore_acquisition_variable",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_acquisition_variable=dict( + argstr="-ignore_acquisition_variable", + ), ignore_ecat_acquisition_variable=dict( argstr="-ignore_ecat_acquisition_variable", ), - ignore_ecat_main=dict(argstr="-ignore_ecat_main",), - ignore_ecat_subheader_variable=dict(argstr="-ignore_ecat_subheader_variable",), - ignore_patient_variable=dict(argstr="-ignore_patient_variable",), - ignore_study_variable=dict(argstr="-ignore_study_variable",), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - no_decay_corr_fctr=dict(argstr="-no_decay_corr_fctr",), + ignore_ecat_main=dict( + argstr="-ignore_ecat_main", + ), + ignore_ecat_subheader_variable=dict( + argstr="-ignore_ecat_subheader_variable", + ), + ignore_patient_variable=dict( + argstr="-ignore_patient_variable", + ), + ignore_study_variable=dict( + argstr="-ignore_study_variable", + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + no_decay_corr_fctr=dict( + argstr="-no_decay_corr_fctr", + ), output_file=dict( argstr="%s", extensions=None, @@ -26,7 +48,9 @@ def test_ToEcat_inputs(): name_template="%s_to_ecat.v", position=-1, ), - voxels_as_integers=dict(argstr="-label",), + voxels_as_integers=dict( + argstr="-label", + ), ) inputs = ToEcat.input_spec() @@ -36,7 +60,11 @@ def test_ToEcat_inputs(): def test_ToEcat_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = ToEcat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_ToRaw.py b/nipype/interfaces/minc/tests/test_auto_ToRaw.py index 7a15e49f65..39940170f6 100644 --- a/nipype/interfaces/minc/tests/test_auto_ToRaw.py +++ b/nipype/interfaces/minc/tests/test_auto_ToRaw.py @@ -4,12 +4,33 @@ def test_ToRaw_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - nonormalize=dict(argstr="-nonormalize", xor=("normalize", "nonormalize"),), - normalize=dict(argstr="-normalize", xor=("normalize", "nonormalize"),), - out_file=dict(argstr="> %s", extensions=None, genfile=True, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + nonormalize=dict( + argstr="-nonormalize", + xor=("normalize", "nonormalize"), + ), + normalize=dict( + argstr="-normalize", + xor=("normalize", "nonormalize"), + ), + out_file=dict( + argstr="> %s", + extensions=None, + genfile=True, + position=-1, + ), output_file=dict( extensions=None, hash_files=False, @@ -73,7 +94,9 @@ def test_ToRaw_inputs(): "write_double", ), ), - write_range=dict(argstr="-range %s %s",), + write_range=dict( + argstr="-range %s %s", + ), write_short=dict( argstr="-short", xor=( @@ -85,9 +108,13 @@ def test_ToRaw_inputs(): "write_double", ), ), - write_signed=dict(argstr="-signed", xor=("write_signed", "write_unsigned"),), + write_signed=dict( + argstr="-signed", + xor=("write_signed", "write_unsigned"), + ), write_unsigned=dict( - argstr="-unsigned", xor=("write_signed", "write_unsigned"), + argstr="-unsigned", + xor=("write_signed", "write_unsigned"), ), ) inputs = ToRaw.input_spec() @@ -98,7 +125,11 @@ def test_ToRaw_inputs(): def test_ToRaw_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = ToRaw.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_VolSymm.py b/nipype/interfaces/minc/tests/test_auto_VolSymm.py index aeb8e6d23a..a1b89616f2 100644 --- a/nipype/interfaces/minc/tests/test_auto_VolSymm.py +++ b/nipype/interfaces/minc/tests/test_auto_VolSymm.py @@ -4,15 +4,37 @@ def test_VolSymm_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - config_file=dict(argstr="-config_file %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - fit_linear=dict(argstr="-linear",), - fit_nonlinear=dict(argstr="-nonlinear",), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + config_file=dict( + argstr="-config_file %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fit_linear=dict( + argstr="-linear", + ), + fit_nonlinear=dict( + argstr="-nonlinear", + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), input_grid_files=dict(), - nofit=dict(argstr="-nofit",), + nofit=dict( + argstr="-nofit", + ), output_file=dict( argstr="%s", extensions=None, @@ -32,10 +54,18 @@ def test_VolSymm_inputs(): name_template="%s_vol_symm.xfm", position=-2, ), - verbose=dict(argstr="-verbose",), - x=dict(argstr="-x",), - y=dict(argstr="-y",), - z=dict(argstr="-z",), + verbose=dict( + argstr="-verbose", + ), + x=dict( + argstr="-x", + ), + y=dict( + argstr="-y", + ), + z=dict( + argstr="-z", + ), ) inputs = VolSymm.input_spec() @@ -46,9 +76,15 @@ def test_VolSymm_inputs(): def test_VolSymm_outputs(): output_map = dict( - output_file=dict(extensions=None,), - output_grid=dict(extensions=None,), - trans_file=dict(extensions=None,), + output_file=dict( + extensions=None, + ), + output_grid=dict( + extensions=None, + ), + trans_file=dict( + extensions=None, + ), ) outputs = VolSymm.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_Volcentre.py b/nipype/interfaces/minc/tests/test_auto_Volcentre.py index 492714adf4..cf9f777f70 100644 --- a/nipype/interfaces/minc/tests/test_auto_Volcentre.py +++ b/nipype/interfaces/minc/tests/test_auto_Volcentre.py @@ -4,12 +4,29 @@ def test_Volcentre_inputs(): input_map = dict( - args=dict(argstr="%s",), - centre=dict(argstr="-centre %s %s %s",), - clobber=dict(argstr="-clobber", usedefault=True,), - com=dict(argstr="-com",), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + centre=dict( + argstr="-centre %s %s %s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + com=dict( + argstr="-com", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), output_file=dict( argstr="%s", extensions=None, @@ -19,8 +36,12 @@ def test_Volcentre_inputs(): name_template="%s_volcentre.mnc", position=-1, ), - verbose=dict(argstr="-verbose",), - zero_dircos=dict(argstr="-zero_dircos",), + verbose=dict( + argstr="-verbose", + ), + zero_dircos=dict( + argstr="-zero_dircos", + ), ) inputs = Volcentre.input_spec() @@ -30,7 +51,11 @@ def test_Volcentre_inputs(): def test_Volcentre_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Volcentre.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Voliso.py b/nipype/interfaces/minc/tests/test_auto_Voliso.py index 534315d0cf..40d01b5767 100644 --- a/nipype/interfaces/minc/tests/test_auto_Voliso.py +++ b/nipype/interfaces/minc/tests/test_auto_Voliso.py @@ -4,13 +4,32 @@ def test_Voliso_inputs(): input_map = dict( - args=dict(argstr="%s",), - avgstep=dict(argstr="--avgstep",), - clobber=dict(argstr="--clobber", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - maxstep=dict(argstr="--maxstep %s",), - minstep=dict(argstr="--minstep %s",), + args=dict( + argstr="%s", + ), + avgstep=dict( + argstr="--avgstep", + ), + clobber=dict( + argstr="--clobber", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + maxstep=dict( + argstr="--maxstep %s", + ), + minstep=dict( + argstr="--minstep %s", + ), output_file=dict( argstr="%s", extensions=None, @@ -20,7 +39,9 @@ def test_Voliso_inputs(): name_template="%s_voliso.mnc", position=-1, ), - verbose=dict(argstr="--verbose",), + verbose=dict( + argstr="--verbose", + ), ) inputs = Voliso.input_spec() @@ -30,7 +51,11 @@ def test_Voliso_inputs(): def test_Voliso_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Voliso.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_Volpad.py b/nipype/interfaces/minc/tests/test_auto_Volpad.py index ce67c4ef73..5102199657 100644 --- a/nipype/interfaces/minc/tests/test_auto_Volpad.py +++ b/nipype/interfaces/minc/tests/test_auto_Volpad.py @@ -4,13 +4,32 @@ def test_Volpad_inputs(): input_map = dict( - args=dict(argstr="%s",), - auto=dict(argstr="-auto",), - auto_freq=dict(argstr="-auto_freq %s",), - clobber=dict(argstr="-clobber", usedefault=True,), - distance=dict(argstr="-distance %s",), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + auto=dict( + argstr="-auto", + ), + auto_freq=dict( + argstr="-auto_freq %s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + distance=dict( + argstr="-distance %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), output_file=dict( argstr="%s", extensions=None, @@ -20,9 +39,15 @@ def test_Volpad_inputs(): name_template="%s_volpad.mnc", position=-1, ), - smooth=dict(argstr="-smooth",), - smooth_distance=dict(argstr="-smooth_distance %s",), - verbose=dict(argstr="-verbose",), + smooth=dict( + argstr="-smooth", + ), + smooth_distance=dict( + argstr="-smooth_distance %s", + ), + verbose=dict( + argstr="-verbose", + ), ) inputs = Volpad.input_spec() @@ -32,7 +57,11 @@ def test_Volpad_inputs(): def test_Volpad_outputs(): - output_map = dict(output_file=dict(extensions=None,),) + output_map = dict( + output_file=dict( + extensions=None, + ), + ) outputs = Volpad.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_XfmAvg.py b/nipype/interfaces/minc/tests/test_auto_XfmAvg.py index f688494751..f5df6f4d54 100644 --- a/nipype/interfaces/minc/tests/test_auto_XfmAvg.py +++ b/nipype/interfaces/minc/tests/test_auto_XfmAvg.py @@ -4,17 +4,45 @@ def test_XfmAvg_inputs(): input_map = dict( - args=dict(argstr="%s",), - avg_linear=dict(argstr="-avg_linear",), - avg_nonlinear=dict(argstr="-avg_nonlinear",), - clobber=dict(argstr="-clobber", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - ignore_linear=dict(argstr="-ignore_linear",), - ignore_nonlinear=dict(argstr="-ignore_nonline",), - input_files=dict(argstr="%s", mandatory=True, position=-2, sep=" ",), + args=dict( + argstr="%s", + ), + avg_linear=dict( + argstr="-avg_linear", + ), + avg_nonlinear=dict( + argstr="-avg_nonlinear", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_linear=dict( + argstr="-ignore_linear", + ), + ignore_nonlinear=dict( + argstr="-ignore_nonline", + ), + input_files=dict( + argstr="%s", + mandatory=True, + position=-2, + sep=" ", + ), input_grid_files=dict(), - output_file=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - verbose=dict(argstr="-verbose",), + output_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + verbose=dict( + argstr="-verbose", + ), ) inputs = XfmAvg.input_spec() @@ -25,7 +53,12 @@ def test_XfmAvg_inputs(): def test_XfmAvg_outputs(): output_map = dict( - output_file=dict(extensions=None,), output_grid=dict(extensions=None,), + output_file=dict( + extensions=None, + ), + output_grid=dict( + extensions=None, + ), ) outputs = XfmAvg.output_spec() diff --git a/nipype/interfaces/minc/tests/test_auto_XfmConcat.py b/nipype/interfaces/minc/tests/test_auto_XfmConcat.py index 23642895da..58144779b8 100644 --- a/nipype/interfaces/minc/tests/test_auto_XfmConcat.py +++ b/nipype/interfaces/minc/tests/test_auto_XfmConcat.py @@ -4,10 +4,23 @@ def test_XfmConcat_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - input_files=dict(argstr="%s", mandatory=True, position=-2, sep=" ",), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_files=dict( + argstr="%s", + mandatory=True, + position=-2, + sep=" ", + ), input_grid_files=dict(), output_file=dict( argstr="%s", @@ -18,7 +31,9 @@ def test_XfmConcat_inputs(): name_template="%s_xfmconcat.xfm", position=-1, ), - verbose=dict(argstr="-verbose",), + verbose=dict( + argstr="-verbose", + ), ) inputs = XfmConcat.input_spec() @@ -28,7 +43,12 @@ def test_XfmConcat_inputs(): def test_XfmConcat_outputs(): - output_map = dict(output_file=dict(extensions=None,), output_grids=dict(),) + output_map = dict( + output_file=dict( + extensions=None, + ), + output_grids=dict(), + ) outputs = XfmConcat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/minc/tests/test_auto_XfmInvert.py b/nipype/interfaces/minc/tests/test_auto_XfmInvert.py index 7f0c42c433..aa8fb61ccd 100644 --- a/nipype/interfaces/minc/tests/test_auto_XfmInvert.py +++ b/nipype/interfaces/minc/tests/test_auto_XfmInvert.py @@ -4,12 +4,32 @@ def test_XfmInvert_inputs(): input_map = dict( - args=dict(argstr="%s",), - clobber=dict(argstr="-clobber", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - input_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - output_file=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - verbose=dict(argstr="-verbose",), + args=dict( + argstr="%s", + ), + clobber=dict( + argstr="-clobber", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + input_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + output_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + verbose=dict( + argstr="-verbose", + ), ) inputs = XfmInvert.input_spec() @@ -20,7 +40,12 @@ def test_XfmInvert_inputs(): def test_XfmInvert_outputs(): output_map = dict( - output_file=dict(extensions=None,), output_grid=dict(extensions=None,), + output_file=dict( + extensions=None, + ), + output_grid=dict( + extensions=None, + ), ) outputs = XfmInvert.output_spec() diff --git a/nipype/interfaces/mipav/__init__.py b/nipype/interfaces/mipav/__init__.py index 85cc052c1e..9cde4c0bcd 100644 --- a/nipype/interfaces/mipav/__init__.py +++ b/nipype/interfaces/mipav/__init__.py @@ -1,5 +1,5 @@ -# -*- coding: utf-8 -*- """MIPAV enables quantitative analysis and visualization of multimodal medical images.""" + from .developer import ( JistLaminarVolumetricLayering, JistBrainMgdmSegmentation, diff --git a/nipype/interfaces/mipav/developer.py b/nipype/interfaces/mipav/developer.py index 52e2b01b01..a76f2e35c4 100644 --- a/nipype/interfaces/mipav/developer.py +++ b/nipype/interfaces/mipav/developer.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ..base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -481,7 +473,7 @@ class MedicAlgorithmLesionToadsInputSpec(CommandLineInputSpec): desc="Atlas File - No Lesion - T1 Only", exists=True, argstr="--inAtlas4 %s" ) inMaximum = traits.Int( - desc="Maximum distance from the interventricular WM boundary to downweight the lesion membership to avoid false postives", + desc="Maximum distance from the interventricular WM boundary to downweight the lesion membership to avoid false positives", argstr="--inMaximum %d", ) inMaximum2 = traits.Int(desc="Maximum Ventircle Distance", argstr="--inMaximum2 %d") @@ -499,7 +491,7 @@ class MedicAlgorithmLesionToadsInputSpec(CommandLineInputSpec): argstr="--inAtlas5 %f", ) inSmooting = traits.Float( - desc="Controls the effect of neighberhood voxels on the membership", + desc="Controls the effect of neighborhood voxels on the membership", argstr="--inSmooting %f", ) inMaximum4 = traits.Float( @@ -603,7 +595,7 @@ class MedicAlgorithmLesionToadsOutputSpec(TraitedSpec): class MedicAlgorithmLesionToads(SEMLikeCommandLine): - """Algorithm for simulataneous brain structures and MS lesion segmentation of MS Brains. + """Algorithm for simultaneous brain structures and MS lesion segmentation of MS Brains. The brain segmentation is topologically consistent and the algorithm can use multiple MR sequences as input data. @@ -1085,7 +1077,7 @@ class MedicAlgorithmSPECTRE2010InputSpec(CommandLineInputSpec): argstr="--inAtlas %s", ) inInitial = traits.Int( - desc="Erosion of the inital mask, which is based on the probability mask and the classification., The initial mask is ouput as the d0 volume at the conclusion of SPECTRE.", + desc="Erosion of the initial mask, which is based on the probability mask and the classification., The initial mask is output as the d0 volume at the conclusion of SPECTRE.", argstr="--inInitial %d", ) inImage = traits.Enum( @@ -1253,7 +1245,7 @@ class MedicAlgorithmSPECTRE2010InputSpec(CommandLineInputSpec): traits.Bool, File(), hash_files=False, - desc="Tissue classification of of the whole input volume.", + desc="Tissue classification of the whole input volume.", argstr="--outFANTASM %s", ) outd0 = traits.Either( @@ -1310,7 +1302,7 @@ class MedicAlgorithmSPECTRE2010OutputSpec(TraitedSpec): ) outPrior = File(desc="Probability prior from the atlas registrations", exists=True) outFANTASM = File( - desc="Tissue classification of of the whole input volume.", exists=True + desc="Tissue classification of the whole input volume.", exists=True ) outd0 = File(desc="Initial Brainmask", exists=True) outMidsagittal = File(desc="Plane dividing the brain hemispheres", exists=True) diff --git a/nipype/interfaces/mipav/generate_classes.py b/nipype/interfaces/mipav/generate_classes.py index 55f0f6a5db..ab91e48150 100644 --- a/nipype/interfaces/mipav/generate_classes.py +++ b/nipype/interfaces/mipav/generate_classes.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - if __name__ == "__main__": from nipype.interfaces.slicer.generate_classes import generate_all_classes diff --git a/nipype/interfaces/mipav/tests/__init__.py b/nipype/interfaces/mipav/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/mipav/tests/__init__.py +++ b/nipype/interfaces/mipav/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py b/nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py index d97c5d904b..9daa1b996e 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistBrainMgdmSegmentation.py @@ -4,32 +4,96 @@ def test_JistBrainMgdmSegmentation_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inAdjust=dict(argstr="--inAdjust %s",), - inAtlas=dict(argstr="--inAtlas %s", extensions=None,), - inCompute=dict(argstr="--inCompute %s",), - inCurvature=dict(argstr="--inCurvature %f",), - inData=dict(argstr="--inData %f",), - inFLAIR=dict(argstr="--inFLAIR %s", extensions=None,), - inMP2RAGE=dict(argstr="--inMP2RAGE %s", extensions=None,), - inMP2RAGE2=dict(argstr="--inMP2RAGE2 %s", extensions=None,), - inMPRAGE=dict(argstr="--inMPRAGE %s", extensions=None,), - inMax=dict(argstr="--inMax %d",), - inMin=dict(argstr="--inMin %f",), - inOutput=dict(argstr="--inOutput %s",), - inPV=dict(argstr="--inPV %s", extensions=None,), - inPosterior=dict(argstr="--inPosterior %f",), - inSteps=dict(argstr="--inSteps %d",), - inTopology=dict(argstr="--inTopology %s",), - null=dict(argstr="--null %s",), - outLevelset=dict(argstr="--outLevelset %s", hash_files=False,), - outPosterior2=dict(argstr="--outPosterior2 %s", hash_files=False,), - outPosterior3=dict(argstr="--outPosterior3 %s", hash_files=False,), - outSegmented=dict(argstr="--outSegmented %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inAdjust=dict( + argstr="--inAdjust %s", + ), + inAtlas=dict( + argstr="--inAtlas %s", + extensions=None, + ), + inCompute=dict( + argstr="--inCompute %s", + ), + inCurvature=dict( + argstr="--inCurvature %f", + ), + inData=dict( + argstr="--inData %f", + ), + inFLAIR=dict( + argstr="--inFLAIR %s", + extensions=None, + ), + inMP2RAGE=dict( + argstr="--inMP2RAGE %s", + extensions=None, + ), + inMP2RAGE2=dict( + argstr="--inMP2RAGE2 %s", + extensions=None, + ), + inMPRAGE=dict( + argstr="--inMPRAGE %s", + extensions=None, + ), + inMax=dict( + argstr="--inMax %d", + ), + inMin=dict( + argstr="--inMin %f", + ), + inOutput=dict( + argstr="--inOutput %s", + ), + inPV=dict( + argstr="--inPV %s", + extensions=None, + ), + inPosterior=dict( + argstr="--inPosterior %f", + ), + inSteps=dict( + argstr="--inSteps %d", + ), + inTopology=dict( + argstr="--inTopology %s", + ), + null=dict( + argstr="--null %s", + ), + outLevelset=dict( + argstr="--outLevelset %s", + hash_files=False, + ), + outPosterior2=dict( + argstr="--outPosterior2 %s", + hash_files=False, + ), + outPosterior3=dict( + argstr="--outPosterior3 %s", + hash_files=False, + ), + outSegmented=dict( + argstr="--outSegmented %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistBrainMgdmSegmentation.input_spec() @@ -40,10 +104,18 @@ def test_JistBrainMgdmSegmentation_inputs(): def test_JistBrainMgdmSegmentation_outputs(): output_map = dict( - outLevelset=dict(extensions=None,), - outPosterior2=dict(extensions=None,), - outPosterior3=dict(extensions=None,), - outSegmented=dict(extensions=None,), + outLevelset=dict( + extensions=None, + ), + outPosterior2=dict( + extensions=None, + ), + outPosterior3=dict( + extensions=None, + ), + outSegmented=dict( + extensions=None, + ), ) outputs = JistBrainMgdmSegmentation.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageDuraEstimation.py b/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageDuraEstimation.py index fa55aa0d75..e7706b16b5 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageDuraEstimation.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageDuraEstimation.py @@ -4,17 +4,44 @@ def test_JistBrainMp2rageDuraEstimation_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inDistance=dict(argstr="--inDistance %f",), - inSecond=dict(argstr="--inSecond %s", extensions=None,), - inSkull=dict(argstr="--inSkull %s", extensions=None,), - inoutput=dict(argstr="--inoutput %s",), - null=dict(argstr="--null %s",), - outDura=dict(argstr="--outDura %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inDistance=dict( + argstr="--inDistance %f", + ), + inSecond=dict( + argstr="--inSecond %s", + extensions=None, + ), + inSkull=dict( + argstr="--inSkull %s", + extensions=None, + ), + inoutput=dict( + argstr="--inoutput %s", + ), + null=dict( + argstr="--null %s", + ), + outDura=dict( + argstr="--outDura %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistBrainMp2rageDuraEstimation.input_spec() @@ -24,7 +51,11 @@ def test_JistBrainMp2rageDuraEstimation_inputs(): def test_JistBrainMp2rageDuraEstimation_outputs(): - output_map = dict(outDura=dict(extensions=None,),) + output_map = dict( + outDura=dict( + extensions=None, + ), + ) outputs = JistBrainMp2rageDuraEstimation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageSkullStripping.py b/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageSkullStripping.py index 5f4a6eb616..637b50dcad 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageSkullStripping.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistBrainMp2rageSkullStripping.py @@ -4,21 +4,61 @@ def test_JistBrainMp2rageSkullStripping_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inFilter=dict(argstr="--inFilter %s", extensions=None,), - inSecond=dict(argstr="--inSecond %s", extensions=None,), - inSkip=dict(argstr="--inSkip %s",), - inT1=dict(argstr="--inT1 %s", extensions=None,), - inT1weighted=dict(argstr="--inT1weighted %s", extensions=None,), - null=dict(argstr="--null %s",), - outBrain=dict(argstr="--outBrain %s", hash_files=False,), - outMasked=dict(argstr="--outMasked %s", hash_files=False,), - outMasked2=dict(argstr="--outMasked2 %s", hash_files=False,), - outMasked3=dict(argstr="--outMasked3 %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inFilter=dict( + argstr="--inFilter %s", + extensions=None, + ), + inSecond=dict( + argstr="--inSecond %s", + extensions=None, + ), + inSkip=dict( + argstr="--inSkip %s", + ), + inT1=dict( + argstr="--inT1 %s", + extensions=None, + ), + inT1weighted=dict( + argstr="--inT1weighted %s", + extensions=None, + ), + null=dict( + argstr="--null %s", + ), + outBrain=dict( + argstr="--outBrain %s", + hash_files=False, + ), + outMasked=dict( + argstr="--outMasked %s", + hash_files=False, + ), + outMasked2=dict( + argstr="--outMasked2 %s", + hash_files=False, + ), + outMasked3=dict( + argstr="--outMasked3 %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistBrainMp2rageSkullStripping.input_spec() @@ -29,10 +69,18 @@ def test_JistBrainMp2rageSkullStripping_inputs(): def test_JistBrainMp2rageSkullStripping_outputs(): output_map = dict( - outBrain=dict(extensions=None,), - outMasked=dict(extensions=None,), - outMasked2=dict(extensions=None,), - outMasked3=dict(extensions=None,), + outBrain=dict( + extensions=None, + ), + outMasked=dict( + extensions=None, + ), + outMasked2=dict( + extensions=None, + ), + outMasked3=dict( + extensions=None, + ), ) outputs = JistBrainMp2rageSkullStripping.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistBrainPartialVolumeFilter.py b/nipype/interfaces/mipav/tests/test_auto_JistBrainPartialVolumeFilter.py index 016b18f1e7..61a3e2b074 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistBrainPartialVolumeFilter.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistBrainPartialVolumeFilter.py @@ -4,16 +4,40 @@ def test_JistBrainPartialVolumeFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inInput=dict(argstr="--inInput %s", extensions=None,), - inPV=dict(argstr="--inPV %s",), - inoutput=dict(argstr="--inoutput %s",), - null=dict(argstr="--null %s",), - outPartial=dict(argstr="--outPartial %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inInput=dict( + argstr="--inInput %s", + extensions=None, + ), + inPV=dict( + argstr="--inPV %s", + ), + inoutput=dict( + argstr="--inoutput %s", + ), + null=dict( + argstr="--null %s", + ), + outPartial=dict( + argstr="--outPartial %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistBrainPartialVolumeFilter.input_spec() @@ -23,7 +47,11 @@ def test_JistBrainPartialVolumeFilter_inputs(): def test_JistBrainPartialVolumeFilter_outputs(): - output_map = dict(outPartial=dict(extensions=None,),) + output_map = dict( + outPartial=dict( + extensions=None, + ), + ) outputs = JistBrainPartialVolumeFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistCortexSurfaceMeshInflation.py b/nipype/interfaces/mipav/tests/test_auto_JistCortexSurfaceMeshInflation.py index 88ae68161c..41ae9c5cce 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistCortexSurfaceMeshInflation.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistCortexSurfaceMeshInflation.py @@ -4,21 +4,56 @@ def test_JistCortexSurfaceMeshInflation_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inLevelset=dict(argstr="--inLevelset %s", extensions=None,), - inLorentzian=dict(argstr="--inLorentzian %s",), - inMax=dict(argstr="--inMax %d",), - inMean=dict(argstr="--inMean %f",), - inSOR=dict(argstr="--inSOR %f",), - inStep=dict(argstr="--inStep %d",), - inTopology=dict(argstr="--inTopology %s",), - null=dict(argstr="--null %s",), - outInflated=dict(argstr="--outInflated %s", hash_files=False,), - outOriginal=dict(argstr="--outOriginal %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inLevelset=dict( + argstr="--inLevelset %s", + extensions=None, + ), + inLorentzian=dict( + argstr="--inLorentzian %s", + ), + inMax=dict( + argstr="--inMax %d", + ), + inMean=dict( + argstr="--inMean %f", + ), + inSOR=dict( + argstr="--inSOR %f", + ), + inStep=dict( + argstr="--inStep %d", + ), + inTopology=dict( + argstr="--inTopology %s", + ), + null=dict( + argstr="--null %s", + ), + outInflated=dict( + argstr="--outInflated %s", + hash_files=False, + ), + outOriginal=dict( + argstr="--outOriginal %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistCortexSurfaceMeshInflation.input_spec() @@ -29,7 +64,12 @@ def test_JistCortexSurfaceMeshInflation_inputs(): def test_JistCortexSurfaceMeshInflation_outputs(): output_map = dict( - outInflated=dict(extensions=None,), outOriginal=dict(extensions=None,), + outInflated=dict( + extensions=None, + ), + outOriginal=dict( + extensions=None, + ), ) outputs = JistCortexSurfaceMeshInflation.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py b/nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py index aaab939380..94d9cc525a 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistIntensityMp2rageMasking.py @@ -4,22 +4,63 @@ def test_JistIntensityMp2rageMasking_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inBackground=dict(argstr="--inBackground %s",), - inMasking=dict(argstr="--inMasking %s",), - inQuantitative=dict(argstr="--inQuantitative %s", extensions=None,), - inSecond=dict(argstr="--inSecond %s", extensions=None,), - inSkip=dict(argstr="--inSkip %s",), - inT1weighted=dict(argstr="--inT1weighted %s", extensions=None,), - null=dict(argstr="--null %s",), - outMasked=dict(argstr="--outMasked_T1_Map %s", hash_files=False,), - outMasked2=dict(argstr="--outMasked_T1weighted %s", hash_files=False,), - outSignal=dict(argstr="--outSignal_Proba %s", hash_files=False,), - outSignal2=dict(argstr="--outSignal_Mask %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inBackground=dict( + argstr="--inBackground %s", + ), + inMasking=dict( + argstr="--inMasking %s", + ), + inQuantitative=dict( + argstr="--inQuantitative %s", + extensions=None, + ), + inSecond=dict( + argstr="--inSecond %s", + extensions=None, + ), + inSkip=dict( + argstr="--inSkip %s", + ), + inT1weighted=dict( + argstr="--inT1weighted %s", + extensions=None, + ), + null=dict( + argstr="--null %s", + ), + outMasked=dict( + argstr="--outMasked_T1_Map %s", + hash_files=False, + ), + outMasked2=dict( + argstr="--outMasked_T1weighted %s", + hash_files=False, + ), + outSignal=dict( + argstr="--outSignal_Proba %s", + hash_files=False, + ), + outSignal2=dict( + argstr="--outSignal_Mask %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistIntensityMp2rageMasking.input_spec() @@ -30,10 +71,18 @@ def test_JistIntensityMp2rageMasking_inputs(): def test_JistIntensityMp2rageMasking_outputs(): output_map = dict( - outMasked=dict(extensions=None,), - outMasked2=dict(extensions=None,), - outSignal=dict(extensions=None,), - outSignal2=dict(extensions=None,), + outMasked=dict( + extensions=None, + ), + outMasked2=dict( + extensions=None, + ), + outSignal=dict( + extensions=None, + ), + outSignal2=dict( + extensions=None, + ), ) outputs = JistIntensityMp2rageMasking.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileCalculator.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileCalculator.py index d8447b9773..0cc1501e4f 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileCalculator.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileCalculator.py @@ -4,16 +4,41 @@ def test_JistLaminarProfileCalculator_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inIntensity=dict(argstr="--inIntensity %s", extensions=None,), - inMask=dict(argstr="--inMask %s", extensions=None,), - incomputed=dict(argstr="--incomputed %s",), - null=dict(argstr="--null %s",), - outResult=dict(argstr="--outResult %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inIntensity=dict( + argstr="--inIntensity %s", + extensions=None, + ), + inMask=dict( + argstr="--inMask %s", + extensions=None, + ), + incomputed=dict( + argstr="--incomputed %s", + ), + null=dict( + argstr="--null %s", + ), + outResult=dict( + argstr="--outResult %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistLaminarProfileCalculator.input_spec() @@ -23,7 +48,11 @@ def test_JistLaminarProfileCalculator_inputs(): def test_JistLaminarProfileCalculator_outputs(): - output_map = dict(outResult=dict(extensions=None,),) + output_map = dict( + outResult=dict( + extensions=None, + ), + ) outputs = JistLaminarProfileCalculator.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileGeometry.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileGeometry.py index 4a0c4f392a..758d331935 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileGeometry.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileGeometry.py @@ -4,18 +4,46 @@ def test_JistLaminarProfileGeometry_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inProfile=dict(argstr="--inProfile %s", extensions=None,), - incomputed=dict(argstr="--incomputed %s",), - inoutside=dict(argstr="--inoutside %f",), - inregularization=dict(argstr="--inregularization %s",), - insmoothing=dict(argstr="--insmoothing %f",), - null=dict(argstr="--null %s",), - outResult=dict(argstr="--outResult %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inProfile=dict( + argstr="--inProfile %s", + extensions=None, + ), + incomputed=dict( + argstr="--incomputed %s", + ), + inoutside=dict( + argstr="--inoutside %f", + ), + inregularization=dict( + argstr="--inregularization %s", + ), + insmoothing=dict( + argstr="--insmoothing %f", + ), + null=dict( + argstr="--null %s", + ), + outResult=dict( + argstr="--outResult %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistLaminarProfileGeometry.input_spec() @@ -25,7 +53,11 @@ def test_JistLaminarProfileGeometry_inputs(): def test_JistLaminarProfileGeometry_outputs(): - output_map = dict(outResult=dict(extensions=None,),) + output_map = dict( + outResult=dict( + extensions=None, + ), + ) outputs = JistLaminarProfileGeometry.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py index 3ad28793f0..65841c48a9 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarProfileSampling.py @@ -4,17 +4,46 @@ def test_JistLaminarProfileSampling_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inCortex=dict(argstr="--inCortex %s", extensions=None,), - inIntensity=dict(argstr="--inIntensity %s", extensions=None,), - inProfile=dict(argstr="--inProfile %s", extensions=None,), - null=dict(argstr="--null %s",), - outProfile2=dict(argstr="--outProfile2 %s", hash_files=False,), - outProfilemapped=dict(argstr="--outProfilemapped %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inCortex=dict( + argstr="--inCortex %s", + extensions=None, + ), + inIntensity=dict( + argstr="--inIntensity %s", + extensions=None, + ), + inProfile=dict( + argstr="--inProfile %s", + extensions=None, + ), + null=dict( + argstr="--null %s", + ), + outProfile2=dict( + argstr="--outProfile2 %s", + hash_files=False, + ), + outProfilemapped=dict( + argstr="--outProfilemapped %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistLaminarProfileSampling.input_spec() @@ -25,7 +54,12 @@ def test_JistLaminarProfileSampling_inputs(): def test_JistLaminarProfileSampling_outputs(): output_map = dict( - outProfile2=dict(extensions=None,), outProfilemapped=dict(extensions=None,), + outProfile2=dict( + extensions=None, + ), + outProfilemapped=dict( + extensions=None, + ), ) outputs = JistLaminarProfileSampling.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarROIAveraging.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarROIAveraging.py index 7120db3045..fed4abfca1 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarROIAveraging.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarROIAveraging.py @@ -4,17 +4,45 @@ def test_JistLaminarROIAveraging_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inIntensity=dict(argstr="--inIntensity %s", extensions=None,), - inMask=dict(argstr="--inMask %s", extensions=None,), - inROI=dict(argstr="--inROI %s", extensions=None,), - inROI2=dict(argstr="--inROI2 %s",), - null=dict(argstr="--null %s",), - outROI3=dict(argstr="--outROI3 %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inIntensity=dict( + argstr="--inIntensity %s", + extensions=None, + ), + inMask=dict( + argstr="--inMask %s", + extensions=None, + ), + inROI=dict( + argstr="--inROI %s", + extensions=None, + ), + inROI2=dict( + argstr="--inROI2 %s", + ), + null=dict( + argstr="--null %s", + ), + outROI3=dict( + argstr="--outROI3 %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistLaminarROIAveraging.input_spec() @@ -24,7 +52,11 @@ def test_JistLaminarROIAveraging_inputs(): def test_JistLaminarROIAveraging_outputs(): - output_map = dict(outROI3=dict(extensions=None,),) + output_map = dict( + outROI3=dict( + extensions=None, + ), + ) outputs = JistLaminarROIAveraging.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_JistLaminarVolumetricLayering.py b/nipype/interfaces/mipav/tests/test_auto_JistLaminarVolumetricLayering.py index 7b57e483ef..31d34ae32e 100644 --- a/nipype/interfaces/mipav/tests/test_auto_JistLaminarVolumetricLayering.py +++ b/nipype/interfaces/mipav/tests/test_auto_JistLaminarVolumetricLayering.py @@ -4,26 +4,73 @@ def test_JistLaminarVolumetricLayering_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inInner=dict(argstr="--inInner %s", extensions=None,), - inLayering=dict(argstr="--inLayering %s",), - inLayering2=dict(argstr="--inLayering2 %s",), - inMax=dict(argstr="--inMax %d",), - inMin=dict(argstr="--inMin %f",), - inNumber=dict(argstr="--inNumber %d",), - inOuter=dict(argstr="--inOuter %s", extensions=None,), - inTopology=dict(argstr="--inTopology %s",), - incurvature=dict(argstr="--incurvature %d",), - inpresmooth=dict(argstr="--inpresmooth %s",), - inratio=dict(argstr="--inratio %f",), - null=dict(argstr="--null %s",), - outContinuous=dict(argstr="--outContinuous %s", hash_files=False,), - outDiscrete=dict(argstr="--outDiscrete %s", hash_files=False,), - outLayer=dict(argstr="--outLayer %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inInner=dict( + argstr="--inInner %s", + extensions=None, + ), + inLayering=dict( + argstr="--inLayering %s", + ), + inLayering2=dict( + argstr="--inLayering2 %s", + ), + inMax=dict( + argstr="--inMax %d", + ), + inMin=dict( + argstr="--inMin %f", + ), + inNumber=dict( + argstr="--inNumber %d", + ), + inOuter=dict( + argstr="--inOuter %s", + extensions=None, + ), + inTopology=dict( + argstr="--inTopology %s", + ), + incurvature=dict( + argstr="--incurvature %d", + ), + inpresmooth=dict( + argstr="--inpresmooth %s", + ), + inratio=dict( + argstr="--inratio %f", + ), + null=dict( + argstr="--null %s", + ), + outContinuous=dict( + argstr="--outContinuous %s", + hash_files=False, + ), + outDiscrete=dict( + argstr="--outDiscrete %s", + hash_files=False, + ), + outLayer=dict( + argstr="--outLayer %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = JistLaminarVolumetricLayering.input_spec() @@ -34,9 +81,15 @@ def test_JistLaminarVolumetricLayering_inputs(): def test_JistLaminarVolumetricLayering_outputs(): output_map = dict( - outContinuous=dict(extensions=None,), - outDiscrete=dict(extensions=None,), - outLayer=dict(extensions=None,), + outContinuous=dict( + extensions=None, + ), + outDiscrete=dict( + extensions=None, + ), + outLayer=dict( + extensions=None, + ), ) outputs = JistLaminarVolumetricLayering.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmImageCalculator.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmImageCalculator.py index 9d7ff807d6..7b9a0fc859 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmImageCalculator.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmImageCalculator.py @@ -4,16 +4,41 @@ def test_MedicAlgorithmImageCalculator_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inOperation=dict(argstr="--inOperation %s",), - inVolume=dict(argstr="--inVolume %s", extensions=None,), - inVolume2=dict(argstr="--inVolume2 %s", extensions=None,), - null=dict(argstr="--null %s",), - outResult=dict(argstr="--outResult %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inOperation=dict( + argstr="--inOperation %s", + ), + inVolume=dict( + argstr="--inVolume %s", + extensions=None, + ), + inVolume2=dict( + argstr="--inVolume2 %s", + extensions=None, + ), + null=dict( + argstr="--null %s", + ), + outResult=dict( + argstr="--outResult %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = MedicAlgorithmImageCalculator.input_spec() @@ -23,7 +48,11 @@ def test_MedicAlgorithmImageCalculator_inputs(): def test_MedicAlgorithmImageCalculator_outputs(): - output_map = dict(outResult=dict(extensions=None,),) + output_map = dict( + outResult=dict( + extensions=None, + ), + ) outputs = MedicAlgorithmImageCalculator.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmLesionToads.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmLesionToads.py index f9036d1207..4fb5f2567b 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmLesionToads.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmLesionToads.py @@ -4,42 +4,131 @@ def test_MedicAlgorithmLesionToads_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inAtlas=dict(argstr="--inAtlas %s",), - inAtlas2=dict(argstr="--inAtlas2 %s", extensions=None,), - inAtlas3=dict(argstr="--inAtlas3 %s", extensions=None,), - inAtlas4=dict(argstr="--inAtlas4 %s", extensions=None,), - inAtlas5=dict(argstr="--inAtlas5 %f",), - inAtlas6=dict(argstr="--inAtlas6 %s",), - inConnectivity=dict(argstr="--inConnectivity %s",), - inCorrect=dict(argstr="--inCorrect %s",), - inFLAIR=dict(argstr="--inFLAIR %s", extensions=None,), - inInclude=dict(argstr="--inInclude %s",), - inMaximum=dict(argstr="--inMaximum %d",), - inMaximum2=dict(argstr="--inMaximum2 %d",), - inMaximum3=dict(argstr="--inMaximum3 %d",), - inMaximum4=dict(argstr="--inMaximum4 %f",), - inMaximum5=dict(argstr="--inMaximum5 %d",), - inOutput=dict(argstr="--inOutput %s",), - inOutput2=dict(argstr="--inOutput2 %s",), - inOutput3=dict(argstr="--inOutput3 %s",), - inSmooting=dict(argstr="--inSmooting %f",), - inT1_MPRAGE=dict(argstr="--inT1_MPRAGE %s", extensions=None,), - inT1_SPGR=dict(argstr="--inT1_SPGR %s", extensions=None,), - null=dict(argstr="--null %s",), - outCortical=dict(argstr="--outCortical %s", hash_files=False,), - outFilled=dict(argstr="--outFilled %s", hash_files=False,), - outHard=dict(argstr="--outHard %s", hash_files=False,), - outHard2=dict(argstr="--outHard2 %s", hash_files=False,), - outInhomogeneity=dict(argstr="--outInhomogeneity %s", hash_files=False,), - outLesion=dict(argstr="--outLesion %s", hash_files=False,), - outMembership=dict(argstr="--outMembership %s", hash_files=False,), - outSulcal=dict(argstr="--outSulcal %s", hash_files=False,), - outWM=dict(argstr="--outWM %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inAtlas=dict( + argstr="--inAtlas %s", + ), + inAtlas2=dict( + argstr="--inAtlas2 %s", + extensions=None, + ), + inAtlas3=dict( + argstr="--inAtlas3 %s", + extensions=None, + ), + inAtlas4=dict( + argstr="--inAtlas4 %s", + extensions=None, + ), + inAtlas5=dict( + argstr="--inAtlas5 %f", + ), + inAtlas6=dict( + argstr="--inAtlas6 %s", + ), + inConnectivity=dict( + argstr="--inConnectivity %s", + ), + inCorrect=dict( + argstr="--inCorrect %s", + ), + inFLAIR=dict( + argstr="--inFLAIR %s", + extensions=None, + ), + inInclude=dict( + argstr="--inInclude %s", + ), + inMaximum=dict( + argstr="--inMaximum %d", + ), + inMaximum2=dict( + argstr="--inMaximum2 %d", + ), + inMaximum3=dict( + argstr="--inMaximum3 %d", + ), + inMaximum4=dict( + argstr="--inMaximum4 %f", + ), + inMaximum5=dict( + argstr="--inMaximum5 %d", + ), + inOutput=dict( + argstr="--inOutput %s", + ), + inOutput2=dict( + argstr="--inOutput2 %s", + ), + inOutput3=dict( + argstr="--inOutput3 %s", + ), + inSmooting=dict( + argstr="--inSmooting %f", + ), + inT1_MPRAGE=dict( + argstr="--inT1_MPRAGE %s", + extensions=None, + ), + inT1_SPGR=dict( + argstr="--inT1_SPGR %s", + extensions=None, + ), + null=dict( + argstr="--null %s", + ), + outCortical=dict( + argstr="--outCortical %s", + hash_files=False, + ), + outFilled=dict( + argstr="--outFilled %s", + hash_files=False, + ), + outHard=dict( + argstr="--outHard %s", + hash_files=False, + ), + outHard2=dict( + argstr="--outHard2 %s", + hash_files=False, + ), + outInhomogeneity=dict( + argstr="--outInhomogeneity %s", + hash_files=False, + ), + outLesion=dict( + argstr="--outLesion %s", + hash_files=False, + ), + outMembership=dict( + argstr="--outMembership %s", + hash_files=False, + ), + outSulcal=dict( + argstr="--outSulcal %s", + hash_files=False, + ), + outWM=dict( + argstr="--outWM %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = MedicAlgorithmLesionToads.input_spec() @@ -50,15 +139,33 @@ def test_MedicAlgorithmLesionToads_inputs(): def test_MedicAlgorithmLesionToads_outputs(): output_map = dict( - outCortical=dict(extensions=None,), - outFilled=dict(extensions=None,), - outHard=dict(extensions=None,), - outHard2=dict(extensions=None,), - outInhomogeneity=dict(extensions=None,), - outLesion=dict(extensions=None,), - outMembership=dict(extensions=None,), - outSulcal=dict(extensions=None,), - outWM=dict(extensions=None,), + outCortical=dict( + extensions=None, + ), + outFilled=dict( + extensions=None, + ), + outHard=dict( + extensions=None, + ), + outHard2=dict( + extensions=None, + ), + outInhomogeneity=dict( + extensions=None, + ), + outLesion=dict( + extensions=None, + ), + outMembership=dict( + extensions=None, + ), + outSulcal=dict( + extensions=None, + ), + outWM=dict( + extensions=None, + ), ) outputs = MedicAlgorithmLesionToads.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmMipavReorient.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmMipavReorient.py index 0c941fdbc7..49c307f27f 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmMipavReorient.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmMipavReorient.py @@ -4,22 +4,59 @@ def test_MedicAlgorithmMipavReorient_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inInterpolation=dict(argstr="--inInterpolation %s",), - inNew=dict(argstr="--inNew %s",), - inResolution=dict(argstr="--inResolution %s",), - inSource=dict(argstr="--inSource %s", sep=";",), - inTemplate=dict(argstr="--inTemplate %s", extensions=None,), - inUser=dict(argstr="--inUser %s",), - inUser2=dict(argstr="--inUser2 %s",), - inUser3=dict(argstr="--inUser3 %s",), - inUser4=dict(argstr="--inUser4 %s",), - null=dict(argstr="--null %s",), - outReoriented=dict(argstr="--outReoriented %s", sep=";",), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inInterpolation=dict( + argstr="--inInterpolation %s", + ), + inNew=dict( + argstr="--inNew %s", + ), + inResolution=dict( + argstr="--inResolution %s", + ), + inSource=dict( + argstr="--inSource %s", + sep=";", + ), + inTemplate=dict( + argstr="--inTemplate %s", + extensions=None, + ), + inUser=dict( + argstr="--inUser %s", + ), + inUser2=dict( + argstr="--inUser2 %s", + ), + inUser3=dict( + argstr="--inUser3 %s", + ), + inUser4=dict( + argstr="--inUser4 %s", + ), + null=dict( + argstr="--null %s", + ), + outReoriented=dict( + argstr="--outReoriented %s", + sep=";", + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = MedicAlgorithmMipavReorient.input_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmN3.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmN3.py index d9a8a25023..bf895247a6 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmN3.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmN3.py @@ -4,23 +4,62 @@ def test_MedicAlgorithmN3_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inAutomatic=dict(argstr="--inAutomatic %s",), - inEnd=dict(argstr="--inEnd %f",), - inField=dict(argstr="--inField %f",), - inInput=dict(argstr="--inInput %s", extensions=None,), - inKernel=dict(argstr="--inKernel %f",), - inMaximum=dict(argstr="--inMaximum %d",), - inSignal=dict(argstr="--inSignal %f",), - inSubsample=dict(argstr="--inSubsample %f",), - inWeiner=dict(argstr="--inWeiner %f",), - null=dict(argstr="--null %s",), - outInhomogeneity=dict(argstr="--outInhomogeneity %s", hash_files=False,), - outInhomogeneity2=dict(argstr="--outInhomogeneity2 %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inAutomatic=dict( + argstr="--inAutomatic %s", + ), + inEnd=dict( + argstr="--inEnd %f", + ), + inField=dict( + argstr="--inField %f", + ), + inInput=dict( + argstr="--inInput %s", + extensions=None, + ), + inKernel=dict( + argstr="--inKernel %f", + ), + inMaximum=dict( + argstr="--inMaximum %d", + ), + inSignal=dict( + argstr="--inSignal %f", + ), + inSubsample=dict( + argstr="--inSubsample %f", + ), + inWeiner=dict( + argstr="--inWeiner %f", + ), + null=dict( + argstr="--null %s", + ), + outInhomogeneity=dict( + argstr="--outInhomogeneity %s", + hash_files=False, + ), + outInhomogeneity2=dict( + argstr="--outInhomogeneity2 %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = MedicAlgorithmN3.input_spec() @@ -31,8 +70,12 @@ def test_MedicAlgorithmN3_inputs(): def test_MedicAlgorithmN3_outputs(): output_map = dict( - outInhomogeneity=dict(extensions=None,), - outInhomogeneity2=dict(extensions=None,), + outInhomogeneity=dict( + extensions=None, + ), + outInhomogeneity2=dict( + extensions=None, + ), ) outputs = MedicAlgorithmN3.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmSPECTRE2010.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmSPECTRE2010.py index 8e51a9c7bc..b62def8a4f 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmSPECTRE2010.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmSPECTRE2010.py @@ -4,55 +4,166 @@ def test_MedicAlgorithmSPECTRE2010_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inApply=dict(argstr="--inApply %s",), - inAtlas=dict(argstr="--inAtlas %s", extensions=None,), - inBackground=dict(argstr="--inBackground %f",), - inCoarse=dict(argstr="--inCoarse %f",), - inCost=dict(argstr="--inCost %s",), - inDegrees=dict(argstr="--inDegrees %s",), - inFind=dict(argstr="--inFind %s",), - inFine=dict(argstr="--inFine %f",), - inImage=dict(argstr="--inImage %s",), - inInhomogeneity=dict(argstr="--inInhomogeneity %s",), - inInitial=dict(argstr="--inInitial %d",), - inInitial2=dict(argstr="--inInitial2 %f",), - inInput=dict(argstr="--inInput %s", extensions=None,), - inMMC=dict(argstr="--inMMC %d",), - inMMC2=dict(argstr="--inMMC2 %d",), - inMaximum=dict(argstr="--inMaximum %f",), - inMinimum=dict(argstr="--inMinimum %f",), - inMinimum2=dict(argstr="--inMinimum2 %f",), - inMultiple=dict(argstr="--inMultiple %d",), - inMultithreading=dict(argstr="--inMultithreading %s",), - inNumber=dict(argstr="--inNumber %d",), - inNumber2=dict(argstr="--inNumber2 %d",), - inOutput=dict(argstr="--inOutput %s",), - inOutput2=dict(argstr="--inOutput2 %s",), - inOutput3=dict(argstr="--inOutput3 %s",), - inOutput4=dict(argstr="--inOutput4 %s",), - inOutput5=dict(argstr="--inOutput5 %s",), - inRegistration=dict(argstr="--inRegistration %s",), - inResample=dict(argstr="--inResample %s",), - inRun=dict(argstr="--inRun %s",), - inSkip=dict(argstr="--inSkip %s",), - inSmoothing=dict(argstr="--inSmoothing %f",), - inSubsample=dict(argstr="--inSubsample %s",), - inUse=dict(argstr="--inUse %s",), - null=dict(argstr="--null %s",), - outFANTASM=dict(argstr="--outFANTASM %s", hash_files=False,), - outMask=dict(argstr="--outMask %s", hash_files=False,), - outMidsagittal=dict(argstr="--outMidsagittal %s", hash_files=False,), - outOriginal=dict(argstr="--outOriginal %s", hash_files=False,), - outPrior=dict(argstr="--outPrior %s", hash_files=False,), - outSegmentation=dict(argstr="--outSegmentation %s", hash_files=False,), - outSplitHalves=dict(argstr="--outSplitHalves %s", hash_files=False,), - outStripped=dict(argstr="--outStripped %s", hash_files=False,), - outd0=dict(argstr="--outd0 %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inApply=dict( + argstr="--inApply %s", + ), + inAtlas=dict( + argstr="--inAtlas %s", + extensions=None, + ), + inBackground=dict( + argstr="--inBackground %f", + ), + inCoarse=dict( + argstr="--inCoarse %f", + ), + inCost=dict( + argstr="--inCost %s", + ), + inDegrees=dict( + argstr="--inDegrees %s", + ), + inFind=dict( + argstr="--inFind %s", + ), + inFine=dict( + argstr="--inFine %f", + ), + inImage=dict( + argstr="--inImage %s", + ), + inInhomogeneity=dict( + argstr="--inInhomogeneity %s", + ), + inInitial=dict( + argstr="--inInitial %d", + ), + inInitial2=dict( + argstr="--inInitial2 %f", + ), + inInput=dict( + argstr="--inInput %s", + extensions=None, + ), + inMMC=dict( + argstr="--inMMC %d", + ), + inMMC2=dict( + argstr="--inMMC2 %d", + ), + inMaximum=dict( + argstr="--inMaximum %f", + ), + inMinimum=dict( + argstr="--inMinimum %f", + ), + inMinimum2=dict( + argstr="--inMinimum2 %f", + ), + inMultiple=dict( + argstr="--inMultiple %d", + ), + inMultithreading=dict( + argstr="--inMultithreading %s", + ), + inNumber=dict( + argstr="--inNumber %d", + ), + inNumber2=dict( + argstr="--inNumber2 %d", + ), + inOutput=dict( + argstr="--inOutput %s", + ), + inOutput2=dict( + argstr="--inOutput2 %s", + ), + inOutput3=dict( + argstr="--inOutput3 %s", + ), + inOutput4=dict( + argstr="--inOutput4 %s", + ), + inOutput5=dict( + argstr="--inOutput5 %s", + ), + inRegistration=dict( + argstr="--inRegistration %s", + ), + inResample=dict( + argstr="--inResample %s", + ), + inRun=dict( + argstr="--inRun %s", + ), + inSkip=dict( + argstr="--inSkip %s", + ), + inSmoothing=dict( + argstr="--inSmoothing %f", + ), + inSubsample=dict( + argstr="--inSubsample %s", + ), + inUse=dict( + argstr="--inUse %s", + ), + null=dict( + argstr="--null %s", + ), + outFANTASM=dict( + argstr="--outFANTASM %s", + hash_files=False, + ), + outMask=dict( + argstr="--outMask %s", + hash_files=False, + ), + outMidsagittal=dict( + argstr="--outMidsagittal %s", + hash_files=False, + ), + outOriginal=dict( + argstr="--outOriginal %s", + hash_files=False, + ), + outPrior=dict( + argstr="--outPrior %s", + hash_files=False, + ), + outSegmentation=dict( + argstr="--outSegmentation %s", + hash_files=False, + ), + outSplitHalves=dict( + argstr="--outSplitHalves %s", + hash_files=False, + ), + outStripped=dict( + argstr="--outStripped %s", + hash_files=False, + ), + outd0=dict( + argstr="--outd0 %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = MedicAlgorithmSPECTRE2010.input_spec() @@ -63,15 +174,33 @@ def test_MedicAlgorithmSPECTRE2010_inputs(): def test_MedicAlgorithmSPECTRE2010_outputs(): output_map = dict( - outFANTASM=dict(extensions=None,), - outMask=dict(extensions=None,), - outMidsagittal=dict(extensions=None,), - outOriginal=dict(extensions=None,), - outPrior=dict(extensions=None,), - outSegmentation=dict(extensions=None,), - outSplitHalves=dict(extensions=None,), - outStripped=dict(extensions=None,), - outd0=dict(extensions=None,), + outFANTASM=dict( + extensions=None, + ), + outMask=dict( + extensions=None, + ), + outMidsagittal=dict( + extensions=None, + ), + outOriginal=dict( + extensions=None, + ), + outPrior=dict( + extensions=None, + ), + outSegmentation=dict( + extensions=None, + ), + outSplitHalves=dict( + extensions=None, + ), + outStripped=dict( + extensions=None, + ), + outd0=dict( + extensions=None, + ), ) outputs = MedicAlgorithmSPECTRE2010.output_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmThresholdToBinaryMask.py b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmThresholdToBinaryMask.py index ca0179d231..bdd6e4e1b6 100644 --- a/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmThresholdToBinaryMask.py +++ b/nipype/interfaces/mipav/tests/test_auto_MedicAlgorithmThresholdToBinaryMask.py @@ -4,17 +4,43 @@ def test_MedicAlgorithmThresholdToBinaryMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inLabel=dict(argstr="--inLabel %s", sep=";",), - inMaximum=dict(argstr="--inMaximum %f",), - inMinimum=dict(argstr="--inMinimum %f",), - inUse=dict(argstr="--inUse %s",), - null=dict(argstr="--null %s",), - outBinary=dict(argstr="--outBinary %s", sep=";",), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inLabel=dict( + argstr="--inLabel %s", + sep=";", + ), + inMaximum=dict( + argstr="--inMaximum %f", + ), + inMinimum=dict( + argstr="--inMinimum %f", + ), + inUse=dict( + argstr="--inUse %s", + ), + null=dict( + argstr="--null %s", + ), + outBinary=dict( + argstr="--outBinary %s", + sep=";", + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = MedicAlgorithmThresholdToBinaryMask.input_spec() diff --git a/nipype/interfaces/mipav/tests/test_auto_RandomVol.py b/nipype/interfaces/mipav/tests/test_auto_RandomVol.py index 1dd7520626..4929f54d6a 100644 --- a/nipype/interfaces/mipav/tests/test_auto_RandomVol.py +++ b/nipype/interfaces/mipav/tests/test_auto_RandomVol.py @@ -4,22 +4,57 @@ def test_RandomVol_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inField=dict(argstr="--inField %s",), - inLambda=dict(argstr="--inLambda %f",), - inMaximum=dict(argstr="--inMaximum %d",), - inMinimum=dict(argstr="--inMinimum %d",), - inSize=dict(argstr="--inSize %d",), - inSize2=dict(argstr="--inSize2 %d",), - inSize3=dict(argstr="--inSize3 %d",), - inSize4=dict(argstr="--inSize4 %d",), - inStandard=dict(argstr="--inStandard %d",), - null=dict(argstr="--null %s",), - outRand1=dict(argstr="--outRand1 %s", hash_files=False,), - xDefaultMem=dict(argstr="-xDefaultMem %d",), - xMaxProcess=dict(argstr="-xMaxProcess %d", usedefault=True,), - xPrefExt=dict(argstr="--xPrefExt %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inField=dict( + argstr="--inField %s", + ), + inLambda=dict( + argstr="--inLambda %f", + ), + inMaximum=dict( + argstr="--inMaximum %d", + ), + inMinimum=dict( + argstr="--inMinimum %d", + ), + inSize=dict( + argstr="--inSize %d", + ), + inSize2=dict( + argstr="--inSize2 %d", + ), + inSize3=dict( + argstr="--inSize3 %d", + ), + inSize4=dict( + argstr="--inSize4 %d", + ), + inStandard=dict( + argstr="--inStandard %d", + ), + null=dict( + argstr="--null %s", + ), + outRand1=dict( + argstr="--outRand1 %s", + hash_files=False, + ), + xDefaultMem=dict( + argstr="-xDefaultMem %d", + ), + xMaxProcess=dict( + argstr="-xMaxProcess %d", + usedefault=True, + ), + xPrefExt=dict( + argstr="--xPrefExt %s", + ), ) inputs = RandomVol.input_spec() @@ -29,7 +64,11 @@ def test_RandomVol_inputs(): def test_RandomVol_outputs(): - output_map = dict(outRand1=dict(extensions=None,),) + output_map = dict( + outRand1=dict( + extensions=None, + ), + ) outputs = RandomVol.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mixins/__init__.py b/nipype/interfaces/mixins/__init__.py index a64dc34ff2..e54986231f 100644 --- a/nipype/interfaces/mixins/__init__.py +++ b/nipype/interfaces/mixins/__init__.py @@ -3,3 +3,4 @@ ReportCapableInputSpec, ReportCapableOutputSpec, ) +from .fixheader import CopyHeaderInputSpec, CopyHeaderInterface diff --git a/nipype/interfaces/mixins/fixheader.py b/nipype/interfaces/mixins/fixheader.py new file mode 100644 index 0000000000..7bbff18f2b --- /dev/null +++ b/nipype/interfaces/mixins/fixheader.py @@ -0,0 +1,136 @@ +from ..base import BaseInterface, BaseInterfaceInputSpec, traits +from ...utils.imagemanip import copy_header as _copy_header + + +class CopyHeaderInputSpec(BaseInterfaceInputSpec): + copy_header = traits.Bool( + desc="Copy headers of the input image into the output image" + ) + + +class CopyHeaderInterface(BaseInterface): + """Copy headers if the copy_header input is ``True`` + + This interface mixin adds a post-run hook that allows for copying + an input header to an output file. + The subclass should specify a ``_copy_header_map`` that maps the **output** + image to the **input** image whose header should be copied. + + This feature is intended for tools that are intended to adjust voxel data without + modifying the header, but for some reason do not reliably preserve the header. + + Here we show an example interface that takes advantage of the mixin by simply + setting the data block: + + >>> import os + >>> import numpy as np + >>> import nibabel as nb + >>> from nipype.interfaces.base import SimpleInterface, TraitedSpec, File + >>> from nipype.interfaces.mixins import CopyHeaderInputSpec, CopyHeaderInterface + + >>> class ZerofileInputSpec(CopyHeaderInputSpec): + ... in_file = File(mandatory=True, exists=True) + + >>> class ZerofileOutputSpec(TraitedSpec): + ... out_file = File() + + >>> class ZerofileInterface(SimpleInterface, CopyHeaderInterface): + ... input_spec = ZerofileInputSpec + ... output_spec = ZerofileOutputSpec + ... _copy_header_map = {'out_file': 'in_file'} + ... + ... def _run_interface(self, runtime): + ... img = nb.load(self.inputs.in_file) + ... # Just set the data. Let the CopyHeaderInterface mixin fix the affine and header. + ... nb.Nifti1Image(np.zeros(img.shape, dtype=np.uint8), None).to_filename('out.nii') + ... self._results = {'out_file': os.path.abspath('out.nii')} + ... return runtime + + Consider a file of all ones and a non-trivial affine: + + >>> in_file = 'test.nii' + >>> nb.Nifti1Image(np.ones((5,5,5), dtype=np.int16), + ... affine=np.diag((4, 3, 2, 1))).to_filename(in_file) + + The default behavior would produce a file with similar data: + + >>> res = ZerofileInterface(in_file=in_file).run() + >>> out_img = nb.load(res.outputs.out_file) + >>> out_img.shape + (5, 5, 5) + >>> np.all(out_img.get_fdata() == 0) + True + + An updated data type: + + >>> out_img.get_data_dtype() + dtype('uint8') + + But a different affine: + + >>> np.array_equal(out_img.affine, np.diag((4, 3, 2, 1))) + False + + With ``copy_header=True``, then the affine is also equal: + + >>> res = ZerofileInterface(in_file=in_file, copy_header=True).run() + >>> out_img = nb.load(res.outputs.out_file) + >>> np.array_equal(out_img.affine, np.diag((4, 3, 2, 1))) + True + + The data properties remain as expected: + + >>> out_img.shape + (5, 5, 5) + >>> out_img.get_data_dtype() + dtype('uint8') + >>> np.all(out_img.get_fdata() == 0) + True + + By default, the data type of the output file is permitted to vary from the + inputs. That is, the data type is preserved. + If the data type of the original file is preferred, the ``_copy_header_map`` + can indicate the output data type should **not** be preserved by providing a + tuple of the input and ``False``. + + >>> ZerofileInterface._copy_header_map['out_file'] = ('in_file', False) + + >>> res = ZerofileInterface(in_file=in_file, copy_header=True).run() + >>> out_img = nb.load(res.outputs.out_file) + >>> out_img.get_data_dtype() + dtype('>> np.array_equal(out_img.affine, np.diag((4, 3, 2, 1))) + True + >>> out_img.shape + (5, 5, 5) + >>> np.all(out_img.get_fdata() == 0) + True + + Providing a tuple where the second value is ``True`` is also permissible to + achieve the default behavior. + + """ + + _copy_header_map = None + + def _post_run_hook(self, runtime): + """Copy headers for outputs, if required.""" + runtime = super()._post_run_hook(runtime) + + if self._copy_header_map is None or not self.inputs.copy_header: + return runtime + + inputs = self.inputs.get_traitsfree() + outputs = self.aggregate_outputs(runtime=runtime).get_traitsfree() + defined_outputs = set(outputs.keys()).intersection(self._copy_header_map.keys()) + for out in defined_outputs: + inp = self._copy_header_map[out] + keep_dtype = True + if isinstance(inp, tuple): + inp, keep_dtype = inp + _copy_header(inputs[inp], outputs[out], keep_dtype=keep_dtype) + + return runtime diff --git a/nipype/interfaces/mixins/reporting.py b/nipype/interfaces/mixins/reporting.py index 182738ca64..a836cfa3fa 100644 --- a/nipype/interfaces/mixins/reporting.py +++ b/nipype/interfaces/mixins/reporting.py @@ -1,7 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -""" class mixin and utilities for enabling reports for nipype interfaces """ +"""class mixin and utilities for enabling reports for nipype interfaces""" import os from abc import abstractmethod @@ -31,11 +30,11 @@ class ReportCapableInterface(BaseInterface): _out_report = None def __init__(self, generate_report=False, **kwargs): - super(ReportCapableInterface, self).__init__(**kwargs) + super().__init__(**kwargs) self.generate_report = generate_report def _post_run_hook(self, runtime): - runtime = super(ReportCapableInterface, self)._post_run_hook(runtime) + runtime = super()._post_run_hook(runtime) # leave early if there's nothing to do if not self.generate_report: @@ -53,7 +52,7 @@ def _post_run_hook(self, runtime): def _list_outputs(self): try: - outputs = super(ReportCapableInterface, self)._list_outputs() + outputs = super()._list_outputs() except NotImplementedError: outputs = {} if self._out_report is not None: diff --git a/nipype/interfaces/mixins/tests/__init__.py b/nipype/interfaces/mixins/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/mixins/tests/__init__.py +++ b/nipype/interfaces/mixins/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/mixins/tests/test_auto_CopyHeaderInterface.py b/nipype/interfaces/mixins/tests/test_auto_CopyHeaderInterface.py new file mode 100644 index 0000000000..58f9bc0864 --- /dev/null +++ b/nipype/interfaces/mixins/tests/test_auto_CopyHeaderInterface.py @@ -0,0 +1,11 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..fixheader import CopyHeaderInterface + + +def test_CopyHeaderInterface_inputs(): + input_map = dict() + inputs = CopyHeaderInterface.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mne/__init__.py b/nipype/interfaces/mne/__init__.py index 820780e54d..7eba176251 100644 --- a/nipype/interfaces/mne/__init__.py +++ b/nipype/interfaces/mne/__init__.py @@ -1,3 +1,3 @@ -# -*- coding: utf-8 -*- """MNE is a software for exploring, visualizing, and analyzing human neurophysiological data.""" + from .base import WatershedBEM diff --git a/nipype/interfaces/mne/base.py b/nipype/interfaces/mne/base.py index f410da794a..c8b1f6012d 100644 --- a/nipype/interfaces/mne/base.py +++ b/nipype/interfaces/mne/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os.path as op import glob @@ -98,9 +97,9 @@ class WatershedBEM(FSCommand): >>> bem.inputs.subjects_dir = '.' >>> bem.cmdline 'mne watershed_bem --overwrite --subject subj1 --volume T1' - >>> bem.run() # doctest: +SKIP + >>> bem.run() # doctest: +SKIP - """ + """ _cmd = "mne watershed_bem" input_spec = WatershedBEMInputSpec @@ -113,7 +112,7 @@ def _get_files(self, path, key, dirval, altkey=None): keydir = op.join(path, dirval) if altkey: key = altkey - globpattern = op.join(keydir, "".join((globprefix, key, globsuffix))) + globpattern = op.join(keydir, f"{globprefix}{key}{globsuffix}") return glob.glob(globpattern) def _list_outputs(self): @@ -133,15 +132,13 @@ def _list_outputs(self): if val: value_list = simplify_list(val) if isinstance(value_list, list): - out_files = [] - for value in value_list: - out_files.append(op.abspath(value)) + out_files = [op.abspath(value) for value in value_list] elif isinstance(value_list, (str, bytes)): out_files = op.abspath(value_list) else: raise TypeError outputs[k] = out_files - if not k.rfind("surface") == -1: + if k.rfind("surface") != -1: mesh_paths.append(out_files) outputs["mesh_files"] = mesh_paths return outputs diff --git a/nipype/interfaces/mne/tests/__init__.py b/nipype/interfaces/mne/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/mne/tests/__init__.py +++ b/nipype/interfaces/mne/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/mne/tests/test_auto_WatershedBEM.py b/nipype/interfaces/mne/tests/test_auto_WatershedBEM.py index 30e6a1de7e..57f1b40e4d 100644 --- a/nipype/interfaces/mne/tests/test_auto_WatershedBEM.py +++ b/nipype/interfaces/mne/tests/test_auto_WatershedBEM.py @@ -4,13 +4,32 @@ def test_WatershedBEM_inputs(): input_map = dict( - args=dict(argstr="%s",), - atlas_mode=dict(argstr="--atlas",), - environ=dict(nohash=True, usedefault=True,), - overwrite=dict(argstr="--overwrite", usedefault=True,), - subject_id=dict(argstr="--subject %s", mandatory=True,), - subjects_dir=dict(mandatory=True, usedefault=True,), - volume=dict(argstr="--volume %s", usedefault=True,), + args=dict( + argstr="%s", + ), + atlas_mode=dict( + argstr="--atlas", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + overwrite=dict( + argstr="--overwrite", + usedefault=True, + ), + subject_id=dict( + argstr="--subject %s", + mandatory=True, + ), + subjects_dir=dict( + mandatory=True, + usedefault=True, + ), + volume=dict( + argstr="--volume %s", + usedefault=True, + ), ) inputs = WatershedBEM.input_spec() @@ -21,13 +40,32 @@ def test_WatershedBEM_inputs(): def test_WatershedBEM_outputs(): output_map = dict( - brain_surface=dict(extensions=None, loc="bem/watershed",), - cor_files=dict(altkey="COR", loc="bem/watershed/ws",), - fif_file=dict(altkey="fif", extensions=None, loc="bem",), - inner_skull_surface=dict(extensions=None, loc="bem/watershed",), + brain_surface=dict( + extensions=None, + loc="bem/watershed", + ), + cor_files=dict( + altkey="COR", + loc="bem/watershed/ws", + ), + fif_file=dict( + altkey="fif", + extensions=None, + loc="bem", + ), + inner_skull_surface=dict( + extensions=None, + loc="bem/watershed", + ), mesh_files=dict(), - outer_skin_surface=dict(extensions=None, loc="bem/watershed",), - outer_skull_surface=dict(extensions=None, loc="bem/watershed",), + outer_skin_surface=dict( + extensions=None, + loc="bem/watershed", + ), + outer_skull_surface=dict( + extensions=None, + loc="bem/watershed", + ), ) outputs = WatershedBEM.output_spec() diff --git a/nipype/interfaces/mrtrix/__init__.py b/nipype/interfaces/mrtrix/__init__.py index 3aafdc1db7..232dc119cf 100644 --- a/nipype/interfaces/mrtrix/__init__.py +++ b/nipype/interfaces/mrtrix/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """MRTrix version 2 (DEPRECATED) -- tools to perform various types of diffusion MRI analyses.""" diff --git a/nipype/interfaces/mrtrix/convert.py b/nipype/interfaces/mrtrix/convert.py index b2314271c4..783974c667 100644 --- a/nipype/interfaces/mrtrix/convert.py +++ b/nipype/interfaces/mrtrix/convert.py @@ -1,29 +1,25 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os.path as op import nibabel as nb -import nibabel.trackvis as trk import numpy as np -from nibabel.trackvis import HeaderError from nibabel.volumeutils import native_code from nibabel.orientations import aff2axcodes from ... import logging from ...utils.filemanip import split_filename from ..base import TraitedSpec, File, isdefined -from ..dipy.base import DipyBaseInterface, HAVE_DIPY as have_dipy +from ..dipy.base import DipyBaseInterface iflogger = logging.getLogger("nipype.interface") def get_vox_dims(volume): import nibabel as nb - from nipype.utils import NUMPY_MMAP if isinstance(volume, list): volume = volume[0] - nii = nb.load(volume, mmap=NUMPY_MMAP) + nii = nb.load(volume) hdr = nii.header voxdims = hdr.get_zooms() return [float(voxdims[0]), float(voxdims[1]), float(voxdims[2])] @@ -31,24 +27,26 @@ def get_vox_dims(volume): def get_data_dims(volume): import nibabel as nb - from nipype.utils import NUMPY_MMAP if isinstance(volume, list): volume = volume[0] - nii = nb.load(volume, mmap=NUMPY_MMAP) + nii = nb.load(volume) hdr = nii.header datadims = hdr.get_data_shape() return [int(datadims[0]), int(datadims[1]), int(datadims[2])] def transform_to_affine(streams, header, affine): - from dipy.tracking.utils import move_streamlines + try: + from dipy.tracking.utils import transform_tracking_output + except ImportError: + from dipy.tracking.utils import move_streamlines as transform_tracking_output rotation, scale = np.linalg.qr(affine) - streams = move_streamlines(streams, rotation) + streams = transform_tracking_output(streams, rotation) scale[0:3, 0:3] = np.dot(scale[0:3, 0:3], np.diag(1.0 / header["voxel_size"])) scale[0:3, 3] = abs(scale[0:3, 3]) - streams = move_streamlines(streams, scale) + streams = transform_tracking_output(streams, scale) return streams @@ -118,9 +116,9 @@ def track_gen(track_points): pts_str = fileobj.read(n_pts * bytesize) nan_str = fileobj.read(bytesize) if len(pts_str) < (n_pts * bytesize): - if not n_streams == stream_count: - raise HeaderError( - "Expecting %s points, found only %s" % (stream_count, n_streams) + if n_streams != stream_count: + raise nb.trackvis.HeaderError( + f"Expecting {stream_count} points, found only {n_streams}" ) iflogger.error( "Expecting %s points, found only %s", stream_count, n_streams @@ -195,7 +193,14 @@ class MRTrix2TrackVis(DipyBaseInterface): output_spec = MRTrix2TrackVisOutputSpec def _run_interface(self, runtime): - from dipy.tracking.utils import move_streamlines, affine_from_fsl_mat_file + from dipy.tracking.utils import affine_from_fsl_mat_file + + try: + from dipy.tracking.utils import transform_tracking_output + except ImportError: + from dipy.tracking.utils import ( + move_streamlines as transform_tracking_output, + ) dx, dy, dz = get_data_dims(self.inputs.image_file) vx, vy, vz = get_vox_dims(self.inputs.image_file) @@ -245,9 +250,9 @@ def _run_interface(self, runtime): axcode = aff2axcodes(reg_affine) trk_header["voxel_order"] = axcode[0] + axcode[1] + axcode[2] - final_streamlines = move_streamlines(transformed_streamlines, aff) + final_streamlines = transform_tracking_output(transformed_streamlines, aff) trk_tracks = ((ii, None, None) for ii in final_streamlines) - trk.write(out_filename, trk_tracks, trk_header) + nb.trackvis.write(out_filename, trk_tracks, trk_header) iflogger.info("Saving transformed Trackvis file as %s", out_filename) iflogger.info("New TrackVis Header:") iflogger.info(trk_header) @@ -263,7 +268,7 @@ def _run_interface(self, runtime): streamlines, trk_header, affine ) trk_tracks = ((ii, None, None) for ii in transformed_streamlines) - trk.write(out_filename, trk_tracks, trk_header) + nb.trackvis.write(out_filename, trk_tracks, trk_header) iflogger.info("Saving Trackvis file as %s", out_filename) iflogger.info("TrackVis Header:") iflogger.info(trk_header) diff --git a/nipype/interfaces/mrtrix/preprocess.py b/nipype/interfaces/mrtrix/preprocess.py index 48f4bde719..8f585cb901 100644 --- a/nipype/interfaces/mrtrix/preprocess.py +++ b/nipype/interfaces/mrtrix/preprocess.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -217,10 +216,15 @@ class DWI2TensorInputSpec(CommandLineInputSpec): "specified when computing the tensor." ), ) + mask = File( + exists=True, + argstr="-mask %s", + desc="Only perform computation within the specified binary brain mask image.", + ) quiet = traits.Bool( argstr="-quiet", position=1, - desc=("Do not display information messages or progress " "status."), + desc=("Do not display information messages or progress status."), ) debug = traits.Bool(argstr="-debug", position=1, desc="Display debugging messages.") @@ -865,6 +869,17 @@ class MRTransformInputSpec(CommandLineInputSpec): position=1, desc="Invert the specified transform before using it", ) + linear_transform = File( + exists=True, + argstr="-linear %s", + position=1, + desc=( + "Specify a linear transform to apply, in the form of a 3x4 or 4x4 ascii file. " + "Note the standard reverse convention is used, " + "where the transform maps points in the template image to the moving image. " + "Note that the reverse convention is still assumed even if no -template image is supplied." + ), + ) replace_transform = traits.Bool( argstr="-replace", position=1, diff --git a/nipype/interfaces/mrtrix/tensors.py b/nipype/interfaces/mrtrix/tensors.py index d7cbb5f7a8..3680282b89 100644 --- a/nipype/interfaces/mrtrix/tensors.py +++ b/nipype/interfaces/mrtrix/tensors.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -191,7 +190,7 @@ class ConstrainedSphericalDeconvolution(CommandLine): First, the fact the signal attenuation profile is real implies that it has conjugate symmetry, i.e. Y(l,-m) = Y(l,m)* (where * denotes the complex conjugate). Second, the diffusion profile should be antipodally symmetric (i.e. S(x) = S(-x)), implying that all odd l components should be zero. - Therefore, this program only computes the even elements. Note that the spherical harmonics equations used here + Therefore, this program only computes the even elements. Note that the spherical harmonics equations used here differ slightly from those conventionally used, in that the (-1)^m factor has been omitted. This should be taken into account in all subsequent calculations. Each volume in the output image corresponds to a different spherical harmonic component, according to the following convention: diff --git a/nipype/interfaces/mrtrix/tests/__init__.py b/nipype/interfaces/mrtrix/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/mrtrix/tests/__init__.py +++ b/nipype/interfaces/mrtrix/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/mrtrix/tests/test_auto_ConstrainedSphericalDeconvolution.py b/nipype/interfaces/mrtrix/tests/test_auto_ConstrainedSphericalDeconvolution.py index cee549fae9..ad93f35b9a 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_ConstrainedSphericalDeconvolution.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_ConstrainedSphericalDeconvolution.py @@ -4,21 +4,70 @@ def test_ConstrainedSphericalDeconvolution_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug",), - directions_file=dict(argstr="-directions %s", extensions=None, position=-2,), - encoding_file=dict(argstr="-grad %s", extensions=None, position=1,), - environ=dict(nohash=True, usedefault=True,), - filter_file=dict(argstr="-filter %s", extensions=None, position=-2,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - iterations=dict(argstr="-niter %s",), - lambda_value=dict(argstr="-lambda %s",), - mask_image=dict(argstr="-mask %s", extensions=None, position=2,), - maximum_harmonic_order=dict(argstr="-lmax %s",), - normalise=dict(argstr="-normalise", position=3,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - response_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - threshold_value=dict(argstr="-threshold %s",), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + ), + directions_file=dict( + argstr="-directions %s", + extensions=None, + position=-2, + ), + encoding_file=dict( + argstr="-grad %s", + extensions=None, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filter_file=dict( + argstr="-filter %s", + extensions=None, + position=-2, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + iterations=dict( + argstr="-niter %s", + ), + lambda_value=dict( + argstr="-lambda %s", + ), + mask_image=dict( + argstr="-mask %s", + extensions=None, + position=2, + ), + maximum_harmonic_order=dict( + argstr="-lmax %s", + ), + normalise=dict( + argstr="-normalise", + position=3, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + response_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + threshold_value=dict( + argstr="-threshold %s", + ), ) inputs = ConstrainedSphericalDeconvolution.input_spec() @@ -28,7 +77,11 @@ def test_ConstrainedSphericalDeconvolution_inputs(): def test_ConstrainedSphericalDeconvolution_outputs(): - output_map = dict(spherical_harmonics_image=dict(extensions=None,),) + output_map = dict( + spherical_harmonics_image=dict( + extensions=None, + ), + ) outputs = ConstrainedSphericalDeconvolution.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_DWI2SphericalHarmonicsImage.py b/nipype/interfaces/mrtrix/tests/test_auto_DWI2SphericalHarmonicsImage.py index 7bd1399f30..97b5885baf 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_DWI2SphericalHarmonicsImage.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_DWI2SphericalHarmonicsImage.py @@ -4,15 +4,38 @@ def test_DWI2SphericalHarmonicsImage_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), encoding_file=dict( - argstr="-grad %s", extensions=None, mandatory=True, position=1, + argstr="-grad %s", + extensions=None, + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + maximum_harmonic_order=dict( + argstr="-lmax %s", + ), + normalise=dict( + argstr="-normalise", + position=3, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, ), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - maximum_harmonic_order=dict(argstr="-lmax %s",), - normalise=dict(argstr="-normalise", position=3,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), ) inputs = DWI2SphericalHarmonicsImage.input_spec() @@ -22,7 +45,11 @@ def test_DWI2SphericalHarmonicsImage_inputs(): def test_DWI2SphericalHarmonicsImage_outputs(): - output_map = dict(spherical_harmonics_image=dict(extensions=None,),) + output_map = dict( + spherical_harmonics_image=dict( + extensions=None, + ), + ) outputs = DWI2SphericalHarmonicsImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_DWI2Tensor.py b/nipype/interfaces/mrtrix/tests/test_auto_DWI2Tensor.py index 476f68e9ef..72a2820cc1 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_DWI2Tensor.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_DWI2Tensor.py @@ -4,13 +4,41 @@ def test_DWI2Tensor_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - encoding_file=dict(argstr="-grad %s", extensions=None, position=2,), - environ=dict(nohash=True, usedefault=True,), - ignore_slice_by_volume=dict(argstr="-ignoreslices %s", position=2, sep=" ",), - ignore_volumes=dict(argstr="-ignorevolumes %s", position=2, sep=" ",), - in_file=dict(argstr="%s", mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + encoding_file=dict( + argstr="-grad %s", + extensions=None, + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignore_slice_by_volume=dict( + argstr="-ignoreslices %s", + position=2, + sep=" ", + ), + ignore_volumes=dict( + argstr="-ignorevolumes %s", + position=2, + sep=" ", + ), + in_file=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + ), out_filename=dict( argstr="%s", extensions=None, @@ -19,7 +47,10 @@ def test_DWI2Tensor_inputs(): output_name="tensor", position=-1, ), - quiet=dict(argstr="-quiet", position=1,), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = DWI2Tensor.input_spec() @@ -29,7 +60,11 @@ def test_DWI2Tensor_inputs(): def test_DWI2Tensor_outputs(): - output_map = dict(tensor=dict(extensions=None,),) + output_map = dict( + tensor=dict( + extensions=None, + ), + ) outputs = DWI2Tensor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py b/nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py index 66122fcfdb..c6fe4f586e 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_DiffusionTensorStreamlineTrack.py @@ -4,13 +4,27 @@ def test_DiffusionTensorStreamlineTrack_inputs(): input_map = dict( - args=dict(argstr="%s",), - cutoff_value=dict(argstr="-cutoff %s", units="NA",), - desired_number_of_tracks=dict(argstr="-number %d",), - do_not_precompute=dict(argstr="-noprecomputed",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + cutoff_value=dict( + argstr="-cutoff %s", + units="NA", + ), + desired_number_of_tracks=dict( + argstr="-number %d", + ), + do_not_precompute=dict( + argstr="-noprecomputed", + ), + environ=dict( + nohash=True, + usedefault=True, + ), exclude_file=dict( - argstr="-exclude %s", extensions=None, xor=["exclude_file", "exclude_spec"], + argstr="-exclude %s", + extensions=None, + xor=["exclude_file", "exclude_spec"], ), exclude_spec=dict( argstr="-exclude %s", @@ -20,11 +34,21 @@ def test_DiffusionTensorStreamlineTrack_inputs(): xor=["exclude_file", "exclude_spec"], ), gradient_encoding_file=dict( - argstr="-grad %s", extensions=None, mandatory=True, position=-2, + argstr="-grad %s", + extensions=None, + mandatory=True, + position=-2, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, ), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), include_file=dict( - argstr="-include %s", extensions=None, xor=["include_file", "include_spec"], + argstr="-include %s", + extensions=None, + xor=["include_file", "include_spec"], ), include_spec=dict( argstr="-include %s", @@ -33,11 +57,23 @@ def test_DiffusionTensorStreamlineTrack_inputs(): units="mm", xor=["include_file", "include_spec"], ), - initial_cutoff_value=dict(argstr="-initcutoff %s", units="NA",), - initial_direction=dict(argstr="-initdirection %s", units="voxels",), - inputmodel=dict(argstr="%s", position=-3, usedefault=True,), + initial_cutoff_value=dict( + argstr="-initcutoff %s", + units="NA", + ), + initial_direction=dict( + argstr="-initdirection %s", + units="voxels", + ), + inputmodel=dict( + argstr="%s", + position=-3, + usedefault=True, + ), mask_file=dict( - argstr="-mask %s", extensions=None, xor=["mask_file", "mask_spec"], + argstr="-mask %s", + extensions=None, + xor=["mask_file", "mask_spec"], ), mask_spec=dict( argstr="-mask %s", @@ -46,11 +82,24 @@ def test_DiffusionTensorStreamlineTrack_inputs(): units="mm", xor=["mask_file", "mask_spec"], ), - maximum_number_of_tracks=dict(argstr="-maxnum %d",), - maximum_tract_length=dict(argstr="-length %s", units="mm",), - minimum_radius_of_curvature=dict(argstr="-curvature %s", units="mm",), - minimum_tract_length=dict(argstr="-minlength %s", units="mm",), - no_mask_interpolation=dict(argstr="-nomaskinterp",), + maximum_number_of_tracks=dict( + argstr="-maxnum %d", + ), + maximum_tract_length=dict( + argstr="-length %s", + units="mm", + ), + minimum_radius_of_curvature=dict( + argstr="-curvature %s", + units="mm", + ), + minimum_tract_length=dict( + argstr="-minlength %s", + units="mm", + ), + no_mask_interpolation=dict( + argstr="-nomaskinterp", + ), out_file=dict( argstr="%s", extensions=None, @@ -60,7 +109,9 @@ def test_DiffusionTensorStreamlineTrack_inputs(): position=-1, ), seed_file=dict( - argstr="-seed %s", extensions=None, xor=["seed_file", "seed_spec"], + argstr="-seed %s", + extensions=None, + xor=["seed_file", "seed_spec"], ), seed_spec=dict( argstr="-seed %s", @@ -69,9 +120,16 @@ def test_DiffusionTensorStreamlineTrack_inputs(): units="mm", xor=["seed_file", "seed_spec"], ), - step_size=dict(argstr="-step %s", units="mm",), - stop=dict(argstr="-stop",), - unidirectional=dict(argstr="-unidirectional",), + step_size=dict( + argstr="-step %s", + units="mm", + ), + stop=dict( + argstr="-stop", + ), + unidirectional=dict( + argstr="-unidirectional", + ), ) inputs = DiffusionTensorStreamlineTrack.input_spec() @@ -81,7 +139,11 @@ def test_DiffusionTensorStreamlineTrack_inputs(): def test_DiffusionTensorStreamlineTrack_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = DiffusionTensorStreamlineTrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Directions2Amplitude.py b/nipype/interfaces/mrtrix/tests/test_auto_Directions2Amplitude.py index 66c75db7dc..4685b0e9d6 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Directions2Amplitude.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Directions2Amplitude.py @@ -4,12 +4,28 @@ def test_Directions2Amplitude_inputs(): input_map = dict( - args=dict(argstr="%s",), - display_debug=dict(argstr="-debug",), - display_info=dict(argstr="-info",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - num_peaks=dict(argstr="-num %s",), + args=dict( + argstr="%s", + ), + display_debug=dict( + argstr="-debug", + ), + display_info=dict( + argstr="-info", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + num_peaks=dict( + argstr="-num %s", + ), out_file=dict( argstr="%s", extensions=None, @@ -19,9 +35,17 @@ def test_Directions2Amplitude_inputs(): name_template="%s_amplitudes.mif", position=-1, ), - peak_directions=dict(argstr="-direction %s", sep=" ",), - peaks_image=dict(argstr="-peaks %s", extensions=None,), - quiet_display=dict(argstr="-quiet",), + peak_directions=dict( + argstr="-direction %s", + sep=" ", + ), + peaks_image=dict( + argstr="-peaks %s", + extensions=None, + ), + quiet_display=dict( + argstr="-quiet", + ), ) inputs = Directions2Amplitude.input_spec() @@ -31,7 +55,11 @@ def test_Directions2Amplitude_inputs(): def test_Directions2Amplitude_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Directions2Amplitude.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Erode.py b/nipype/interfaces/mrtrix/tests/test_auto_Erode.py index cb038461ad..86a6a3d0b1 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Erode.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Erode.py @@ -4,14 +4,40 @@ def test_Erode_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - dilate=dict(argstr="-dilate", position=1,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - number_of_passes=dict(argstr="-npass %s",), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - quiet=dict(argstr="-quiet", position=1,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + dilate=dict( + argstr="-dilate", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + number_of_passes=dict( + argstr="-npass %s", + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = Erode.input_spec() @@ -21,7 +47,11 @@ def test_Erode_inputs(): def test_Erode_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Erode.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_EstimateResponseForSH.py b/nipype/interfaces/mrtrix/tests/test_auto_EstimateResponseForSH.py index 4040fe9479..e93a7744fc 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_EstimateResponseForSH.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_EstimateResponseForSH.py @@ -4,18 +4,49 @@ def test_EstimateResponseForSH_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug",), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + ), encoding_file=dict( - argstr="-grad %s", extensions=None, mandatory=True, position=1, - ), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - mask_image=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - maximum_harmonic_order=dict(argstr="-lmax %s",), - normalise=dict(argstr="-normalise",), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - quiet=dict(argstr="-quiet",), + argstr="-grad %s", + extensions=None, + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + mask_image=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + maximum_harmonic_order=dict( + argstr="-lmax %s", + ), + normalise=dict( + argstr="-normalise", + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + ), ) inputs = EstimateResponseForSH.input_spec() @@ -25,7 +56,11 @@ def test_EstimateResponseForSH_inputs(): def test_EstimateResponseForSH_outputs(): - output_map = dict(response=dict(extensions=None,),) + output_map = dict( + response=dict( + extensions=None, + ), + ) outputs = EstimateResponseForSH.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_FSL2MRTrix.py b/nipype/interfaces/mrtrix/tests/test_auto_FSL2MRTrix.py index 4772abcbc4..3e11a7db45 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_FSL2MRTrix.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_FSL2MRTrix.py @@ -4,12 +4,27 @@ def test_FSL2MRTrix_inputs(): input_map = dict( - bval_file=dict(extensions=None, mandatory=True,), - bvec_file=dict(extensions=None, mandatory=True,), - invert_x=dict(usedefault=True,), - invert_y=dict(usedefault=True,), - invert_z=dict(usedefault=True,), - out_encoding_file=dict(extensions=None, genfile=True,), + bval_file=dict( + extensions=None, + mandatory=True, + ), + bvec_file=dict( + extensions=None, + mandatory=True, + ), + invert_x=dict( + usedefault=True, + ), + invert_y=dict( + usedefault=True, + ), + invert_z=dict( + usedefault=True, + ), + out_encoding_file=dict( + extensions=None, + genfile=True, + ), ) inputs = FSL2MRTrix.input_spec() @@ -19,7 +34,11 @@ def test_FSL2MRTrix_inputs(): def test_FSL2MRTrix_outputs(): - output_map = dict(encoding_file=dict(extensions=None,),) + output_map = dict( + encoding_file=dict( + extensions=None, + ), + ) outputs = FSL2MRTrix.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_FilterTracks.py b/nipype/interfaces/mrtrix/tests/test_auto_FilterTracks.py index 0ce949eb41..c7b9c19d24 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_FilterTracks.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_FilterTracks.py @@ -4,11 +4,21 @@ def test_FilterTracks_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), exclude_file=dict( - argstr="-exclude %s", extensions=None, xor=["exclude_file", "exclude_spec"], + argstr="-exclude %s", + extensions=None, + xor=["exclude_file", "exclude_spec"], ), exclude_spec=dict( argstr="-exclude %s", @@ -17,9 +27,16 @@ def test_FilterTracks_inputs(): units="mm", xor=["exclude_file", "exclude_spec"], ), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), include_file=dict( - argstr="-include %s", extensions=None, xor=["include_file", "include_spec"], + argstr="-include %s", + extensions=None, + xor=["include_file", "include_spec"], ), include_spec=dict( argstr="-include %s", @@ -28,9 +45,16 @@ def test_FilterTracks_inputs(): units="mm", xor=["include_file", "include_spec"], ), - invert=dict(argstr="-invert",), - minimum_tract_length=dict(argstr="-minlength %s", units="mm",), - no_mask_interpolation=dict(argstr="-nomaskinterp",), + invert=dict( + argstr="-invert", + ), + minimum_tract_length=dict( + argstr="-minlength %s", + units="mm", + ), + no_mask_interpolation=dict( + argstr="-nomaskinterp", + ), out_file=dict( argstr="%s", extensions=None, @@ -39,7 +63,10 @@ def test_FilterTracks_inputs(): name_template="%s_filt", position=-1, ), - quiet=dict(argstr="-quiet", position=1,), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = FilterTracks.input_spec() @@ -49,7 +76,11 @@ def test_FilterTracks_inputs(): def test_FilterTracks_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = FilterTracks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_FindShPeaks.py b/nipype/interfaces/mrtrix/tests/test_auto_FindShPeaks.py index c8e6a9cb3d..62132f795a 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_FindShPeaks.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_FindShPeaks.py @@ -4,15 +4,34 @@ def test_FindShPeaks_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), directions_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-2, + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + display_debug=dict( + argstr="-debug", + ), + display_info=dict( + argstr="-info", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + num_peaks=dict( + argstr="-num %s", ), - display_debug=dict(argstr="-debug",), - display_info=dict(argstr="-info",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - num_peaks=dict(argstr="-num %s",), out_file=dict( argstr="%s", extensions=None, @@ -22,10 +41,20 @@ def test_FindShPeaks_inputs(): name_template="%s_peak_dirs.mif", position=-1, ), - peak_directions=dict(argstr="-direction %s", sep=" ",), - peak_threshold=dict(argstr="-threshold %s",), - peaks_image=dict(argstr="-peaks %s", extensions=None,), - quiet_display=dict(argstr="-quiet",), + peak_directions=dict( + argstr="-direction %s", + sep=" ", + ), + peak_threshold=dict( + argstr="-threshold %s", + ), + peaks_image=dict( + argstr="-peaks %s", + extensions=None, + ), + quiet_display=dict( + argstr="-quiet", + ), ) inputs = FindShPeaks.input_spec() @@ -35,7 +64,11 @@ def test_FindShPeaks_inputs(): def test_FindShPeaks_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = FindShPeaks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_GenerateDirections.py b/nipype/interfaces/mrtrix/tests/test_auto_GenerateDirections.py index f980f9386b..63b66ab1e6 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_GenerateDirections.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_GenerateDirections.py @@ -4,12 +4,27 @@ def test_GenerateDirections_inputs(): input_map = dict( - args=dict(argstr="%s",), - display_debug=dict(argstr="-debug",), - display_info=dict(argstr="-info",), - environ=dict(nohash=True, usedefault=True,), - niter=dict(argstr="-niter %s",), - num_dirs=dict(argstr="%s", mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + display_debug=dict( + argstr="-debug", + ), + display_info=dict( + argstr="-info", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + niter=dict( + argstr="-niter %s", + ), + num_dirs=dict( + argstr="%s", + mandatory=True, + position=-2, + ), out_file=dict( argstr="%s", extensions=None, @@ -18,8 +33,12 @@ def test_GenerateDirections_inputs(): name_template="directions_%d.txt", position=-1, ), - power=dict(argstr="-power %s",), - quiet_display=dict(argstr="-quiet",), + power=dict( + argstr="-power %s", + ), + quiet_display=dict( + argstr="-quiet", + ), ) inputs = GenerateDirections.input_spec() @@ -29,7 +48,11 @@ def test_GenerateDirections_inputs(): def test_GenerateDirections_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = GenerateDirections.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_GenerateWhiteMatterMask.py b/nipype/interfaces/mrtrix/tests/test_auto_GenerateWhiteMatterMask.py index dc58ac51d2..09b893f105 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_GenerateWhiteMatterMask.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_GenerateWhiteMatterMask.py @@ -4,16 +4,39 @@ def test_GenerateWhiteMatterMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - binary_mask=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + binary_mask=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), encoding_file=dict( - argstr="-grad %s", extensions=None, mandatory=True, position=1, + argstr="-grad %s", + extensions=None, + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + noise_level_margin=dict( + argstr="-margin %s", ), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - noise_level_margin=dict(argstr="-margin %s",), out_WMProb_filename=dict( - argstr="%s", extensions=None, genfile=True, position=-1, + argstr="%s", + extensions=None, + genfile=True, + position=-1, ), ) inputs = GenerateWhiteMatterMask.input_spec() @@ -24,7 +47,11 @@ def test_GenerateWhiteMatterMask_inputs(): def test_GenerateWhiteMatterMask_outputs(): - output_map = dict(WMprobabilitymap=dict(extensions=None,),) + output_map = dict( + WMprobabilitymap=dict( + extensions=None, + ), + ) outputs = GenerateWhiteMatterMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRConvert.py b/nipype/interfaces/mrtrix/tests/test_auto_MRConvert.py index 792beb6aa0..7e819a66da 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRConvert.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRConvert.py @@ -4,20 +4,69 @@ def test_MRConvert_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - extension=dict(position=2, usedefault=True,), - extract_at_axis=dict(argstr="-coord %s", position=1,), - extract_at_coordinate=dict(argstr="%s", position=2, sep=",",), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - layout=dict(argstr="-output %s", position=2,), - offset_bias=dict(argstr="-scale %d", position=3, units="mm",), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - output_datatype=dict(argstr="-output %s", position=2,), - prs=dict(argstr="-prs", position=3,), - replace_NaN_with_zero=dict(argstr="-zero", position=3,), - resample=dict(argstr="-scale %d", position=3, units="mm",), - voxel_dims=dict(argstr="-vox %s", position=3, sep=",",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extension=dict( + position=2, + usedefault=True, + ), + extract_at_axis=dict( + argstr="-coord %s", + position=1, + ), + extract_at_coordinate=dict( + argstr="%s", + position=2, + sep=",", + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + layout=dict( + argstr="-output %s", + position=2, + ), + offset_bias=dict( + argstr="-scale %d", + position=3, + units="mm", + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + output_datatype=dict( + argstr="-output %s", + position=2, + ), + prs=dict( + argstr="-prs", + position=3, + ), + replace_NaN_with_zero=dict( + argstr="-zero", + position=3, + ), + resample=dict( + argstr="-scale %d", + position=3, + units="mm", + ), + voxel_dims=dict( + argstr="-vox %s", + position=3, + sep=",", + ), ) inputs = MRConvert.input_spec() @@ -27,7 +76,11 @@ def test_MRConvert_inputs(): def test_MRConvert_outputs(): - output_map = dict(converted=dict(extensions=None,),) + output_map = dict( + converted=dict( + extensions=None, + ), + ) outputs = MRConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRMultiply.py b/nipype/interfaces/mrtrix/tests/test_auto_MRMultiply.py index 5525ef1130..daa1231f06 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRMultiply.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRMultiply.py @@ -4,12 +4,32 @@ def test_MRMultiply_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="%s", mandatory=True, position=-2,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - quiet=dict(argstr="-quiet", position=1,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = MRMultiply.input_spec() @@ -19,7 +39,11 @@ def test_MRMultiply_inputs(): def test_MRMultiply_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRMultiply.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRTransform.py b/nipype/interfaces/mrtrix/tests/test_auto_MRTransform.py index 60e0f452ac..f619525575 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRTransform.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRTransform.py @@ -4,18 +4,64 @@ def test_MRTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), - flip_x=dict(argstr="-flipx", position=1,), - in_files=dict(argstr="%s", mandatory=True, position=-2,), - invert=dict(argstr="-inverse", position=1,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - quiet=dict(argstr="-quiet", position=1,), - reference_image=dict(argstr="-reference %s", extensions=None, position=1,), - replace_transform=dict(argstr="-replace", position=1,), - template_image=dict(argstr="-template %s", extensions=None, position=1,), - transformation_file=dict(argstr="-transform %s", extensions=None, position=1,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip_x=dict( + argstr="-flipx", + position=1, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + invert=dict( + argstr="-inverse", + position=1, + ), + linear_transform=dict( + argstr="-linear %s", + extensions=None, + position=1, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + position=1, + ), + reference_image=dict( + argstr="-reference %s", + extensions=None, + position=1, + ), + replace_transform=dict( + argstr="-replace", + position=1, + ), + template_image=dict( + argstr="-template %s", + extensions=None, + position=1, + ), + transformation_file=dict( + argstr="-transform %s", + extensions=None, + position=1, + ), ) inputs = MRTransform.input_spec() @@ -25,7 +71,11 @@ def test_MRTransform_inputs(): def test_MRTransform_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRTrix2TrackVis.py b/nipype/interfaces/mrtrix/tests/test_auto_MRTrix2TrackVis.py index 05f80b4646..0fb54a3020 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRTrix2TrackVis.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRTrix2TrackVis.py @@ -4,11 +4,24 @@ def test_MRTrix2TrackVis_inputs(): input_map = dict( - image_file=dict(extensions=None,), - in_file=dict(extensions=None, mandatory=True,), - matrix_file=dict(extensions=None,), - out_filename=dict(extensions=None, genfile=True, usedefault=True,), - registration_image_file=dict(extensions=None,), + image_file=dict( + extensions=None, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + matrix_file=dict( + extensions=None, + ), + out_filename=dict( + extensions=None, + genfile=True, + usedefault=True, + ), + registration_image_file=dict( + extensions=None, + ), ) inputs = MRTrix2TrackVis.input_spec() @@ -18,7 +31,11 @@ def test_MRTrix2TrackVis_inputs(): def test_MRTrix2TrackVis_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRTrix2TrackVis.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRTrixInfo.py b/nipype/interfaces/mrtrix/tests/test_auto_MRTrixInfo.py index 5e3fd2882e..eecdc39bf5 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRTrixInfo.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRTrixInfo.py @@ -4,9 +4,19 @@ def test_MRTrixInfo_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), ) inputs = MRTrixInfo.input_spec() diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MRTrixViewer.py b/nipype/interfaces/mrtrix/tests/test_auto_MRTrixViewer.py index 711191bd16..8eab033221 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MRTrixViewer.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MRTrixViewer.py @@ -4,11 +4,26 @@ def test_MRTrixViewer_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), - in_files=dict(argstr="%s", mandatory=True, position=-2,), - quiet=dict(argstr="-quiet", position=1,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = MRTrixViewer.input_spec() diff --git a/nipype/interfaces/mrtrix/tests/test_auto_MedianFilter3D.py b/nipype/interfaces/mrtrix/tests/test_auto_MedianFilter3D.py index 0b3f38dcbc..7a0974d9b8 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_MedianFilter3D.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_MedianFilter3D.py @@ -4,12 +4,33 @@ def test_MedianFilter3D_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - quiet=dict(argstr="-quiet", position=1,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = MedianFilter3D.input_spec() @@ -19,7 +40,11 @@ def test_MedianFilter3D_inputs(): def test_MedianFilter3D_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MedianFilter3D.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_ProbabilisticSphericallyDeconvolutedStreamlineTrack.py b/nipype/interfaces/mrtrix/tests/test_auto_ProbabilisticSphericallyDeconvolutedStreamlineTrack.py index e640da1306..8dded55576 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_ProbabilisticSphericallyDeconvolutedStreamlineTrack.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_ProbabilisticSphericallyDeconvolutedStreamlineTrack.py @@ -4,13 +4,27 @@ def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_inputs(): input_map = dict( - args=dict(argstr="%s",), - cutoff_value=dict(argstr="-cutoff %s", units="NA",), - desired_number_of_tracks=dict(argstr="-number %d",), - do_not_precompute=dict(argstr="-noprecomputed",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + cutoff_value=dict( + argstr="-cutoff %s", + units="NA", + ), + desired_number_of_tracks=dict( + argstr="-number %d", + ), + do_not_precompute=dict( + argstr="-noprecomputed", + ), + environ=dict( + nohash=True, + usedefault=True, + ), exclude_file=dict( - argstr="-exclude %s", extensions=None, xor=["exclude_file", "exclude_spec"], + argstr="-exclude %s", + extensions=None, + xor=["exclude_file", "exclude_spec"], ), exclude_spec=dict( argstr="-exclude %s", @@ -19,9 +33,16 @@ def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_inputs(): units="mm", xor=["exclude_file", "exclude_spec"], ), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), include_file=dict( - argstr="-include %s", extensions=None, xor=["include_file", "include_spec"], + argstr="-include %s", + extensions=None, + xor=["include_file", "include_spec"], ), include_spec=dict( argstr="-include %s", @@ -30,11 +51,23 @@ def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_inputs(): units="mm", xor=["include_file", "include_spec"], ), - initial_cutoff_value=dict(argstr="-initcutoff %s", units="NA",), - initial_direction=dict(argstr="-initdirection %s", units="voxels",), - inputmodel=dict(argstr="%s", position=-3, usedefault=True,), + initial_cutoff_value=dict( + argstr="-initcutoff %s", + units="NA", + ), + initial_direction=dict( + argstr="-initdirection %s", + units="voxels", + ), + inputmodel=dict( + argstr="%s", + position=-3, + usedefault=True, + ), mask_file=dict( - argstr="-mask %s", extensions=None, xor=["mask_file", "mask_spec"], + argstr="-mask %s", + extensions=None, + xor=["mask_file", "mask_spec"], ), mask_spec=dict( argstr="-mask %s", @@ -43,12 +76,27 @@ def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_inputs(): units="mm", xor=["mask_file", "mask_spec"], ), - maximum_number_of_tracks=dict(argstr="-maxnum %d",), - maximum_number_of_trials=dict(argstr="-trials %s",), - maximum_tract_length=dict(argstr="-length %s", units="mm",), - minimum_radius_of_curvature=dict(argstr="-curvature %s", units="mm",), - minimum_tract_length=dict(argstr="-minlength %s", units="mm",), - no_mask_interpolation=dict(argstr="-nomaskinterp",), + maximum_number_of_tracks=dict( + argstr="-maxnum %d", + ), + maximum_number_of_trials=dict( + argstr="-trials %s", + ), + maximum_tract_length=dict( + argstr="-length %s", + units="mm", + ), + minimum_radius_of_curvature=dict( + argstr="-curvature %s", + units="mm", + ), + minimum_tract_length=dict( + argstr="-minlength %s", + units="mm", + ), + no_mask_interpolation=dict( + argstr="-nomaskinterp", + ), out_file=dict( argstr="%s", extensions=None, @@ -58,7 +106,9 @@ def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_inputs(): position=-1, ), seed_file=dict( - argstr="-seed %s", extensions=None, xor=["seed_file", "seed_spec"], + argstr="-seed %s", + extensions=None, + xor=["seed_file", "seed_spec"], ), seed_spec=dict( argstr="-seed %s", @@ -67,9 +117,16 @@ def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_inputs(): units="mm", xor=["seed_file", "seed_spec"], ), - step_size=dict(argstr="-step %s", units="mm",), - stop=dict(argstr="-stop",), - unidirectional=dict(argstr="-unidirectional",), + step_size=dict( + argstr="-step %s", + units="mm", + ), + stop=dict( + argstr="-stop", + ), + unidirectional=dict( + argstr="-unidirectional", + ), ) inputs = ProbabilisticSphericallyDeconvolutedStreamlineTrack.input_spec() @@ -79,7 +136,11 @@ def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_inputs(): def test_ProbabilisticSphericallyDeconvolutedStreamlineTrack_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = ProbabilisticSphericallyDeconvolutedStreamlineTrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py b/nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py index bc32741331..c717eb628b 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_SphericallyDeconvolutedStreamlineTrack.py @@ -4,13 +4,27 @@ def test_SphericallyDeconvolutedStreamlineTrack_inputs(): input_map = dict( - args=dict(argstr="%s",), - cutoff_value=dict(argstr="-cutoff %s", units="NA",), - desired_number_of_tracks=dict(argstr="-number %d",), - do_not_precompute=dict(argstr="-noprecomputed",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + cutoff_value=dict( + argstr="-cutoff %s", + units="NA", + ), + desired_number_of_tracks=dict( + argstr="-number %d", + ), + do_not_precompute=dict( + argstr="-noprecomputed", + ), + environ=dict( + nohash=True, + usedefault=True, + ), exclude_file=dict( - argstr="-exclude %s", extensions=None, xor=["exclude_file", "exclude_spec"], + argstr="-exclude %s", + extensions=None, + xor=["exclude_file", "exclude_spec"], ), exclude_spec=dict( argstr="-exclude %s", @@ -19,9 +33,16 @@ def test_SphericallyDeconvolutedStreamlineTrack_inputs(): units="mm", xor=["exclude_file", "exclude_spec"], ), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), include_file=dict( - argstr="-include %s", extensions=None, xor=["include_file", "include_spec"], + argstr="-include %s", + extensions=None, + xor=["include_file", "include_spec"], ), include_spec=dict( argstr="-include %s", @@ -30,11 +51,23 @@ def test_SphericallyDeconvolutedStreamlineTrack_inputs(): units="mm", xor=["include_file", "include_spec"], ), - initial_cutoff_value=dict(argstr="-initcutoff %s", units="NA",), - initial_direction=dict(argstr="-initdirection %s", units="voxels",), - inputmodel=dict(argstr="%s", position=-3, usedefault=True,), + initial_cutoff_value=dict( + argstr="-initcutoff %s", + units="NA", + ), + initial_direction=dict( + argstr="-initdirection %s", + units="voxels", + ), + inputmodel=dict( + argstr="%s", + position=-3, + usedefault=True, + ), mask_file=dict( - argstr="-mask %s", extensions=None, xor=["mask_file", "mask_spec"], + argstr="-mask %s", + extensions=None, + xor=["mask_file", "mask_spec"], ), mask_spec=dict( argstr="-mask %s", @@ -43,11 +76,24 @@ def test_SphericallyDeconvolutedStreamlineTrack_inputs(): units="mm", xor=["mask_file", "mask_spec"], ), - maximum_number_of_tracks=dict(argstr="-maxnum %d",), - maximum_tract_length=dict(argstr="-length %s", units="mm",), - minimum_radius_of_curvature=dict(argstr="-curvature %s", units="mm",), - minimum_tract_length=dict(argstr="-minlength %s", units="mm",), - no_mask_interpolation=dict(argstr="-nomaskinterp",), + maximum_number_of_tracks=dict( + argstr="-maxnum %d", + ), + maximum_tract_length=dict( + argstr="-length %s", + units="mm", + ), + minimum_radius_of_curvature=dict( + argstr="-curvature %s", + units="mm", + ), + minimum_tract_length=dict( + argstr="-minlength %s", + units="mm", + ), + no_mask_interpolation=dict( + argstr="-nomaskinterp", + ), out_file=dict( argstr="%s", extensions=None, @@ -57,7 +103,9 @@ def test_SphericallyDeconvolutedStreamlineTrack_inputs(): position=-1, ), seed_file=dict( - argstr="-seed %s", extensions=None, xor=["seed_file", "seed_spec"], + argstr="-seed %s", + extensions=None, + xor=["seed_file", "seed_spec"], ), seed_spec=dict( argstr="-seed %s", @@ -66,9 +114,16 @@ def test_SphericallyDeconvolutedStreamlineTrack_inputs(): units="mm", xor=["seed_file", "seed_spec"], ), - step_size=dict(argstr="-step %s", units="mm",), - stop=dict(argstr="-stop",), - unidirectional=dict(argstr="-unidirectional",), + step_size=dict( + argstr="-step %s", + units="mm", + ), + stop=dict( + argstr="-stop", + ), + unidirectional=dict( + argstr="-unidirectional", + ), ) inputs = SphericallyDeconvolutedStreamlineTrack.input_spec() @@ -78,7 +133,11 @@ def test_SphericallyDeconvolutedStreamlineTrack_inputs(): def test_SphericallyDeconvolutedStreamlineTrack_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = SphericallyDeconvolutedStreamlineTrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_StreamlineTrack.py b/nipype/interfaces/mrtrix/tests/test_auto_StreamlineTrack.py index bf58f3fcd0..d8f1a5c869 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_StreamlineTrack.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_StreamlineTrack.py @@ -4,13 +4,27 @@ def test_StreamlineTrack_inputs(): input_map = dict( - args=dict(argstr="%s",), - cutoff_value=dict(argstr="-cutoff %s", units="NA",), - desired_number_of_tracks=dict(argstr="-number %d",), - do_not_precompute=dict(argstr="-noprecomputed",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + cutoff_value=dict( + argstr="-cutoff %s", + units="NA", + ), + desired_number_of_tracks=dict( + argstr="-number %d", + ), + do_not_precompute=dict( + argstr="-noprecomputed", + ), + environ=dict( + nohash=True, + usedefault=True, + ), exclude_file=dict( - argstr="-exclude %s", extensions=None, xor=["exclude_file", "exclude_spec"], + argstr="-exclude %s", + extensions=None, + xor=["exclude_file", "exclude_spec"], ), exclude_spec=dict( argstr="-exclude %s", @@ -19,9 +33,16 @@ def test_StreamlineTrack_inputs(): units="mm", xor=["exclude_file", "exclude_spec"], ), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), include_file=dict( - argstr="-include %s", extensions=None, xor=["include_file", "include_spec"], + argstr="-include %s", + extensions=None, + xor=["include_file", "include_spec"], ), include_spec=dict( argstr="-include %s", @@ -30,11 +51,23 @@ def test_StreamlineTrack_inputs(): units="mm", xor=["include_file", "include_spec"], ), - initial_cutoff_value=dict(argstr="-initcutoff %s", units="NA",), - initial_direction=dict(argstr="-initdirection %s", units="voxels",), - inputmodel=dict(argstr="%s", position=-3, usedefault=True,), + initial_cutoff_value=dict( + argstr="-initcutoff %s", + units="NA", + ), + initial_direction=dict( + argstr="-initdirection %s", + units="voxels", + ), + inputmodel=dict( + argstr="%s", + position=-3, + usedefault=True, + ), mask_file=dict( - argstr="-mask %s", extensions=None, xor=["mask_file", "mask_spec"], + argstr="-mask %s", + extensions=None, + xor=["mask_file", "mask_spec"], ), mask_spec=dict( argstr="-mask %s", @@ -43,11 +76,24 @@ def test_StreamlineTrack_inputs(): units="mm", xor=["mask_file", "mask_spec"], ), - maximum_number_of_tracks=dict(argstr="-maxnum %d",), - maximum_tract_length=dict(argstr="-length %s", units="mm",), - minimum_radius_of_curvature=dict(argstr="-curvature %s", units="mm",), - minimum_tract_length=dict(argstr="-minlength %s", units="mm",), - no_mask_interpolation=dict(argstr="-nomaskinterp",), + maximum_number_of_tracks=dict( + argstr="-maxnum %d", + ), + maximum_tract_length=dict( + argstr="-length %s", + units="mm", + ), + minimum_radius_of_curvature=dict( + argstr="-curvature %s", + units="mm", + ), + minimum_tract_length=dict( + argstr="-minlength %s", + units="mm", + ), + no_mask_interpolation=dict( + argstr="-nomaskinterp", + ), out_file=dict( argstr="%s", extensions=None, @@ -57,7 +103,9 @@ def test_StreamlineTrack_inputs(): position=-1, ), seed_file=dict( - argstr="-seed %s", extensions=None, xor=["seed_file", "seed_spec"], + argstr="-seed %s", + extensions=None, + xor=["seed_file", "seed_spec"], ), seed_spec=dict( argstr="-seed %s", @@ -66,9 +114,16 @@ def test_StreamlineTrack_inputs(): units="mm", xor=["seed_file", "seed_spec"], ), - step_size=dict(argstr="-step %s", units="mm",), - stop=dict(argstr="-stop",), - unidirectional=dict(argstr="-unidirectional",), + step_size=dict( + argstr="-step %s", + units="mm", + ), + stop=dict( + argstr="-stop", + ), + unidirectional=dict( + argstr="-unidirectional", + ), ) inputs = StreamlineTrack.input_spec() @@ -78,7 +133,11 @@ def test_StreamlineTrack_inputs(): def test_StreamlineTrack_outputs(): - output_map = dict(tracked=dict(extensions=None,),) + output_map = dict( + tracked=dict( + extensions=None, + ), + ) outputs = StreamlineTrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2ApparentDiffusion.py b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2ApparentDiffusion.py index da5225cc42..c32daa3574 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2ApparentDiffusion.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2ApparentDiffusion.py @@ -4,12 +4,33 @@ def test_Tensor2ApparentDiffusion_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - quiet=dict(argstr="-quiet", position=1,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = Tensor2ApparentDiffusion.input_spec() @@ -19,7 +40,11 @@ def test_Tensor2ApparentDiffusion_inputs(): def test_Tensor2ApparentDiffusion_outputs(): - output_map = dict(ADC=dict(extensions=None,),) + output_map = dict( + ADC=dict( + extensions=None, + ), + ) outputs = Tensor2ApparentDiffusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2FractionalAnisotropy.py b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2FractionalAnisotropy.py index 8f9937b550..bf90806f74 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2FractionalAnisotropy.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2FractionalAnisotropy.py @@ -4,12 +4,33 @@ def test_Tensor2FractionalAnisotropy_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - quiet=dict(argstr="-quiet", position=1,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = Tensor2FractionalAnisotropy.input_spec() @@ -19,7 +40,11 @@ def test_Tensor2FractionalAnisotropy_inputs(): def test_Tensor2FractionalAnisotropy_outputs(): - output_map = dict(FA=dict(extensions=None,),) + output_map = dict( + FA=dict( + extensions=None, + ), + ) outputs = Tensor2FractionalAnisotropy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2Vector.py b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2Vector.py index dcc58860a4..a87eefef7e 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Tensor2Vector.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Tensor2Vector.py @@ -4,12 +4,33 @@ def test_Tensor2Vector_inputs(): input_map = dict( - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - quiet=dict(argstr="-quiet", position=1,), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + position=1, + ), ) inputs = Tensor2Vector.input_spec() @@ -19,7 +40,11 @@ def test_Tensor2Vector_inputs(): def test_Tensor2Vector_outputs(): - output_map = dict(vector=dict(extensions=None,),) + output_map = dict( + vector=dict( + extensions=None, + ), + ) outputs = Tensor2Vector.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Threshold.py b/nipype/interfaces/mrtrix/tests/test_auto_Threshold.py index b1e9a27016..0a67f4db56 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Threshold.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Threshold.py @@ -4,16 +4,47 @@ def test_Threshold_inputs(): input_map = dict( - absolute_threshold_value=dict(argstr="-abs %s",), - args=dict(argstr="%s",), - debug=dict(argstr="-debug", position=1,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - invert=dict(argstr="-invert", position=1,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - percentage_threshold_value=dict(argstr="-percent %s",), - quiet=dict(argstr="-quiet", position=1,), - replace_zeros_with_NaN=dict(argstr="-nan", position=1,), + absolute_threshold_value=dict( + argstr="-abs %s", + ), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-debug", + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + invert=dict( + argstr="-invert", + position=1, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + percentage_threshold_value=dict( + argstr="-percent %s", + ), + quiet=dict( + argstr="-quiet", + position=1, + ), + replace_zeros_with_NaN=dict( + argstr="-nan", + position=1, + ), ) inputs = Threshold.input_spec() @@ -23,7 +54,11 @@ def test_Threshold_inputs(): def test_Threshold_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Threshold.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tests/test_auto_Tracks2Prob.py b/nipype/interfaces/mrtrix/tests/test_auto_Tracks2Prob.py index b8bc425de7..9323ba74f2 100644 --- a/nipype/interfaces/mrtrix/tests/test_auto_Tracks2Prob.py +++ b/nipype/interfaces/mrtrix/tests/test_auto_Tracks2Prob.py @@ -4,16 +4,52 @@ def test_Tracks2Prob_inputs(): input_map = dict( - args=dict(argstr="%s",), - colour=dict(argstr="-colour", position=3,), - environ=dict(nohash=True, usedefault=True,), - fraction=dict(argstr="-fraction", position=3,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - out_filename=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - output_datatype=dict(argstr="-datatype %s", position=2,), - resample=dict(argstr="-resample %d", position=3, units="mm",), - template_file=dict(argstr="-template %s", extensions=None, position=1,), - voxel_dims=dict(argstr="-vox %s", position=2, sep=",",), + args=dict( + argstr="%s", + ), + colour=dict( + argstr="-colour", + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fraction=dict( + argstr="-fraction", + position=3, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + out_filename=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + output_datatype=dict( + argstr="-datatype %s", + position=2, + ), + resample=dict( + argstr="-resample %d", + position=3, + units="mm", + ), + template_file=dict( + argstr="-template %s", + extensions=None, + position=1, + ), + voxel_dims=dict( + argstr="-vox %s", + position=2, + sep=",", + ), ) inputs = Tracks2Prob.input_spec() @@ -23,7 +59,11 @@ def test_Tracks2Prob_inputs(): def test_Tracks2Prob_outputs(): - output_map = dict(tract_image=dict(extensions=None,),) + output_map = dict( + tract_image=dict( + extensions=None, + ), + ) outputs = Tracks2Prob.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix/tracking.py b/nipype/interfaces/mrtrix/tracking.py index b7465cdbf2..53e805eeb6 100644 --- a/nipype/interfaces/mrtrix/tracking.py +++ b/nipype/interfaces/mrtrix/tracking.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -119,7 +118,7 @@ class Tracks2ProbInputSpec(CommandLineInputSpec): exists=True, argstr="-template %s", position=1, - desc="an image file to be used as a template for the output (the output image wil have the same transform and field of view)", + desc="an image file to be used as a template for the output (the output image will have the same transform and field of view)", ) voxel_dims = traits.List( traits.Float, @@ -215,7 +214,7 @@ class StreamlineTrackInputSpec(CommandLineInputSpec): mandatory=True, position=-2, desc="the image containing the source data." - "The type of data required depends on the type of tracking as set in the preceeding argument. For DT methods, " + "The type of data required depends on the type of tracking as set in the preceding argument. For DT methods, " "the base DWI are needed. For SD methods, the SH harmonic coefficients of the FOD are needed.", ) @@ -388,14 +387,14 @@ class StreamlineTrack(CommandLine): ------- >>> import nipype.interfaces.mrtrix as mrt - >>> strack = mrt.StreamlineTrack() - >>> strack.inputs.inputmodel = 'SD_PROB' - >>> strack.inputs.in_file = 'data.Bfloat' - >>> strack.inputs.seed_file = 'seed_mask.nii' - >>> strack.inputs.mask_file = 'mask.nii' - >>> strack.cmdline + >>> streamtrack = mrt.StreamlineTrack() + >>> streamtrack.inputs.inputmodel = 'SD_PROB' + >>> streamtrack.inputs.in_file = 'data.Bfloat' + >>> streamtrack.inputs.seed_file = 'seed_mask.nii' + >>> streamtrack.inputs.mask_file = 'mask.nii' + >>> streamtrack.cmdline 'streamtrack -mask mask.nii -seed seed_mask.nii SD_PROB data.Bfloat data_tracked.tck' - >>> strack.run() # doctest: +SKIP + >>> streamtrack.run() # doctest: +SKIP """ _cmd = "streamtrack" @@ -423,17 +422,17 @@ class DiffusionTensorStreamlineTrack(StreamlineTrack): ------- >>> import nipype.interfaces.mrtrix as mrt - >>> dtstrack = mrt.DiffusionTensorStreamlineTrack() - >>> dtstrack.inputs.in_file = 'data.Bfloat' - >>> dtstrack.inputs.seed_file = 'seed_mask.nii' - >>> dtstrack.run() # doctest: +SKIP + >>> dtstreamtrack = mrt.DiffusionTensorStreamlineTrack() + >>> dtstreamtrack.inputs.in_file = 'data.Bfloat' + >>> dtstreamtrack.inputs.seed_file = 'seed_mask.nii' + >>> dtstreamtrack.run() # doctest: +SKIP """ input_spec = DiffusionTensorStreamlineTrackInputSpec def __init__(self, command=None, **inputs): inputs["inputmodel"] = "DT_STREAM" - return super(DiffusionTensorStreamlineTrack, self).__init__(command, **inputs) + return super().__init__(command, **inputs) class ProbabilisticSphericallyDeconvolutedStreamlineTrackInputSpec( @@ -467,9 +466,7 @@ class ProbabilisticSphericallyDeconvolutedStreamlineTrack(StreamlineTrack): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "SD_PROB" - return super( - ProbabilisticSphericallyDeconvolutedStreamlineTrack, self - ).__init__(command, **inputs) + return super().__init__(command, **inputs) class SphericallyDeconvolutedStreamlineTrack(StreamlineTrack): @@ -494,6 +491,4 @@ class SphericallyDeconvolutedStreamlineTrack(StreamlineTrack): def __init__(self, command=None, **inputs): inputs["inputmodel"] = "SD_STREAM" - return super(SphericallyDeconvolutedStreamlineTrack, self).__init__( - command, **inputs - ) + return super().__init__(command, **inputs) diff --git a/nipype/interfaces/mrtrix3/__init__.py b/nipype/interfaces/mrtrix3/__init__.py index 2970918844..3bd9f55250 100644 --- a/nipype/interfaces/mrtrix3/__init__.py +++ b/nipype/interfaces/mrtrix3/__init__.py @@ -2,26 +2,35 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- """MRTrix3 provides software tools to perform various types of diffusion MRI analyses.""" -from .utils import ( - Mesh2PVE, - Generate5tt, - BrainMask, - TensorMetrics, - ComputeTDI, - TCK2VTK, - MRMath, - MRConvert, - MRResize, - DWIExtract, -) +from .connectivity import BuildConnectome, LabelConfig, LabelConvert from .preprocess import ( - ResponseSD, ACTPrepareFSL, - ReplaceFSwithFIRST, + DWIBiasCorrect, DWIDenoise, + DWIPreproc, MRDeGibbs, - DWIBiasCorrect, + ReplaceFSwithFIRST, + ResponseSD, ) +from .reconst import ConstrainedSphericalDeconvolution, EstimateFOD, FitTensor from .tracking import Tractography -from .reconst import FitTensor, EstimateFOD -from .connectivity import LabelConfig, LabelConvert, BuildConnectome +from .utils import ( + TCK2VTK, + BrainMask, + ComputeTDI, + DWIExtract, + Generate5tt, + Mesh2PVE, + MRCat, + MRConvert, + MRMath, + MRResize, + MRTransform, + SH2Amp, + SHConv, + TensorMetrics, + TransformFSLConvert, + MaskFilter, + MTNormalise, + Generate5tt2gmwmi, +) diff --git a/nipype/interfaces/mrtrix3/base.py b/nipype/interfaces/mrtrix3/base.py index 15b208b4cd..cd5d492fcf 100644 --- a/nipype/interfaces/mrtrix3/base.py +++ b/nipype/interfaces/mrtrix3/base.py @@ -2,12 +2,14 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- -from ... import logging, LooseVersion -from ...utils.filemanip import which +from looseversion import LooseVersion + +from ... import logging from ..base import ( CommandLineInputSpec, CommandLine, traits, + Tuple, File, isdefined, PackageInfo, @@ -36,7 +38,7 @@ def parse_version(raw_info): @classmethod def looseversion(cls): - """ Return a comparable version object + """Return a comparable version object If no version found, use LooseVersion('0.0.0') """ @@ -46,7 +48,7 @@ def looseversion(cls): class MRTrix3BaseInputSpec(CommandLineInputSpec): nthreads = traits.Int( argstr="-nthreads %d", - desc="number of threads. if zero, the number" " of available cpus will be used", + desc="number of threads. if zero, the number of available cpus will be used", nohash=True, ) # DW gradient table import options @@ -56,7 +58,7 @@ class MRTrix3BaseInputSpec(CommandLineInputSpec): desc="dw gradient scheme (MRTrix format)", xor=["grad_fsl"], ) - grad_fsl = traits.Tuple( + grad_fsl = Tuple( File(exists=True), File(exists=True), argstr="-fslgrad %s %s", @@ -79,6 +81,15 @@ class MRTrix3BaseInputSpec(CommandLineInputSpec): exists=True, argstr="-fslgrad %s %s", desc="bvecs file in FSL format" ) in_bval = File(exists=True, desc="bvals file in FSL format") + out_bvec = File( + exists=False, + argstr="-export_grad_fsl %s %s", + desc="export bvec file in FSL format", + ) + out_bval = File( + exists=False, + desc="export bval file in FSL format", + ) class MRTrix3Base(CommandLine): @@ -91,13 +102,14 @@ def _format_arg(self, name, trait_spec, value): value = cpu_count() except: iflogger.warning("Number of threads could not be computed") - pass return trait_spec.argstr % value if name == "in_bvec": return trait_spec.argstr % (value, self.inputs.in_bval) + if name == "out_bvec": + return trait_spec.argstr % (value, self.inputs.out_bval) - return super(MRTrix3Base, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _parse_inputs(self, skip=None): if skip is None: @@ -112,13 +124,13 @@ def _parse_inputs(self, skip=None): if is_bvec or is_bval: if not is_bvec or not is_bval: raise RuntimeError( - "If using bvecs and bvals inputs, both" "should be defined" + "If using bvecs and bvals inputs, both should be defined" ) skip += ["in_bval"] except AttributeError: pass - return super(MRTrix3Base, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) @property def version(self): diff --git a/nipype/interfaces/mrtrix3/connectivity.py b/nipype/interfaces/mrtrix3/connectivity.py index 308eccd45f..a3dde940dc 100644 --- a/nipype/interfaces/mrtrix3/connectivity.py +++ b/nipype/interfaces/mrtrix3/connectivity.py @@ -25,7 +25,7 @@ class BuildConnectomeInputSpec(CommandLineInputSpec): nthreads = traits.Int( argstr="-nthreads %d", - desc="number of threads. if zero, the number" " of available cpus will be used", + desc="number of threads. if zero, the number of available cpus will be used", nohash=True, ) @@ -62,19 +62,19 @@ class BuildConnectomeInputSpec(CommandLineInputSpec): "mean_scalar", "invlength_invnodevolume", argstr="-metric %s", - desc="specify the edge" " weight metric", + desc="specify the edge weight metric", ) in_scalar = File( exists=True, argstr="-image %s", - desc="provide the associated image " "for the mean_scalar metric", + desc="provide the associated image for the mean_scalar metric", ) in_weights = File( exists=True, argstr="-tck_weights_in %s", - desc="specify a text scalar " "file containing the streamline weights", + desc="specify a text scalar file containing the streamline weights", ) keep_unassigned = traits.Bool( @@ -174,7 +174,7 @@ class LabelConfigInputSpec(CommandLineInputSpec): ) nthreads = traits.Int( argstr="-nthreads %d", - desc="number of threads. if zero, the number" " of available cpus will be used", + desc="number of threads. if zero, the number of available cpus will be used", nohash=True, ) @@ -208,20 +208,20 @@ def _parse_inputs(self, skip=None): skip = [] if not isdefined(self.inputs.in_config): - from distutils.spawn import find_executable + from shutil import which - path = find_executable(self._cmd) + path = which(self._cmd) if path is None: - path = os.getenv(MRTRIX3_HOME, "/opt/mrtrix3") + path = os.getenv("MRTRIX3_HOME", "/opt/mrtrix3") else: path = op.dirname(op.dirname(path)) self.inputs.in_config = op.join( path, - "src/dwi/tractography/connectomics/" "example_configs/fs_default.txt", + "src/dwi/tractography/connectomics/example_configs/fs_default.txt", ) - return super(LabelConfig, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _list_outputs(self): outputs = self.output_spec().get() @@ -265,7 +265,7 @@ class LabelConvertInputSpec(CommandLineInputSpec): ) num_threads = traits.Int( argstr="-nthreads %d", - desc="number of threads. if zero, the number" " of available cpus will be used", + desc="number of threads. if zero, the number of available cpus will be used", nohash=True, ) @@ -304,16 +304,16 @@ def _parse_inputs(self, skip=None): path = which(self._cmd) if path is None: - path = os.getenv(MRTRIX3_HOME, "/opt/mrtrix3") + path = os.getenv("MRTRIX3_HOME", "/opt/mrtrix3") else: path = op.dirname(op.dirname(path)) self.inputs.in_config = op.join( path, - "src/dwi/tractography/connectomics/" "example_configs/fs_default.txt", + "src/dwi/tractography/connectomics/example_configs/fs_default.txt", ) - return super(LabelConvert, self)._parse_inputs(skip=skip) + return super()._parse_inputs(skip=skip) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/mrtrix3/preprocess.py b/nipype/interfaces/mrtrix3/preprocess.py index 9384ef43c7..0165087376 100644 --- a/nipype/interfaces/mrtrix3/preprocess.py +++ b/nipype/interfaces/mrtrix3/preprocess.py @@ -5,24 +5,29 @@ import os.path as op from ..base import ( - CommandLineInputSpec, CommandLine, - traits, - TraitedSpec, + CommandLineInputSpec, + Directory, File, - isdefined, - Undefined, InputMultiObject, + TraitedSpec, + Undefined, + traits, + Tuple, ) -from .base import MRTrix3BaseInputSpec, MRTrix3Base +from .base import MRTrix3Base, MRTrix3BaseInputSpec class DWIDenoiseInputSpec(MRTrix3BaseInputSpec): in_file = File( - exists=True, argstr="%s", position=-2, mandatory=True, desc="input DWI image" + exists=True, + argstr="%s", + position=-2, + mandatory=True, + desc="input DWI image", ) mask = File(exists=True, argstr="-mask %s", position=1, desc="mask image") - extent = traits.Tuple( + extent = Tuple( (traits.Int, traits.Int, traits.Int), argstr="-extent %d,%d,%d", desc="set the window size of the denoising filter. (default = 5,5,5)", @@ -88,10 +93,15 @@ class DWIDenoise(MRTrix3Base): class MRDeGibbsInputSpec(MRTrix3BaseInputSpec): in_file = File( - exists=True, argstr="%s", position=-2, mandatory=True, desc="input DWI image" + exists=True, + argstr="%s", + position=-2, + mandatory=True, + desc="input DWI image", ) - axes = traits.ListInt( - default_value=[0, 1], + axes = traits.List( + traits.Int, + [0, 1], usedefault=True, sep=",", minlen=2, @@ -177,19 +187,25 @@ class MRDeGibbs(MRTrix3Base): class DWIBiasCorrectInputSpec(MRTrix3BaseInputSpec): in_file = File( - exists=True, argstr="%s", position=-2, mandatory=True, desc="input DWI image" + exists=True, + argstr="%s", + position=-2, + mandatory=True, + desc="input DWI image", ) in_mask = File(argstr="-mask %s", desc="input mask image for bias field estimation") use_ants = traits.Bool( - argstr="-ants", + argstr="ants", mandatory=True, desc="use ANTS N4 to estimate the inhomogeneity field", + position=0, xor=["use_fsl"], ) use_fsl = traits.Bool( - argstr="-fsl", + argstr="fsl", mandatory=True, desc="use FSL FAST to estimate the inhomogeneity field", + position=0, xor=["use_ants"], ) bias = File(argstr="-bias %s", desc="bias field") @@ -224,7 +240,7 @@ class DWIBiasCorrect(MRTrix3Base): >>> bias_correct.inputs.in_file = 'dwi.mif' >>> bias_correct.inputs.use_ants = True >>> bias_correct.cmdline - 'dwibiascorrect -ants dwi.mif dwi_biascorr.mif' + 'dwibiascorrect ants dwi.mif dwi_biascorr.mif' >>> bias_correct.run() # doctest: +SKIP """ @@ -232,6 +248,173 @@ class DWIBiasCorrect(MRTrix3Base): input_spec = DWIBiasCorrectInputSpec output_spec = DWIBiasCorrectOutputSpec + def _format_arg(self, name, trait_spec, value): + if name in ("use_ants", "use_fsl"): + ver = self.version + # Changed in version 3.0, after release candidates + if ver is not None and (ver[0] < "3" or ver.startswith("3.0_RC")): + return f"-{trait_spec.argstr}" + return super()._format_arg(name, trait_spec, value) + + def _list_outputs(self): + outputs = self.output_spec().get() + if self.inputs.out_file: + outputs["out_file"] = op.abspath(self.inputs.out_file) + if self.inputs.bias: + outputs["bias"] = op.abspath(self.inputs.bias) + return outputs + + +class DWIPreprocInputSpec(MRTrix3BaseInputSpec): + in_file = File( + exists=True, + argstr="%s", + position=0, + mandatory=True, + desc="input DWI image", + ) + out_file = File( + "preproc.mif", + argstr="%s", + mandatory=True, + position=1, + usedefault=True, + desc="output file after preprocessing", + ) + rpe_options = traits.Enum( + "none", + "pair", + "all", + "header", + argstr="-rpe_%s", + position=2, + mandatory=True, + desc='Specify acquisition phase-encoding design. "none" for no reversed phase-encoding image, "all" for all DWIs have opposing phase-encoding acquisition, "pair" for using a pair of b0 volumes for inhomogeneity field estimation only, and "header" for phase-encoding information can be found in the image header(s)', + ) + pe_dir = traits.Str( + argstr="-pe_dir %s", + desc="Specify the phase encoding direction of the input series, can be a signed axis number (e.g. -0, 1, +2), an axis designator (e.g. RL, PA, IS), or NIfTI axis codes (e.g. i-, j, k)", + ) + ro_time = traits.Float( + argstr="-readout_time %f", + desc="Total readout time of input series (in seconds)", + ) + in_epi = File( + exists=True, + argstr="-se_epi %s", + desc="Provide an additional image series consisting of spin-echo EPI images, which is to be used exclusively by topup for estimating the inhomogeneity field (i.e. it will not form part of the output image series)", + ) + align_seepi = traits.Bool( + argstr="-align_seepi", + desc="Achieve alignment between the SE-EPI images used for inhomogeneity field estimation, and the DWIs", + ) + json_import = File( + exists=True, + argstr="-json_import %s", + desc="Import image header information from an associated JSON file (may be necessary to determine phase encoding information)", + ) + topup_options = traits.Str( + argstr='-topup_options "%s"', + desc="Manually provide additional command-line options to the topup command", + ) + eddy_options = traits.Str( + argstr='-eddy_options "%s"', + desc="Manually provide additional command-line options to the eddy command", + ) + eddy_mask = File( + exists=True, + argstr="-eddy_mask %s", + desc="Provide a processing mask to use for eddy, instead of having dwifslpreproc generate one internally using dwi2mask", + ) + eddy_slspec = File( + exists=True, + argstr="-eddy_slspec %s", + desc="Provide a file containing slice groupings for eddy's slice-to-volume registration", + ) + eddyqc_text = Directory( + exists=False, + argstr="-eddyqc_text %s", + desc="Copy the various text-based statistical outputs generated by eddy, and the output of eddy_qc (if installed), into an output directory", + ) + eddyqc_all = Directory( + exists=False, + argstr="-eddyqc_all %s", + desc="Copy ALL outputs generated by eddy (including images), and the output of eddy_qc (if installed), into an output directory", + ) + out_grad_mrtrix = File( + "grad.b", + argstr="-export_grad_mrtrix %s", + desc="export new gradient files in mrtrix format", + ) + out_grad_fsl = Tuple( + File("grad.bvecs", desc="bvecs"), + File("grad.bvals", desc="bvals"), + argstr="-export_grad_fsl %s, %s", + desc="export gradient files in FSL format", + ) + + +class DWIPreprocOutputSpec(TraitedSpec): + out_file = File(argstr="%s", desc="output preprocessed image series") + out_grad_mrtrix = File( + "grad.b", + argstr="%s", + usedefault=True, + desc="preprocessed gradient file in mrtrix3 format", + ) + out_fsl_bvec = File( + "grad.bvecs", + argstr="%s", + usedefault=True, + desc="exported fsl gradient bvec file", + ) + out_fsl_bval = File( + "grad.bvals", + argstr="%s", + usedefault=True, + desc="exported fsl gradient bval file", + ) + + +class DWIPreproc(MRTrix3Base): + """ + Perform diffusion image pre-processing using FSL's eddy tool; including inhomogeneity distortion correction using FSL's topup tool if possible + + For more information, see + + + Example + ------- + + >>> import nipype.interfaces.mrtrix3 as mrt + >>> preproc = mrt.DWIPreproc() + >>> preproc.inputs.in_file = 'dwi.mif' + >>> preproc.inputs.rpe_options = 'none' + >>> preproc.inputs.out_file = "preproc.mif" + >>> preproc.inputs.eddy_options = '--slm=linear --repol' # linear second level model and replace outliers + >>> preproc.inputs.out_grad_mrtrix = "grad.b" # export final gradient table in MRtrix format + >>> preproc.inputs.ro_time = 0.165240 # 'TotalReadoutTime' in BIDS JSON metadata files + >>> preproc.inputs.pe_dir = 'j' # 'PhaseEncodingDirection' in BIDS JSON metadata files + >>> preproc.cmdline + 'dwifslpreproc dwi.mif preproc.mif -rpe_none -eddy_options "--slm=linear --repol" -export_grad_mrtrix grad.b -pe_dir j -readout_time 0.165240' + >>> preproc.run() # doctest: +SKIP + """ + + _cmd = "dwifslpreproc" + input_spec = DWIPreprocInputSpec + output_spec = DWIPreprocOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["out_file"] = op.abspath(self.inputs.out_file) + if self.inputs.out_grad_mrtrix: + outputs["out_grad_mrtrix"] = op.abspath(self.inputs.out_grad_mrtrix) + if self.inputs.out_grad_fsl: + outputs["out_fsl_bvec"] = op.abspath(self.inputs.out_grad_fsl[0]) + outputs["out_fsl_bval"] = op.abspath(self.inputs.out_grad_fsl[1]) + + return outputs + class ResponseSDInputSpec(MRTrix3BaseInputSpec): algorithm = traits.Enum( @@ -245,7 +428,11 @@ class ResponseSDInputSpec(MRTrix3BaseInputSpec): desc="response estimation algorithm (multi-tissue)", ) in_file = File( - exists=True, argstr="%s", position=-5, mandatory=True, desc="input DWI image" + exists=True, + argstr="%s", + position=-5, + mandatory=True, + desc="input DWI image", ) mtt_file = File(argstr="%s", position=-4, desc="input 5tt image") wm_file = File( @@ -369,10 +556,17 @@ class ReplaceFSwithFIRSTInputSpec(CommandLineInputSpec): desc="input anatomical image", ) in_t1w = File( - exists=True, argstr="%s", mandatory=True, position=-3, desc="input T1 image" + exists=True, + argstr="%s", + mandatory=True, + position=-3, + desc="input T1 image", ) in_config = File( - exists=True, argstr="%s", position=-2, desc="connectome configuration file" + exists=True, + argstr="%s", + position=-2, + desc="connectome configuration file", ) out_file = File( diff --git a/nipype/interfaces/mrtrix3/reconst.py b/nipype/interfaces/mrtrix3/reconst.py index 2f2854ed8c..bfcd055186 100644 --- a/nipype/interfaces/mrtrix3/reconst.py +++ b/nipype/interfaces/mrtrix3/reconst.py @@ -4,7 +4,7 @@ import os.path as op -from ..base import traits, TraitedSpec, File, Undefined, InputMultiObject +from ..base import traits, TraitedSpec, File, InputMultiObject, isdefined from .base import MRTrix3BaseInputSpec, MRTrix3Base @@ -29,9 +29,7 @@ class FitTensorInputSpec(MRTrix3BaseInputSpec): in_mask = File( exists=True, argstr="-mask %s", - desc=( - "only perform computation within the specified " "binary brain mask image" - ), + desc=("only perform computation within the specified binary brain mask image"), ) method = traits.Enum( "nonlinear", @@ -50,10 +48,18 @@ class FitTensorInputSpec(MRTrix3BaseInputSpec): "only applies to the non-linear methods" ), ) + predicted_signal = File( + argstr="-predicted_signal %s", + desc=( + "specify a file to contain the predicted signal from the tensor " + "fits. This can be used to calculate the residual signal" + ), + ) class FitTensorOutputSpec(TraitedSpec): out_file = File(exists=True, desc="the output DTI file") + predicted_signal = File(desc="Predicted signal from fitted tensors") class FitTensor(MRTrix3Base): @@ -81,6 +87,8 @@ class FitTensor(MRTrix3Base): def _list_outputs(self): outputs = self.output_spec().get() outputs["out_file"] = op.abspath(self.inputs.out_file) + if isdefined(self.inputs.predicted_signal): + outputs["predicted_signal"] = op.abspath(self.inputs.predicted_signal) return outputs @@ -144,30 +152,47 @@ class EstimateFODInputSpec(MRTrix3BaseInputSpec): "[ az el ] pairs for the directions." ), ) + predicted_signal = File( + argstr="-predicted_signal %s", + desc=( + "specify a file to contain the predicted signal from the FOD " + "estimates. This can be used to calculate the residual signal." + "Note that this is only valid if algorithm == 'msmt_csd'. " + "For single shell reconstructions use a combination of SHConv " + "and SH2Amp instead." + ), + ) class EstimateFODOutputSpec(TraitedSpec): wm_odf = File(argstr="%s", desc="output WM ODF") gm_odf = File(argstr="%s", desc="output GM ODF") csf_odf = File(argstr="%s", desc="output CSF ODF") + predicted_signal = File(desc="output predicted signal") class EstimateFOD(MRTrix3Base): """ Estimate fibre orientation distributions from diffusion data using spherical deconvolution + .. warning:: + + The CSD algorithm does not work as intended, but fixing it in this interface could break + existing workflows. This interface has been superseded by + :py:class:`.ConstrainedSphericalDecomposition`. + Example ------- >>> import nipype.interfaces.mrtrix3 as mrt >>> fod = mrt.EstimateFOD() - >>> fod.inputs.algorithm = 'csd' + >>> fod.inputs.algorithm = 'msmt_csd' >>> fod.inputs.in_file = 'dwi.mif' >>> fod.inputs.wm_txt = 'wm.txt' >>> fod.inputs.grad_fsl = ('bvecs', 'bvals') - >>> fod.cmdline # doctest: +ELLIPSIS - 'dwi2fod -fslgrad bvecs bvals -lmax 8 csd dwi.mif wm.txt wm.mif gm.mif csf.mif' - >>> fod.run() # doctest: +SKIP + >>> fod.cmdline + 'dwi2fod -fslgrad bvecs bvals -lmax 8 msmt_csd dwi.mif wm.txt wm.mif gm.mif csf.mif' + >>> fod.run() # doctest: +SKIP """ _cmd = "dwi2fod" @@ -177,8 +202,58 @@ class EstimateFOD(MRTrix3Base): def _list_outputs(self): outputs = self.output_spec().get() outputs["wm_odf"] = op.abspath(self.inputs.wm_odf) - if self.inputs.gm_odf != Undefined: + if isdefined(self.inputs.gm_odf): outputs["gm_odf"] = op.abspath(self.inputs.gm_odf) - if self.inputs.csf_odf != Undefined: + if isdefined(self.inputs.csf_odf): outputs["csf_odf"] = op.abspath(self.inputs.csf_odf) + if isdefined(self.inputs.predicted_signal): + if self.inputs.algorithm != "msmt_csd": + raise Exception( + "'predicted_signal' option can only be used with " + "the 'msmt_csd' algorithm" + ) + outputs["predicted_signal"] = op.abspath(self.inputs.predicted_signal) return outputs + + +class ConstrainedSphericalDeconvolutionInputSpec(EstimateFODInputSpec): + gm_odf = File(argstr="%s", position=-3, desc="output GM ODF") + csf_odf = File(argstr="%s", position=-1, desc="output CSF ODF") + max_sh = InputMultiObject( + traits.Int, + argstr="-lmax %s", + sep=",", + desc=( + "maximum harmonic degree of response function - single value for single-shell response, list for multi-shell response" + ), + ) + + +class ConstrainedSphericalDeconvolution(EstimateFOD): + """ + Estimate fibre orientation distributions from diffusion data using spherical deconvolution + + This interface supersedes :py:class:`.EstimateFOD`. + The old interface has contained a bug when using the CSD algorithm as opposed to the MSMT CSD + algorithm, but fixing it could potentially break existing workflows. The new interface works + the same, but does not populate the following inputs by default: + + * ``gm_odf`` + * ``csf_odf`` + * ``max_sh`` + + Example + ------- + + >>> import nipype.interfaces.mrtrix3 as mrt + >>> fod = mrt.ConstrainedSphericalDeconvolution() + >>> fod.inputs.algorithm = 'csd' + >>> fod.inputs.in_file = 'dwi.mif' + >>> fod.inputs.wm_txt = 'wm.txt' + >>> fod.inputs.grad_fsl = ('bvecs', 'bvals') + >>> fod.cmdline + 'dwi2fod -fslgrad bvecs bvals csd dwi.mif wm.txt wm.mif' + >>> fod.run() # doctest: +SKIP + """ + + input_spec = ConstrainedSphericalDeconvolutionInputSpec diff --git a/nipype/interfaces/mrtrix3/tests/__init__.py b/nipype/interfaces/mrtrix3/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/mrtrix3/tests/__init__.py +++ b/nipype/interfaces/mrtrix3/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ACTPrepareFSL.py b/nipype/interfaces/mrtrix3/tests/test_auto_ACTPrepareFSL.py index 8064175d65..a9334f5412 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_ACTPrepareFSL.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ACTPrepareFSL.py @@ -4,11 +4,25 @@ def test_ACTPrepareFSL_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, ), ) inputs = ACTPrepareFSL.input_spec() @@ -19,7 +33,11 @@ def test_ACTPrepareFSL_inputs(): def test_ACTPrepareFSL_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ACTPrepareFSL.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_BrainMask.py b/nipype/interfaces/mrtrix3/tests/test_auto_BrainMask.py index c7ce6cc9af..26f94fcab0 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_BrainMask.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_BrainMask.py @@ -4,17 +4,55 @@ def test_BrainMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, ), ) inputs = BrainMask.input_spec() @@ -25,7 +63,11 @@ def test_BrainMask_inputs(): def test_BrainMask_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BrainMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_BuildConnectome.py b/nipype/interfaces/mrtrix3/tests/test_auto_BuildConnectome.py index 95aae6fc03..bfb0b1f0c9 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_BuildConnectome.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_BuildConnectome.py @@ -4,23 +4,64 @@ def test_BuildConnectome_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - in_parc=dict(argstr="%s", extensions=None, position=-2,), - in_scalar=dict(argstr="-image %s", extensions=None,), - in_weights=dict(argstr="-tck_weights_in %s", extensions=None,), - keep_unassigned=dict(argstr="-keep_unassigned",), - metric=dict(argstr="-metric %s",), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + in_parc=dict( + argstr="%s", + extensions=None, + position=-2, + ), + in_scalar=dict( + argstr="-image %s", + extensions=None, + ), + in_weights=dict( + argstr="-tck_weights_in %s", + extensions=None, + ), + keep_unassigned=dict( + argstr="-keep_unassigned", + ), + metric=dict( + argstr="-metric %s", + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + search_forward=dict( + argstr="-assignment_forward_search %f", + ), + search_radius=dict( + argstr="-assignment_radial_search %f", + ), + search_reverse=dict( + argstr="-assignment_reverse_search %f", + ), + vox_lookup=dict( + argstr="-assignment_voxel_lookup", + ), + zero_diagonal=dict( + argstr="-zero_diagonal", ), - search_forward=dict(argstr="-assignment_forward_search %f",), - search_radius=dict(argstr="-assignment_radial_search %f",), - search_reverse=dict(argstr="-assignment_reverse_search %f",), - vox_lookup=dict(argstr="-assignment_voxel_lookup",), - zero_diagonal=dict(argstr="-zero_diagonal",), ) inputs = BuildConnectome.input_spec() @@ -30,7 +71,11 @@ def test_BuildConnectome_inputs(): def test_BuildConnectome_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BuildConnectome.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ComputeTDI.py b/nipype/interfaces/mrtrix3/tests/test_auto_ComputeTDI.py index f6a8734cef..ab1d984425 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_ComputeTDI.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ComputeTDI.py @@ -4,27 +4,82 @@ def test_ComputeTDI_inputs(): input_map = dict( - args=dict(argstr="%s",), - contrast=dict(argstr="-constrast %s",), - data_type=dict(argstr="-datatype %s",), - dixel=dict(argstr="-dixel %s", extensions=None,), - ends_only=dict(argstr="-ends_only",), - environ=dict(nohash=True, usedefault=True,), - fwhm_tck=dict(argstr="-fwhm_tck %f",), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - in_map=dict(argstr="-image %s", extensions=None,), - map_zero=dict(argstr="-map_zero",), - max_tod=dict(argstr="-tod %d",), - nthreads=dict(argstr="-nthreads %d", nohash=True,), - out_file=dict(argstr="%s", extensions=None, position=-1, usedefault=True,), - precise=dict(argstr="-precise",), - reference=dict(argstr="-template %s", extensions=None,), - stat_tck=dict(argstr="-stat_tck %s",), - stat_vox=dict(argstr="-stat_vox %s",), - tck_weights=dict(argstr="-tck_weights_in %s", extensions=None,), - upsample=dict(argstr="-upsample %d",), - use_dec=dict(argstr="-dec",), - vox_size=dict(argstr="-vox %s", sep=",",), + args=dict( + argstr="%s", + ), + contrast=dict( + argstr="-constrast %s", + ), + data_type=dict( + argstr="-datatype %s", + ), + dixel=dict( + argstr="-dixel %s", + extensions=None, + ), + ends_only=dict( + argstr="-ends_only", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm_tck=dict( + argstr="-fwhm_tck %f", + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + in_map=dict( + argstr="-image %s", + extensions=None, + ), + map_zero=dict( + argstr="-map_zero", + ), + max_tod=dict( + argstr="-tod %d", + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + position=-1, + usedefault=True, + ), + precise=dict( + argstr="-precise", + ), + reference=dict( + argstr="-template %s", + extensions=None, + ), + stat_tck=dict( + argstr="-stat_tck %s", + ), + stat_vox=dict( + argstr="-stat_vox %s", + ), + tck_weights=dict( + argstr="-tck_weights_in %s", + extensions=None, + ), + upsample=dict( + argstr="-upsample %d", + ), + use_dec=dict( + argstr="-dec", + ), + vox_size=dict( + argstr="-vox %s", + sep=",", + ), ) inputs = ComputeTDI.input_spec() @@ -34,7 +89,11 @@ def test_ComputeTDI_inputs(): def test_ComputeTDI_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ComputeTDI.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ConstrainedSphericalDeconvolution.py b/nipype/interfaces/mrtrix3/tests/test_auto_ConstrainedSphericalDeconvolution.py new file mode 100644 index 0000000000..1348326728 --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ConstrainedSphericalDeconvolution.py @@ -0,0 +1,138 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..reconst import ConstrainedSphericalDeconvolution + + +def test_ConstrainedSphericalDeconvolution_inputs(): + input_map = dict( + algorithm=dict( + argstr="%s", + mandatory=True, + position=-8, + ), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + csf_odf=dict( + argstr="%s", + extensions=None, + position=-1, + ), + csf_txt=dict( + argstr="%s", + extensions=None, + position=-2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gm_odf=dict( + argstr="%s", + extensions=None, + position=-3, + ), + gm_txt=dict( + argstr="%s", + extensions=None, + position=-4, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_dirs=dict( + argstr="-directions %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-7, + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + max_sh=dict( + argstr="-lmax %s", + sep=",", + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + predicted_signal=dict( + argstr="-predicted_signal %s", + extensions=None, + ), + shell=dict( + argstr="-shell %s", + sep=",", + ), + wm_odf=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-5, + usedefault=True, + ), + wm_txt=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-6, + ), + ) + inputs = ConstrainedSphericalDeconvolution.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_ConstrainedSphericalDeconvolution_outputs(): + output_map = dict( + csf_odf=dict( + argstr="%s", + extensions=None, + ), + gm_odf=dict( + argstr="%s", + extensions=None, + ), + predicted_signal=dict( + extensions=None, + ), + wm_odf=dict( + argstr="%s", + extensions=None, + ), + ) + outputs = ConstrainedSphericalDeconvolution.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_DWIBiasCorrect.py b/nipype/interfaces/mrtrix3/tests/test_auto_DWIBiasCorrect.py index 210b39b141..82beccfa9d 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_DWIBiasCorrect.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_DWIBiasCorrect.py @@ -4,17 +4,57 @@ def test_DWIBiasCorrect_inputs(): input_map = dict( - args=dict(argstr="%s",), - bias=dict(argstr="-bias %s", extensions=None,), - bval_scale=dict(argstr="-bvalue_scaling %s",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - in_mask=dict(argstr="-mask %s", extensions=None,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + args=dict( + argstr="%s", + ), + bias=dict( + argstr="-bias %s", + extensions=None, + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + in_mask=dict( + argstr="-mask %s", + extensions=None, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), out_file=dict( argstr="%s", extensions=None, @@ -24,8 +64,18 @@ def test_DWIBiasCorrect_inputs(): name_template="%s_biascorr", position=-1, ), - use_ants=dict(argstr="-ants", mandatory=True, xor=["use_fsl"],), - use_fsl=dict(argstr="-fsl", mandatory=True, xor=["use_ants"],), + use_ants=dict( + argstr="ants", + mandatory=True, + position=0, + xor=["use_fsl"], + ), + use_fsl=dict( + argstr="fsl", + mandatory=True, + position=0, + xor=["use_ants"], + ), ) inputs = DWIBiasCorrect.input_spec() @@ -35,7 +85,14 @@ def test_DWIBiasCorrect_inputs(): def test_DWIBiasCorrect_outputs(): - output_map = dict(bias=dict(extensions=None,), out_file=dict(extensions=None,),) + output_map = dict( + bias=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + ) outputs = DWIBiasCorrect.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_DWIDenoise.py b/nipype/interfaces/mrtrix3/tests/test_auto_DWIDenoise.py index d5050327aa..edd2ee254d 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_DWIDenoise.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_DWIDenoise.py @@ -4,16 +4,46 @@ def test_DWIDenoise_inputs(): input_map = dict( - args=dict(argstr="%s",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - environ=dict(nohash=True, usedefault=True,), - extent=dict(argstr="-extent %d,%d,%d",), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - mask=dict(argstr="-mask %s", extensions=None, position=1,), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + extent=dict( + argstr="-extent %d,%d,%d", + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + position=1, + ), noise=dict( argstr="-noise %s", extensions=None, @@ -21,7 +51,17 @@ def test_DWIDenoise_inputs(): name_source="in_file", name_template="%s_noise", ), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), out_file=dict( argstr="%s", extensions=None, @@ -39,7 +79,14 @@ def test_DWIDenoise_inputs(): def test_DWIDenoise_outputs(): - output_map = dict(noise=dict(extensions=None,), out_file=dict(extensions=None,),) + output_map = dict( + noise=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + ) outputs = DWIDenoise.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_DWIExtract.py b/nipype/interfaces/mrtrix3/tests/test_auto_DWIExtract.py index 18fa49c260..a2d05a6fdc 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_DWIExtract.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_DWIExtract.py @@ -4,20 +4,68 @@ def test_DWIExtract_inputs(): input_map = dict( - args=dict(argstr="%s",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - bzero=dict(argstr="-bzero",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - nobzero=dict(argstr="-no_bzero",), - nthreads=dict(argstr="-nthreads %d", nohash=True,), - out_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - shell=dict(argstr="-shell %s", sep=",",), - singleshell=dict(argstr="-singleshell",), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + bzero=dict( + argstr="-bzero", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + nobzero=dict( + argstr="-no_bzero", + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + shell=dict( + argstr="-shell %s", + sep=",", + ), + singleshell=dict( + argstr="-singleshell", + ), ) inputs = DWIExtract.input_spec() @@ -27,7 +75,11 @@ def test_DWIExtract_inputs(): def test_DWIExtract_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = DWIExtract.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_DWIPreproc.py b/nipype/interfaces/mrtrix3/tests/test_auto_DWIPreproc.py new file mode 100644 index 0000000000..7c0231bd70 --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_DWIPreproc.py @@ -0,0 +1,140 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..preprocess import DWIPreproc + + +def test_DWIPreproc_inputs(): + input_map = dict( + align_seepi=dict( + argstr="-align_seepi", + ), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + eddy_mask=dict( + argstr="-eddy_mask %s", + extensions=None, + ), + eddy_options=dict( + argstr='-eddy_options "%s"', + ), + eddy_slspec=dict( + argstr="-eddy_slspec %s", + extensions=None, + ), + eddyqc_all=dict( + argstr="-eddyqc_all %s", + ), + eddyqc_text=dict( + argstr="-eddyqc_text %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_epi=dict( + argstr="-se_epi %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + json_import=dict( + argstr="-json_import %s", + extensions=None, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + usedefault=True, + ), + out_grad_fsl=dict( + argstr="-export_grad_fsl %s, %s", + ), + out_grad_mrtrix=dict( + argstr="-export_grad_mrtrix %s", + extensions=None, + ), + pe_dir=dict( + argstr="-pe_dir %s", + ), + ro_time=dict( + argstr="-readout_time %f", + ), + rpe_options=dict( + argstr="-rpe_%s", + mandatory=True, + position=2, + ), + topup_options=dict( + argstr='-topup_options "%s"', + ), + ) + inputs = DWIPreproc.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_DWIPreproc_outputs(): + output_map = dict( + out_file=dict( + argstr="%s", + extensions=None, + ), + out_fsl_bval=dict( + argstr="%s", + extensions=None, + usedefault=True, + ), + out_fsl_bvec=dict( + argstr="%s", + extensions=None, + usedefault=True, + ), + out_grad_mrtrix=dict( + argstr="%s", + extensions=None, + usedefault=True, + ), + ) + outputs = DWIPreproc.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_EstimateFOD.py b/nipype/interfaces/mrtrix3/tests/test_auto_EstimateFOD.py index bfadae423f..378dd4a220 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_EstimateFOD.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_EstimateFOD.py @@ -4,28 +4,110 @@ def test_EstimateFOD_inputs(): input_map = dict( - algorithm=dict(argstr="%s", mandatory=True, position=-8,), - args=dict(argstr="%s",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - csf_odf=dict(argstr="%s", extensions=None, position=-1, usedefault=True,), - csf_txt=dict(argstr="%s", extensions=None, position=-2,), - environ=dict(nohash=True, usedefault=True,), - gm_odf=dict(argstr="%s", extensions=None, position=-3, usedefault=True,), - gm_txt=dict(argstr="%s", extensions=None, position=-4,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_dirs=dict(argstr="-directions %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-7,), - mask_file=dict(argstr="-mask %s", extensions=None,), - max_sh=dict(argstr="-lmax %s", sep=",", usedefault=True,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), - shell=dict(argstr="-shell %s", sep=",",), + algorithm=dict( + argstr="%s", + mandatory=True, + position=-8, + ), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + csf_odf=dict( + argstr="%s", + extensions=None, + position=-1, + usedefault=True, + ), + csf_txt=dict( + argstr="%s", + extensions=None, + position=-2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gm_odf=dict( + argstr="%s", + extensions=None, + position=-3, + usedefault=True, + ), + gm_txt=dict( + argstr="%s", + extensions=None, + position=-4, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_dirs=dict( + argstr="-directions %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-7, + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + max_sh=dict( + argstr="-lmax %s", + sep=",", + usedefault=True, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + predicted_signal=dict( + argstr="-predicted_signal %s", + extensions=None, + ), + shell=dict( + argstr="-shell %s", + sep=",", + ), wm_odf=dict( - argstr="%s", extensions=None, mandatory=True, position=-5, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-5, + usedefault=True, + ), + wm_txt=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-6, ), - wm_txt=dict(argstr="%s", extensions=None, mandatory=True, position=-6,), ) inputs = EstimateFOD.input_spec() @@ -36,9 +118,21 @@ def test_EstimateFOD_inputs(): def test_EstimateFOD_outputs(): output_map = dict( - csf_odf=dict(argstr="%s", extensions=None,), - gm_odf=dict(argstr="%s", extensions=None,), - wm_odf=dict(argstr="%s", extensions=None,), + csf_odf=dict( + argstr="%s", + extensions=None, + ), + gm_odf=dict( + argstr="%s", + extensions=None, + ), + predicted_signal=dict( + extensions=None, + ), + wm_odf=dict( + argstr="%s", + extensions=None, + ), ) outputs = EstimateFOD.output_spec() diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_FitTensor.py b/nipype/interfaces/mrtrix3/tests/test_auto_FitTensor.py index d586dbaf59..884b87be06 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_FitTensor.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_FitTensor.py @@ -4,21 +4,71 @@ def test_FitTensor_inputs(): input_map = dict( - args=dict(argstr="%s",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - in_mask=dict(argstr="-mask %s", extensions=None,), - method=dict(argstr="-method %s",), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + in_mask=dict( + argstr="-mask %s", + extensions=None, + ), + method=dict( + argstr="-method %s", + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + predicted_signal=dict( + argstr="-predicted_signal %s", + extensions=None, + ), + reg_term=dict( + argstr="-regularisation %f", + max_ver="0.3.13", ), - reg_term=dict(argstr="-regularisation %f", max_ver="0.3.13",), ) inputs = FitTensor.input_spec() @@ -28,7 +78,14 @@ def test_FitTensor_inputs(): def test_FitTensor_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + predicted_signal=dict( + extensions=None, + ), + ) outputs = FitTensor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt.py b/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt.py index d41fd52a11..d8f6e53364 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt.py @@ -4,17 +4,90 @@ def test_Generate5tt_inputs(): input_map = dict( - algorithm=dict(argstr="%s", mandatory=True, position=-3,), - args=dict(argstr="%s",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), - out_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), + algorithm=dict( + argstr="%s", + mandatory=True, + position=-3, + ), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + hippocampi=dict( + argstr="-hippocampi %s", + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + lut_file=dict( + argstr="-lut %s", + extensions=None, + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + nocrop=dict( + argstr="-nocrop", + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + premasked=dict( + argstr="-premasked", + ), + sgm_amyg_hipp=dict( + argstr="-sgm_amyg_hipp", + ), + t2_image=dict( + argstr="-t2 %s", + extensions=None, + ), + template=dict( + argstr="-template %s", + extensions=None, + ), + white_stem=dict( + argstr="-white_stem", + ), ) inputs = Generate5tt.input_spec() @@ -24,7 +97,11 @@ def test_Generate5tt_inputs(): def test_Generate5tt_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Generate5tt.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt2gmwmi.py b/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt2gmwmi.py new file mode 100644 index 0000000000..2f4fc24e5d --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_Generate5tt2gmwmi.py @@ -0,0 +1,79 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import Generate5tt2gmwmi + + +def test_Generate5tt2gmwmi_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + mask_in=dict( + argstr="-mask_in %s", + extensions=None, + position=-3, + ), + mask_out=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + ) + inputs = Generate5tt2gmwmi.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_Generate5tt2gmwmi_outputs(): + output_map = dict( + mask_out=dict( + extensions=None, + ), + ) + outputs = Generate5tt2gmwmi.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_LabelConfig.py b/nipype/interfaces/mrtrix3/tests/test_auto_LabelConfig.py index 2c37a6bc93..15116f9bb8 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_LabelConfig.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_LabelConfig.py @@ -4,19 +4,55 @@ def test_LabelConfig_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_config=dict(argstr="%s", extensions=None, position=-2,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - lut_aal=dict(argstr="-lut_aal %s", extensions=None,), - lut_basic=dict(argstr="-lut_basic %s", extensions=None,), - lut_fs=dict(argstr="-lut_freesurfer %s", extensions=None,), - lut_itksnap=dict(argstr="-lut_itksnap %s", extensions=None,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_config=dict( + argstr="%s", + extensions=None, + position=-2, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + lut_aal=dict( + argstr="-lut_aal %s", + extensions=None, + ), + lut_basic=dict( + argstr="-lut_basic %s", + extensions=None, + ), + lut_fs=dict( + argstr="-lut_freesurfer %s", + extensions=None, + ), + lut_itksnap=dict( + argstr="-lut_itksnap %s", + extensions=None, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + spine=dict( + argstr="-spine %s", + extensions=None, ), - spine=dict(argstr="-spine %s", extensions=None,), ) inputs = LabelConfig.input_spec() @@ -26,7 +62,11 @@ def test_LabelConfig_inputs(): def test_LabelConfig_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = LabelConfig.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_LabelConvert.py b/nipype/interfaces/mrtrix3/tests/test_auto_LabelConvert.py index 9db9bb4df5..98512ac317 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_LabelConvert.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_LabelConvert.py @@ -4,16 +4,45 @@ def test_LabelConvert_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_config=dict(argstr="%s", extensions=None, position=-2,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-4,), - in_lut=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - num_threads=dict(argstr="-nthreads %d", nohash=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_config=dict( + argstr="%s", + extensions=None, + position=-2, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-4, + ), + in_lut=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + num_threads=dict( + argstr="-nthreads %d", + nohash=True, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + spine=dict( + argstr="-spine %s", + extensions=None, ), - spine=dict(argstr="-spine %s", extensions=None,), ) inputs = LabelConvert.input_spec() @@ -23,7 +52,11 @@ def test_LabelConvert_inputs(): def test_LabelConvert_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = LabelConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRCat.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRCat.py new file mode 100644 index 0000000000..25bfea5d37 --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRCat.py @@ -0,0 +1,80 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import MRCat + + +def test_MRCat_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + axis=dict( + argstr="-axis %s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + datatype=dict( + argstr="-datatype %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + ) + inputs = MRCat.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_MRCat_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = MRCat.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRConvert.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRConvert.py index 2440113e20..0cd3c95794 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_MRConvert.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRConvert.py @@ -4,22 +4,82 @@ def test_MRConvert_inputs(): input_map = dict( - args=dict(argstr="%s",), - axes=dict(argstr="-axes %s", sep=",",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - coord=dict(argstr="-coord %s", sep=" ",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + args=dict( + argstr="%s", + ), + axes=dict( + argstr="-axes %s", + sep=",", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + coord=dict( + argstr="-coord %s", + sep=" ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + json_export=dict( + argstr="-json_export %s", + extensions=None, + mandatory=False, + ), + json_import=dict( + argstr="-json_import %s", + extensions=None, + mandatory=False, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + scaling=dict( + argstr="-scaling %s", + sep=",", + ), + vox=dict( + argstr="-vox %s", + sep=",", ), - scaling=dict(argstr="-scaling %s", sep=",",), - vox=dict(argstr="-vox %s", sep=",",), ) inputs = MRConvert.input_spec() @@ -29,7 +89,20 @@ def test_MRConvert_inputs(): def test_MRConvert_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + json_export=dict( + extensions=None, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + ) outputs = MRConvert.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRDeGibbs.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRDeGibbs.py index 439e834eb2..83f5bfef4b 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_MRDeGibbs.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRDeGibbs.py @@ -4,19 +4,66 @@ def test_MRDeGibbs_inputs(): input_map = dict( - args=dict(argstr="%s",), - axes=dict(argstr="-axes %s", maxlen=2, minlen=2, sep=",", usedefault=True,), - bval_scale=dict(argstr="-bvalue_scaling %s",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - maxW=dict(argstr="-maxW %d", usedefault=True,), - minW=dict(argstr="-minW %d", usedefault=True,), - nshifts=dict(argstr="-nshifts %d", usedefault=True,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + args=dict( + argstr="%s", + ), + axes=dict( + argstr="-axes %s", + sep=",", + usedefault=True, + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + maxW=dict( + argstr="-maxW %d", + usedefault=True, + ), + minW=dict( + argstr="-minW %d", + usedefault=True, + ), + nshifts=dict( + argstr="-nshifts %d", + usedefault=True, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), out_file=dict( argstr="%s", extensions=None, @@ -34,7 +81,11 @@ def test_MRDeGibbs_inputs(): def test_MRDeGibbs_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRDeGibbs.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRMath.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRMath.py index 33f9c82d22..10470bea7a 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_MRMath.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRMath.py @@ -4,18 +4,63 @@ def test_MRMath_inputs(): input_map = dict( - args=dict(argstr="%s",), - axis=dict(argstr="-axis %d",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), - operation=dict(argstr="%s", mandatory=True, position=-2,), - out_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), + args=dict( + argstr="%s", + ), + axis=dict( + argstr="-axis %d", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + operation=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), ) inputs = MRMath.input_spec() @@ -25,7 +70,11 @@ def test_MRMath_inputs(): def test_MRMath_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRMath.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRResize.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRResize.py index cf41dfe856..4728309194 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_MRResize.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRResize.py @@ -4,19 +4,58 @@ def test_MRResize_inputs(): input_map = dict( - args=dict(argstr="%s",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), image_size=dict( - argstr="-size %d,%d,%d", mandatory=True, xor=["voxel_size", "scale_factor"], + argstr="-size %d,%d,%d", + mandatory=True, + xor=["voxel_size", "scale_factor"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + interpolation=dict( + argstr="-interp %s", + usedefault=True, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, ), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - interpolation=dict(argstr="-interp %s", usedefault=True,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), out_file=dict( argstr="%s", extensions=None, @@ -26,7 +65,9 @@ def test_MRResize_inputs(): position=-1, ), scale_factor=dict( - argstr="-scale %g,%g,%g", mandatory=True, xor=["image_size", "voxel_size"], + argstr="-scale %g,%g,%g", + mandatory=True, + xor=["image_size", "voxel_size"], ), voxel_size=dict( argstr="-voxel %g,%g,%g", @@ -42,7 +83,11 @@ def test_MRResize_inputs(): def test_MRResize_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MRResize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRTransform.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRTransform.py new file mode 100644 index 0000000000..e0337da2a9 --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRTransform.py @@ -0,0 +1,104 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import MRTransform + + +def test_MRTransform_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + debug=dict( + argstr="-debug", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flip_x=dict( + argstr="-flipx", + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_files=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + invert=dict( + argstr="-inverse", + ), + linear_transform=dict( + argstr="-linear %s", + extensions=None, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + quiet=dict( + argstr="-quiet", + ), + reference_image=dict( + argstr="-reference %s", + extensions=None, + ), + replace_transform=dict( + argstr="-replace", + ), + template_image=dict( + argstr="-template %s", + extensions=None, + ), + transformation_file=dict( + argstr="-transform %s", + extensions=None, + ), + ) + inputs = MRTransform.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_MRTransform_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = MRTransform.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MRTrix3Base.py b/nipype/interfaces/mrtrix3/tests/test_auto_MRTrix3Base.py index a5042e58d9..7689f14f11 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_MRTrix3Base.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MRTrix3Base.py @@ -4,7 +4,13 @@ def test_MRTrix3Base_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = MRTrix3Base.input_spec() diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MTNormalise.py b/nipype/interfaces/mrtrix3/tests/test_auto_MTNormalise.py new file mode 100644 index 0000000000..8463e5a64a --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MTNormalise.py @@ -0,0 +1,103 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import MTNormalise + + +def test_MTNormalise_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + csf_fod=dict( + argstr="%s", + extensions=None, + position=5, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gm_fod=dict( + argstr="%s", + extensions=None, + position=3, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + position=-1, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_file_csf=dict( + argstr="%s", + extensions=None, + position=6, + ), + out_file_gm=dict( + argstr="%s", + extensions=None, + position=4, + ), + out_file_wm=dict( + argstr="%s", + extensions=None, + position=2, + ), + wm_fod=dict( + argstr="%s", + extensions=None, + position=1, + ), + ) + inputs = MTNormalise.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_MTNormalise_outputs(): + output_map = dict( + out_file_csf=dict( + extensions=None, + ), + out_file_gm=dict( + extensions=None, + ), + out_file_wm=dict( + extensions=None, + ), + ) + outputs = MTNormalise.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_MaskFilter.py b/nipype/interfaces/mrtrix3/tests/test_auto_MaskFilter.py new file mode 100644 index 0000000000..5443c09e15 --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_MaskFilter.py @@ -0,0 +1,54 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import MaskFilter + + +def test_MaskFilter_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filter=dict( + argstr="%s", + mandatory=True, + position=-2, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + npass=dict( + argstr="-npass %d", + position=1, + ), + out_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + name_source=["input_image"], + position=-1, + ), + ) + inputs = MaskFilter.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_MaskFilter_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = MaskFilter.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_Mesh2PVE.py b/nipype/interfaces/mrtrix3/tests/test_auto_Mesh2PVE.py index 602d3c0228..0fd63be8af 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_Mesh2PVE.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_Mesh2PVE.py @@ -4,14 +4,36 @@ def test_Mesh2PVE_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), - in_first=dict(argstr="-first %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + in_first=dict( + argstr="-first %s", + extensions=None, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + reference=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, ), - reference=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), ) inputs = Mesh2PVE.input_spec() @@ -21,7 +43,11 @@ def test_Mesh2PVE_inputs(): def test_Mesh2PVE_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Mesh2PVE.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ReplaceFSwithFIRST.py b/nipype/interfaces/mrtrix3/tests/test_auto_ReplaceFSwithFIRST.py index 802f2fd64a..ef3053cede 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_ReplaceFSwithFIRST.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ReplaceFSwithFIRST.py @@ -4,13 +4,36 @@ def test_ReplaceFSwithFIRST_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_config=dict(argstr="%s", extensions=None, position=-2,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-4,), - in_t1w=dict(argstr="%s", extensions=None, mandatory=True, position=-3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_config=dict( + argstr="%s", + extensions=None, + position=-2, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-4, + ), + in_t1w=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, ), ) inputs = ReplaceFSwithFIRST.input_spec() @@ -21,7 +44,11 @@ def test_ReplaceFSwithFIRST_inputs(): def test_ReplaceFSwithFIRST_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ReplaceFSwithFIRST.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_ResponseSD.py b/nipype/interfaces/mrtrix3/tests/test_auto_ResponseSD.py index b35f6529e7..1b9d4db9b9 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_ResponseSD.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_ResponseSD.py @@ -4,22 +4,83 @@ def test_ResponseSD_inputs(): input_map = dict( - algorithm=dict(argstr="%s", mandatory=True, position=1,), - args=dict(argstr="%s",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - csf_file=dict(argstr="%s", extensions=None, position=-1,), - environ=dict(nohash=True, usedefault=True,), - gm_file=dict(argstr="%s", extensions=None, position=-2,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-5,), - in_mask=dict(argstr="-mask %s", extensions=None,), - max_sh=dict(argstr="-lmax %s", sep=",",), - mtt_file=dict(argstr="%s", extensions=None, position=-4,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), - wm_file=dict(argstr="%s", extensions=None, position=-3, usedefault=True,), + algorithm=dict( + argstr="%s", + mandatory=True, + position=1, + ), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + csf_file=dict( + argstr="%s", + extensions=None, + position=-1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gm_file=dict( + argstr="%s", + extensions=None, + position=-2, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-5, + ), + in_mask=dict( + argstr="-mask %s", + extensions=None, + ), + max_sh=dict( + argstr="-lmax %s", + sep=",", + ), + mtt_file=dict( + argstr="%s", + extensions=None, + position=-4, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + wm_file=dict( + argstr="%s", + extensions=None, + position=-3, + usedefault=True, + ), ) inputs = ResponseSD.input_spec() @@ -30,9 +91,18 @@ def test_ResponseSD_inputs(): def test_ResponseSD_outputs(): output_map = dict( - csf_file=dict(argstr="%s", extensions=None,), - gm_file=dict(argstr="%s", extensions=None,), - wm_file=dict(argstr="%s", extensions=None,), + csf_file=dict( + argstr="%s", + extensions=None, + ), + gm_file=dict( + argstr="%s", + extensions=None, + ), + wm_file=dict( + argstr="%s", + extensions=None, + ), ) outputs = ResponseSD.output_spec() diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_SH2Amp.py b/nipype/interfaces/mrtrix3/tests/test_auto_SH2Amp.py new file mode 100644 index 0000000000..ab75fc1f8a --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_SH2Amp.py @@ -0,0 +1,55 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import SH2Amp + + +def test_SH2Amp_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + directions=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + nonnegative=dict( + argstr="-nonnegative", + ), + out_file=dict( + argstr="%s", + extensions=None, + name_source=["in_file"], + name_template="%s_amp.mif", + position=-1, + usedefault=True, + ), + ) + inputs = SH2Amp.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_SH2Amp_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = SH2Amp.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_SHConv.py b/nipype/interfaces/mrtrix3/tests/test_auto_SHConv.py new file mode 100644 index 0000000000..992e6984a8 --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_SHConv.py @@ -0,0 +1,52 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import SHConv + + +def test_SHConv_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-3, + ), + out_file=dict( + argstr="%s", + extensions=None, + name_source=["in_file"], + name_template="%s_shconv.mif", + position=-1, + usedefault=True, + ), + response=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + ) + inputs = SHConv.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_SHConv_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + ) + outputs = SHConv.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_TCK2VTK.py b/nipype/interfaces/mrtrix3/tests/test_auto_TCK2VTK.py index 2c72dee012..215dafedc0 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_TCK2VTK.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_TCK2VTK.py @@ -4,13 +4,37 @@ def test_TCK2VTK_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - nthreads=dict(argstr="-nthreads %d", nohash=True,), - out_file=dict(argstr="%s", extensions=None, position=-1, usedefault=True,), - reference=dict(argstr="-image %s", extensions=None,), - voxel=dict(argstr="-image %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + position=-1, + usedefault=True, + ), + reference=dict( + argstr="-image %s", + extensions=None, + ), + voxel=dict( + argstr="-image %s", + extensions=None, + ), ) inputs = TCK2VTK.input_spec() @@ -20,7 +44,11 @@ def test_TCK2VTK_inputs(): def test_TCK2VTK_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TCK2VTK.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_TensorMetrics.py b/nipype/interfaces/mrtrix3/tests/test_auto_TensorMetrics.py index be6736cecb..28c33b0796 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_TensorMetrics.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_TensorMetrics.py @@ -4,16 +4,97 @@ def test_TensorMetrics_inputs(): input_map = dict( - args=dict(argstr="%s",), - component=dict(argstr="-num %s", sep=",", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-1,), - in_mask=dict(argstr="-mask %s", extensions=None,), - modulate=dict(argstr="-modulate %s",), - out_adc=dict(argstr="-adc %s", extensions=None,), - out_eval=dict(argstr="-value %s", extensions=None,), - out_evec=dict(argstr="-vector %s", extensions=None,), - out_fa=dict(argstr="-fa %s", extensions=None,), + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + component=dict( + argstr="-num %s", + sep=",", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + ), + in_mask=dict( + argstr="-mask %s", + extensions=None, + ), + modulate=dict( + argstr="-modulate %s", + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_ad=dict( + argstr="-ad %s", + extensions=None, + ), + out_adc=dict( + argstr="-adc %s", + extensions=None, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_cl=dict( + argstr="-cl %s", + extensions=None, + ), + out_cp=dict( + argstr="-cp %s", + extensions=None, + ), + out_cs=dict( + argstr="-cs %s", + extensions=None, + ), + out_eval=dict( + argstr="-value %s", + extensions=None, + ), + out_evec=dict( + argstr="-vector %s", + extensions=None, + ), + out_fa=dict( + argstr="-fa %s", + extensions=None, + ), + out_rd=dict( + argstr="-rd %s", + extensions=None, + ), ) inputs = TensorMetrics.input_spec() @@ -24,10 +105,33 @@ def test_TensorMetrics_inputs(): def test_TensorMetrics_outputs(): output_map = dict( - out_adc=dict(extensions=None,), - out_eval=dict(extensions=None,), - out_evec=dict(extensions=None,), - out_fa=dict(extensions=None,), + out_ad=dict( + extensions=None, + ), + out_adc=dict( + extensions=None, + ), + out_cl=dict( + extensions=None, + ), + out_cp=dict( + extensions=None, + ), + out_cs=dict( + extensions=None, + ), + out_eval=dict( + extensions=None, + ), + out_evec=dict( + extensions=None, + ), + out_fa=dict( + extensions=None, + ), + out_rd=dict( + extensions=None, + ), ) outputs = TensorMetrics.output_spec() diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_Tractography.py b/nipype/interfaces/mrtrix3/tests/test_auto_Tractography.py index 9c1b51d363..87fac016f3 100644 --- a/nipype/interfaces/mrtrix3/tests/test_auto_Tractography.py +++ b/nipype/interfaces/mrtrix3/tests/test_auto_Tractography.py @@ -4,60 +4,175 @@ def test_Tractography_inputs(): input_map = dict( - act_file=dict(argstr="-act %s", extensions=None,), - algorithm=dict(argstr="-algorithm %s", usedefault=True,), - angle=dict(argstr="-angle %f",), - args=dict(argstr="%s",), - backtrack=dict(argstr="-backtrack",), - bval_scale=dict(argstr="-bvalue_scaling %s",), - crop_at_gmwmi=dict(argstr="-crop_at_gmwmi",), - cutoff=dict(argstr="-cutoff %f",), - cutoff_init=dict(argstr="-initcutoff %f",), - downsample=dict(argstr="-downsample %f",), - environ=dict(nohash=True, usedefault=True,), - grad_file=dict(argstr="-grad %s", extensions=None, xor=["grad_fsl"],), - grad_fsl=dict(argstr="-fslgrad %s %s", xor=["grad_file"],), - in_bval=dict(extensions=None,), - in_bvec=dict(argstr="-fslgrad %s %s", extensions=None,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=-2,), - init_dir=dict(argstr="-initdirection %f,%f,%f",), - max_length=dict(argstr="-maxlength %f",), - max_seed_attempts=dict(argstr="-max_seed_attempts %d",), - max_tracks=dict(argstr="-maxnum %d",), - min_length=dict(argstr="-minlength %f",), - n_samples=dict(argstr="-samples %d", usedefault=True,), - n_tracks=dict(argstr="-number %d", max_ver="0.4",), - n_trials=dict(argstr="-trials %d",), - noprecompt=dict(argstr="-noprecomputed",), - nthreads=dict(argstr="-nthreads %d", nohash=True,), + act_file=dict( + argstr="-act %s", + extensions=None, + ), + algorithm=dict( + argstr="-algorithm %s", + usedefault=True, + ), + angle=dict( + argstr="-angle %f", + ), + args=dict( + argstr="%s", + ), + backtrack=dict( + argstr="-backtrack", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + crop_at_gmwmi=dict( + argstr="-crop_at_gmwmi", + ), + cutoff=dict( + argstr="-cutoff %f", + ), + cutoff_init=dict( + argstr="-initcutoff %f", + ), + downsample=dict( + argstr="-downsample %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-2, + ), + init_dir=dict( + argstr="-initdirection %f,%f,%f", + ), + max_length=dict( + argstr="-maxlength %f", + ), + max_seed_attempts=dict( + argstr="-max_seed_attempts %d", + ), + max_tracks=dict( + argstr="-maxnum %d", + ), + min_length=dict( + argstr="-minlength %f", + ), + n_samples=dict( + argstr="-samples %d", + usedefault=True, + ), + n_tracks=dict( + argstr="-number %d", + max_ver="0.4", + ), + n_trials=dict( + argstr="-trials %d", + ), + noprecompt=dict( + argstr="-noprecomputed", + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), out_file=dict( - argstr="%s", extensions=None, mandatory=True, position=-1, usedefault=True, - ), - out_seeds=dict(argstr="-output_seeds %s", extensions=None, usedefault=True,), - power=dict(argstr="-power %d",), - roi_excl=dict(argstr="-exclude %s",), - roi_incl=dict(argstr="-include %s",), - roi_mask=dict(argstr="-mask %s",), - seed_dynamic=dict(argstr="-seed_dynamic %s", extensions=None,), + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + out_seeds=dict( + argstr="-output_seeds %s", + extensions=None, + usedefault=True, + ), + power=dict( + argstr="-power %d", + ), + roi_excl=dict( + argstr="-exclude %s", + ), + roi_incl=dict( + argstr="-include %s", + ), + roi_mask=dict( + argstr="-mask %s", + ), + seed_dynamic=dict( + argstr="-seed_dynamic %s", + extensions=None, + ), seed_gmwmi=dict( - argstr="-seed_gmwmi %s", extensions=None, requires=["act_file"], + argstr="-seed_gmwmi %s", + extensions=None, + requires=["act_file"], ), seed_grid_voxel=dict( - argstr="-seed_grid_per_voxel %s %d", xor=["seed_image", "seed_rnd_voxel"], + argstr="-seed_grid_per_voxel %s %d", + xor=["seed_image", "seed_rnd_voxel"], + ), + seed_image=dict( + argstr="-seed_image %s", + extensions=None, + ), + seed_rejection=dict( + argstr="-seed_rejection %s", + extensions=None, ), - seed_image=dict(argstr="-seed_image %s", extensions=None,), - seed_rejection=dict(argstr="-seed_rejection %s", extensions=None,), seed_rnd_voxel=dict( argstr="-seed_random_per_voxel %s %d", xor=["seed_image", "seed_grid_voxel"], ), - seed_sphere=dict(argstr="-seed_sphere %f,%f,%f,%f",), - select=dict(argstr="-select %d", min_ver="3",), - sph_trait=dict(argstr="%f,%f,%f,%f",), - step_size=dict(argstr="-step %f",), - stop=dict(argstr="-stop",), - unidirectional=dict(argstr="-unidirectional",), - use_rk4=dict(argstr="-rk4",), + seed_sphere=dict( + argstr="-seed_sphere %f,%f,%f,%f", + ), + select=dict( + argstr="-select %d", + min_ver="3", + ), + sph_trait=dict( + argstr="%f,%f,%f,%f", + ), + step_size=dict( + argstr="-step %f", + ), + stop=dict( + argstr="-stop", + ), + unidirectional=dict( + argstr="-unidirectional", + ), + use_rk4=dict( + argstr="-rk4", + ), ) inputs = Tractography.input_spec() @@ -68,7 +183,12 @@ def test_Tractography_inputs(): def test_Tractography_outputs(): output_map = dict( - out_file=dict(extensions=None,), out_seeds=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + out_seeds=dict( + extensions=None, + ), ) outputs = Tractography.output_spec() diff --git a/nipype/interfaces/mrtrix3/tests/test_auto_TransformFSLConvert.py b/nipype/interfaces/mrtrix3/tests/test_auto_TransformFSLConvert.py new file mode 100644 index 0000000000..48a528a75e --- /dev/null +++ b/nipype/interfaces/mrtrix3/tests/test_auto_TransformFSLConvert.py @@ -0,0 +1,93 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..utils import TransformFSLConvert + + +def test_TransformFSLConvert_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + bval_scale=dict( + argstr="-bvalue_scaling %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flirt_import=dict( + argstr="flirt_import", + mandatory=True, + position=-2, + usedefault=True, + ), + grad_file=dict( + argstr="-grad %s", + extensions=None, + xor=["grad_fsl"], + ), + grad_fsl=dict( + argstr="-fslgrad %s %s", + xor=["grad_file"], + ), + in_bval=dict( + extensions=None, + ), + in_bvec=dict( + argstr="-fslgrad %s %s", + extensions=None, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + in_transform=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + nthreads=dict( + argstr="-nthreads %d", + nohash=True, + ), + out_bval=dict( + extensions=None, + ), + out_bvec=dict( + argstr="-export_grad_fsl %s %s", + extensions=None, + ), + out_transform=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=-1, + usedefault=True, + ), + reference=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + ) + inputs = TransformFSLConvert.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_TransformFSLConvert_outputs(): + output_map = dict( + out_transform=dict( + extensions=None, + ), + ) + outputs = TransformFSLConvert.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/mrtrix3/tracking.py b/nipype/interfaces/mrtrix3/tracking.py index 301f5deeff..abb18139d1 100644 --- a/nipype/interfaces/mrtrix3/tracking.py +++ b/nipype/interfaces/mrtrix3/tracking.py @@ -4,12 +4,12 @@ import os.path as op -from ..base import traits, TraitedSpec, File +from ..base import traits, Tuple, TraitedSpec, File from .base import MRTrix3BaseInputSpec, MRTrix3Base class TractographyInputSpec(MRTrix3BaseInputSpec): - sph_trait = traits.Tuple( + sph_trait = Tuple( traits.Float, traits.Float, traits.Float, traits.Float, argstr="%f,%f,%f,%f" ) @@ -117,15 +117,11 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): ) max_length = traits.Float( argstr="-maxlength %f", - desc=( - "set the maximum length of any track in mm (default is " "100 x voxelsize)" - ), + desc=("set the maximum length of any track in mm (default is 100 x voxelsize)"), ) min_length = traits.Float( argstr="-minlength %f", - desc=( - "set the minimum length of any track in mm (default is " "5 x voxelsize)" - ), + desc=("set the minimum length of any track in mm (default is 5 x voxelsize)"), ) cutoff = traits.Float( argstr="-cutoff %f", @@ -155,7 +151,7 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): "(default is to track in both directions)" ), ) - init_dir = traits.Tuple( + init_dir = Tuple( traits.Float, traits.Float, traits.Float, @@ -195,7 +191,7 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): stop = traits.Bool( argstr="-stop", desc=( - "stop propagating a streamline once it has traversed all " "include regions" + "stop propagating a streamline once it has traversed all include regions" ), ) downsample = traits.Float( @@ -224,7 +220,7 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): ) # Tractography seeding options - seed_sphere = traits.Tuple( + seed_sphere = Tuple( traits.Float, traits.Float, traits.Float, @@ -237,7 +233,7 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): argstr="-seed_image %s", desc="seed streamlines entirely at random within mask", ) - seed_rnd_voxel = traits.Tuple( + seed_rnd_voxel = Tuple( File(exists=True), traits.Int(), argstr="-seed_random_per_voxel %s %d", @@ -247,7 +243,7 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): "image; random placement of seeds in each voxel" ), ) - seed_grid_voxel = traits.Tuple( + seed_grid_voxel = Tuple( File(exists=True), traits.Int(), argstr="-seed_grid_per_voxel %s %d", @@ -299,14 +295,14 @@ class TractographyInputSpec(MRTrix3BaseInputSpec): "out_seeds.nii.gz", usedefault=True, argstr="-output_seeds %s", - desc=("output the seed location of all successful streamlines to" " a file"), + desc=("output the seed location of all successful streamlines to a file"), ) class TractographyOutputSpec(TraitedSpec): out_file = File(exists=True, desc="the output filtered tracks") out_seeds = File( - desc=("output the seed location of all successful" " streamlines to a file") + desc=("output the seed location of all successful streamlines to a file") ) @@ -367,7 +363,7 @@ def _format_arg(self, name, trait_spec, value): value = ["%f" % v for v in value] return trait_spec.argstr % ",".join(value) - return super(Tractography, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) def _list_outputs(self): outputs = self.output_spec().get() diff --git a/nipype/interfaces/mrtrix3/utils.py b/nipype/interfaces/mrtrix3/utils.py index d13b5d0ce7..1a7c81dada 100644 --- a/nipype/interfaces/mrtrix3/utils.py +++ b/nipype/interfaces/mrtrix3/utils.py @@ -4,12 +4,15 @@ import os.path as op +from ...utils.filemanip import split_filename from ..base import ( CommandLineInputSpec, CommandLine, traits, + Tuple, TraitedSpec, File, + Directory, InputMultiPath, isdefined, ) @@ -64,6 +67,101 @@ def _list_outputs(self): return outputs +class MRCatInputSpec(MRTrix3BaseInputSpec): + in_files = traits.List( + File(exists=True), + argstr="%s", + position=-2, + mandatory=True, + desc="files to concatenate", + ) + + out_file = File( + "concatenated.mif", + argstr="%s", + mandatory=True, + position=-1, + usedefault=True, + desc="output concatenated image", + ) + + axis = traits.Int( + argstr="-axis %s", + desc="""specify axis along which concatenation should be performed. By default, + the program will use the last non-singleton, non-spatial axis of any of + the input images - in other words axis 3 or whichever axis (greater than + 3) of the input images has size greater than one""", + ) + + datatype = traits.Enum( + "float32", + "float32le", + "float32be", + "float64", + "float64le", + "float64be", + "int64", + "uint64", + "int64le", + "uint64le", + "int64be", + "uint64be", + "int32", + "uint32", + "int32le", + "uint32le", + "int32be", + "uint32be", + "int16", + "uint16", + "int16le", + "uint16le", + "int16be", + "uint16be", + "cfloat32", + "cfloat32le", + "cfloat32be", + "cfloat64", + "cfloat64le", + "cfloat64be", + "int8", + "uint8", + "bit", + argstr="-datatype %s", + desc="specify output image data type", + ) + + +class MRCatOutputSpec(TraitedSpec): + out_file = File(exists=True, desc="the output concatenated image") + + +class MRCat(CommandLine): + """ + Concatenate several images into one + + + Example + ------- + + >>> import nipype.interfaces.mrtrix3 as mrt + >>> mrcat = mrt.MRCat() + >>> mrcat.inputs.in_files = ['dwi.mif','mask.mif'] + >>> mrcat.cmdline # doctest: +ELLIPSIS + 'mrcat dwi.mif mask.mif concatenated.mif' + >>> mrcat.run() # doctest: +SKIP + """ + + _cmd = "mrcat" + input_spec = MRCatInputSpec + output_spec = MRCatOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["out_file"] = op.abspath(self.inputs.out_file) + return outputs + + class Mesh2PVEInputSpec(CommandLineInputSpec): in_file = File( exists=True, argstr="%s", mandatory=True, position=-3, desc="input mesh" @@ -128,15 +226,64 @@ class Generate5ttInputSpec(MRTrix3BaseInputSpec): "fsl", "gif", "freesurfer", + "hsvs", argstr="%s", position=-3, mandatory=True, desc="tissue segmentation algorithm", ) - in_file = File( - exists=True, argstr="%s", mandatory=True, position=-2, desc="input image" + in_file = traits.Either( + File(exists=True), + Directory(exists=True), + argstr="%s", + mandatory=True, + position=-2, + desc="input image / directory", ) out_file = File(argstr="%s", mandatory=True, position=-1, desc="output image") + t2_image = File( + exists=True, + argstr="-t2 %s", + desc="Provide a T2-weighted image in addition to the default T1-weighted image. (Only for 'fsl' algorithm)", + ) + mask_file = File( + exists=True, + argstr="-mask %s", + desc="Provide a brain mask image. (Only for 'fsl' algorithm)", + ) + premasked = traits.Bool( + argstr="-premasked", + desc="Assume that the input image is already brain-masked. (Only for 'fsl' algorithm)", + ) + nocrop = traits.Bool( + argstr="-nocrop", + desc="Do not crop the image to the region of interest.", + ) + sgm_amyg_hipp = traits.Bool( + argstr="-sgm_amyg_hipp", + desc="Include the amygdala and hippocampus in the subcortical grey matter segment.", + ) + template = File( + exists=True, + argstr="-template %s", + desc="Provide an image that will form the template for the generated 5TT image. (Only for 'hsvs' algorithm)", + ) + hippocampi = traits.Enum( + "subfields", + "first", + "aseg", + argstr="-hippocampi %s", + desc="Choose the method used to segment the hippocampi. (Only for 'freesurfer' algorithm)", + ) + white_stem = traits.Bool( + argstr="-white_stem", + desc="Classify the brainstem as white matter. (Only for 'hsvs' algorithm)", + ) + lut_file = File( + exists=True, + argstr="-lut %s", + desc="Manually provide path to the lookup table on which the input parcellation image is based. (Only for 'freesurfer' algorithm)", + ) class Generate5ttOutputSpec(TraitedSpec): @@ -171,13 +318,22 @@ def _list_outputs(self): return outputs -class TensorMetricsInputSpec(CommandLineInputSpec): +class TensorMetricsInputSpec(MRTrix3BaseInputSpec): in_file = File( - exists=True, argstr="%s", mandatory=True, position=-1, desc="input DTI image" + exists=True, + argstr="%s", + mandatory=True, + position=-1, + desc="input DTI image", ) out_fa = File(argstr="-fa %s", desc="output FA file") out_adc = File(argstr="-adc %s", desc="output ADC file") + out_ad = File(argstr="-ad %s", desc="output AD file") + out_rd = File(argstr="-rd %s", desc="output RD file") + out_cl = File(argstr="-cl %s", desc="output CL file") + out_cp = File(argstr="-cp %s", desc="output CP file") + out_cs = File(argstr="-cs %s", desc="output CS file") out_evec = File(argstr="-vector %s", desc="output selected eigenvector(s) file") out_eval = File(argstr="-value %s", desc="output selected eigenvalue(s) file") component = traits.List( @@ -193,22 +349,25 @@ class TensorMetricsInputSpec(CommandLineInputSpec): in_mask = File( exists=True, argstr="-mask %s", - desc=( - "only perform computation within the specified binary" " brain mask image" - ), + desc=("only perform computation within the specified binary brain mask image"), ) modulate = traits.Enum( "FA", "none", "eval", argstr="-modulate %s", - desc=("how to modulate the magnitude of the" " eigenvectors"), + desc=("how to modulate the magnitude of the eigenvectors"), ) class TensorMetricsOutputSpec(TraitedSpec): out_fa = File(desc="output FA file") out_adc = File(desc="output ADC file") + out_ad = File(desc="output AD file") + out_rd = File(desc="output RD file") + out_cl = File(desc="output CL file") + out_cp = File(desc="output CP file") + out_cs = File(desc="output CS file") out_evec = File(desc="output selected eigenvector(s) file") out_eval = File(desc="output selected eigenvalue(s) file") @@ -254,7 +413,7 @@ class ComputeTDIInputSpec(CommandLineInputSpec): reference = File( exists=True, argstr="-template %s", - desc="a reference" "image to be used as template", + desc="a reference image to be used as template", ) vox_size = traits.List( traits.Int, argstr="-vox %s", sep=",", desc="voxel dimensions" @@ -274,7 +433,7 @@ class ComputeTDIInputSpec(CommandLineInputSpec): ) max_tod = traits.Int( argstr="-tod %d", - desc="generate a Track Orientation " "Distribution (TOD) in each voxel.", + desc="generate a Track Orientation Distribution (TOD) in each voxel.", ) contrast = traits.Enum( @@ -286,7 +445,7 @@ class ComputeTDIInputSpec(CommandLineInputSpec): "fod_amp", "curvature", argstr="-constrast %s", - desc="define the desired " "form of contrast for the output image", + desc="define the desired form of contrast for the output image", ) in_map = File( exists=True, @@ -343,7 +502,7 @@ class ComputeTDIInputSpec(CommandLineInputSpec): argstr="-upsample %d", desc="upsample the tracks by" " some ratio using Hermite interpolation before " - "mappping", + "mapping", ) precise = traits.Bool( @@ -353,17 +512,17 @@ class ComputeTDIInputSpec(CommandLineInputSpec): "(these lengths are then taken into account during TWI calculation)", ) ends_only = traits.Bool( - argstr="-ends_only", desc="only map the streamline" " endpoints to the image" + argstr="-ends_only", desc="only map the streamline endpoints to the image" ) tck_weights = File( exists=True, argstr="-tck_weights_in %s", - desc="specify" " a text scalar file containing the streamline weights", + desc="specify a text scalar file containing the streamline weights", ) nthreads = traits.Int( argstr="-nthreads %d", - desc="number of threads. if zero, the number" " of available cpus will be used", + desc="number of threads. if zero, the number of available cpus will be used", nohash=True, ) @@ -460,7 +619,7 @@ class TCK2VTKInputSpec(CommandLineInputSpec): nthreads = traits.Int( argstr="-nthreads %d", - desc="number of threads. if zero, the number" " of available cpus will be used", + desc="number of threads. if zero, the number of available cpus will be used", nohash=True, ) @@ -560,7 +719,7 @@ class MRConvertInputSpec(MRTrix3BaseInputSpec): desc="output image", ) coord = traits.List( - traits.Float, + traits.Int, sep=" ", argstr="-coord %s", desc="extract data at the specified coordinates", @@ -580,10 +739,28 @@ class MRConvertInputSpec(MRTrix3BaseInputSpec): argstr="-scaling %s", desc="specify the data scaling parameter", ) + json_import = File( + exists=True, + argstr="-json_import %s", + mandatory=False, + desc="import data from a JSON file into header key-value pairs", + ) + json_export = File( + exists=False, + argstr="-json_export %s", + mandatory=False, + desc="export data from an image header key-value pairs into a JSON file", + ) class MRConvertOutputSpec(TraitedSpec): out_file = File(exists=True, desc="output image") + json_export = File( + exists=True, + desc="exported data from an image header key-value pairs in a JSON file", + ) + out_bvec = File(exists=True, desc="export bvec file in FSL format") + out_bval = File(exists=True, desc="export bvec file in FSL format") class MRConvert(MRTrix3Base): @@ -610,9 +787,174 @@ class MRConvert(MRTrix3Base): def _list_outputs(self): outputs = self.output_spec().get() outputs["out_file"] = op.abspath(self.inputs.out_file) + if self.inputs.json_export: + outputs["json_export"] = op.abspath(self.inputs.json_export) + if self.inputs.out_bvec: + outputs["out_bvec"] = op.abspath(self.inputs.out_bvec) + if self.inputs.out_bval: + outputs["out_bval"] = op.abspath(self.inputs.out_bval) return outputs +class TransformFSLConvertInputSpec(MRTrix3BaseInputSpec): + in_file = File( + exists=True, + argstr="%s", + mandatory=True, + position=1, + desc="FLIRT input image", + ) + reference = File( + exists=True, + argstr="%s", + mandatory=True, + position=2, + desc="FLIRT reference image", + ) + in_transform = File( + exists=True, + argstr="%s", + mandatory=True, + position=0, + desc="FLIRT output transformation matrix", + ) + out_transform = File( + "transform_mrtrix.txt", + argstr="%s", + mandatory=True, + position=-1, + usedefault=True, + desc="output transformed affine in mrtrix3's format", + ) + flirt_import = traits.Bool( + True, + argstr="flirt_import", + mandatory=True, + usedefault=True, + position=-2, + desc="import transform from FSL's FLIRT.", + ) + + +class TransformFSLConvertOutputSpec(TraitedSpec): + out_transform = File( + exists=True, desc="output transformed affine in mrtrix3's format" + ) + + +class TransformFSLConvert(MRTrix3Base): + """ + Perform conversion between FSL's transformation matrix format to mrtrix3's. + """ + + _cmd = "transformconvert" + input_spec = TransformFSLConvertInputSpec + output_spec = TransformFSLConvertOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["out_transform"] = op.abspath(self.inputs.out_transform) + return outputs + + +class MRTransformInputSpec(MRTrix3BaseInputSpec): + in_files = InputMultiPath( + File(exists=True), + argstr="%s", + mandatory=True, + position=-2, + desc="Input images to be transformed", + ) + out_file = File( + genfile=True, + argstr="%s", + position=-1, + desc="Output image", + ) + invert = traits.Bool( + argstr="-inverse", + desc="Invert the specified transform before using it", + ) + linear_transform = File( + exists=True, + argstr="-linear %s", + desc=( + "Specify a linear transform to apply, in the form of a 3x4 or 4x4 ascii file. " + "Note the standard reverse convention is used, " + "where the transform maps points in the template image to the moving image. " + "Note that the reverse convention is still assumed even if no -template image is supplied." + ), + ) + replace_transform = traits.Bool( + argstr="-replace", + desc="replace the current transform by that specified, rather than applying it to the current transform", + ) + transformation_file = File( + exists=True, + argstr="-transform %s", + desc="The transform to apply, in the form of a 4x4 ascii file.", + ) + template_image = File( + exists=True, + argstr="-template %s", + desc="Reslice the input image to match the specified template image.", + ) + reference_image = File( + exists=True, + argstr="-reference %s", + desc="in case the transform supplied maps from the input image onto a reference image, use this option to specify the reference. Note that this implicitly sets the -replace option.", + ) + flip_x = traits.Bool( + argstr="-flipx", + desc="assume the transform is supplied assuming a coordinate system with the x-axis reversed relative to the MRtrix convention (i.e. x increases from right to left). This is required to handle transform matrices produced by FSL's FLIRT command. This is only used in conjunction with the -reference option.", + ) + quiet = traits.Bool( + argstr="-quiet", + desc="Do not display information messages or progress status.", + ) + debug = traits.Bool(argstr="-debug", desc="Display debugging messages.") + + +class MRTransformOutputSpec(TraitedSpec): + out_file = File(exists=True, desc="the output image of the transformation") + + +class MRTransform(MRTrix3Base): + """ + Apply spatial transformations or reslice images + + Example + ------- + + >>> MRxform = MRTransform() + >>> MRxform.inputs.in_files = 'anat_coreg.mif' + >>> MRxform.run() # doctest: +SKIP + """ + + _cmd = "mrtransform" + input_spec = MRTransformInputSpec + output_spec = MRTransformOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["out_file"] = self.inputs.out_file + if not isdefined(outputs["out_file"]): + outputs["out_file"] = op.abspath(self._gen_outfilename()) + else: + outputs["out_file"] = op.abspath(outputs["out_file"]) + return outputs + + def _gen_filename(self, name): + if name == "out_file": + return self._gen_outfilename() + else: + return None + + def _gen_outfilename(self): + _, name, _ = split_filename(self.inputs.in_files[0]) + return name + "_MRTransform.mif" + + class MRMathInputSpec(MRTrix3BaseInputSpec): in_file = File( exists=True, argstr="%s", mandatory=True, position=-3, desc="input image" @@ -637,7 +979,7 @@ class MRMathInputSpec(MRTrix3BaseInputSpec): desc="operation to computer along a specified axis", ) axis = traits.Int( - 0, argstr="-axis %d", desc="specfied axis to perform the operation along" + 0, argstr="-axis %d", desc="specified axis to perform the operation along" ) @@ -679,21 +1021,21 @@ class MRResizeInputSpec(MRTrix3BaseInputSpec): in_file = File( exists=True, argstr="%s", position=-2, mandatory=True, desc="input DWI image" ) - image_size = traits.Tuple( + image_size = Tuple( (traits.Int, traits.Int, traits.Int), argstr="-size %d,%d,%d", mandatory=True, desc="Number of voxels in each dimension of output image", xor=["voxel_size", "scale_factor"], ) - voxel_size = traits.Tuple( + voxel_size = Tuple( (traits.Float, traits.Float, traits.Float), argstr="-voxel %g,%g,%g", mandatory=True, desc="Desired voxel size in mm for the output image", xor=["image_size", "scale_factor"], ) - scale_factor = traits.Tuple( + scale_factor = Tuple( (traits.Float, traits.Float, traits.Float), argstr="-scale %g,%g,%g", mandatory=True, @@ -765,3 +1107,306 @@ class MRResize(MRTrix3Base): _cmd = "mrresize" input_spec = MRResizeInputSpec output_spec = MRResizeOutputSpec + + +class SHConvInputSpec(CommandLineInputSpec): + in_file = File( + exists=True, + argstr="%s", + mandatory=True, + position=-3, + desc="input ODF image", + ) + # General options + response = File( + exists=True, + mandatory=True, + argstr="%s", + position=-2, + desc=("The response function"), + ) + out_file = File( + name_template="%s_shconv.mif", + name_source=["in_file"], + argstr="%s", + position=-1, + usedefault=True, + desc="the output spherical harmonics", + ) + + +class SHConvOutputSpec(TraitedSpec): + out_file = File(exists=True, desc="the output convoluted spherical harmonics file") + + +class SHConv(CommandLine): + """ + Convolve spherical harmonics with a tissue response function. Useful for + checking residuals of ODF estimates. + + + Example + ------- + + >>> import nipype.interfaces.mrtrix3 as mrt + >>> sh = mrt.SHConv() + >>> sh.inputs.in_file = 'csd.mif' + >>> sh.inputs.response = 'response.txt' + >>> sh.cmdline + 'shconv csd.mif response.txt csd_shconv.mif' + >>> sh.run() # doctest: +SKIP + """ + + _cmd = "shconv" + input_spec = SHConvInputSpec + output_spec = SHConvOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["out_file"] = op.abspath(self.inputs.out_file) + return outputs + + +class SH2AmpInputSpec(CommandLineInputSpec): + in_file = File( + exists=True, + argstr="%s", + mandatory=True, + position=-3, + desc="input ODF image", + ) + # General options + directions = File( + exists=True, + mandatory=True, + argstr="%s", + position=-2, + desc=( + "The gradient directions along which to sample the spherical " + "harmonics MRtrix format" + ), + ) + out_file = File( + name_template="%s_amp.mif", + name_source=["in_file"], + argstr="%s", + position=-1, + usedefault=True, + desc="the output spherical harmonics", + ) + nonnegative = traits.Bool( + argstr="-nonnegative", desc="cap all negative amplitudes to zero" + ) + + +class SH2AmpOutputSpec(TraitedSpec): + out_file = File(exists=True, desc="the output convoluted spherical harmonics file") + + +class SH2Amp(CommandLine): + """ + Sample spherical harmonics on a set of gradient orientations. Useful for + checking residuals of ODF estimates. + + + Example + ------- + + >>> import nipype.interfaces.mrtrix3 as mrt + >>> sh = mrt.SH2Amp() + >>> sh.inputs.in_file = 'sh.mif' + >>> sh.inputs.directions = 'grads.txt' + >>> sh.cmdline + 'sh2amp sh.mif grads.txt sh_amp.mif' + >>> sh.run() # doctest: +SKIP + """ + + _cmd = "sh2amp" + input_spec = SH2AmpInputSpec + output_spec = SH2AmpOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["out_file"] = op.abspath(self.inputs.out_file) + return outputs + + +class MaskFilterInputSpec(CommandLineInputSpec): + in_file = File( + exists=True, + mandatory=True, + argstr="%s", + position=-3, + desc="Input mask", + ) + filter = traits.Str( + mandatory=True, + argstr="%s", + position=-2, + desc="Filter to perform (e.g. dilate, erode)", + ) + out_file = File( + name_source=["input_image"], + mandatory=True, + argstr="%s", + position=-1, + desc="Output mask", + ) + npass = traits.Int(argstr="-npass %d", position=1, desc="Number of passes") + + +class MaskFilterOutputSpec(TraitedSpec): + out_file = File(exists=True, desc="the filtered output mask") + + +class MaskFilter(CommandLine): + """ + Perform filtering operations on 3D / 4D mask images. + Only supports dilate / erode filters at the moment. + For more information see: https://mrtrix.readthedocs.io/en/latest/reference/commands/maskfilter.html + + + Example + ------- + + >>> import nipype.interfaces.mrtrix3 as mrt + >>> mf = mrt.MaskFilter() + >>> mf.inputs.in_file = 'mask.mif' + >>> mf.inputs.filter = 'dilate' + >>> mf.inputs.npass = 2 + >>> mf.inputs.out_file = 'mask_filtered.mif' + >>> mf.cmdline + 'maskfilter -npass 2 mask.mif dilate mask_filtered.mif' + >>> mf.run() # doctest: +SKIP + """ + + _cmd = "maskfilter" + input_spec = MaskFilterInputSpec + output_spec = MaskFilterOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["out_file"] = op.abspath(self.inputs.out_file) + return outputs + + +class MTNormaliseInputSpec(MRTrix3BaseInputSpec): + wm_fod = File( + argstr="%s", + exists=True, + position=1, + desc="input fod of white matter tissue compartment", + ) + out_file_wm = File( + argstr="%s", position=2, desc="output file of white matter tissue compartment" + ) + gm_fod = File( + argstr="%s", + exists=True, + position=3, + desc="input fod of grey matter tissue compartment", + ) + out_file_gm = File( + argstr="%s", position=4, desc="output file of grey matter tissue compartment" + ) + csf_fod = File( + argstr="%s", exists=True, position=5, desc="input fod of CSF tissue compartment" + ) + out_file_csf = File( + argstr="%s", position=6, desc="output file of CSF tissue compartment 3" + ) + mask = File(argstr="-mask %s", exists=True, position=-1, desc="input brain mask") + + +class MTNormaliseOutputSpec(TraitedSpec): + out_file_wm = File(exists=True, desc="the normalized white matter fod") + out_file_gm = File(exists=True, desc="the normalized grey matter fod") + out_file_csf = File(exists=True, desc="the normalized csf fod") + + +class MTNormalise(CommandLine): + """ + Multi-tissue informed log-domain intensity normalisation + + + Example + ------- + + >>> import nipype.interfaces.mrtrix3 as mrt + >>> mtn = mrt.MTNormalise() + >>> mtn.inputs.wm_fod = 'wmfod.mif' + >>> mtn.inputs.gm_fod = 'gmfod.mif' + >>> mtn.inputs.csf_fod = 'csffod.mif' + >>> mtn.inputs.out_file_wm = 'wmfod_norm.mif' + >>> mtn.inputs.out_file_gm = 'gmfod_norm.mif' + >>> mtn.inputs.out_file_csf = 'csffod_norm.mif' + >>> mtn.inputs.mask = 'mask.mif' + >>> mtn.cmdline + 'mtnormalise wmfod.mif wmfod_norm.mif gmfod.mif gmfod_norm.mif csffod.mif csffod_norm.mif -mask mask.mif' + >>> mtn.run() # doctest: +SKIP + """ + + _cmd = "mtnormalise" + input_spec = MTNormaliseInputSpec + output_spec = MTNormaliseOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["out_file_wm"] = op.abspath(self.inputs.out_file_wm) + outputs["out_file_gm"] = op.abspath(self.inputs.out_file_gm) + outputs["out_file_csf"] = op.abspath(self.inputs.out_file_csf) + return outputs + + +class Generate5tt2gmwmiInputSpec(MRTrix3BaseInputSpec): + in_file = File( + exists=True, + argstr="%s", + mandatory=True, + position=-2, + desc="the input 5TT segmented anatomical image", + ) + mask_out = File( + "mask_gmwmi.mif", + argstr="%s", + mandatory=True, + position=-1, + desc="the output mask image", + ) + mask_in = File( + argstr="-mask_in %s", + position=-3, + desc="filter an input mask image according to those voxels that lie upon the grey matter - white matter boundary", + ) + + +class Generate5tt2gmwmiOutputSpec(TraitedSpec): + mask_out = File(exists=True, desc="the output mask file") + + +class Generate5tt2gmwmi(CommandLine): + """ + Generate a mask image appropriate for seeding streamlines on + the grey matter-white matter interface + + + Example + ------- + + >>> import nipype.interfaces.mrtrix3 as mrt + >>> gmwmi = mrt.Generate5tt2gmwmi() + >>> gmwmi.inputs.in_file = '5tt_in.mif' + >>> gmwmi.inputs.mask_out = 'mask_gmwmi.mif' + >>> gmwmi.cmdline + '5tt2gmwmi 5tt_in.mif mask_gmwmi.mif' + >>> gmwmi.run() # doctest: +SKIP + """ + + _cmd = "5tt2gmwmi" + input_spec = Generate5tt2gmwmiInputSpec + output_spec = Generate5tt2gmwmiOutputSpec + + def _list_outputs(self): + outputs = self.output_spec().get() + outputs["mask_out"] = op.abspath(self.inputs.mask_out) + return outputs diff --git a/nipype/interfaces/niftyfit/asl.py b/nipype/interfaces/niftyfit/asl.py index 5c23769e8f..a23507bbd4 100644 --- a/nipype/interfaces/niftyfit/asl.py +++ b/nipype/interfaces/niftyfit/asl.py @@ -4,13 +4,13 @@ The ASL module of niftyfit, which wraps the fitting methods in NiftyFit. """ -from ..base import File, TraitedSpec, traits, CommandLineInputSpec +from ..base import File, TraitedSpec, traits, Tuple, CommandLineInputSpec from .base import NiftyFitCommand from ..niftyreg.base import get_custom_path class FitAslInputSpec(CommandLineInputSpec): - """ Input Spec for FitAsl. """ + """Input Spec for FitAsl.""" desc = "Filename of the 4D ASL (control/label) source image (mandatory)." source_file = File( @@ -113,7 +113,7 @@ class FitAslInputSpec(CommandLineInputSpec): pv0 = traits.Int(desc=desc, argstr="-pv0 %d") pv2 = traits.Int(desc="In plane PV kernel size [3x3].", argstr="-pv2 %d") - pv3 = traits.Tuple( + pv3 = Tuple( traits.Int, traits.Int, traits.Int, @@ -129,7 +129,7 @@ class FitAslInputSpec(CommandLineInputSpec): class FitAslOutputSpec(TraitedSpec): - """ Output Spec for FitAsl. """ + """Output Spec for FitAsl.""" desc = "Filename of the Cerebral Blood Flow map (in ml/100g/min)." cbf_file = File(exists=True, desc=desc) diff --git a/nipype/interfaces/niftyfit/base.py b/nipype/interfaces/niftyfit/base.py index 7af72cd30d..dc004c871c 100644 --- a/nipype/interfaces/niftyfit/base.py +++ b/nipype/interfaces/niftyfit/base.py @@ -31,8 +31,8 @@ class NiftyFitCommand(CommandLine): _suffix = "_nf" def __init__(self, **inputs): - """ Init method calling super. No version to be checked.""" - super(NiftyFitCommand, self).__init__(**inputs) + """Init method calling super. No version to be checked.""" + super().__init__(**inputs) def _gen_fname(self, basename, out_dir=None, suffix=None, ext=None): if basename == "": @@ -45,5 +45,5 @@ def _gen_fname(self, basename, out_dir=None, suffix=None, ext=None): if ext is not None: final_ext = ext if suffix is not None: - final_bn = "".join((final_bn, suffix)) + final_bn = f"{final_bn}{suffix}" return os.path.abspath(os.path.join(out_dir, final_bn + final_ext)) diff --git a/nipype/interfaces/niftyfit/dwi.py b/nipype/interfaces/niftyfit/dwi.py index 1cfc8826d8..6d82809694 100644 --- a/nipype/interfaces/niftyfit/dwi.py +++ b/nipype/interfaces/niftyfit/dwi.py @@ -4,13 +4,13 @@ The dwi module of niftyfit, which wraps the fitting methods in NiftyFit. """ -from ..base import File, TraitedSpec, traits, isdefined, CommandLineInputSpec +from ..base import File, TraitedSpec, traits, Tuple, isdefined, CommandLineInputSpec from .base import NiftyFitCommand from ..niftyreg.base import get_custom_path class FitDwiInputSpec(CommandLineInputSpec): - """ Input Spec for FitDwi. """ + """Input Spec for FitDwi.""" # Inputs options source_file = File( @@ -72,7 +72,7 @@ class FitDwiInputSpec(CommandLineInputSpec): mcmap_file = File( name_source=["source_file"], name_template="%s_mcmap.nii.gz", - desc="Filename of multi-compartment model parameter map " "(-ivim,-ball,-nod)", + desc="Filename of multi-compartment model parameter map (-ivim,-ball,-nod)", argstr="-mcmap %s", requires=["nodv_flag"], ) @@ -226,7 +226,7 @@ class FitDwiInputSpec(CommandLineInputSpec): desc = "Maximum number of non-linear LSQR iterations [100x2 passes])" maxit_val = traits.Int(desc=desc, argstr="-maxit %d", requires=["gn_flag"]) desc = "LM parameters (initial value, decrease rate) [100,1.2]." - lm_vals = traits.Tuple( + lm_vals = Tuple( traits.Float, traits.Float, argstr="-lm %f %f", requires=["gn_flag"], desc=desc ) desc = "Use Gauss-Newton algorithm [Levenberg-Marquardt]." @@ -244,7 +244,7 @@ class FitDwiInputSpec(CommandLineInputSpec): desc = "Use location-weighted least squares for DTI fitting [3x3 Gaussian]" swls_val = traits.Float(desc=desc, argstr="-swls %f") slice_no = traits.Int(desc="Fit to single slice number.", argstr="-slice %d") - voxel = traits.Tuple( + voxel = Tuple( traits.Int, traits.Int, traits.Int, @@ -281,7 +281,7 @@ class FitDwiInputSpec(CommandLineInputSpec): class FitDwiOutputSpec(TraitedSpec): - """ Output Spec for FitDwi. """ + """Output Spec for FitDwi.""" error_file = File(desc="Filename of parameter error maps") res_file = File(desc="Filename of model residual map") @@ -295,7 +295,7 @@ class FitDwiOutputSpec(TraitedSpec): tenmap2_file = File(desc="Filename of tensor map [lower tri]") mcmap_file = File( - desc="Filename of multi-compartment model " "parameter map (-ivim,-ball,-nod)." + desc="Filename of multi-compartment model parameter map (-ivim,-ball,-nod)." ) mcout = File(desc="Filename of mc samples (ascii text file)") @@ -338,11 +338,11 @@ def _format_arg(self, name, trait_spec, value): return "" if name == "tenmap2_file" and self.inputs.ten_type != "lower-tri": return "" - return super(FitDwi, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) class DwiToolInputSpec(CommandLineInputSpec): - """ Input Spec for DwiTool. """ + """Input Spec for DwiTool.""" desc = "The source image containing the fitted model." source_file = File( @@ -540,7 +540,7 @@ class DwiToolInputSpec(CommandLineInputSpec): class DwiToolOutputSpec(TraitedSpec): - """ Output Spec for DwiTool. """ + """Output Spec for DwiTool.""" desc = "Filename of multi-compartment model parameter map \ (-ivim,-ball,-nod)" @@ -600,4 +600,4 @@ def _format_arg(self, name, trait_spec, value): self.inputs.dti_flag2 ): return "" - return super(DwiTool, self)._format_arg(name, trait_spec, value) + return super()._format_arg(name, trait_spec, value) diff --git a/nipype/interfaces/niftyfit/qt1.py b/nipype/interfaces/niftyfit/qt1.py index 9337de2306..d868f856ab 100644 --- a/nipype/interfaces/niftyfit/qt1.py +++ b/nipype/interfaces/niftyfit/qt1.py @@ -5,13 +5,13 @@ in NiftyFit. """ -from ..base import TraitedSpec, File, traits, CommandLineInputSpec +from ..base import TraitedSpec, File, traits, Tuple, CommandLineInputSpec from .base import NiftyFitCommand from ..niftyreg.base import get_custom_path class FitQt1InputSpec(CommandLineInputSpec): - """ Input Spec for FitQt1. """ + """Input Spec for FitQt1.""" desc = "Filename of the 4D Multi-Echo T1 source image." source_file = File( @@ -79,7 +79,7 @@ class FitQt1InputSpec(CommandLineInputSpec): # set position to be ahead of TIs nb_comp = traits.Int(desc=desc, position=6, argstr="-nc %d") desc = "Set LM parameters (initial value, decrease rate) [100,1.2]." - lm_val = traits.Tuple( + lm_val = Tuple( traits.Float, traits.Float, desc=desc, argstr="-lm %f %f", position=7 ) desc = "Use Gauss-Newton algorithm [Levenberg-Marquardt]." @@ -87,7 +87,7 @@ class FitQt1InputSpec(CommandLineInputSpec): slice_no = traits.Int( desc="Fit to single slice number.", argstr="-slice %d", position=9 ) - voxel = traits.Tuple( + voxel = Tuple( traits.Int, traits.Int, traits.Int, @@ -144,7 +144,7 @@ class FitQt1InputSpec(CommandLineInputSpec): class FitQt1OutputSpec(TraitedSpec): - """ Output Spec for FitQt1. """ + """Output Spec for FitQt1.""" t1map_file = File(desc="Filename of the estimated output T1 map (in ms)") m0map_file = File(desc="Filename of the m0 map") diff --git a/nipype/interfaces/niftyfit/tests/test_asl.py b/nipype/interfaces/niftyfit/tests/test_asl.py index bbcfd4f01a..b919e0a483 100644 --- a/nipype/interfaces/niftyfit/tests/test_asl.py +++ b/nipype/interfaces/niftyfit/tests/test_asl.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -13,7 +12,7 @@ @pytest.mark.skipif(no_nifty_tool(cmd="fit_asl"), reason="niftyfit is not installed") def test_fit_asl(): - """ Testing FitAsl interface.""" + """Testing FitAsl interface.""" # Create the test node fit_asl = FitAsl() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_DwiTool.py b/nipype/interfaces/niftyfit/tests/test_auto_DwiTool.py index cf81acdc55..ca14384031 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_DwiTool.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_DwiTool.py @@ -4,8 +4,14 @@ def test_DwiTool_inputs(): input_map = dict( - args=dict(argstr="%s",), - b0_file=dict(argstr="-b0 %s", extensions=None, position=4,), + args=dict( + argstr="%s", + ), + b0_file=dict( + argstr="-b0 %s", + extensions=None, + position=4, + ), ball_flag=dict( argstr="-ball", position=6, @@ -32,10 +38,23 @@ def test_DwiTool_inputs(): "nodv_flag", ], ), - bval_file=dict(argstr="-bval %s", extensions=None, mandatory=True, position=2,), - bvec_file=dict(argstr="-bvec %s", extensions=None, position=3,), - diso_val=dict(argstr="-diso %f",), - dpr_val=dict(argstr="-dpr %f",), + bval_file=dict( + argstr="-bval %s", + extensions=None, + mandatory=True, + position=2, + ), + bvec_file=dict( + argstr="-bvec %s", + extensions=None, + position=3, + ), + diso_val=dict( + argstr="-diso %f", + ), + dpr_val=dict( + argstr="-dpr %f", + ), dti_flag=dict( argstr="-dti", position=6, @@ -62,7 +81,10 @@ def test_DwiTool_inputs(): "nodv_flag", ], ), - environ=dict(nohash=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), famap_file=dict( argstr="-famap %s", extensions=None, @@ -88,7 +110,11 @@ def test_DwiTool_inputs(): name_source=["source_file"], name_template="%s_logdti2.nii.gz", ), - mask_file=dict(argstr="-mask %s", extensions=None, position=5,), + mask_file=dict( + argstr="-mask %s", + extensions=None, + position=5, + ), mcmap_file=dict( argstr="-mcmap %s", extensions=None, @@ -147,7 +173,10 @@ def test_DwiTool_inputs(): name_template="%s_rgbmap.nii.gz", ), source_file=dict( - argstr="-source %s", extensions=None, mandatory=True, position=1, + argstr="-source %s", + extensions=None, + mandatory=True, + position=1, ), syn_file=dict( argstr="-syn %s", @@ -172,13 +201,27 @@ def test_DwiTool_inputs(): def test_DwiTool_outputs(): output_map = dict( - famap_file=dict(extensions=None,), - logdti_file=dict(extensions=None,), - mcmap_file=dict(extensions=None,), - mdmap_file=dict(extensions=None,), - rgbmap_file=dict(extensions=None,), - syn_file=dict(extensions=None,), - v1map_file=dict(extensions=None,), + famap_file=dict( + extensions=None, + ), + logdti_file=dict( + extensions=None, + ), + mcmap_file=dict( + extensions=None, + ), + mdmap_file=dict( + extensions=None, + ), + rgbmap_file=dict( + extensions=None, + ), + syn_file=dict( + extensions=None, + ), + v1map_file=dict( + extensions=None, + ), ) outputs = DwiTool.output_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_FitAsl.py b/nipype/interfaces/niftyfit/tests/test_auto_FitAsl.py index 567831f9f4..14093322cc 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_FitAsl.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_FitAsl.py @@ -4,48 +4,115 @@ def test_FitAsl_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), cbf_file=dict( argstr="-cbf %s", extensions=None, name_source=["source_file"], name_template="%s_cbf.nii.gz", ), - dpld=dict(argstr="-dPLD %f",), - dt_inv2=dict(argstr="-dTinv2 %f",), - eff=dict(argstr="-eff %f",), - environ=dict(nohash=True, usedefault=True,), + dpld=dict( + argstr="-dPLD %f", + ), + dt_inv2=dict( + argstr="-dTinv2 %f", + ), + eff=dict( + argstr="-eff %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), error_file=dict( argstr="-error %s", extensions=None, name_source=["source_file"], name_template="%s_error.nii.gz", ), - gm_plasma=dict(argstr="-gmL %f",), - gm_t1=dict(argstr="-gmT1 %f",), - gm_ttt=dict(argstr="-gmTTT %f",), - ir_output=dict(argstr="-IRoutput %s", extensions=None,), - ir_volume=dict(argstr="-IRvolume %s", extensions=None,), - ldd=dict(argstr="-LDD %f",), - m0map=dict(argstr="-m0map %s", extensions=None,), - m0mape=dict(argstr="-m0mape %s", extensions=None,), - mask=dict(argstr="-mask %s", extensions=None, position=2,), - mul=dict(argstr="-mul %f",), - mulgm=dict(argstr="-sig",), - out=dict(argstr="-out %f",), - pasl=dict(argstr="-pasl",), - pcasl=dict(argstr="-pcasl",), - plasma_coeff=dict(argstr="-L %f",), - pld=dict(argstr="-PLD %f",), - pv0=dict(argstr="-pv0 %d",), - pv2=dict(argstr="-pv2 %d",), - pv3=dict(argstr="-pv3 %d %d %d",), - pv_threshold=dict(argstr="-pvthreshold",), - seg=dict(argstr="-seg %s", extensions=None,), - segstyle=dict(argstr="-segstyle",), - sig=dict(argstr="-sig",), + gm_plasma=dict( + argstr="-gmL %f", + ), + gm_t1=dict( + argstr="-gmT1 %f", + ), + gm_ttt=dict( + argstr="-gmTTT %f", + ), + ir_output=dict( + argstr="-IRoutput %s", + extensions=None, + ), + ir_volume=dict( + argstr="-IRvolume %s", + extensions=None, + ), + ldd=dict( + argstr="-LDD %f", + ), + m0map=dict( + argstr="-m0map %s", + extensions=None, + ), + m0mape=dict( + argstr="-m0mape %s", + extensions=None, + ), + mask=dict( + argstr="-mask %s", + extensions=None, + position=2, + ), + mul=dict( + argstr="-mul %f", + ), + mulgm=dict( + argstr="-sig", + ), + out=dict( + argstr="-out %f", + ), + pasl=dict( + argstr="-pasl", + ), + pcasl=dict( + argstr="-pcasl", + ), + plasma_coeff=dict( + argstr="-L %f", + ), + pld=dict( + argstr="-PLD %f", + ), + pv0=dict( + argstr="-pv0 %d", + ), + pv2=dict( + argstr="-pv2 %d", + ), + pv3=dict( + argstr="-pv3 %d %d %d", + ), + pv_threshold=dict( + argstr="-pvthreshold", + ), + seg=dict( + argstr="-seg %s", + extensions=None, + ), + segstyle=dict( + argstr="-segstyle", + ), + sig=dict( + argstr="-sig", + ), source_file=dict( - argstr="-source %s", extensions=None, mandatory=True, position=1, + argstr="-source %s", + extensions=None, + mandatory=True, + position=1, ), syn_file=dict( argstr="-syn %s", @@ -53,13 +120,28 @@ def test_FitAsl_inputs(): name_source=["source_file"], name_template="%s_syn.nii.gz", ), - t1_art_cmp=dict(argstr="-T1a %f",), - t1map=dict(argstr="-t1map %s", extensions=None,), - t_inv1=dict(argstr="-Tinv1 %f",), - t_inv2=dict(argstr="-Tinv2 %f",), - wm_plasma=dict(argstr="-wmL %f",), - wm_t1=dict(argstr="-wmT1 %f",), - wm_ttt=dict(argstr="-wmTTT %f",), + t1_art_cmp=dict( + argstr="-T1a %f", + ), + t1map=dict( + argstr="-t1map %s", + extensions=None, + ), + t_inv1=dict( + argstr="-Tinv1 %f", + ), + t_inv2=dict( + argstr="-Tinv2 %f", + ), + wm_plasma=dict( + argstr="-wmL %f", + ), + wm_t1=dict( + argstr="-wmT1 %f", + ), + wm_ttt=dict( + argstr="-wmTTT %f", + ), ) inputs = FitAsl.input_spec() @@ -70,9 +152,15 @@ def test_FitAsl_inputs(): def test_FitAsl_outputs(): output_map = dict( - cbf_file=dict(extensions=None,), - error_file=dict(extensions=None,), - syn_file=dict(extensions=None,), + cbf_file=dict( + extensions=None, + ), + error_file=dict( + extensions=None, + ), + syn_file=dict( + extensions=None, + ), ) outputs = FitAsl.output_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_FitDwi.py b/nipype/interfaces/niftyfit/tests/test_auto_FitDwi.py index 57bee972e1..87650ffbd6 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_FitDwi.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_FitDwi.py @@ -4,8 +4,12 @@ def test_FitDwi_inputs(): input_map = dict( - acceptance=dict(argstr="-accpetance %f",), - args=dict(argstr="%s",), + acceptance=dict( + argstr="-accpetance %f", + ), + args=dict( + argstr="%s", + ), ball_flag=dict( argstr="-ball", position=4, @@ -30,12 +34,31 @@ def test_FitDwi_inputs(): "nodv_flag", ], ), - bval_file=dict(argstr="-bval %s", extensions=None, mandatory=True, position=2,), - bvec_file=dict(argstr="-bvec %s", extensions=None, mandatory=True, position=3,), - cov_file=dict(argstr="-cov %s", extensions=None,), - csf_t2_val=dict(argstr="-csfT2 %f",), - diso_val=dict(argstr="-diso %f",), - dpr_val=dict(argstr="-dpr %f",), + bval_file=dict( + argstr="-bval %s", + extensions=None, + mandatory=True, + position=2, + ), + bvec_file=dict( + argstr="-bvec %s", + extensions=None, + mandatory=True, + position=3, + ), + cov_file=dict( + argstr="-cov %s", + extensions=None, + ), + csf_t2_val=dict( + argstr="-csfT2 %f", + ), + diso_val=dict( + argstr="-diso %f", + ), + dpr_val=dict( + argstr="-dpr %f", + ), dti_flag=dict( argstr="-dti", position=4, @@ -48,7 +71,10 @@ def test_FitDwi_inputs(): "nodv_flag", ], ), - environ=dict(nohash=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), error_file=dict( argstr="-error %s", extensions=None, @@ -61,7 +87,10 @@ def test_FitDwi_inputs(): name_source=["source_file"], name_template="%s_famap.nii.gz", ), - gn_flag=dict(argstr="-gn", xor=["wls_flag"],), + gn_flag=dict( + argstr="-gn", + xor=["wls_flag"], + ), ivim_flag=dict( argstr="-ivim", position=4, @@ -74,9 +103,18 @@ def test_FitDwi_inputs(): "nodv_flag", ], ), - lm_vals=dict(argstr="-lm %f %f", requires=["gn_flag"],), - mask_file=dict(argstr="-mask %s", extensions=None,), - maxit_val=dict(argstr="-maxit %d", requires=["gn_flag"],), + lm_vals=dict( + argstr="-lm %f %f", + requires=["gn_flag"], + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + maxit_val=dict( + argstr="-maxit %d", + requires=["gn_flag"], + ), mcmap_file=dict( argstr="-mcmap %s", extensions=None, @@ -84,14 +122,18 @@ def test_FitDwi_inputs(): name_template="%s_mcmap.nii.gz", requires=["nodv_flag"], ), - mcmaxit=dict(argstr="-mcmaxit %d",), + mcmaxit=dict( + argstr="-mcmaxit %d", + ), mcout=dict( argstr="-mcout %s", extensions=None, name_source=["source_file"], name_template="%s_mcout.txt", ), - mcsamples=dict(argstr="-mcsamples %d",), + mcsamples=dict( + argstr="-mcsamples %d", + ), mdmap_file=dict( argstr="-mdmap %s", extensions=None, @@ -140,8 +182,13 @@ def test_FitDwi_inputs(): "nod_flag", ], ), - perf_thr=dict(argstr="-perfthreshold %f",), - prior_file=dict(argstr="-prior %s", extensions=None,), + perf_thr=dict( + argstr="-perfthreshold %f", + ), + prior_file=dict( + argstr="-prior %s", + extensions=None, + ), res_file=dict( argstr="-res %s", extensions=None, @@ -155,21 +202,40 @@ def test_FitDwi_inputs(): name_template="%s_rgbmap.nii.gz", requires=["dti_flag"], ), - rot_sform_flag=dict(argstr="-rotsform %d",), - slice_no=dict(argstr="-slice %d",), + rot_sform_flag=dict( + argstr="-rotsform %d", + ), + slice_no=dict( + argstr="-slice %d", + ), source_file=dict( - argstr="-source %s", extensions=None, mandatory=True, position=1, + argstr="-source %s", + extensions=None, + mandatory=True, + position=1, + ), + swls_val=dict( + argstr="-swls %f", ), - swls_val=dict(argstr="-swls %f",), syn_file=dict( argstr="-syn %s", extensions=None, name_source=["source_file"], name_template="%s_syn.nii.gz", ), - te_file=dict(argstr="-TE %s", extensions=None, xor=["te_file"],), - te_value=dict(argstr="-TE %s", extensions=None, xor=["te_file"],), - ten_type=dict(usedefault=True,), + te_file=dict( + argstr="-TE %s", + extensions=None, + xor=["te_file"], + ), + te_value=dict( + argstr="-TE %s", + extensions=None, + xor=["te_file"], + ), + ten_type=dict( + usedefault=True, + ), tenmap2_file=dict( argstr="-tenmap2 %s", extensions=None, @@ -190,10 +256,19 @@ def test_FitDwi_inputs(): name_source=["source_file"], name_template="%s_v1map.nii.gz", ), - vb_flag=dict(argstr="-vb",), - voxel=dict(argstr="-voxel %d %d %d",), - wls_flag=dict(argstr="-wls", xor=["gn_flag"],), - wm_t2_val=dict(argstr="-wmT2 %f",), + vb_flag=dict( + argstr="-vb", + ), + voxel=dict( + argstr="-voxel %d %d %d", + ), + wls_flag=dict( + argstr="-wls", + xor=["gn_flag"], + ), + wm_t2_val=dict( + argstr="-wmT2 %f", + ), ) inputs = FitDwi.input_spec() @@ -204,18 +279,42 @@ def test_FitDwi_inputs(): def test_FitDwi_outputs(): output_map = dict( - error_file=dict(extensions=None,), - famap_file=dict(extensions=None,), - mcmap_file=dict(extensions=None,), - mcout=dict(extensions=None,), - mdmap_file=dict(extensions=None,), - nodiff_file=dict(extensions=None,), - res_file=dict(extensions=None,), - rgbmap_file=dict(extensions=None,), - syn_file=dict(extensions=None,), - tenmap2_file=dict(extensions=None,), - tenmap_file=dict(extensions=None,), - v1map_file=dict(extensions=None,), + error_file=dict( + extensions=None, + ), + famap_file=dict( + extensions=None, + ), + mcmap_file=dict( + extensions=None, + ), + mcout=dict( + extensions=None, + ), + mdmap_file=dict( + extensions=None, + ), + nodiff_file=dict( + extensions=None, + ), + res_file=dict( + extensions=None, + ), + rgbmap_file=dict( + extensions=None, + ), + syn_file=dict( + extensions=None, + ), + tenmap2_file=dict( + extensions=None, + ), + tenmap_file=dict( + extensions=None, + ), + v1map_file=dict( + extensions=None, + ), ) outputs = FitDwi.output_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_FitQt1.py b/nipype/interfaces/niftyfit/tests/test_auto_FitQt1.py index be09fc90fc..ee82b5c900 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_FitQt1.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_FitQt1.py @@ -4,78 +4,158 @@ def test_FitQt1_inputs(): input_map = dict( - acceptance=dict(argstr="-acceptance %f",), - args=dict(argstr="%s",), - b1map=dict(argstr="-b1map %s", extensions=None,), + acceptance=dict( + argstr="-acceptance %f", + ), + args=dict( + argstr="%s", + ), + b1map=dict( + argstr="-b1map %s", + extensions=None, + ), comp_file=dict( argstr="-comp %s", extensions=None, name_source=["source_file"], name_template="%s_comp.nii.gz", ), - environ=dict(nohash=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), error_file=dict( argstr="-error %s", extensions=None, name_source=["source_file"], name_template="%s_error.nii.gz", ), - flips=dict(argstr="-flips %s", sep=" ",), - flips_list=dict(argstr="-fliplist %s", extensions=None,), - gn_flag=dict(argstr="-gn", position=8,), - ir_flag=dict(argstr="-IR", position=13,), - lm_val=dict(argstr="-lm %f %f", position=7,), + flips=dict( + argstr="-flips %s", + sep=" ", + ), + flips_list=dict( + argstr="-fliplist %s", + extensions=None, + ), + gn_flag=dict( + argstr="-gn", + position=8, + ), + ir_flag=dict( + argstr="-IR", + position=13, + ), + lm_val=dict( + argstr="-lm %f %f", + position=7, + ), m0map_file=dict( argstr="-m0map %s", extensions=None, name_source=["source_file"], name_template="%s_m0map.nii.gz", ), - mask=dict(argstr="-mask %s", extensions=None, position=2,), - maxit=dict(argstr="-maxit %d", position=11,), + mask=dict( + argstr="-mask %s", + extensions=None, + position=2, + ), + maxit=dict( + argstr="-maxit %d", + position=11, + ), mcmap_file=dict( argstr="-mcmap %s", extensions=None, name_source=["source_file"], name_template="%s_mcmap.nii.gz", ), - mcmaxit=dict(argstr="-mcmaxit %d",), - mcout=dict(argstr="-mcout %s", extensions=None,), - mcsamples=dict(argstr="-mcsamples %d",), - nb_comp=dict(argstr="-nc %d", position=6,), - prior=dict(argstr="-prior %s", extensions=None, position=3,), + mcmaxit=dict( + argstr="-mcmaxit %d", + ), + mcout=dict( + argstr="-mcout %s", + extensions=None, + ), + mcsamples=dict( + argstr="-mcsamples %d", + ), + nb_comp=dict( + argstr="-nc %d", + position=6, + ), + prior=dict( + argstr="-prior %s", + extensions=None, + position=3, + ), res_file=dict( argstr="-res %s", extensions=None, name_source=["source_file"], name_template="%s_res.nii.gz", ), - slice_no=dict(argstr="-slice %d", position=9,), + slice_no=dict( + argstr="-slice %d", + position=9, + ), source_file=dict( - argstr="-source %s", extensions=None, mandatory=True, position=1, + argstr="-source %s", + extensions=None, + mandatory=True, + position=1, + ), + spgr=dict( + argstr="-SPGR", + ), + sr_flag=dict( + argstr="-SR", + position=12, ), - spgr=dict(argstr="-SPGR",), - sr_flag=dict(argstr="-SR", position=12,), syn_file=dict( argstr="-syn %s", extensions=None, name_source=["source_file"], name_template="%s_syn.nii.gz", ), - t1_list=dict(argstr="-T1list %s", extensions=None,), + t1_list=dict( + argstr="-T1list %s", + extensions=None, + ), t1map_file=dict( argstr="-t1map %s", extensions=None, name_source=["source_file"], name_template="%s_t1map.nii.gz", ), - t1max=dict(argstr="-T1max %f",), - t1min=dict(argstr="-T1min %f",), - te_value=dict(argstr="-TE %f", position=4,), - tis=dict(argstr="-TIs %s", position=14, sep=" ",), - tis_list=dict(argstr="-TIlist %s", extensions=None,), - tr_value=dict(argstr="-TR %f", position=5,), - voxel=dict(argstr="-voxel %d %d %d", position=10,), + t1max=dict( + argstr="-T1max %f", + ), + t1min=dict( + argstr="-T1min %f", + ), + te_value=dict( + argstr="-TE %f", + position=4, + ), + tis=dict( + argstr="-TIs %s", + position=14, + sep=" ", + ), + tis_list=dict( + argstr="-TIlist %s", + extensions=None, + ), + tr_value=dict( + argstr="-TR %f", + position=5, + ), + voxel=dict( + argstr="-voxel %d %d %d", + position=10, + ), ) inputs = FitQt1.input_spec() @@ -86,13 +166,27 @@ def test_FitQt1_inputs(): def test_FitQt1_outputs(): output_map = dict( - comp_file=dict(extensions=None,), - error_file=dict(extensions=None,), - m0map_file=dict(extensions=None,), - mcmap_file=dict(extensions=None,), - res_file=dict(extensions=None,), - syn_file=dict(extensions=None,), - t1map_file=dict(extensions=None,), + comp_file=dict( + extensions=None, + ), + error_file=dict( + extensions=None, + ), + m0map_file=dict( + extensions=None, + ), + mcmap_file=dict( + extensions=None, + ), + res_file=dict( + extensions=None, + ), + syn_file=dict( + extensions=None, + ), + t1map_file=dict( + extensions=None, + ), ) outputs = FitQt1.output_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_auto_NiftyFitCommand.py b/nipype/interfaces/niftyfit/tests/test_auto_NiftyFitCommand.py index e6fb0b0bbb..f12ccad480 100644 --- a/nipype/interfaces/niftyfit/tests/test_auto_NiftyFitCommand.py +++ b/nipype/interfaces/niftyfit/tests/test_auto_NiftyFitCommand.py @@ -4,7 +4,13 @@ def test_NiftyFitCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = NiftyFitCommand.input_spec() diff --git a/nipype/interfaces/niftyfit/tests/test_dwi.py b/nipype/interfaces/niftyfit/tests/test_dwi.py index a726301203..e3bfab3d66 100644 --- a/nipype/interfaces/niftyfit/tests/test_dwi.py +++ b/nipype/interfaces/niftyfit/tests/test_dwi.py @@ -12,7 +12,7 @@ @pytest.mark.skipif(no_nifty_tool(cmd="fit_dwi"), reason="niftyfit is not installed") def test_fit_dwi(): - """ Testing FitDwi interface.""" + """Testing FitDwi interface.""" # Create a node object fit_dwi = FitDwi() @@ -60,7 +60,7 @@ def test_fit_dwi(): @pytest.mark.skipif(no_nifty_tool(cmd="dwi_tool"), reason="niftyfit is not installed") def test_dwi_tool(): - """ Testing DwiTool interface.""" + """Testing DwiTool interface.""" # Create a node object dwi_tool = DwiTool() diff --git a/nipype/interfaces/niftyfit/tests/test_qt1.py b/nipype/interfaces/niftyfit/tests/test_qt1.py index 9146e7e97f..794e6c5130 100644 --- a/nipype/interfaces/niftyfit/tests/test_qt1.py +++ b/nipype/interfaces/niftyfit/tests/test_qt1.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -12,7 +11,7 @@ @pytest.mark.skipif(no_nifty_tool(cmd="fit_qt1"), reason="niftyfit is not installed") def test_fit_qt1(): - """ Testing FitQt1 interface.""" + """Testing FitQt1 interface.""" # Create a node object fit_qt1 = FitQt1() diff --git a/nipype/interfaces/niftyreg/__init__.py b/nipype/interfaces/niftyreg/__init__.py index 1bc01a9ad5..e22eae03ed 100644 --- a/nipype/interfaces/niftyreg/__init__.py +++ b/nipype/interfaces/niftyreg/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/interfaces/niftyreg/base.py b/nipype/interfaces/niftyreg/base.py index aa343dcfcb..76555c3573 100644 --- a/nipype/interfaces/niftyreg/base.py +++ b/nipype/interfaces/niftyreg/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -15,11 +14,11 @@ See the docstrings of the individual classes for examples. """ -from distutils.version import StrictVersion import os +from packaging.version import Version from ... import logging -from ..base import CommandLine, CommandLineInputSpec, traits, Undefined +from ..base import CommandLine, CommandLineInputSpec, traits, Undefined, PackageInfo from ...utils.filemanip import split_filename iflogger = logging.getLogger("nipype.interface") @@ -29,6 +28,14 @@ def get_custom_path(command, env_dir="NIFTYREGDIR"): return os.path.join(os.getenv(env_dir, ""), command) +class Info(PackageInfo): + version_cmd = get_custom_path("reg_aladin") + " --version" + + @staticmethod + def parse_version(raw_info): + return raw_info + + class NiftyRegCommandInputSpec(CommandLineInputSpec): """Input Spec for niftyreg interfaces.""" @@ -53,18 +60,17 @@ class NiftyRegCommand(CommandLine): def __init__(self, required_version=None, **inputs): self.num_threads = 1 - super(NiftyRegCommand, self).__init__(**inputs) + super().__init__(**inputs) self.required_version = required_version - _version = self.version_from_command() + _version = self.version if _version: - _version = _version.decode("utf-8") - if self._min_version is not None and StrictVersion( - _version - ) < StrictVersion(self._min_version): + if self._min_version is not None and Version(_version) < Version( + self._min_version + ): msg = "A later version of Niftyreg is required (%s < %s)" iflogger.warning(msg, _version, self._min_version) if required_version is not None: - if StrictVersion(_version) != StrictVersion(required_version): + if Version(_version) != Version(required_version): msg = "The version of NiftyReg differs from the required" msg += "(%s != %s)" iflogger.warning(msg, _version, self.required_version) @@ -91,31 +97,29 @@ def _environ_update(self): self.inputs.omp_core_val = Undefined def check_version(self): - _version = self.version_from_command() + _version = self.version if not _version: raise Exception("Niftyreg not found") - # Decoding to string: - _version = _version.decode("utf-8") - if StrictVersion(_version) < StrictVersion(self._min_version): + if Version(_version) < Version(self._min_version): err = "A later version of Niftyreg is required (%s < %s)" raise ValueError(err % (_version, self._min_version)) if self.required_version: - if StrictVersion(_version) != StrictVersion(self.required_version): + if Version(_version) != Version(self.required_version): err = "The version of NiftyReg differs from the required" err += "(%s != %s)" raise ValueError(err % (_version, self.required_version)) @property def version(self): - return self.version_from_command() + return Info.version() def exists(self): - return self.version_from_command() is not None + return self.version is not None def _format_arg(self, name, spec, value): if name == "omp_core_val": self.numthreads = value - return super(NiftyRegCommand, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _gen_fname(self, basename, out_dir=None, suffix=None, ext=None): if basename == "": @@ -128,5 +132,5 @@ def _gen_fname(self, basename, out_dir=None, suffix=None, ext=None): if ext is not None: final_ext = ext if suffix is not None: - final_bn = "".join((final_bn, suffix)) + final_bn = f"{final_bn}{suffix}" return os.path.abspath(os.path.join(out_dir, final_bn + final_ext)) diff --git a/nipype/interfaces/niftyreg/reg.py b/nipype/interfaces/niftyreg/reg.py index f149006d49..2c7657e6ae 100644 --- a/nipype/interfaces/niftyreg/reg.py +++ b/nipype/interfaces/niftyreg/reg.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -9,13 +8,13 @@ """ import os -from ..base import TraitedSpec, File, traits, isdefined +from ..base import TraitedSpec, File, traits, Tuple, isdefined from .base import get_custom_path, NiftyRegCommand, NiftyRegCommandInputSpec from ...utils.filemanip import split_filename class RegAladinInputSpec(NiftyRegCommandInputSpec): - """ Input Spec for RegAladin. """ + """Input Spec for RegAladin.""" # Input reference file ref_file = File( @@ -116,7 +115,7 @@ class RegAladinInputSpec(NiftyRegCommandInputSpec): class RegAladinOutputSpec(TraitedSpec): - """ Output Spec for RegAladin. """ + """Output Spec for RegAladin.""" aff_file = File(desc="The output affine file") res_file = File(desc="The output transformed image") @@ -153,17 +152,17 @@ class RegAladin(NiftyRegCommand): output_spec = RegAladinOutputSpec def _list_outputs(self): - outputs = super(RegAladin, self)._list_outputs() + outputs = super()._list_outputs() # Make a list of the linear transformation file and the input image aff = os.path.abspath(outputs["aff_file"]) flo = os.path.abspath(self.inputs.flo_file) - outputs["avg_output"] = "%s %s" % (aff, flo) + outputs["avg_output"] = f"{aff} {flo}" return outputs class RegF3DInputSpec(NiftyRegCommandInputSpec): - """ Input Spec for RegF3D. """ + """Input Spec for RegF3D.""" # Input reference file ref_file = File( @@ -219,22 +218,22 @@ class RegF3DInputSpec(NiftyRegCommandInputSpec): # Lower threshold for reference image desc = "Lower threshold for reference image at the specified time point" - rlwth2_thr_val = traits.Tuple( + rlwth2_thr_val = Tuple( traits.Range(low=0), traits.Float, desc=desc, argstr="-rLwTh %d %f" ) # Upper threshold for reference image desc = "Upper threshold for reference image at the specified time point" - rupth2_thr_val = traits.Tuple( + rupth2_thr_val = Tuple( traits.Range(low=0), traits.Float, desc=desc, argstr="-rUpTh %d %f" ) # Lower threshold for reference image desc = "Lower threshold for floating image at the specified time point" - flwth2_thr_val = traits.Tuple( + flwth2_thr_val = Tuple( traits.Range(low=0), traits.Float, desc=desc, argstr="-fLwTh %d %f" ) # Upper threshold for reference image desc = "Upper threshold for floating image at the specified time point" - fupth2_thr_val = traits.Tuple( + fupth2_thr_val = Tuple( traits.Range(low=0), traits.Float, desc=desc, argstr="-fUpTh %d %f" ) @@ -264,14 +263,14 @@ class RegF3DInputSpec(NiftyRegCommandInputSpec): desc = "Number of bins in the histogram for reference image for given \ time point" - rbn2_val = traits.Tuple( + rbn2_val = Tuple( traits.Range(low=0), traits.Range(low=0), desc=desc, argstr="-rbn %d %d" ) desc = "Number of bins in the histogram for reference image for given \ time point" - fbn2_val = traits.Tuple( + fbn2_val = Tuple( traits.Range(low=0), traits.Range(low=0), desc=desc, argstr="-fbn %d %d" ) @@ -279,7 +278,7 @@ class RegF3DInputSpec(NiftyRegCommandInputSpec): desc="SD of the Gaussian for computing LNCC", argstr="--lncc %f" ) desc = "SD of the Gaussian for computing LNCC for a given time point" - lncc2_val = traits.Tuple( + lncc2_val = Tuple( traits.Range(low=0), traits.Float, desc=desc, argstr="-lncc %d %f" ) @@ -343,7 +342,7 @@ class RegF3DInputSpec(NiftyRegCommandInputSpec): class RegF3DOutputSpec(TraitedSpec): - """ Output Spec for RegF3D. """ + """Output Spec for RegF3D.""" cpp_file = File(desc="The output CPP file") res_file = File(desc="The output resampled image") @@ -386,7 +385,7 @@ def _remove_extension(in_file): return os.path.join(dn, bn) def _list_outputs(self): - outputs = super(RegF3D, self)._list_outputs() + outputs = super()._list_outputs() if self.inputs.vel_flag is True: res_name = self._remove_extension(outputs["res_file"]) @@ -398,7 +397,7 @@ def _list_outputs(self): if self.inputs.vel_flag is True and isdefined(self.inputs.aff_file): cpp_file = os.path.abspath(outputs["cpp_file"]) flo_file = os.path.abspath(self.inputs.flo_file) - outputs["avg_output"] = "%s %s %s" % ( + outputs["avg_output"] = "{} {} {}".format( self.inputs.aff_file, cpp_file, flo_file, @@ -406,6 +405,6 @@ def _list_outputs(self): else: cpp_file = os.path.abspath(outputs["cpp_file"]) flo_file = os.path.abspath(self.inputs.flo_file) - outputs["avg_output"] = "%s %s" % (cpp_file, flo_file) + outputs["avg_output"] = f"{cpp_file} {flo_file}" return outputs diff --git a/nipype/interfaces/niftyreg/regutils.py b/nipype/interfaces/niftyreg/regutils.py index 032f106933..c69cde5a83 100644 --- a/nipype/interfaces/niftyreg/regutils.py +++ b/nipype/interfaces/niftyreg/regutils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The regutils module provides classes for interfacing with the `niftyreg @@ -8,13 +7,13 @@ """ import os -from ..base import TraitedSpec, File, traits, isdefined +from ..base import TraitedSpec, File, traits, Tuple, isdefined from .base import get_custom_path, NiftyRegCommand, NiftyRegCommandInputSpec from ...utils.filemanip import split_filename class RegResampleInputSpec(NiftyRegCommandInputSpec): - """ Input Spec for RegResample. """ + """Input Spec for RegResample.""" # Input reference file ref_file = File( @@ -78,7 +77,7 @@ class RegResampleInputSpec(NiftyRegCommandInputSpec): class RegResampleOutputSpec(TraitedSpec): - """ Output Spec for RegResample. """ + """Output Spec for RegResample.""" out_file = File(desc="The output filename of the transformed image") @@ -117,16 +116,16 @@ def _format_arg(self, name, spec, value): inter_val = {"NN": 0, "LIN": 1, "CUB": 3, "SINC": 4} return spec.argstr % inter_val[value] else: - return super(RegResample, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) def _overload_extension(self, value, name=None): path, base, _ = split_filename(value) suffix = self.inputs.type - return os.path.join(path, "{0}_{1}.nii.gz".format(base, suffix)) + return os.path.join(path, f"{base}_{suffix}.nii.gz") class RegJacobianInputSpec(NiftyRegCommandInputSpec): - """ Input Spec for RegJacobian. """ + """Input Spec for RegJacobian.""" # Reference file name desc = "Reference/target file (required if specifying CPP transformations." @@ -157,7 +156,7 @@ class RegJacobianInputSpec(NiftyRegCommandInputSpec): class RegJacobianOutputSpec(TraitedSpec): - """ Output Spec for RegJacobian. """ + """Output Spec for RegJacobian.""" out_file = File(desc="The output file") @@ -190,11 +189,11 @@ class RegJacobian(NiftyRegCommand): def _overload_extension(self, value, name=None): path, base, _ = split_filename(value) suffix = self.inputs.type - return os.path.join(path, "{0}_{1}.nii.gz".format(base, suffix)) + return os.path.join(path, f"{base}_{suffix}.nii.gz") class RegToolsInputSpec(NiftyRegCommandInputSpec): - """ Input Spec for RegTools. """ + """Input Spec for RegTools.""" # Input image file in_file = File( @@ -271,12 +270,12 @@ class RegToolsInputSpec(NiftyRegCommandInputSpec): # Smoothing using spline kernel desc = "Smooth the input image using a cubic spline kernel" - smo_s_val = traits.Tuple( + smo_s_val = Tuple( traits.Float, traits.Float, traits.Float, desc=desc, argstr="-smoS %f %f %f" ) # Change the resolution of the input image - chg_res_val = traits.Tuple( + chg_res_val = Tuple( traits.Float, traits.Float, traits.Float, @@ -286,7 +285,7 @@ class RegToolsInputSpec(NiftyRegCommandInputSpec): # Smoothing using Gaussian kernel desc = "Smooth the input image using a Gaussian kernel" - smo_g_val = traits.Tuple( + smo_g_val = Tuple( traits.Float, traits.Float, traits.Float, desc=desc, argstr="-smoG %f %f %f" ) @@ -302,7 +301,7 @@ class RegToolsInputSpec(NiftyRegCommandInputSpec): class RegToolsOutputSpec(TraitedSpec): - """ Output Spec for RegTools. """ + """Output Spec for RegTools.""" out_file = File(desc="The output file", exists=True) @@ -339,11 +338,11 @@ def _format_arg(self, name, spec, value): inter_val = {"NN": 0, "LIN": 1, "CUB": 3, "SINC": 4} return spec.argstr % inter_val[value] else: - return super(RegTools, self)._format_arg(name, spec, value) + return super()._format_arg(name, spec, value) class RegAverageInputSpec(NiftyRegCommandInputSpec): - """ Input Spec for RegAverage. """ + """Input Spec for RegAverage.""" avg_files = traits.List( File(exist=True), @@ -462,7 +461,7 @@ class RegAverageInputSpec(NiftyRegCommandInputSpec): class RegAverageOutputSpec(TraitedSpec): - """ Output Spec for RegAverage. """ + """Output Spec for RegAverage.""" out_file = File(desc="Output file name") @@ -522,16 +521,16 @@ def _list_outputs(self): @property def cmdline(self): - """ Rewrite the cmdline to write options in text_file.""" - argv = super(RegAverage, self).cmdline + """Rewrite the cmdline to write options in text_file.""" + argv = super().cmdline reg_average_cmd = os.path.join(os.getcwd(), "reg_average_cmd") with open(reg_average_cmd, "w") as f: f.write(argv) - return "%s --cmd_file %s" % (self.cmd, reg_average_cmd) + return f"{self.cmd} --cmd_file {reg_average_cmd}" class RegTransformInputSpec(NiftyRegCommandInputSpec): - """ Input Spec for RegTransform. """ + """Input Spec for RegTransform.""" ref1_file = File( exists=True, @@ -674,7 +673,7 @@ class RegTransformInputSpec(NiftyRegCommandInputSpec): ], ) - inv_nrr_input = traits.Tuple( + inv_nrr_input = Tuple( File(exists=True), File(exists=True), desc="Invert a non-linear transformation", @@ -714,7 +713,7 @@ class RegTransformInputSpec(NiftyRegCommandInputSpec): ) argstr_tmp = "-makeAff %f %f %f %f %f %f %f %f %f %f %f %f" - make_aff_input = traits.Tuple( + make_aff_input = Tuple( traits.Float, traits.Float, traits.Float, @@ -767,7 +766,7 @@ class RegTransformInputSpec(NiftyRegCommandInputSpec): desc = "Convert a FLIRT affine transformation to niftyreg affine \ transformation" - flirt_2_nr_input = traits.Tuple( + flirt_2_nr_input = Tuple( File(exists=True), File(exists=True), File(exists=True), @@ -794,7 +793,7 @@ class RegTransformInputSpec(NiftyRegCommandInputSpec): class RegTransformOutputSpec(TraitedSpec): - """ Output Spec for RegTransform. """ + """Output Spec for RegTransform.""" out_file = File(desc="Output File (transformation in any format)") @@ -894,7 +893,7 @@ def _list_outputs(self): class RegMeasureInputSpec(NiftyRegCommandInputSpec): - """ Input Spec for RegMeasure. """ + """Input Spec for RegMeasure.""" # Input reference file ref_file = File( @@ -928,7 +927,7 @@ class RegMeasureInputSpec(NiftyRegCommandInputSpec): class RegMeasureOutputSpec(TraitedSpec): - """ Output Spec for RegMeasure. """ + """Output Spec for RegMeasure.""" out_file = File(desc="The output text file containing the measure") @@ -960,4 +959,4 @@ class RegMeasure(NiftyRegCommand): def _overload_extension(self, value, name=None): path, base, _ = split_filename(value) suffix = self.inputs.measure_type - return os.path.join(path, "{0}_{1}.txt".format(base, suffix)) + return os.path.join(path, f"{base}_{suffix}.txt") diff --git a/nipype/interfaces/niftyreg/tests/__init__.py b/nipype/interfaces/niftyreg/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/niftyreg/tests/__init__.py +++ b/nipype/interfaces/niftyreg/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/niftyreg/tests/test_auto_NiftyRegCommand.py b/nipype/interfaces/niftyreg/tests/test_auto_NiftyRegCommand.py index 75e103edbe..43f72df69f 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_NiftyRegCommand.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_NiftyRegCommand.py @@ -4,9 +4,17 @@ def test_NiftyRegCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), ) inputs = NiftyRegCommand.input_spec() diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegAladin.py b/nipype/interfaces/niftyreg/tests/test_auto_RegAladin.py index 16ca83bdba..a4485d0e20 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegAladin.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegAladin.py @@ -4,45 +4,108 @@ def test_RegAladin_inputs(): input_map = dict( - aff_direct_flag=dict(argstr="-affDirect",), + aff_direct_flag=dict( + argstr="-affDirect", + ), aff_file=dict( argstr="-aff %s", extensions=None, name_source=["flo_file"], name_template="%s_aff.txt", ), - args=dict(argstr="%s",), - cog_flag=dict(argstr="-cog",), - environ=dict(nohash=True, usedefault=True,), - flo_file=dict(argstr="-flo %s", extensions=None, mandatory=True,), - flo_low_val=dict(argstr="-floLowThr %f",), - flo_up_val=dict(argstr="-floUpThr %f",), - fmask_file=dict(argstr="-fmask %s", extensions=None,), - gpuid_val=dict(argstr="-gpuid %i",), - i_val=dict(argstr="-pi %d",), - in_aff_file=dict(argstr="-inaff %s", extensions=None,), - ln_val=dict(argstr="-ln %d",), - lp_val=dict(argstr="-lp %d",), - maxit_val=dict(argstr="-maxit %d",), - nac_flag=dict(argstr="-nac",), - nosym_flag=dict(argstr="-noSym",), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), - platform_val=dict(argstr="-platf %i",), - ref_file=dict(argstr="-ref %s", extensions=None, mandatory=True,), - ref_low_val=dict(argstr="-refLowThr %f",), - ref_up_val=dict(argstr="-refUpThr %f",), + args=dict( + argstr="%s", + ), + cog_flag=dict( + argstr="-cog", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flo_file=dict( + argstr="-flo %s", + extensions=None, + mandatory=True, + ), + flo_low_val=dict( + argstr="-floLowThr %f", + ), + flo_up_val=dict( + argstr="-floUpThr %f", + ), + fmask_file=dict( + argstr="-fmask %s", + extensions=None, + ), + gpuid_val=dict( + argstr="-gpuid %i", + ), + i_val=dict( + argstr="-pi %d", + ), + in_aff_file=dict( + argstr="-inaff %s", + extensions=None, + ), + ln_val=dict( + argstr="-ln %d", + ), + lp_val=dict( + argstr="-lp %d", + ), + maxit_val=dict( + argstr="-maxit %d", + ), + nac_flag=dict( + argstr="-nac", + ), + nosym_flag=dict( + argstr="-noSym", + ), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), + platform_val=dict( + argstr="-platf %i", + ), + ref_file=dict( + argstr="-ref %s", + extensions=None, + mandatory=True, + ), + ref_low_val=dict( + argstr="-refLowThr %f", + ), + ref_up_val=dict( + argstr="-refUpThr %f", + ), res_file=dict( argstr="-res %s", extensions=None, name_source=["flo_file"], name_template="%s_res.nii.gz", ), - rig_only_flag=dict(argstr="-rigOnly",), - rmask_file=dict(argstr="-rmask %s", extensions=None,), - smoo_f_val=dict(argstr="-smooF %f",), - smoo_r_val=dict(argstr="-smooR %f",), - v_val=dict(argstr="-pv %d",), - verbosity_off_flag=dict(argstr="-voff",), + rig_only_flag=dict( + argstr="-rigOnly", + ), + rmask_file=dict( + argstr="-rmask %s", + extensions=None, + ), + smoo_f_val=dict( + argstr="-smooF %f", + ), + smoo_r_val=dict( + argstr="-smooR %f", + ), + v_val=dict( + argstr="-pv %d", + ), + verbosity_off_flag=dict( + argstr="-voff", + ), ) inputs = RegAladin.input_spec() @@ -53,9 +116,13 @@ def test_RegAladin_inputs(): def test_RegAladin_outputs(): output_map = dict( - aff_file=dict(extensions=None,), + aff_file=dict( + extensions=None, + ), avg_output=dict(), - res_file=dict(extensions=None,), + res_file=dict( + extensions=None, + ), ) outputs = RegAladin.output_spec() diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegAverage.py b/nipype/interfaces/niftyreg/tests/test_auto_RegAverage.py index 3ee172453f..0077b85faa 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegAverage.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegAverage.py @@ -4,7 +4,9 @@ def test_RegAverage_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), avg_files=dict( argstr="-avg %s", position=1, @@ -83,11 +85,25 @@ def test_RegAverage_inputs(): "demean2_ref_file", ], ), - environ=dict(nohash=True, usedefault=True,), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), - out_file=dict(argstr="%s", extensions=None, genfile=True, position=0,), + environ=dict( + nohash=True, + usedefault=True, + ), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=0, + ), warp_files=dict( - argstr="%s", position=-1, sep=" ", xor=["avg_files", "avg_lts_files"], + argstr="%s", + position=-1, + sep=" ", + xor=["avg_files", "avg_lts_files"], ), ) inputs = RegAverage.input_spec() @@ -98,7 +114,11 @@ def test_RegAverage_inputs(): def test_RegAverage_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = RegAverage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegF3D.py b/nipype/interfaces/niftyreg/tests/test_auto_RegF3D.py index a70318cd43..b760ebb3d1 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegF3D.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegF3D.py @@ -4,69 +4,181 @@ def test_RegF3D_inputs(): input_map = dict( - aff_file=dict(argstr="-aff %s", extensions=None,), - amc_flag=dict(argstr="-amc",), - args=dict(argstr="%s",), - be_val=dict(argstr="-be %f",), + aff_file=dict( + argstr="-aff %s", + extensions=None, + ), + amc_flag=dict( + argstr="-amc", + ), + args=dict( + argstr="%s", + ), + be_val=dict( + argstr="-be %f", + ), cpp_file=dict( argstr="-cpp %s", extensions=None, name_source=["flo_file"], name_template="%s_cpp.nii.gz", ), - environ=dict(nohash=True, usedefault=True,), - fbn2_val=dict(argstr="-fbn %d %d",), - fbn_val=dict(argstr="--fbn %d",), - flo_file=dict(argstr="-flo %s", extensions=None, mandatory=True,), - flo_smooth_val=dict(argstr="-smooF %f",), - flwth2_thr_val=dict(argstr="-fLwTh %d %f",), - flwth_thr_val=dict(argstr="--fLwTh %f",), - fmask_file=dict(argstr="-fmask %s", extensions=None,), - fupth2_thr_val=dict(argstr="-fUpTh %d %f",), - fupth_thr_val=dict(argstr="--fUpTh %f",), - incpp_file=dict(argstr="-incpp %s", extensions=None,), - jl_val=dict(argstr="-jl %f",), - kld2_flag=dict(argstr="-kld %d",), - kld_flag=dict(argstr="--kld",), - le_val=dict(argstr="-le %f",), - ln_val=dict(argstr="-ln %d",), - lncc2_val=dict(argstr="-lncc %d %f",), - lncc_val=dict(argstr="--lncc %f",), - lp_val=dict(argstr="-lp %d",), - maxit_val=dict(argstr="-maxit %d",), - nmi_flag=dict(argstr="--nmi",), - no_app_jl_flag=dict(argstr="-noAppJL",), - noconj_flag=dict(argstr="-noConj",), - nopy_flag=dict(argstr="-nopy",), - nox_flag=dict(argstr="-nox",), - noy_flag=dict(argstr="-noy",), - noz_flag=dict(argstr="-noz",), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), - pad_val=dict(argstr="-pad %f",), - pert_val=dict(argstr="-pert %d",), - rbn2_val=dict(argstr="-rbn %d %d",), - rbn_val=dict(argstr="--rbn %d",), - ref_file=dict(argstr="-ref %s", extensions=None, mandatory=True,), - ref_smooth_val=dict(argstr="-smooR %f",), + environ=dict( + nohash=True, + usedefault=True, + ), + fbn2_val=dict( + argstr="-fbn %d %d", + ), + fbn_val=dict( + argstr="--fbn %d", + ), + flo_file=dict( + argstr="-flo %s", + extensions=None, + mandatory=True, + ), + flo_smooth_val=dict( + argstr="-smooF %f", + ), + flwth2_thr_val=dict( + argstr="-fLwTh %d %f", + ), + flwth_thr_val=dict( + argstr="--fLwTh %f", + ), + fmask_file=dict( + argstr="-fmask %s", + extensions=None, + ), + fupth2_thr_val=dict( + argstr="-fUpTh %d %f", + ), + fupth_thr_val=dict( + argstr="--fUpTh %f", + ), + incpp_file=dict( + argstr="-incpp %s", + extensions=None, + ), + jl_val=dict( + argstr="-jl %f", + ), + kld2_flag=dict( + argstr="-kld %d", + ), + kld_flag=dict( + argstr="--kld", + ), + le_val=dict( + argstr="-le %f", + ), + ln_val=dict( + argstr="-ln %d", + ), + lncc2_val=dict( + argstr="-lncc %d %f", + ), + lncc_val=dict( + argstr="--lncc %f", + ), + lp_val=dict( + argstr="-lp %d", + ), + maxit_val=dict( + argstr="-maxit %d", + ), + nmi_flag=dict( + argstr="--nmi", + ), + no_app_jl_flag=dict( + argstr="-noAppJL", + ), + noconj_flag=dict( + argstr="-noConj", + ), + nopy_flag=dict( + argstr="-nopy", + ), + nox_flag=dict( + argstr="-nox", + ), + noy_flag=dict( + argstr="-noy", + ), + noz_flag=dict( + argstr="-noz", + ), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), + pad_val=dict( + argstr="-pad %f", + ), + pert_val=dict( + argstr="-pert %d", + ), + rbn2_val=dict( + argstr="-rbn %d %d", + ), + rbn_val=dict( + argstr="--rbn %d", + ), + ref_file=dict( + argstr="-ref %s", + extensions=None, + mandatory=True, + ), + ref_smooth_val=dict( + argstr="-smooR %f", + ), res_file=dict( argstr="-res %s", extensions=None, name_source=["flo_file"], name_template="%s_res.nii.gz", ), - rlwth2_thr_val=dict(argstr="-rLwTh %d %f",), - rlwth_thr_val=dict(argstr="--rLwTh %f",), - rmask_file=dict(argstr="-rmask %s", extensions=None,), - rupth2_thr_val=dict(argstr="-rUpTh %d %f",), - rupth_thr_val=dict(argstr="--rUpTh %f",), - smooth_grad_val=dict(argstr="-smoothGrad %f",), - ssd2_flag=dict(argstr="-ssd %d",), - ssd_flag=dict(argstr="--ssd",), - sx_val=dict(argstr="-sx %f",), - sy_val=dict(argstr="-sy %f",), - sz_val=dict(argstr="-sz %f",), - vel_flag=dict(argstr="-vel",), - verbosity_off_flag=dict(argstr="-voff",), + rlwth2_thr_val=dict( + argstr="-rLwTh %d %f", + ), + rlwth_thr_val=dict( + argstr="--rLwTh %f", + ), + rmask_file=dict( + argstr="-rmask %s", + extensions=None, + ), + rupth2_thr_val=dict( + argstr="-rUpTh %d %f", + ), + rupth_thr_val=dict( + argstr="--rUpTh %f", + ), + smooth_grad_val=dict( + argstr="-smoothGrad %f", + ), + ssd2_flag=dict( + argstr="-ssd %d", + ), + ssd_flag=dict( + argstr="--ssd", + ), + sx_val=dict( + argstr="-sx %f", + ), + sy_val=dict( + argstr="-sy %f", + ), + sz_val=dict( + argstr="-sz %f", + ), + vel_flag=dict( + argstr="-vel", + ), + verbosity_off_flag=dict( + argstr="-voff", + ), ) inputs = RegF3D.input_spec() @@ -78,10 +190,18 @@ def test_RegF3D_inputs(): def test_RegF3D_outputs(): output_map = dict( avg_output=dict(), - cpp_file=dict(extensions=None,), - invcpp_file=dict(extensions=None,), - invres_file=dict(extensions=None,), - res_file=dict(extensions=None,), + cpp_file=dict( + extensions=None, + ), + invcpp_file=dict( + extensions=None, + ), + invres_file=dict( + extensions=None, + ), + res_file=dict( + extensions=None, + ), ) outputs = RegF3D.output_spec() diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegJacobian.py b/nipype/interfaces/niftyreg/tests/test_auto_RegJacobian.py index 5a0291e1af..60c8ce5c08 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegJacobian.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegJacobian.py @@ -4,9 +4,17 @@ def test_RegJacobian_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), out_file=dict( argstr="%s", extensions=None, @@ -14,9 +22,20 @@ def test_RegJacobian_inputs(): name_template="%s", position=-1, ), - ref_file=dict(argstr="-ref %s", extensions=None,), - trans_file=dict(argstr="-trans %s", extensions=None, mandatory=True,), - type=dict(argstr="-%s", position=-2, usedefault=True,), + ref_file=dict( + argstr="-ref %s", + extensions=None, + ), + trans_file=dict( + argstr="-trans %s", + extensions=None, + mandatory=True, + ), + type=dict( + argstr="-%s", + position=-2, + usedefault=True, + ), ) inputs = RegJacobian.input_spec() @@ -26,7 +45,11 @@ def test_RegJacobian_inputs(): def test_RegJacobian_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = RegJacobian.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegMeasure.py b/nipype/interfaces/niftyreg/tests/test_auto_RegMeasure.py index 8ae16aa9c8..8a7e470e6c 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegMeasure.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegMeasure.py @@ -4,18 +4,37 @@ def test_RegMeasure_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - flo_file=dict(argstr="-flo %s", extensions=None, mandatory=True,), - measure_type=dict(argstr="-%s", mandatory=True,), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flo_file=dict( + argstr="-flo %s", + extensions=None, + mandatory=True, + ), + measure_type=dict( + argstr="-%s", + mandatory=True, + ), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, name_source=["flo_file"], name_template="%s", ), - ref_file=dict(argstr="-ref %s", extensions=None, mandatory=True,), + ref_file=dict( + argstr="-ref %s", + extensions=None, + mandatory=True, + ), ) inputs = RegMeasure.input_spec() @@ -25,7 +44,11 @@ def test_RegMeasure_inputs(): def test_RegMeasure_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = RegMeasure.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegResample.py b/nipype/interfaces/niftyreg/tests/test_auto_RegResample.py index 2836efb4f8..6d9c9a93e5 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegResample.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegResample.py @@ -4,11 +4,25 @@ def test_RegResample_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - flo_file=dict(argstr="-flo %s", extensions=None, mandatory=True,), - inter_val=dict(argstr="-inter %d",), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + flo_file=dict( + argstr="-flo %s", + extensions=None, + mandatory=True, + ), + inter_val=dict( + argstr="-inter %d", + ), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), out_file=dict( argstr="%s", extensions=None, @@ -16,14 +30,35 @@ def test_RegResample_inputs(): name_template="%s", position=-1, ), - pad_val=dict(argstr="-pad %f",), - psf_alg=dict(argstr="-psf_alg %d",), - psf_flag=dict(argstr="-psf",), - ref_file=dict(argstr="-ref %s", extensions=None, mandatory=True,), - tensor_flag=dict(argstr="-tensor ",), - trans_file=dict(argstr="-trans %s", extensions=None,), - type=dict(argstr="-%s", position=-2, usedefault=True,), - verbosity_off_flag=dict(argstr="-voff",), + pad_val=dict( + argstr="-pad %f", + ), + psf_alg=dict( + argstr="-psf_alg %d", + ), + psf_flag=dict( + argstr="-psf", + ), + ref_file=dict( + argstr="-ref %s", + extensions=None, + mandatory=True, + ), + tensor_flag=dict( + argstr="-tensor ", + ), + trans_file=dict( + argstr="-trans %s", + extensions=None, + ), + type=dict( + argstr="-%s", + position=-2, + usedefault=True, + ), + verbosity_off_flag=dict( + argstr="-voff", + ), ) inputs = RegResample.input_spec() @@ -33,7 +68,11 @@ def test_RegResample_inputs(): def test_RegResample_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = RegResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegTools.py b/nipype/interfaces/niftyreg/tests/test_auto_RegTools.py index 0b0513ef4d..9abf8184ec 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegTools.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegTools.py @@ -4,31 +4,75 @@ def test_RegTools_inputs(): input_map = dict( - add_val=dict(argstr="-add %s",), - args=dict(argstr="%s",), - bin_flag=dict(argstr="-bin",), - chg_res_val=dict(argstr="-chgres %f %f %f",), - div_val=dict(argstr="-div %s",), - down_flag=dict(argstr="-down",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True,), - inter_val=dict(argstr="-interp %d",), - iso_flag=dict(argstr="-iso",), - mask_file=dict(argstr="-nan %s", extensions=None,), - mul_val=dict(argstr="-mul %s",), - noscl_flag=dict(argstr="-noscl",), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), + add_val=dict( + argstr="-add %s", + ), + args=dict( + argstr="%s", + ), + bin_flag=dict( + argstr="-bin", + ), + chg_res_val=dict( + argstr="-chgres %f %f %f", + ), + div_val=dict( + argstr="-div %s", + ), + down_flag=dict( + argstr="-down", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + ), + inter_val=dict( + argstr="-interp %d", + ), + iso_flag=dict( + argstr="-iso", + ), + mask_file=dict( + argstr="-nan %s", + extensions=None, + ), + mul_val=dict( + argstr="-mul %s", + ), + noscl_flag=dict( + argstr="-noscl", + ), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), out_file=dict( argstr="-out %s", extensions=None, name_source=["in_file"], name_template="%s_tools.nii.gz", ), - rms_val=dict(argstr="-rms %s", extensions=None,), - smo_g_val=dict(argstr="-smoG %f %f %f",), - smo_s_val=dict(argstr="-smoS %f %f %f",), - sub_val=dict(argstr="-sub %s",), - thr_val=dict(argstr="-thr %f",), + rms_val=dict( + argstr="-rms %s", + extensions=None, + ), + smo_g_val=dict( + argstr="-smoG %f %f %f", + ), + smo_s_val=dict( + argstr="-smoS %f %f %f", + ), + sub_val=dict( + argstr="-sub %s", + ), + thr_val=dict( + argstr="-thr %f", + ), ) inputs = RegTools.input_spec() @@ -38,7 +82,11 @@ def test_RegTools_inputs(): def test_RegTools_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = RegTools.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_auto_RegTransform.py b/nipype/interfaces/niftyreg/tests/test_auto_RegTransform.py index 7a16c6e452..b9ee8bf2af 100644 --- a/nipype/interfaces/niftyreg/tests/test_auto_RegTransform.py +++ b/nipype/interfaces/niftyreg/tests/test_auto_RegTransform.py @@ -21,7 +21,9 @@ def test_RegTransform_inputs(): "flirt_2_nr_input", ], ), - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), comp_input=dict( argstr="-comp %s", extensions=None, @@ -40,7 +42,11 @@ def test_RegTransform_inputs(): "flirt_2_nr_input", ], ), - comp_input2=dict(argstr="%s", extensions=None, position=-2,), + comp_input2=dict( + argstr="%s", + extensions=None, + position=-2, + ), def_input=dict( argstr="-def %s", extensions=None, @@ -75,7 +81,10 @@ def test_RegTransform_inputs(): "flirt_2_nr_input", ], ), - environ=dict(nohash=True, usedefault=True,), + environ=dict( + nohash=True, + usedefault=True, + ), flirt_2_nr_input=dict( argstr="-flirtAff2NR %s %s %s", position=-2, @@ -175,11 +184,26 @@ def test_RegTransform_inputs(): "flirt_2_nr_input", ], ), - omp_core_val=dict(argstr="-omp %i", usedefault=True,), - out_file=dict(argstr="%s", extensions=None, genfile=True, position=-1,), - ref1_file=dict(argstr="-ref %s", extensions=None, position=0,), + omp_core_val=dict( + argstr="-omp %i", + usedefault=True, + ), + out_file=dict( + argstr="%s", + extensions=None, + genfile=True, + position=-1, + ), + ref1_file=dict( + argstr="-ref %s", + extensions=None, + position=0, + ), ref2_file=dict( - argstr="-ref2 %s", extensions=None, position=1, requires=["ref1_file"], + argstr="-ref2 %s", + extensions=None, + position=1, + requires=["ref1_file"], ), upd_s_form_input=dict( argstr="-updSform %s", @@ -200,7 +224,10 @@ def test_RegTransform_inputs(): ], ), upd_s_form_input2=dict( - argstr="%s", extensions=None, position=-2, requires=["upd_s_form_input"], + argstr="%s", + extensions=None, + position=-2, + requires=["upd_s_form_input"], ), ) inputs = RegTransform.input_spec() @@ -211,7 +238,11 @@ def test_RegTransform_inputs(): def test_RegTransform_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = RegTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyreg/tests/test_reg.py b/nipype/interfaces/niftyreg/tests/test_reg.py index 77b56e21da..4af3e15bdb 100644 --- a/nipype/interfaces/niftyreg/tests/test_reg.py +++ b/nipype/interfaces/niftyreg/tests/test_reg.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -14,7 +13,7 @@ reason="niftyreg is not installed. reg_aladin not found.", ) def test_reg_aladin(): - """ tests for reg_aladin interface""" + """tests for reg_aladin interface""" # Create a reg_aladin object nr_aladin = RegAladin() @@ -53,7 +52,7 @@ def test_reg_aladin(): no_nifty_tool(cmd="reg_f3d"), reason="niftyreg is not installed. reg_f3d not found." ) def test_reg_f3d(): - """ tests for reg_f3d interface""" + """tests for reg_f3d interface""" # Create a reg_f3d object nr_f3d = RegF3D() diff --git a/nipype/interfaces/niftyreg/tests/test_regutils.py b/nipype/interfaces/niftyreg/tests/test_regutils.py index 26431ddc44..86ec9e5d3a 100644 --- a/nipype/interfaces/niftyreg/tests/test_regutils.py +++ b/nipype/interfaces/niftyreg/tests/test_regutils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -26,7 +25,7 @@ def no_nifty_tool(cmd=None): reason="niftyreg is not installed. reg_resample not found.", ) def test_reg_resample_res(): - """ tests for reg_resample interface """ + """tests for reg_resample interface""" # Create a reg_resample object nr_resample = RegResample() @@ -88,7 +87,7 @@ def test_reg_resample_res(): reason="niftyreg is not installed. reg_jacobian not found.", ) def test_reg_jacobian_jac(): - """ Test interface for RegJacobian """ + """Test interface for RegJacobian""" # Create a reg_jacobian object nr_jacobian = RegJacobian() @@ -156,7 +155,7 @@ def test_reg_jacobian_jac(): reason="niftyreg is not installed. reg_tools not found.", ) def test_reg_tools_mul(): - """ tests for reg_tools interface """ + """tests for reg_tools interface""" # Create a reg_tools object nr_tools = RegTools() @@ -198,7 +197,7 @@ def test_reg_tools_mul(): reason="niftyreg is not installed. reg_average not found.", ) def test_reg_average(): - """ tests for reg_average interface """ + """tests for reg_average interface""" # Create a reg_average object nr_average = RegAverage() @@ -219,7 +218,7 @@ def test_reg_average(): argv = f_obj.read() os.remove(reg_average_cmd) - expected_argv = "%s %s -avg %s %s %s -omp 1" % ( + expected_argv = "{} {} -avg {} {} {} -omp 1".format( get_custom_path("reg_average"), os.path.join(os.getcwd(), "avg_out.nii.gz"), one_file, @@ -230,7 +229,7 @@ def test_reg_average(): assert argv.decode("utf-8") == expected_argv # Test command line with text file - expected_cmd = "%s --cmd_file %s" % ( + expected_cmd = "{} --cmd_file {}".format( get_custom_path("reg_average"), reg_average_cmd, ) @@ -252,7 +251,7 @@ def test_reg_average(): argv = f_obj.read() os.remove(reg_average_cmd) - expected_argv = "%s %s -avg %s %s %s -omp 1" % ( + expected_argv = "{} {} -avg {} {} {} -omp 1".format( get_custom_path("reg_average"), os.path.join(os.getcwd(), "avg_out.txt"), one_file, @@ -277,7 +276,7 @@ def test_reg_average(): argv = f_obj.read() os.remove(reg_average_cmd) - expected_argv = "%s %s -avg_lts %s %s %s -omp 1" % ( + expected_argv = "{} {} -avg_lts {} {} {} -omp 1".format( get_custom_path("reg_average"), os.path.join(os.getcwd(), "avg_out.txt"), one_file, @@ -314,7 +313,7 @@ def test_reg_average(): argv = f_obj.read() os.remove(reg_average_cmd) - expected_argv = "%s %s -avg_tran %s -omp 1 %s %s %s %s %s %s" % ( + expected_argv = "{} {} -avg_tran {} -omp 1 {} {} {} {} {} {}".format( get_custom_path("reg_average"), os.path.join(os.getcwd(), "avg_out.nii.gz"), ref_file, @@ -361,7 +360,7 @@ def test_reg_average(): argv = f_obj.read() os.remove(reg_average_cmd) - expected_argv = "%s %s -demean3 %s -omp 1 %s %s %s %s %s %s %s %s %s" % ( + expected_argv = "{} {} -demean3 {} -omp 1 {} {} {} {} {} {} {} {} {}".format( get_custom_path("reg_average"), os.path.join(os.getcwd(), "avg_out.nii.gz"), ref_file, @@ -384,7 +383,7 @@ def test_reg_average(): reason="niftyreg is not installed. reg_transform not found.", ) def test_reg_transform_def(): - """ tests for reg_transform interface """ + """tests for reg_transform interface""" # Create a reg_transform object nr_transform = RegTransform() @@ -500,7 +499,7 @@ def test_reg_transform_def(): reason="niftyreg is not installed. reg_measure not found.", ) def test_reg_measure(): - """ tests for reg_measure interface """ + """tests for reg_measure interface""" # Create a reg_measure object nr_measure = RegMeasure() diff --git a/nipype/interfaces/niftyseg/base.py b/nipype/interfaces/niftyseg/base.py index 65f1f9ff14..efc6c51721 100644 --- a/nipype/interfaces/niftyseg/base.py +++ b/nipype/interfaces/niftyseg/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -28,9 +27,7 @@ class NiftySegCommand(NiftyFitCommand): _min_version = None def __init__(self, **inputs): - super(NiftySegCommand, self).__init__(**inputs) + super().__init__(**inputs) def get_version(self): - return super(NiftySegCommand, self).version_from_command( - cmd="seg_EM", flag="--version" - ) + return super().version_from_command(cmd="seg_EM", flag="--version") diff --git a/nipype/interfaces/niftyseg/em.py b/nipype/interfaces/niftyseg/em.py index d6fb4d5180..615fe2e64a 100644 --- a/nipype/interfaces/niftyseg/em.py +++ b/nipype/interfaces/niftyseg/em.py @@ -11,7 +11,14 @@ See the docstrings of the individual classes for examples. """ -from ..base import TraitedSpec, File, traits, CommandLineInputSpec, InputMultiPath +from ..base import ( + TraitedSpec, + File, + traits, + Tuple, + CommandLineInputSpec, + InputMultiPath, +) from .base import NiftySegCommand from ..niftyreg.base import get_custom_path @@ -97,16 +104,14 @@ class EMInputSpec(CommandLineInputSpec): Mahalanobis threshold [recommended between 3 and 7] is a convergence \ ratio below which the outlier detection is going to be done [recommended 0.01]" - outlier_val = traits.Tuple( + outlier_val = Tuple( traits.Float(), traits.Float(), argstr="-outlier %s %s", desc=desc ) desc = "Relax Priors [relaxation factor: 00 (recommended=2.0)] /only 3D/" - relax_priors = traits.Tuple( - traits.Float(), traits.Float(), argstr="-rf %s %s", desc=desc - ) + relax_priors = Tuple(traits.Float(), traits.Float(), argstr="-rf %s %s", desc=desc) # outputs out_file = File( @@ -170,4 +175,4 @@ def _format_arg(self, opt, spec, val): _nb_priors = len(self.inputs.priors) return "-priors %d %s" % (_nb_priors, " ".join(self.inputs.priors)) else: - return super(EM, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) diff --git a/nipype/interfaces/niftyseg/label_fusion.py b/nipype/interfaces/niftyseg/label_fusion.py index aa255247d2..56af8a0d20 100644 --- a/nipype/interfaces/niftyseg/label_fusion.py +++ b/nipype/interfaces/niftyseg/label_fusion.py @@ -11,6 +11,7 @@ TraitedSpec, File, traits, + Tuple, isdefined, CommandLineInputSpec, NipypeInterfaceError, @@ -99,7 +100,7 @@ class LabelFusionInput(CommandLineInputSpec): prob_update_flag = traits.Bool(desc=desc, argstr="-prop_update") desc = "Value of P and Q [ 0 < (P,Q) < 1 ] (default = 0.99 0.99)" - set_pq = traits.Tuple(traits.Float, traits.Float, argstr="-setPQ %f %f", desc=desc) + set_pq = Tuple(traits.Float, traits.Float, argstr="-setPQ %f %f", desc=desc) mrf_value = traits.Float( argstr="-MRF_beta %f", desc="MRF prior strength (between 0 and 5)" @@ -186,7 +187,7 @@ def _format_arg(self, opt, spec, val): if opt == "classifier_type" and val == "STEPS": return self.get_steps_args() - return super(LabelFusion, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def get_steps_args(self): if not isdefined(self.inputs.template_file): @@ -283,7 +284,7 @@ def _overload_extension(self, value, name=None): path, base, _ = split_filename(value) _, _, ext = split_filename(self.inputs.in_file) suffix = self.inputs.classifier_type.lower() - return os.path.join(path, "{0}_{1}{2}".format(base, suffix, ext)) + return os.path.join(path, f"{base}_{suffix}{ext}") class CalcTopNCCInputSpec(CommandLineInputSpec): @@ -344,7 +345,7 @@ def aggregate_outputs(self, runtime=None, needed_outputs=None): if runtime is None or not runtime.stdout: try: out_files = load_json(outfile)["files"] - except IOError: + except OSError: return self.run().outputs else: out_files = [] diff --git a/nipype/interfaces/niftyseg/maths.py b/nipype/interfaces/niftyseg/maths.py index c297940695..726dba3e7a 100644 --- a/nipype/interfaces/niftyseg/maths.py +++ b/nipype/interfaces/niftyseg/maths.py @@ -65,7 +65,7 @@ class MathsCommand(NiftySegCommand): The executable seg_maths enables the sequential execution of arithmetic operations, like multiplication (-mul), division (-div) or addition (-add), binarisation (-bin) or thresholding (-thr) operations and - convolution by a Gaussian kernel (-smo). It also alows mathematical + convolution by a Gaussian kernel (-smo). It also allows mathematical morphology based operations like dilation (-dil), erosion (-ero), connected components (-lconcomp) and hole filling (-fill), Euclidean (- euc) and geodesic (-geo) distance transforms, local image similarity @@ -89,7 +89,7 @@ def _overload_extension(self, value, name=None): if suffix != "_merged" and isdefined(self.inputs.operation): suffix = "_" + self.inputs.operation - return os.path.join(path, "{0}{1}{2}".format(base, suffix, ext)) + return os.path.join(path, f"{base}{suffix}{ext}") class UnaryMathsInput(MathsInput): @@ -356,12 +356,12 @@ def _format_arg(self, opt, spec, val): # Only float if val in ["pow", "thr", "uthr", "smo", "edge", "sobel3", "sobel5", "smol"]: if not isdefined(self.inputs.operand_value): - err = "operand_value not set for {0}.".format(val) + err = f"operand_value not set for {val}." raise NipypeInterfaceError(err) # only files elif val in ["min", "llsnorm", "masknan", "hdr_copy"]: if not isdefined(self.inputs.operand_file): - err = "operand_file not set for {0}.".format(val) + err = f"operand_file not set for {val}." raise NipypeInterfaceError(err) # splitinter: elif val == "splitinter": @@ -372,16 +372,16 @@ def _format_arg(self, opt, spec, val): if opt == "operand_value" and float(val) == 0.0: return "0" - return super(BinaryMaths, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _overload_extension(self, value, name=None): if self.inputs.operation == "hdr_copy": path, base, _ = split_filename(value) _, base, ext = split_filename(self.inputs.operand_file) suffix = self.inputs.operation - return os.path.join(path, "{0}{1}{2}".format(base, suffix, ext)) + return os.path.join(path, f"{base}{suffix}{ext}") else: - return super(BinaryMaths, self)._overload_extension(value, name) + return super()._overload_extension(value, name) class BinaryMathsInputInteger(MathsInput): @@ -600,4 +600,4 @@ def _format_arg(self, opt, spec, val): if opt == "merge_files": return "-merge %d %d %s" % (len(val), self.inputs.dimension, " ".join(val)) - return super(Merge, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) diff --git a/nipype/interfaces/niftyseg/stats.py b/nipype/interfaces/niftyseg/stats.py index d872e180eb..8db7764fce 100644 --- a/nipype/interfaces/niftyseg/stats.py +++ b/nipype/interfaces/niftyseg/stats.py @@ -67,7 +67,7 @@ def _parse_stdout(self, stdout): return np.array(out).squeeze() def _run_interface(self, runtime): - new_runtime = super(StatsCommand, self)._run_interface(runtime) + new_runtime = super()._run_interface(runtime) self.output = self._parse_stdout(new_runtime.stdout) return new_runtime @@ -121,7 +121,7 @@ class UnaryStatsInput(StatsInput): * B - Bounding box of all nonzero voxels [ xmin xsize ymin ysize zmin zsize ] * xvox - Output the number of voxels in the x direction. Replace x with y/z for other directions. - * xdim - Output the voxel dimention in the x direction. + * xdim - Output the voxel dimension in the x direction. Replace x with y/z for other directions. """, diff --git a/nipype/interfaces/niftyseg/tests/test_auto_BinaryMaths.py b/nipype/interfaces/niftyseg/tests/test_auto_BinaryMaths.py index ae7bb8a8ef..4c0a962a21 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_BinaryMaths.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_BinaryMaths.py @@ -4,9 +4,19 @@ def test_BinaryMaths_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), operand_file=dict( argstr="%s", extensions=None, @@ -26,7 +36,11 @@ def test_BinaryMaths_inputs(): position=5, xor=["operand_file", "operand_str"], ), - operation=dict(argstr="-%s", mandatory=True, position=4,), + operation=dict( + argstr="-%s", + mandatory=True, + position=4, + ), out_file=dict( argstr="%s", extensions=None, @@ -34,7 +48,10 @@ def test_BinaryMaths_inputs(): name_template="%s", position=-2, ), - output_datatype=dict(argstr="-odt %s", position=-3,), + output_datatype=dict( + argstr="-odt %s", + position=-3, + ), ) inputs = BinaryMaths.input_spec() @@ -44,7 +61,11 @@ def test_BinaryMaths_inputs(): def test_BinaryMaths_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BinaryMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_BinaryMathsInteger.py b/nipype/interfaces/niftyseg/tests/test_auto_BinaryMathsInteger.py index 195a361f58..440cb92bbc 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_BinaryMathsInteger.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_BinaryMathsInteger.py @@ -4,11 +4,29 @@ def test_BinaryMathsInteger_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - operand_value=dict(argstr="%d", mandatory=True, position=5,), - operation=dict(argstr="-%s", mandatory=True, position=4,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + operand_value=dict( + argstr="%d", + mandatory=True, + position=5, + ), + operation=dict( + argstr="-%s", + mandatory=True, + position=4, + ), out_file=dict( argstr="%s", extensions=None, @@ -16,7 +34,10 @@ def test_BinaryMathsInteger_inputs(): name_template="%s", position=-2, ), - output_datatype=dict(argstr="-odt %s", position=-3,), + output_datatype=dict( + argstr="-odt %s", + position=-3, + ), ) inputs = BinaryMathsInteger.input_spec() @@ -26,7 +47,11 @@ def test_BinaryMathsInteger_inputs(): def test_BinaryMathsInteger_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = BinaryMathsInteger.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_BinaryStats.py b/nipype/interfaces/niftyseg/tests/test_auto_BinaryStats.py index 61ef530418..5a5ac7298b 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_BinaryStats.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_BinaryStats.py @@ -4,11 +4,28 @@ def test_BinaryStats_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - larger_voxel=dict(argstr="-t %f", position=-3,), - mask_file=dict(argstr="-m %s", extensions=None, position=-2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + larger_voxel=dict( + argstr="-t %f", + position=-3, + ), + mask_file=dict( + argstr="-m %s", + extensions=None, + position=-2, + ), operand_file=dict( argstr="%s", extensions=None, @@ -17,9 +34,16 @@ def test_BinaryStats_inputs(): xor=["operand_value"], ), operand_value=dict( - argstr="%.8f", mandatory=True, position=5, xor=["operand_file"], + argstr="%.8f", + mandatory=True, + position=5, + xor=["operand_file"], + ), + operation=dict( + argstr="-%s", + mandatory=True, + position=4, ), - operation=dict(argstr="-%s", mandatory=True, position=4,), ) inputs = BinaryStats.input_spec() @@ -29,7 +53,9 @@ def test_BinaryStats_inputs(): def test_BinaryStats_outputs(): - output_map = dict(output=dict(),) + output_map = dict( + output=dict(), + ) outputs = BinaryStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_CalcTopNCC.py b/nipype/interfaces/niftyseg/tests/test_auto_CalcTopNCC.py index f1c16859eb..e0943be61e 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_CalcTopNCC.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_CalcTopNCC.py @@ -4,13 +4,38 @@ def test_CalcTopNCC_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-target %s", extensions=None, mandatory=True, position=1,), - in_templates=dict(argstr="%s", mandatory=True, position=3,), - mask_file=dict(argstr="-mask %s", extensions=None,), - num_templates=dict(argstr="-templates %s", mandatory=True, position=2,), - top_templates=dict(argstr="-n %s", mandatory=True, position=4,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-target %s", + extensions=None, + mandatory=True, + position=1, + ), + in_templates=dict( + argstr="%s", + mandatory=True, + position=3, + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + num_templates=dict( + argstr="-templates %s", + mandatory=True, + position=2, + ), + top_templates=dict( + argstr="-n %s", + mandatory=True, + position=4, + ), ) inputs = CalcTopNCC.input_spec() @@ -20,7 +45,9 @@ def test_CalcTopNCC_inputs(): def test_CalcTopNCC_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = CalcTopNCC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_EM.py b/nipype/interfaces/niftyseg/tests/test_auto_EM.py index ac340e89ff..a0394b174e 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_EM.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_EM.py @@ -4,17 +4,46 @@ def test_EM_inputs(): input_map = dict( - args=dict(argstr="%s",), - bc_order_val=dict(argstr="-bc_order %s", usedefault=True,), - bc_thresh_val=dict(argstr="-bc_thresh %s", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True, position=4,), - mask_file=dict(argstr="-mask %s", extensions=None,), - max_iter=dict(argstr="-max_iter %s", usedefault=True,), - min_iter=dict(argstr="-min_iter %s", usedefault=True,), - mrf_beta_val=dict(argstr="-mrf_beta %s",), + args=dict( + argstr="%s", + ), + bc_order_val=dict( + argstr="-bc_order %s", + usedefault=True, + ), + bc_thresh_val=dict( + argstr="-bc_thresh %s", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + position=4, + ), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + max_iter=dict( + argstr="-max_iter %s", + usedefault=True, + ), + min_iter=dict( + argstr="-min_iter %s", + usedefault=True, + ), + mrf_beta_val=dict( + argstr="-mrf_beta %s", + ), no_prior=dict( - argstr="-nopriors %s", mandatory=True, xor=["prior_4D", "priors"], + argstr="-nopriors %s", + mandatory=True, + xor=["prior_4D", "priors"], ), out_bc_file=dict( argstr="-bc_out %s", @@ -34,16 +63,26 @@ def test_EM_inputs(): name_source=["in_file"], name_template="%s_outlier_em.nii.gz", ), - outlier_val=dict(argstr="-outlier %s %s",), + outlier_val=dict( + argstr="-outlier %s %s", + ), prior_4D=dict( argstr="-prior4D %s", extensions=None, mandatory=True, xor=["no_prior", "priors"], ), - priors=dict(argstr="%s", mandatory=True, xor=["no_prior", "prior_4D"],), - reg_val=dict(argstr="-reg %s",), - relax_priors=dict(argstr="-rf %s %s",), + priors=dict( + argstr="%s", + mandatory=True, + xor=["no_prior", "prior_4D"], + ), + reg_val=dict( + argstr="-reg %s", + ), + relax_priors=dict( + argstr="-rf %s %s", + ), ) inputs = EM.input_spec() @@ -54,9 +93,15 @@ def test_EM_inputs(): def test_EM_outputs(): output_map = dict( - out_bc_file=dict(extensions=None,), - out_file=dict(extensions=None,), - out_outlier_file=dict(extensions=None,), + out_bc_file=dict( + extensions=None, + ), + out_file=dict( + extensions=None, + ), + out_outlier_file=dict( + extensions=None, + ), ) outputs = EM.output_spec() diff --git a/nipype/interfaces/niftyseg/tests/test_auto_FillLesions.py b/nipype/interfaces/niftyseg/tests/test_auto_FillLesions.py index 0e4c3d65bf..9e1b06a892 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_FillLesions.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_FillLesions.py @@ -4,17 +4,47 @@ def test_FillLesions_inputs(): input_map = dict( - args=dict(argstr="%s",), - bin_mask=dict(argstr="-mask %s", extensions=None,), - cwf=dict(argstr="-cwf %f",), - debug=dict(argstr="-debug",), - environ=dict(nohash=True, usedefault=True,), - in_dilation=dict(argstr="-dil %d",), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=1,), - lesion_mask=dict(argstr="-l %s", extensions=None, mandatory=True, position=2,), - match=dict(argstr="-match %f",), - other=dict(argstr="-other",), - out_datatype=dict(argstr="-odt %s",), + args=dict( + argstr="%s", + ), + bin_mask=dict( + argstr="-mask %s", + extensions=None, + ), + cwf=dict( + argstr="-cwf %f", + ), + debug=dict( + argstr="-debug", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_dilation=dict( + argstr="-dil %d", + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=1, + ), + lesion_mask=dict( + argstr="-l %s", + extensions=None, + mandatory=True, + position=2, + ), + match=dict( + argstr="-match %f", + ), + other=dict( + argstr="-other", + ), + out_datatype=dict( + argstr="-odt %s", + ), out_file=dict( argstr="-o %s", extensions=None, @@ -22,11 +52,21 @@ def test_FillLesions_inputs(): name_template="%s_lesions_filled.nii.gz", position=3, ), - search=dict(argstr="-search %f",), - size=dict(argstr="-size %d",), - smooth=dict(argstr="-smo %f",), - use_2d=dict(argstr="-2D",), - verbose=dict(argstr="-v",), + search=dict( + argstr="-search %f", + ), + size=dict( + argstr="-size %d", + ), + smooth=dict( + argstr="-smo %f", + ), + use_2d=dict( + argstr="-2D", + ), + verbose=dict( + argstr="-v", + ), ) inputs = FillLesions.input_spec() @@ -36,7 +76,11 @@ def test_FillLesions_inputs(): def test_FillLesions_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = FillLesions.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_LabelFusion.py b/nipype/interfaces/niftyseg/tests/test_auto_LabelFusion.py index ba319d3475..dc4590a15b 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_LabelFusion.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_LabelFusion.py @@ -4,33 +4,79 @@ def test_LabelFusion_inputs(): input_map = dict( - args=dict(argstr="%s",), - classifier_type=dict(argstr="-%s", mandatory=True, position=2,), - conv=dict(argstr="-conv %f",), + args=dict( + argstr="%s", + ), + classifier_type=dict( + argstr="-%s", + mandatory=True, + position=2, + ), + conv=dict( + argstr="-conv %f", + ), dilation_roi=dict(), - environ=dict(nohash=True, usedefault=True,), - file_to_seg=dict(extensions=None, mandatory=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True, position=1,), + environ=dict( + nohash=True, + usedefault=True, + ), + file_to_seg=dict( + extensions=None, + mandatory=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + position=1, + ), kernel_size=dict(), - mask_file=dict(argstr="-mask %s", extensions=None,), - max_iter=dict(argstr="-max_iter %d",), - mrf_value=dict(argstr="-MRF_beta %f",), + mask_file=dict( + argstr="-mask %s", + extensions=None, + ), + max_iter=dict( + argstr="-max_iter %d", + ), + mrf_value=dict( + argstr="-MRF_beta %f", + ), out_file=dict( argstr="-out %s", extensions=None, name_source=["in_file"], name_template="%s", ), - prob_flag=dict(argstr="-outProb",), - prob_update_flag=dict(argstr="-prop_update",), - proportion=dict(argstr="-prop %s",), - set_pq=dict(argstr="-setPQ %f %f",), - sm_ranking=dict(argstr="-%s", position=3, usedefault=True,), - template_file=dict(extensions=None,), + prob_flag=dict( + argstr="-outProb", + ), + prob_update_flag=dict( + argstr="-prop_update", + ), + proportion=dict( + argstr="-prop %s", + ), + set_pq=dict( + argstr="-setPQ %f %f", + ), + sm_ranking=dict( + argstr="-%s", + position=3, + usedefault=True, + ), + template_file=dict( + extensions=None, + ), template_num=dict(), - unc=dict(argstr="-unc",), - unc_thresh=dict(argstr="-uncthres %f",), - verbose=dict(argstr="-v %s",), + unc=dict( + argstr="-unc", + ), + unc_thresh=dict( + argstr="-uncthres %f", + ), + verbose=dict( + argstr="-v %s", + ), ) inputs = LabelFusion.input_spec() @@ -40,7 +86,11 @@ def test_LabelFusion_inputs(): def test_LabelFusion_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = LabelFusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_MathsCommand.py b/nipype/interfaces/niftyseg/tests/test_auto_MathsCommand.py index f8f7bcf95d..963ddf96f8 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_MathsCommand.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_MathsCommand.py @@ -4,9 +4,19 @@ def test_MathsCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), out_file=dict( argstr="%s", extensions=None, @@ -14,7 +24,10 @@ def test_MathsCommand_inputs(): name_template="%s", position=-2, ), - output_datatype=dict(argstr="-odt %s", position=-3,), + output_datatype=dict( + argstr="-odt %s", + position=-3, + ), ) inputs = MathsCommand.input_spec() @@ -24,7 +37,11 @@ def test_MathsCommand_inputs(): def test_MathsCommand_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MathsCommand.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_Merge.py b/nipype/interfaces/niftyseg/tests/test_auto_Merge.py index cfeb8a01d0..de8dc903e6 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_Merge.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_Merge.py @@ -4,11 +4,27 @@ def test_Merge_inputs(): input_map = dict( - args=dict(argstr="%s",), - dimension=dict(mandatory=True,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - merge_files=dict(argstr="%s", mandatory=True, position=4,), + args=dict( + argstr="%s", + ), + dimension=dict( + mandatory=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + merge_files=dict( + argstr="%s", + mandatory=True, + position=4, + ), out_file=dict( argstr="%s", extensions=None, @@ -16,7 +32,10 @@ def test_Merge_inputs(): name_template="%s", position=-2, ), - output_datatype=dict(argstr="-odt %s", position=-3,), + output_datatype=dict( + argstr="-odt %s", + position=-3, + ), ) inputs = Merge.input_spec() @@ -26,7 +45,11 @@ def test_Merge_inputs(): def test_Merge_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Merge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_NiftySegCommand.py b/nipype/interfaces/niftyseg/tests/test_auto_NiftySegCommand.py index e78d913a4c..37a6ee059c 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_NiftySegCommand.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_NiftySegCommand.py @@ -4,7 +4,13 @@ def test_NiftySegCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = NiftySegCommand.input_spec() diff --git a/nipype/interfaces/niftyseg/tests/test_auto_PatchMatch.py b/nipype/interfaces/niftyseg/tests/test_auto_PatchMatch.py index 3832a197f6..c5b9dba115 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_PatchMatch.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_PatchMatch.py @@ -4,16 +4,40 @@ def test_PatchMatch_inputs(): input_map = dict( - args=dict(argstr="%s",), - cs_size=dict(argstr="-cs %i",), + args=dict( + argstr="%s", + ), + cs_size=dict( + argstr="-cs %i", + ), database_file=dict( - argstr="-db %s", extensions=None, mandatory=True, position=3, + argstr="-db %s", + extensions=None, + mandatory=True, + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + position=1, + ), + it_num=dict( + argstr="-it %i", + ), + mask_file=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + position=2, + ), + match_num=dict( + argstr="-match %i", ), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True, position=1,), - it_num=dict(argstr="-it %i",), - mask_file=dict(argstr="-m %s", extensions=None, mandatory=True, position=2,), - match_num=dict(argstr="-match %i",), out_file=dict( argstr="-o %s", extensions=None, @@ -21,8 +45,12 @@ def test_PatchMatch_inputs(): name_template="%s_pm.nii.gz", position=4, ), - patch_size=dict(argstr="-size %i",), - pm_num=dict(argstr="-pm %i",), + patch_size=dict( + argstr="-size %i", + ), + pm_num=dict( + argstr="-pm %i", + ), ) inputs = PatchMatch.input_spec() @@ -32,7 +60,11 @@ def test_PatchMatch_inputs(): def test_PatchMatch_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = PatchMatch.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_StatsCommand.py b/nipype/interfaces/niftyseg/tests/test_auto_StatsCommand.py index b0332f1a46..6b173663a9 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_StatsCommand.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_StatsCommand.py @@ -4,11 +4,28 @@ def test_StatsCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - larger_voxel=dict(argstr="-t %f", position=-3,), - mask_file=dict(argstr="-m %s", extensions=None, position=-2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + larger_voxel=dict( + argstr="-t %f", + position=-3, + ), + mask_file=dict( + argstr="-m %s", + extensions=None, + position=-2, + ), ) inputs = StatsCommand.input_spec() @@ -18,7 +35,9 @@ def test_StatsCommand_inputs(): def test_StatsCommand_outputs(): - output_map = dict(output=dict(),) + output_map = dict( + output=dict(), + ) outputs = StatsCommand.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_TupleMaths.py b/nipype/interfaces/niftyseg/tests/test_auto_TupleMaths.py index 9fc193b442..ef1d4c401f 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_TupleMaths.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_TupleMaths.py @@ -4,9 +4,19 @@ def test_TupleMaths_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), operand_file1=dict( argstr="%s", extensions=None, @@ -22,12 +32,22 @@ def test_TupleMaths_inputs(): xor=["operand_value2"], ), operand_value1=dict( - argstr="%.8f", mandatory=True, position=5, xor=["operand_file1"], + argstr="%.8f", + mandatory=True, + position=5, + xor=["operand_file1"], ), operand_value2=dict( - argstr="%.8f", mandatory=True, position=6, xor=["operand_file2"], + argstr="%.8f", + mandatory=True, + position=6, + xor=["operand_file2"], + ), + operation=dict( + argstr="-%s", + mandatory=True, + position=4, ), - operation=dict(argstr="-%s", mandatory=True, position=4,), out_file=dict( argstr="%s", extensions=None, @@ -35,7 +55,10 @@ def test_TupleMaths_inputs(): name_template="%s", position=-2, ), - output_datatype=dict(argstr="-odt %s", position=-3,), + output_datatype=dict( + argstr="-odt %s", + position=-3, + ), ) inputs = TupleMaths.input_spec() @@ -45,7 +68,11 @@ def test_TupleMaths_inputs(): def test_TupleMaths_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = TupleMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_UnaryMaths.py b/nipype/interfaces/niftyseg/tests/test_auto_UnaryMaths.py index 0409efb5c7..f8189f0f84 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_UnaryMaths.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_UnaryMaths.py @@ -4,10 +4,24 @@ def test_UnaryMaths_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - operation=dict(argstr="-%s", mandatory=True, position=4,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + operation=dict( + argstr="-%s", + mandatory=True, + position=4, + ), out_file=dict( argstr="%s", extensions=None, @@ -15,7 +29,10 @@ def test_UnaryMaths_inputs(): name_template="%s", position=-2, ), - output_datatype=dict(argstr="-odt %s", position=-3,), + output_datatype=dict( + argstr="-odt %s", + position=-3, + ), ) inputs = UnaryMaths.input_spec() @@ -25,7 +42,11 @@ def test_UnaryMaths_inputs(): def test_UnaryMaths_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = UnaryMaths.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_auto_UnaryStats.py b/nipype/interfaces/niftyseg/tests/test_auto_UnaryStats.py index 177f044fd1..117ab819b6 100644 --- a/nipype/interfaces/niftyseg/tests/test_auto_UnaryStats.py +++ b/nipype/interfaces/niftyseg/tests/test_auto_UnaryStats.py @@ -4,12 +4,33 @@ def test_UnaryStats_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), - larger_voxel=dict(argstr="-t %f", position=-3,), - mask_file=dict(argstr="-m %s", extensions=None, position=-2,), - operation=dict(argstr="-%s", mandatory=True, position=4,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), + larger_voxel=dict( + argstr="-t %f", + position=-3, + ), + mask_file=dict( + argstr="-m %s", + extensions=None, + position=-2, + ), + operation=dict( + argstr="-%s", + mandatory=True, + position=4, + ), ) inputs = UnaryStats.input_spec() @@ -19,7 +40,9 @@ def test_UnaryStats_inputs(): def test_UnaryStats_outputs(): - output_map = dict(output=dict(),) + output_map = dict( + output=dict(), + ) outputs = UnaryStats.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/niftyseg/tests/test_em_interfaces.py b/nipype/interfaces/niftyseg/tests/test_em_interfaces.py index 5615f3e61c..c90d93a6ba 100644 --- a/nipype/interfaces/niftyseg/tests/test_em_interfaces.py +++ b/nipype/interfaces/niftyseg/tests/test_em_interfaces.py @@ -11,7 +11,6 @@ @pytest.mark.skipif(no_nifty_tool(cmd="seg_EM"), reason="niftyseg is not installed") def test_seg_em(): - # Create a node object seg_em = EM() diff --git a/nipype/interfaces/niftyseg/tests/test_extra_PatchMatch.py b/nipype/interfaces/niftyseg/tests/test_extra_PatchMatch.py index 18156e37f1..53d5bd4170 100644 --- a/nipype/interfaces/niftyseg/tests/test_extra_PatchMatch.py +++ b/nipype/interfaces/niftyseg/tests/test_extra_PatchMatch.py @@ -13,7 +13,6 @@ no_nifty_tool(cmd="seg_PatchMatch"), reason="niftyseg is not installed" ) def test_seg_patchmatch(): - # Create a node object seg_patchmatch = PatchMatch() diff --git a/nipype/interfaces/niftyseg/tests/test_label_fusion.py b/nipype/interfaces/niftyseg/tests/test_label_fusion.py index 0a469a774e..824b98c230 100644 --- a/nipype/interfaces/niftyseg/tests/test_label_fusion.py +++ b/nipype/interfaces/niftyseg/tests/test_label_fusion.py @@ -13,7 +13,7 @@ no_nifty_tool(cmd="seg_LabFusion"), reason="niftyseg is not installed" ) def test_seg_lab_fusion(): - """ Test interfaces for seg_labfusion""" + """Test interfaces for seg_labfusion""" # Create a node object steps = LabelFusion() @@ -98,7 +98,7 @@ def test_seg_lab_fusion(): no_nifty_tool(cmd="seg_CalcTopNCC"), reason="niftyseg is not installed" ) def test_seg_calctopncc(): - """ Test interfaces for seg_CalctoNCC""" + """Test interfaces for seg_CalctoNCC""" # Create a node object calctopncc = CalcTopNCC() @@ -120,6 +120,6 @@ def test_seg_calctopncc(): calctopncc.inputs.top_templates = 1 cmd_tmp = "{cmd} -target {in_file} -templates 2 {file1} {file2} -n 1" - expected_cmd = cmd_tmp.format(cmd=cmd, in_file=in_file, file1=file1, file2=file2,) + expected_cmd = cmd_tmp.format(cmd=cmd, in_file=in_file, file1=file1, file2=file2) assert calctopncc.cmdline == expected_cmd diff --git a/nipype/interfaces/niftyseg/tests/test_lesions.py b/nipype/interfaces/niftyseg/tests/test_lesions.py index d46b380cc2..2daece08cb 100644 --- a/nipype/interfaces/niftyseg/tests/test_lesions.py +++ b/nipype/interfaces/niftyseg/tests/test_lesions.py @@ -13,7 +13,6 @@ no_nifty_tool(cmd="seg_FillLesions"), reason="niftyseg is not installed" ) def test_seg_filllesions(): - # Create a node object seg_fill = FillLesions() diff --git a/nipype/interfaces/niftyseg/tests/test_maths.py b/nipype/interfaces/niftyseg/tests/test_maths.py index 84740b7447..6c0251d7f5 100644 --- a/nipype/interfaces/niftyseg/tests/test_maths.py +++ b/nipype/interfaces/niftyseg/tests/test_maths.py @@ -11,7 +11,6 @@ @pytest.mark.skipif(no_nifty_tool(cmd="seg_maths"), reason="niftyseg is not installed") def test_unary_maths(): - # Create a node object unarym = UnaryMaths() @@ -38,7 +37,6 @@ def test_unary_maths(): @pytest.mark.skipif(no_nifty_tool(cmd="seg_maths"), reason="niftyseg is not installed") def test_binary_maths(): - # Create a node object binarym = BinaryMaths() @@ -65,7 +63,6 @@ def test_binary_maths(): @pytest.mark.skipif(no_nifty_tool(cmd="seg_maths"), reason="niftyseg is not installed") def test_int_binary_maths(): - # Create a node object ibinarym = BinaryMathsInteger() @@ -93,7 +90,6 @@ def test_int_binary_maths(): @pytest.mark.skipif(no_nifty_tool(cmd="seg_maths"), reason="niftyseg is not installed") def test_tuple_maths(): - # Create a node object tuplem = TupleMaths() @@ -124,7 +120,6 @@ def test_tuple_maths(): @pytest.mark.skipif(no_nifty_tool(cmd="seg_maths"), reason="niftyseg is not installed") def test_merge(): - # Create a node object merge = Merge() diff --git a/nipype/interfaces/niftyseg/tests/test_stats.py b/nipype/interfaces/niftyseg/tests/test_stats.py index cfeefe404a..b3bb9a3bb0 100644 --- a/nipype/interfaces/niftyseg/tests/test_stats.py +++ b/nipype/interfaces/niftyseg/tests/test_stats.py @@ -11,7 +11,7 @@ @pytest.mark.skipif(no_nifty_tool(cmd="seg_stats"), reason="niftyseg is not installed") def test_unary_stats(): - """ Test for the seg_stats interfaces """ + """Test for the seg_stats interfaces""" # Create a node object unarys = UnaryStats() @@ -28,14 +28,14 @@ def test_unary_stats(): unarys.inputs.in_file = in_file unarys.inputs.operation = "a" - expected_cmd = "{cmd} {in_file} -a".format(cmd=cmd, in_file=in_file) + expected_cmd = f"{cmd} {in_file} -a" assert unarys.cmdline == expected_cmd @pytest.mark.skipif(no_nifty_tool(cmd="seg_stats"), reason="niftyseg is not installed") def test_binary_stats(): - """ Test for the seg_stats interfaces """ + """Test for the seg_stats interfaces""" # Create a node object binarys = BinaryStats() @@ -53,6 +53,6 @@ def test_binary_stats(): binarys.inputs.operand_value = 2 binarys.inputs.operation = "sa" - expected_cmd = "{cmd} {in_file} -sa 2.00000000".format(cmd=cmd, in_file=in_file) + expected_cmd = f"{cmd} {in_file} -sa 2.00000000" assert binarys.cmdline == expected_cmd diff --git a/nipype/interfaces/nilearn.py b/nipype/interfaces/nilearn.py index 55f6982213..df6413320e 100644 --- a/nipype/interfaces/nilearn.py +++ b/nipype/interfaces/nilearn.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Nilearn is a Python library for fast and easy statistical learning on NeuroImaging data.""" @@ -45,7 +44,7 @@ class SignalExtractionInputSpec(BaseInterfaceInputSpec): "signals.tsv", usedefault=True, exists=False, - desc="The name of the file to output to. " "signals.tsv by default", + desc="The name of the file to output to. signals.tsv by default", ) incl_shared_variance = traits.Bool( True, @@ -99,20 +98,18 @@ class SignalExtraction(NilearnBaseInterface, SimpleInterface): def _run_interface(self, runtime): maskers = self._process_inputs() - signals = [] - for masker in maskers: - signals.append(masker.fit_transform(self.inputs.in_file)) + signals = [masker.fit_transform(self.inputs.in_file) for masker in maskers] region_signals = np.hstack(signals) output = np.vstack((self.inputs.class_labels, region_signals.astype(str))) # save output self._results["out_file"] = os.path.join(runtime.cwd, self.inputs.out_file) - np.savetxt(self._results["out_file"], output, fmt=b"%s", delimiter="\t") + np.savetxt(self._results["out_file"], output, fmt="%s", delimiter="\t") return runtime def _process_inputs(self): - """ validate and process inputs into useful form. + """validate and process inputs into useful form. Returns a list of nilearn maskers and the list of corresponding label names.""" import nilearn.input_data as nl @@ -128,10 +125,10 @@ def _process_inputs(self): else: # 4d labels n_labels = label_data.shape[3] if self.inputs.incl_shared_variance: # independent computation - for img in nli.iter_img(label_data): - maskers.append( - nl.NiftiMapsMasker(self._4d(img.dataobj, img.affine)) - ) + maskers.extend( + nl.NiftiMapsMasker(self._4d(img.dataobj, img.affine)) + for img in nli.iter_img(label_data) + ) else: # one computation fitting all maskers.append(nl.NiftiMapsMasker(label_data)) @@ -155,7 +152,7 @@ def _process_inputs(self): if self.inputs.include_global: global_label_data = label_data.dataobj.sum(axis=3) # sum across all regions global_label_data = ( - np.rint(global_label_data).astype(int).clip(0, 1) + np.rint(global_label_data).clip(0, 1).astype('u1') ) # binarize global_label_data = self._4d(global_label_data, label_data.affine) global_masker = nl.NiftiLabelsMasker( @@ -170,6 +167,6 @@ def _process_inputs(self): return maskers def _4d(self, array, affine): - """ takes a 3-dimensional numpy array and an affine, - returns the equivalent 4th dimensional nifti file """ + """takes a 3-dimensional numpy array and an affine, + returns the equivalent 4th dimensional nifti file""" return nb.Nifti1Image(array[:, :, :, np.newaxis], affine) diff --git a/nipype/interfaces/nipy/__init__.py b/nipype/interfaces/nipy/__init__.py index 72317edae0..ad8b66d887 100644 --- a/nipype/interfaces/nipy/__init__.py +++ b/nipype/interfaces/nipy/__init__.py @@ -1,5 +1,5 @@ -# -*- coding: utf-8 -*- """NIPY is a python project for analysis of structural and functional neuroimaging data.""" + from .model import FitGLM, EstimateContrast from .preprocess import ComputeMask, SpaceTimeRealigner from .utils import Similarity diff --git a/nipype/interfaces/nipy/base.py b/nipype/interfaces/nipy/base.py index 0991730e81..1f8f1e4657 100644 --- a/nipype/interfaces/nipy/base.py +++ b/nipype/interfaces/nipy/base.py @@ -1,7 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -""" Base interface for nipy """ +"""Base interface for nipy""" from ..base import LibraryBaseInterface from ...utils.misc import package_check @@ -12,7 +11,7 @@ have_nipy = True try: package_check("nipy") -except ImportError: +except: have_nipy = False diff --git a/nipype/interfaces/nipy/model.py b/nipype/interfaces/nipy/model.py index b931947c19..c99a4acaea 100644 --- a/nipype/interfaces/nipy/model.py +++ b/nipype/interfaces/nipy/model.py @@ -1,10 +1,10 @@ -# -*- coding: utf-8 -*- import os from .base import NipyBaseInterface from ..base import ( TraitedSpec, traits, + Tuple, File, OutputMultiPath, BaseInterfaceInputSpec, @@ -20,7 +20,7 @@ class FitGLMInputSpec(BaseInterfaceInputSpec): desc=( "Session specific information generated by" " ``modelgen.SpecifyModel``, FitGLM does " - "not support multiple runs uless they are " + "not support multiple runs unless they are " "concatenated (see SpecifyModel options)" ), ) @@ -29,7 +29,7 @@ class FitGLMInputSpec(BaseInterfaceInputSpec): "Canonical With Derivative", "FIR", desc=( - "that specifies the hemodynamic reponse " + "that specifies the hemodynamic response " "function it can be 'Canonical', 'Canonical " "With Derivative' or 'FIR'" ), @@ -50,7 +50,7 @@ class FitGLMInputSpec(BaseInterfaceInputSpec): model = traits.Enum( "ar1", "spherical", - desc=("autoregressive mode is available only for the " "kalman method"), + desc=("autoregressive mode is available only for the kalman method"), usedefault=True, ) method = traits.Enum( @@ -65,11 +65,11 @@ class FitGLMInputSpec(BaseInterfaceInputSpec): ) mask = File( exists=True, - desc=("restrict the fitting only to the region defined " "by this mask"), + desc=("restrict the fitting only to the region defined by this mask"), ) normalize_design_matrix = traits.Bool( False, - desc=("normalize (zscore) the " "regressors before fitting"), + desc=("normalize (zscore) the regressors before fitting"), usedefault=True, ) save_residuals = traits.Bool(False, usedefault=True) @@ -138,10 +138,7 @@ def _run_interface(self, runtime): hpf = 0 drift_model = "Blank" - reg_names = [] - for reg in session_info[0]["regress"]: - reg_names.append(reg["name"]) - + reg_names = [reg["name"] for reg in session_info[0]["regress"]] reg_vals = np.zeros((nscans, len(reg_names))) for i in range(len(reg_names)): reg_vals[:, i] = np.array(session_info[0]["regress"][i]["val"]).reshape( @@ -247,31 +244,31 @@ def _list_outputs(self): class EstimateContrastInputSpec(BaseInterfaceInputSpec): contrasts = traits.List( traits.Either( - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("F"), traits.List( traits.Either( - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), diff --git a/nipype/interfaces/nipy/preprocess.py b/nipype/interfaces/nipy/preprocess.py index 115b7f93ad..a85c8d3ad4 100644 --- a/nipype/interfaces/nipy/preprocess.py +++ b/nipype/interfaces/nipy/preprocess.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os import nibabel as nb @@ -6,7 +5,7 @@ from ...utils.filemanip import split_filename, fname_presuffix -from .base import NipyBaseInterface, have_nipy +from .base import NipyBaseInterface from ..base import ( TraitedSpec, traits, @@ -61,7 +60,7 @@ def _run_interface(self, runtime): brain_mask = compute_mask(**args) _, name, ext = split_filename(self.inputs.mean_volume) - self._brain_mask_path = os.path.abspath("%s_mask.%s" % (name, ext)) + self._brain_mask_path = os.path.abspath(f"{name}_mask.{ext}") nb.save( nb.Nifti1Image(brain_mask.astype(np.uint8), nii.affine), self._brain_mask_path, @@ -120,7 +119,7 @@ class SpaceTimeRealignerOutputSpec(TraitedSpec): out_file = OutputMultiPath(File(exists=True), desc="Realigned files") par_file = OutputMultiPath( File(exists=True), - desc=("Motion parameter files. Angles are not " "euler angles"), + desc=("Motion parameter files. Angles are not euler angles"), ) @@ -204,7 +203,7 @@ def _run_interface(self, runtime): # nipy does not encode euler angles. return in original form of # translation followed by rotation vector see: # http://en.wikipedia.org/wiki/Rodrigues'_rotation_formula - for i, mo in enumerate(motion): + for mo in motion: params = [ "%.10f" % item for item in np.hstack((mo.translation, mo.rotation)) ] @@ -240,7 +239,7 @@ class TrimOutputSpec(TraitedSpec): class Trim(NipyBaseInterface): - """ Simple interface to trim a few volumes from a 4d fmri nifti file + """Simple interface to trim a few volumes from a 4d fmri nifti file Examples -------- diff --git a/nipype/interfaces/nipy/tests/__init__.py b/nipype/interfaces/nipy/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/nipy/tests/__init__.py +++ b/nipype/interfaces/nipy/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/nipy/tests/test_auto_ComputeMask.py b/nipype/interfaces/nipy/tests/test_auto_ComputeMask.py index aa34d55caf..db1b784a03 100644 --- a/nipype/interfaces/nipy/tests/test_auto_ComputeMask.py +++ b/nipype/interfaces/nipy/tests/test_auto_ComputeMask.py @@ -7,8 +7,13 @@ def test_ComputeMask_inputs(): M=dict(), cc=dict(), m=dict(), - mean_volume=dict(extensions=None, mandatory=True,), - reference_volume=dict(extensions=None,), + mean_volume=dict( + extensions=None, + mandatory=True, + ), + reference_volume=dict( + extensions=None, + ), ) inputs = ComputeMask.input_spec() @@ -18,7 +23,11 @@ def test_ComputeMask_inputs(): def test_ComputeMask_outputs(): - output_map = dict(brain_mask=dict(extensions=None,),) + output_map = dict( + brain_mask=dict( + extensions=None, + ), + ) outputs = ComputeMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/nipy/tests/test_auto_EstimateContrast.py b/nipype/interfaces/nipy/tests/test_auto_EstimateContrast.py index c89423bc74..172f2205fd 100644 --- a/nipype/interfaces/nipy/tests/test_auto_EstimateContrast.py +++ b/nipype/interfaces/nipy/tests/test_auto_EstimateContrast.py @@ -4,15 +4,35 @@ def test_EstimateContrast_inputs(): input_map = dict( - axis=dict(mandatory=True,), - beta=dict(extensions=None, mandatory=True,), - constants=dict(mandatory=True,), - contrasts=dict(mandatory=True,), - dof=dict(mandatory=True,), - mask=dict(extensions=None,), - nvbeta=dict(mandatory=True,), - reg_names=dict(mandatory=True,), - s2=dict(extensions=None, mandatory=True,), + axis=dict( + mandatory=True, + ), + beta=dict( + extensions=None, + mandatory=True, + ), + constants=dict( + mandatory=True, + ), + contrasts=dict( + mandatory=True, + ), + dof=dict( + mandatory=True, + ), + mask=dict( + extensions=None, + ), + nvbeta=dict( + mandatory=True, + ), + reg_names=dict( + mandatory=True, + ), + s2=dict( + extensions=None, + mandatory=True, + ), ) inputs = EstimateContrast.input_spec() @@ -22,7 +42,11 @@ def test_EstimateContrast_inputs(): def test_EstimateContrast_outputs(): - output_map = dict(p_maps=dict(), stat_maps=dict(), z_maps=dict(),) + output_map = dict( + p_maps=dict(), + stat_maps=dict(), + z_maps=dict(), + ) outputs = EstimateContrast.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/nipy/tests/test_auto_FitGLM.py b/nipype/interfaces/nipy/tests/test_auto_FitGLM.py index 7aa96870c7..f04081214c 100644 --- a/nipype/interfaces/nipy/tests/test_auto_FitGLM.py +++ b/nipype/interfaces/nipy/tests/test_auto_FitGLM.py @@ -4,16 +4,36 @@ def test_FitGLM_inputs(): input_map = dict( - TR=dict(mandatory=True,), - drift_model=dict(usedefault=True,), - hrf_model=dict(usedefault=True,), - mask=dict(extensions=None,), - method=dict(usedefault=True,), - model=dict(usedefault=True,), - normalize_design_matrix=dict(usedefault=True,), - plot_design_matrix=dict(usedefault=True,), - save_residuals=dict(usedefault=True,), - session_info=dict(mandatory=True,), + TR=dict( + mandatory=True, + ), + drift_model=dict( + usedefault=True, + ), + hrf_model=dict( + usedefault=True, + ), + mask=dict( + extensions=None, + ), + method=dict( + usedefault=True, + ), + model=dict( + usedefault=True, + ), + normalize_design_matrix=dict( + usedefault=True, + ), + plot_design_matrix=dict( + usedefault=True, + ), + save_residuals=dict( + usedefault=True, + ), + session_info=dict( + mandatory=True, + ), ) inputs = FitGLM.input_spec() @@ -24,15 +44,23 @@ def test_FitGLM_inputs(): def test_FitGLM_outputs(): output_map = dict( - a=dict(extensions=None,), + a=dict( + extensions=None, + ), axis=dict(), - beta=dict(extensions=None,), + beta=dict( + extensions=None, + ), constants=dict(), dof=dict(), nvbeta=dict(), reg_names=dict(), - residuals=dict(extensions=None,), - s2=dict(extensions=None,), + residuals=dict( + extensions=None, + ), + s2=dict( + extensions=None, + ), ) outputs = FitGLM.output_spec() diff --git a/nipype/interfaces/nipy/tests/test_auto_Similarity.py b/nipype/interfaces/nipy/tests/test_auto_Similarity.py index ac0b3c853a..81e8622078 100644 --- a/nipype/interfaces/nipy/tests/test_auto_Similarity.py +++ b/nipype/interfaces/nipy/tests/test_auto_Similarity.py @@ -4,11 +4,23 @@ def test_Similarity_inputs(): input_map = dict( - mask1=dict(extensions=None,), - mask2=dict(extensions=None,), - metric=dict(usedefault=True,), - volume1=dict(extensions=None, mandatory=True,), - volume2=dict(extensions=None, mandatory=True,), + mask1=dict( + extensions=None, + ), + mask2=dict( + extensions=None, + ), + metric=dict( + usedefault=True, + ), + volume1=dict( + extensions=None, + mandatory=True, + ), + volume2=dict( + extensions=None, + mandatory=True, + ), ) inputs = Similarity.input_spec() @@ -18,7 +30,9 @@ def test_Similarity_inputs(): def test_Similarity_outputs(): - output_map = dict(similarity=dict(),) + output_map = dict( + similarity=dict(), + ) outputs = Similarity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/nipy/tests/test_auto_SpaceTimeRealigner.py b/nipype/interfaces/nipy/tests/test_auto_SpaceTimeRealigner.py index 2025d62498..fd65848f72 100644 --- a/nipype/interfaces/nipy/tests/test_auto_SpaceTimeRealigner.py +++ b/nipype/interfaces/nipy/tests/test_auto_SpaceTimeRealigner.py @@ -4,10 +4,17 @@ def test_SpaceTimeRealigner_inputs(): input_map = dict( - in_file=dict(mandatory=True, min_ver="0.4.0.dev",), - slice_info=dict(requires=["slice_times"],), + in_file=dict( + mandatory=True, + min_ver="0.4.0.dev", + ), + slice_info=dict( + requires=["slice_times"], + ), slice_times=dict(), - tr=dict(requires=["slice_times"],), + tr=dict( + requires=["slice_times"], + ), ) inputs = SpaceTimeRealigner.input_spec() @@ -17,7 +24,10 @@ def test_SpaceTimeRealigner_inputs(): def test_SpaceTimeRealigner_outputs(): - output_map = dict(out_file=dict(), par_file=dict(),) + output_map = dict( + out_file=dict(), + par_file=dict(), + ) outputs = SpaceTimeRealigner.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/nipy/tests/test_auto_Trim.py b/nipype/interfaces/nipy/tests/test_auto_Trim.py index 4b33c8b4b2..c4ecee3007 100644 --- a/nipype/interfaces/nipy/tests/test_auto_Trim.py +++ b/nipype/interfaces/nipy/tests/test_auto_Trim.py @@ -4,11 +4,22 @@ def test_Trim_inputs(): input_map = dict( - begin_index=dict(usedefault=True,), - end_index=dict(usedefault=True,), - in_file=dict(extensions=None, mandatory=True,), - out_file=dict(extensions=None,), - suffix=dict(usedefault=True,), + begin_index=dict( + usedefault=True, + ), + end_index=dict( + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + out_file=dict( + extensions=None, + ), + suffix=dict( + usedefault=True, + ), ) inputs = Trim.input_spec() @@ -18,7 +29,11 @@ def test_Trim_inputs(): def test_Trim_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Trim.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/nipy/utils.py b/nipype/interfaces/nipy/utils.py index 08eb80e0b2..96773f27dc 100644 --- a/nipype/interfaces/nipy/utils.py +++ b/nipype/interfaces/nipy/utils.py @@ -1,10 +1,8 @@ -# -*- coding: utf-8 -*- - import warnings import numpy as np import nibabel as nb -from .base import NipyBaseInterface, have_nipy +from .base import NipyBaseInterface from ..base import TraitedSpec, traits, BaseInterfaceInputSpec, File, isdefined @@ -63,7 +61,7 @@ def __init__(self, **inputs): ), DeprecationWarning, ) - super(Similarity, self).__init__(**inputs) + super().__init__(**inputs) def _run_interface(self, runtime): from nipy.algorithms.registration.histogram_registration import ( diff --git a/nipype/interfaces/nitime/__init__.py b/nipype/interfaces/nitime/__init__.py index f3fc84079a..883d417ba0 100644 --- a/nipype/interfaces/nitime/__init__.py +++ b/nipype/interfaces/nitime/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Nitime is a library for time-series analysis of data from neuroscience experiments.""" diff --git a/nipype/interfaces/nitime/analysis.py b/nipype/interfaces/nitime/analysis.py index ffaf5380ce..7c936e4b03 100644 --- a/nipype/interfaces/nitime/analysis.py +++ b/nipype/interfaces/nitime/analysis.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -32,7 +31,6 @@ class CoherenceAnalyzerInputSpec(BaseInterfaceInputSpec): - # Input either csv file, or time-series object and use _xor_inputs to # discriminate _xor_inputs = ("in_file", "in_TS") @@ -144,22 +142,20 @@ def _read_csv(self): """ # Check that input conforms to expectations: - first_row = open(self.inputs.in_file).readline() + with open(self.inputs.in_file) as f: + first_row = f.readline() if not first_row[1].isalpha(): raise ValueError( "First row of in_file should contain ROI names as strings of characters" ) - - roi_names = ( - open(self.inputs.in_file).readline().replace('"', "").strip("\n").split(",") - ) + roi_names = first_row.replace('"', "").strip("\n").split(",") # Transpose, so that the time is the last dimension: data = np.loadtxt(self.inputs.in_file, skiprows=1, delimiter=",").T return data, roi_names def _csv2ts(self): - """ Read data from the in_file and generate a nitime TimeSeries object""" + """Read data from the in_file and generate a nitime TimeSeries object""" from nitime.timeseries import TimeSeries data, roi_names = self._read_csv() @@ -257,16 +253,15 @@ def _make_output_files(self): tmp_f = tempfile.mkstemp()[1] np.savetxt(tmp_f, this[0], delimiter=",") - fid = open( + with open( fname_presuffix(self.inputs.output_csv_file, suffix="_%s" % this[1]), "w+", - ) - # this writes ROIs as header line - fid.write("," + ",".join(self.ROIs) + "\n") - # this writes ROI and data to a line - for r, line in zip(self.ROIs, open(tmp_f)): - fid.write("%s,%s" % (r, line)) - fid.close() + ) as fid: + # this writes ROIs as header line + fid.write("," + ",".join(self.ROIs) + "\n") + # this writes ROI and data to a line + for r, line in zip(self.ROIs, open(tmp_f)): + fid.write(f"{r},{line}") def _make_output_figures(self): """ diff --git a/nipype/interfaces/nitime/base.py b/nipype/interfaces/nitime/base.py index fb31cafc75..4109bc3a74 100644 --- a/nipype/interfaces/nitime/base.py +++ b/nipype/interfaces/nitime/base.py @@ -1,7 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -""" Base interface for nitime """ +"""Base interface for nitime""" from ..base import LibraryBaseInterface diff --git a/nipype/interfaces/nitime/tests/__init__.py b/nipype/interfaces/nitime/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/nitime/tests/__init__.py +++ b/nipype/interfaces/nitime/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/nitime/tests/test_auto_CoherenceAnalyzer.py b/nipype/interfaces/nitime/tests/test_auto_CoherenceAnalyzer.py index d188c27800..8c70d059ab 100644 --- a/nipype/interfaces/nitime/tests/test_auto_CoherenceAnalyzer.py +++ b/nipype/interfaces/nitime/tests/test_auto_CoherenceAnalyzer.py @@ -4,15 +4,30 @@ def test_CoherenceAnalyzer_inputs(): input_map = dict( - NFFT=dict(usedefault=True,), + NFFT=dict( + usedefault=True, + ), TR=dict(), - figure_type=dict(usedefault=True,), - frequency_range=dict(usedefault=True,), + figure_type=dict( + usedefault=True, + ), + frequency_range=dict( + usedefault=True, + ), in_TS=dict(), - in_file=dict(extensions=None, requires=("TR",),), - n_overlap=dict(usedefault=True,), - output_csv_file=dict(extensions=None,), - output_figure_file=dict(extensions=None,), + in_file=dict( + extensions=None, + requires=("TR",), + ), + n_overlap=dict( + usedefault=True, + ), + output_csv_file=dict( + extensions=None, + ), + output_figure_file=dict( + extensions=None, + ), ) inputs = CoherenceAnalyzer.input_spec() @@ -24,11 +39,19 @@ def test_CoherenceAnalyzer_inputs(): def test_CoherenceAnalyzer_outputs(): output_map = dict( coherence_array=dict(), - coherence_csv=dict(extensions=None,), - coherence_fig=dict(extensions=None,), + coherence_csv=dict( + extensions=None, + ), + coherence_fig=dict( + extensions=None, + ), timedelay_array=dict(), - timedelay_csv=dict(extensions=None,), - timedelay_fig=dict(extensions=None,), + timedelay_csv=dict( + extensions=None, + ), + timedelay_fig=dict( + extensions=None, + ), ) outputs = CoherenceAnalyzer.output_spec() diff --git a/nipype/interfaces/nitime/tests/test_nitime.py b/nipype/interfaces/nitime/tests/test_nitime.py index 507e1856ae..8351a3c38a 100644 --- a/nipype/interfaces/nitime/tests/test_nitime.py +++ b/nipype/interfaces/nitime/tests/test_nitime.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -17,7 +16,7 @@ @pytest.mark.skipif(no_nitime, reason="nitime is not installed") def test_read_csv(): """Test that reading the data from csv file gives you back a reasonable - time-series object """ + time-series object""" CA = nitime.CoherenceAnalyzer() CA.inputs.TR = 1.89 # bogus value just to pass traits test CA.inputs.in_file = example_data("fmri_timeseries_nolabels.csv") @@ -32,7 +31,7 @@ def test_read_csv(): @pytest.mark.skipif(no_nitime, reason="nitime is not installed") def test_coherence_analysis(tmpdir): - """Test that the coherence analyzer works """ + """Test that the coherence analyzer works""" import nitime.analysis as nta import nitime.timeseries as ts @@ -52,7 +51,9 @@ def test_coherence_analysis(tmpdir): # This is the nitime analysis: TR = 1.89 - data_rec = np.recfromcsv(example_data("fmri_timeseries.csv")) + data_rec = np.genfromtxt( + example_data("fmri_timeseries.csv"), delimiter=',', names=True + ) roi_names = np.array(data_rec.dtype.names) n_samples = data_rec.shape[0] data = np.zeros((len(roi_names), n_samples)) diff --git a/nipype/interfaces/petpvc.py b/nipype/interfaces/petpvc.py index 6d0b8f7e04..a1f042eed9 100644 --- a/nipype/interfaces/petpvc.py +++ b/nipype/interfaces/petpvc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """PETPVC is a toolbox for partial volume correction in positron emission tomography.""" @@ -38,6 +37,7 @@ "RBV+VC", "RL", "VC", + "STC", ] @@ -76,6 +76,7 @@ class PETPVCInputSpec(CommandLineInputSpec): * Muller Gartner -- ``MG`` * Muller Gartner with Van-Cittert -- ``MG+VC`` * Muller Gartner with Richardson-Lucy -- ``MG+RL`` + * Single-target correction -- ``STC`` """, ) @@ -155,7 +156,7 @@ class PETPVC(CommandLine): output_spec = PETPVCOutputSpec _cmd = "petpvc" - references_ = [ + _references = [ { "entry": BibTeX( "@article{0031-9155-61-22-7975," @@ -183,7 +184,7 @@ def _list_outputs(self): if not isdefined(outputs["out_file"]): method_name = self.inputs.pvc.lower() outputs["out_file"] = self._gen_fname( - self.inputs.in_file, suffix="_{}_pvc".format(method_name) + self.inputs.in_file, suffix=f"_{method_name}_pvc" ) outputs["out_file"] = os.path.abspath(outputs["out_file"]) @@ -195,8 +196,8 @@ def _gen_fname( """Generate a filename based on the given parameters. The filename will take the form: cwd/basename. - If change_ext is True, it will use the extentions specified in - intputs.output_type. + If change_ext is True, it will use the extensions specified in + inputs.output_type. Parameters ---------- @@ -224,7 +225,7 @@ def _gen_fname( cwd = os.getcwd() if change_ext: if suffix: - suffix = "".join((suffix, ext)) + suffix = f"{suffix}{ext}" else: suffix = ext if suffix is None: diff --git a/nipype/interfaces/quickshear.py b/nipype/interfaces/quickshear.py index b7409fdbf3..8dee91e2c2 100644 --- a/nipype/interfaces/quickshear.py +++ b/nipype/interfaces/quickshear.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """Quickshear is a simple geometric defacing algorithm.""" from .base import CommandLineInputSpec, CommandLine, traits, TraitedSpec, File @@ -27,7 +26,7 @@ class QuickshearInputSpec(CommandLineInputSpec): buff = traits.Int( position=4, argstr="%d", - desc="buffer size (in voxels) between shearing " "plane and the brain", + desc="buffer size (in voxels) between shearing plane and the brain", ) @@ -75,7 +74,7 @@ class Quickshear(CommandLine): input_spec = QuickshearInputSpec output_spec = QuickshearOutputSpec - references_ = [ + _references = [ { "entry": BibTeX( "@inproceedings{Schimke2011," diff --git a/nipype/interfaces/r.py b/nipype/interfaces/r.py new file mode 100644 index 0000000000..1894d00960 --- /dev/null +++ b/nipype/interfaces/r.py @@ -0,0 +1,113 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +"""Interfaces to run R scripts.""" +import os +from shutil import which + +from .base import ( + CommandLineInputSpec, + isdefined, + CommandLine, + traits, + File, +) + + +def get_r_command(): + if "NIPYPE_NO_R" in os.environ: + return None + r_cmd = os.getenv("RCMD", default="R") + + return r_cmd if which(r_cmd) else None + + +no_r = get_r_command() is None + + +class RInputSpec(CommandLineInputSpec): + """Basic expected inputs to R interface""" + + script = traits.Str( + argstr='-e "%s"', desc="R code to run", mandatory=True, position=-1 + ) + # non-commandline options + rfile = traits.Bool(True, desc="Run R using R script", usedefault=True) + script_file = File( + "pyscript.R", usedefault=True, desc="Name of file to write R code to" + ) + + +class RCommand(CommandLine): + """Interface that runs R code + + >>> import nipype.interfaces.r as r + >>> r = r.RCommand(rfile=False) # doctest: +SKIP + >>> r.inputs.script = "Sys.getenv('USER')" # doctest: +SKIP + >>> out = r.run() # doctest: +SKIP + """ + + _cmd = get_r_command() + input_spec = RInputSpec + + def __init__(self, r_cmd=None, **inputs): + """initializes interface to r + (default 'R') + """ + super().__init__(**inputs) + if r_cmd and isdefined(r_cmd): + self._cmd = r_cmd + + # For r commands force all output to be returned since r + # does not have a clean way of notifying an error + self.terminal_output = "allatonce" + + def set_default_r_cmd(self, r_cmd): + """Set the default R command line for R classes. + + This method is used to set values for all R + subclasses. + """ + self._cmd = r_cmd + + def set_default_rfile(self, rfile): + """Set the default R script file format for R classes. + + This method is used to set values for all R + subclasses. + """ + self._rfile = rfile + + def _run_interface(self, runtime): + self.terminal_output = "allatonce" + runtime = super()._run_interface(runtime) + if "R code threw an exception" in runtime.stderr: + self.raise_exception(runtime) + return runtime + + def _format_arg(self, name, trait_spec, value): + if name in ["script"]: + argstr = trait_spec.argstr + return self._gen_r_command(argstr, value) + return super()._format_arg(name, trait_spec, value) + + def _gen_r_command(self, argstr, script_lines): + """Generates commands and, if rfile specified, writes it to disk.""" + if not self.inputs.rfile: + # replace newlines with ;, strip comments + script = "; ".join( + [ + line + for line in script_lines.split("\n") + if not line.strip().startswith("#") + ] + ) + # escape " and $ + script = script.replace('"', '\\"') + script = script.replace("$", "\\$") + else: + script_path = os.path.join(os.getcwd(), self.inputs.script_file) + with open(script_path, "w") as rfile: + rfile.write(script_lines) + script = "source('%s')" % script_path + + return argstr % script diff --git a/nipype/interfaces/robex/__init__.py b/nipype/interfaces/robex/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/interfaces/robex/preprocess.py b/nipype/interfaces/robex/preprocess.py new file mode 100644 index 0000000000..b2e92e94cb --- /dev/null +++ b/nipype/interfaces/robex/preprocess.py @@ -0,0 +1,64 @@ +from nipype.interfaces.base import ( + TraitedSpec, + CommandLineInputSpec, + CommandLine, + File, + traits, +) + + +class RobexInputSpec(CommandLineInputSpec): + in_file = File( + desc="Input volume", exists=True, mandatory=True, position=0, argstr="%s" + ) + out_file = File( + desc="Output volume", + position=1, + argstr="%s", + hash_files=False, + name_template='%s_brain', + name_source=["in_file"], + keep_extension=True, + ) + out_mask = File( + desc="Output mask", + position=2, + argstr="%s", + hash_files=False, + name_template='%s_brainmask', + name_source=["in_file"], + keep_extension=True, + ) + seed = traits.Int(desc="Seed for random number generator", position=3, argstr="%i") + + +class RobexOutputSpec(TraitedSpec): + out_file = File(desc="Output volume") + out_mask = File(desc="Output mask") + + +class RobexSegment(CommandLine): + """ + + ROBEX is an automatic whole-brain extraction tool for T1-weighted MRI data (commonly known as skull stripping). + ROBEX aims for robust skull-stripping across datasets with no parameter settings. It fits a triangular mesh, + constrained by a shape model, to the probabilistic output of a supervised brain boundary classifier. + Because the shape model cannot perfectly accommodate unseen cases, a small free deformation is subsequently allowed. + The deformation is optimized using graph cuts. + The method ROBEX is based on was published in IEEE Transactions on Medical Imaging; + please visit the website http://www.jeiglesias.com to download the paper. + + Examples + -------- + >>> from nipype.interfaces.robex.preprocess import RobexSegment + >>> robex = RobexSegment() + >>> robex.inputs.in_file = 'structural.nii' + >>> robex.cmdline + 'runROBEX.sh structural.nii structural_brain.nii structural_brainmask.nii' + >>> robex.run() # doctest: +SKIP + + """ + + input_spec = RobexInputSpec + output_spec = RobexOutputSpec + _cmd = 'runROBEX.sh' diff --git a/nipype/interfaces/robex/tests/__init__.py b/nipype/interfaces/robex/tests/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/interfaces/robex/tests/test_auto_RobexSegment.py b/nipype/interfaces/robex/tests/test_auto_RobexSegment.py new file mode 100644 index 0000000000..caccd469e3 --- /dev/null +++ b/nipype/interfaces/robex/tests/test_auto_RobexSegment.py @@ -0,0 +1,63 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..preprocess import RobexSegment + + +def test_RobexSegment_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + out_file=dict( + argstr="%s", + extensions=None, + hash_files=False, + keep_extension=True, + name_source=["in_file"], + name_template="%s_brain", + position=1, + ), + out_mask=dict( + argstr="%s", + extensions=None, + hash_files=False, + keep_extension=True, + name_source=["in_file"], + name_template="%s_brainmask", + position=2, + ), + seed=dict( + argstr="%i", + position=3, + ), + ) + inputs = RobexSegment.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_RobexSegment_outputs(): + output_map = dict( + out_file=dict( + extensions=None, + ), + out_mask=dict( + extensions=None, + ), + ) + outputs = RobexSegment.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/semtools/__init__.py b/nipype/interfaces/semtools/__init__.py index a09c926c37..317273cfd8 100644 --- a/nipype/interfaces/semtools/__init__.py +++ b/nipype/interfaces/semtools/__init__.py @@ -1,5 +1,5 @@ -# -*- coding: utf-8 -*- """SEM Tools are useful tools for Structural Equation Modeling.""" + from .diffusion import * from .featurecreator import GenerateCsfClippedFromClassifiedImage from .segmentation import * diff --git a/nipype/interfaces/semtools/brains/__init__.py b/nipype/interfaces/semtools/brains/__init__.py index dd369fb168..9177db7e3d 100644 --- a/nipype/interfaces/semtools/brains/__init__.py +++ b/nipype/interfaces/semtools/brains/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .segmentation import SimilarityIndex, BRAINSTalairach, BRAINSTalairachMask from .utilities import ( HistogramMatchingFilter, diff --git a/nipype/interfaces/semtools/brains/classify.py b/nipype/interfaces/semtools/brains/classify.py index f59b53183e..149e63c95e 100644 --- a/nipype/interfaces/semtools/brains/classify.py +++ b/nipype/interfaces/semtools/brains/classify.py @@ -1,21 +1,12 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) @@ -67,21 +58,20 @@ class BRAINSPosteriorToContinuousClassOutputSpec(TraitedSpec): class BRAINSPosteriorToContinuousClass(SEMLikeCommandLine): """title: Tissue Classification -category: BRAINS.Classify - -description: This program will generate an 8-bit continuous tissue classified image based on BRAINSABC posterior images. + category: BRAINS.Classify -version: 3.0 + description: This program will generate an 8-bit continuous tissue classified image based on BRAINSABC posterior images. -documentation-url: http://www.nitrc.org/plugins/mwiki/index.php/brains:BRAINSClassify + version: 3.0 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://www.nitrc.org/plugins/mwiki/index.php/brains:BRAINSClassify -contributor: Vincent A. Magnotta + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: Funding for this work was provided by NIH/NINDS award NS050568 + contributor: Vincent A. Magnotta -""" + acknowledgements: Funding for this work was provided by NIH/NINDS award NS050568 + """ input_spec = BRAINSPosteriorToContinuousClassInputSpec output_spec = BRAINSPosteriorToContinuousClassOutputSpec diff --git a/nipype/interfaces/semtools/brains/segmentation.py b/nipype/interfaces/semtools/brains/segmentation.py index 5b0a901277..a6dbfbd449 100644 --- a/nipype/interfaces/semtools/brains/segmentation.py +++ b/nipype/interfaces/semtools/brains/segmentation.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -46,17 +38,16 @@ class SimilarityIndexOutputSpec(TraitedSpec): class SimilarityIndex(SEMLikeCommandLine): """title: BRAINSCut:SimilarityIndexComputation -category: BRAINS.Segmentation - -description: Automatic analysis of BRAINSCut Output + category: BRAINS.Segmentation -version: 1.0 + description: Automatic analysis of BRAINSCut Output -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 1.0 -contributor: Eunyoung Regin Kim + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: Eunyoung Regin Kim + """ input_spec = SimilarityIndexInputSpec output_spec = SimilarityIndexOutputSpec @@ -113,21 +104,20 @@ class BRAINSTalairachOutputSpec(TraitedSpec): class BRAINSTalairach(SEMLikeCommandLine): """title: BRAINS Talairach -category: BRAINS.Segmentation + category: BRAINS.Segmentation -description: This program creates a VTK structured grid defining the Talairach coordinate system based on four points: AC, PC, IRP, and SLA. The resulting structred grid can be written as either a classic VTK file or the new VTK XML file format. Two representations of the resulting grid can be written. The first is a bounding box representation that also contains the location of the AC and PC points. The second representation is the full Talairach grid representation that includes the additional rows of boxes added to the inferior allowing full coverage of the cerebellum. + description: This program creates a VTK structured grid defining the Talairach coordinate system based on four points: AC, PC, IRP, and SLA. The resulting structured grid can be written as either a classic VTK file or the new VTK XML file format. Two representations of the resulting grid can be written. The first is a bounding box representation that also contains the location of the AC and PC points. The second representation is the full Talairach grid representation that includes the additional rows of boxes added to the inferior allowing full coverage of the cerebellum. -version: 0.1 + version: 0.1 -documentation-url: http://www.nitrc.org/plugins/mwiki/index.php/brains:BRAINSTalairach + documentation-url: http://www.nitrc.org/plugins/mwiki/index.php/brains:BRAINSTalairach -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: Steven Dunn and Vincent Magnotta + contributor: Steven Dunn and Vincent Magnotta -acknowledgements: Funding for this work was provided by NIH/NINDS award NS050568 - -""" + acknowledgements: Funding for this work was provided by NIH/NINDS award NS050568 + """ input_spec = BRAINSTalairachInputSpec output_spec = BRAINSTalairachOutputSpec @@ -178,21 +168,20 @@ class BRAINSTalairachMaskOutputSpec(TraitedSpec): class BRAINSTalairachMask(SEMLikeCommandLine): """title: Talairach Mask -category: BRAINS.Segmentation - -description: This program creates a binary image representing the specified Talairach region. The input is an example image to define the physical space for the resulting image, the Talairach grid representation in VTK format, and the file containing the Talairach box definitions to be generated. These can be combined in BRAINS to create a label map using the procedure Brains::WorkupUtils::CreateLabelMapFromBinaryImages. + category: BRAINS.Segmentation -version: 0.1 + description: This program creates a binary image representing the specified Talairach region. The input is an example image to define the physical space for the resulting image, the Talairach grid representation in VTK format, and the file containing the Talairach box definitions to be generated. These can be combined in BRAINS to create a label map using the procedure Brains::WorkupUtils::CreateLabelMapFromBinaryImages. -documentation-url: http://www.nitrc.org/plugins/mwiki/index.php/brains:BRAINSTalairachMask + version: 0.1 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://www.nitrc.org/plugins/mwiki/index.php/brains:BRAINSTalairachMask -contributor: Steven Dunn and Vincent Magnotta + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: Funding for this work was provided by NIH/NINDS award NS050568 + contributor: Steven Dunn and Vincent Magnotta -""" + acknowledgements: Funding for this work was provided by NIH/NINDS award NS050568 + """ input_spec = BRAINSTalairachMaskInputSpec output_spec = BRAINSTalairachMaskOutputSpec diff --git a/nipype/interfaces/semtools/brains/tests/__init__.py b/nipype/interfaces/semtools/brains/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/brains/tests/__init__.py +++ b/nipype/interfaces/semtools/brains/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSPosteriorToContinuousClass.py b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSPosteriorToContinuousClass.py index fd22f39bba..9098ee2640 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSPosteriorToContinuousClass.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSPosteriorToContinuousClass.py @@ -4,16 +4,45 @@ def test_BRAINSPosteriorToContinuousClass_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputBasalGmVolume=dict(argstr="--inputBasalGmVolume %s", extensions=None,), - inputCrblGmVolume=dict(argstr="--inputCrblGmVolume %s", extensions=None,), - inputCrblWmVolume=dict(argstr="--inputCrblWmVolume %s", extensions=None,), - inputCsfVolume=dict(argstr="--inputCsfVolume %s", extensions=None,), - inputSurfaceGmVolume=dict(argstr="--inputSurfaceGmVolume %s", extensions=None,), - inputVbVolume=dict(argstr="--inputVbVolume %s", extensions=None,), - inputWhiteVolume=dict(argstr="--inputWhiteVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputBasalGmVolume=dict( + argstr="--inputBasalGmVolume %s", + extensions=None, + ), + inputCrblGmVolume=dict( + argstr="--inputCrblGmVolume %s", + extensions=None, + ), + inputCrblWmVolume=dict( + argstr="--inputCrblWmVolume %s", + extensions=None, + ), + inputCsfVolume=dict( + argstr="--inputCsfVolume %s", + extensions=None, + ), + inputSurfaceGmVolume=dict( + argstr="--inputSurfaceGmVolume %s", + extensions=None, + ), + inputVbVolume=dict( + argstr="--inputVbVolume %s", + extensions=None, + ), + inputWhiteVolume=dict( + argstr="--inputWhiteVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = BRAINSPosteriorToContinuousClass.input_spec() @@ -23,7 +52,11 @@ def test_BRAINSPosteriorToContinuousClass_inputs(): def test_BRAINSPosteriorToContinuousClass_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSPosteriorToContinuousClass.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairach.py b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairach.py index 0999af73d0..195ebdcad0 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairach.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairach.py @@ -4,19 +4,53 @@ def test_BRAINSTalairach_inputs(): input_map = dict( - AC=dict(argstr="--AC %s", sep=",",), - ACisIndex=dict(argstr="--ACisIndex ",), - IRP=dict(argstr="--IRP %s", sep=",",), - IRPisIndex=dict(argstr="--IRPisIndex ",), - PC=dict(argstr="--PC %s", sep=",",), - PCisIndex=dict(argstr="--PCisIndex ",), - SLA=dict(argstr="--SLA %s", sep=",",), - SLAisIndex=dict(argstr="--SLAisIndex ",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputBox=dict(argstr="--outputBox %s", hash_files=False,), - outputGrid=dict(argstr="--outputGrid %s", hash_files=False,), + AC=dict( + argstr="--AC %s", + sep=",", + ), + ACisIndex=dict( + argstr="--ACisIndex ", + ), + IRP=dict( + argstr="--IRP %s", + sep=",", + ), + IRPisIndex=dict( + argstr="--IRPisIndex ", + ), + PC=dict( + argstr="--PC %s", + sep=",", + ), + PCisIndex=dict( + argstr="--PCisIndex ", + ), + SLA=dict( + argstr="--SLA %s", + sep=",", + ), + SLAisIndex=dict( + argstr="--SLAisIndex ", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputBox=dict( + argstr="--outputBox %s", + hash_files=False, + ), + outputGrid=dict( + argstr="--outputGrid %s", + hash_files=False, + ), ) inputs = BRAINSTalairach.input_spec() @@ -27,7 +61,12 @@ def test_BRAINSTalairach_inputs(): def test_BRAINSTalairach_outputs(): output_map = dict( - outputBox=dict(extensions=None,), outputGrid=dict(extensions=None,), + outputBox=dict( + extensions=None, + ), + outputGrid=dict( + extensions=None, + ), ) outputs = BRAINSTalairach.output_spec() diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairachMask.py b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairachMask.py index 959733ce42..2470e42f47 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairachMask.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_BRAINSTalairachMask.py @@ -4,14 +4,35 @@ def test_BRAINSTalairachMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - expand=dict(argstr="--expand ",), - hemisphereMode=dict(argstr="--hemisphereMode %s",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - talairachBox=dict(argstr="--talairachBox %s", extensions=None,), - talairachParameters=dict(argstr="--talairachParameters %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expand=dict( + argstr="--expand ", + ), + hemisphereMode=dict( + argstr="--hemisphereMode %s", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + talairachBox=dict( + argstr="--talairachBox %s", + extensions=None, + ), + talairachParameters=dict( + argstr="--talairachParameters %s", + extensions=None, + ), ) inputs = BRAINSTalairachMask.input_spec() @@ -21,7 +42,11 @@ def test_BRAINSTalairachMask_inputs(): def test_BRAINSTalairachMask_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSTalairachMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_GenerateEdgeMapImage.py b/nipype/interfaces/semtools/brains/tests/test_auto_GenerateEdgeMapImage.py index 766c9c7a2b..218c67a4b0 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_GenerateEdgeMapImage.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_GenerateEdgeMapImage.py @@ -4,19 +4,43 @@ def test_GenerateEdgeMapImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMRVolumes=dict(argstr="--inputMRVolumes %s...",), - inputMask=dict(argstr="--inputMask %s", extensions=None,), - lowerPercentileMatching=dict(argstr="--lowerPercentileMatching %f",), - maximumOutputRange=dict(argstr="--maximumOutputRange %d",), - minimumOutputRange=dict(argstr="--minimumOutputRange %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputEdgeMap=dict(argstr="--outputEdgeMap %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMRVolumes=dict( + argstr="--inputMRVolumes %s...", + ), + inputMask=dict( + argstr="--inputMask %s", + extensions=None, + ), + lowerPercentileMatching=dict( + argstr="--lowerPercentileMatching %f", + ), + maximumOutputRange=dict( + argstr="--maximumOutputRange %d", + ), + minimumOutputRange=dict( + argstr="--minimumOutputRange %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputEdgeMap=dict( + argstr="--outputEdgeMap %s", + hash_files=False, + ), outputMaximumGradientImage=dict( - argstr="--outputMaximumGradientImage %s", hash_files=False, + argstr="--outputMaximumGradientImage %s", + hash_files=False, + ), + upperPercentileMatching=dict( + argstr="--upperPercentileMatching %f", ), - upperPercentileMatching=dict(argstr="--upperPercentileMatching %f",), ) inputs = GenerateEdgeMapImage.input_spec() @@ -27,8 +51,12 @@ def test_GenerateEdgeMapImage_inputs(): def test_GenerateEdgeMapImage_outputs(): output_map = dict( - outputEdgeMap=dict(extensions=None,), - outputMaximumGradientImage=dict(extensions=None,), + outputEdgeMap=dict( + extensions=None, + ), + outputMaximumGradientImage=dict( + extensions=None, + ), ) outputs = GenerateEdgeMapImage.output_spec() diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_GeneratePurePlugMask.py b/nipype/interfaces/semtools/brains/tests/test_auto_GeneratePurePlugMask.py index 5cba5f42d9..e68b03dcf9 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_GeneratePurePlugMask.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_GeneratePurePlugMask.py @@ -4,12 +4,27 @@ def test_GeneratePurePlugMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputImageModalities=dict(argstr="--inputImageModalities %s...",), - numberOfSubSamples=dict(argstr="--numberOfSubSamples %s", sep=",",), - outputMaskFile=dict(argstr="--outputMaskFile %s", hash_files=False,), - threshold=dict(argstr="--threshold %f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputImageModalities=dict( + argstr="--inputImageModalities %s...", + ), + numberOfSubSamples=dict( + argstr="--numberOfSubSamples %s", + sep=",", + ), + outputMaskFile=dict( + argstr="--outputMaskFile %s", + hash_files=False, + ), + threshold=dict( + argstr="--threshold %f", + ), ) inputs = GeneratePurePlugMask.input_spec() @@ -19,7 +34,11 @@ def test_GeneratePurePlugMask_inputs(): def test_GeneratePurePlugMask_outputs(): - output_map = dict(outputMaskFile=dict(extensions=None,),) + output_map = dict( + outputMaskFile=dict( + extensions=None, + ), + ) outputs = GeneratePurePlugMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_HistogramMatchingFilter.py b/nipype/interfaces/semtools/brains/tests/test_auto_HistogramMatchingFilter.py index 746857c627..110aec4891 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_HistogramMatchingFilter.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_HistogramMatchingFilter.py @@ -4,20 +4,48 @@ def test_HistogramMatchingFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - histogramAlgorithm=dict(argstr="--histogramAlgorithm %s",), - inputBinaryVolume=dict(argstr="--inputBinaryVolume %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - numberOfMatchPoints=dict(argstr="--numberOfMatchPoints %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + histogramAlgorithm=dict( + argstr="--histogramAlgorithm %s", + ), + inputBinaryVolume=dict( + argstr="--inputBinaryVolume %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + numberOfMatchPoints=dict( + argstr="--numberOfMatchPoints %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), referenceBinaryVolume=dict( - argstr="--referenceBinaryVolume %s", extensions=None, + argstr="--referenceBinaryVolume %s", + extensions=None, + ), + referenceVolume=dict( + argstr="--referenceVolume %s", + extensions=None, + ), + verbose=dict( + argstr="--verbose ", + ), + writeHistogram=dict( + argstr="--writeHistogram %s", ), - referenceVolume=dict(argstr="--referenceVolume %s", extensions=None,), - verbose=dict(argstr="--verbose ",), - writeHistogram=dict(argstr="--writeHistogram %s",), ) inputs = HistogramMatchingFilter.input_spec() @@ -27,7 +55,11 @@ def test_HistogramMatchingFilter_inputs(): def test_HistogramMatchingFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = HistogramMatchingFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py b/nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py index 348ecf67d0..881e3379de 100644 --- a/nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py +++ b/nipype/interfaces/semtools/brains/tests/test_auto_SimilarityIndex.py @@ -4,12 +4,28 @@ def test_SimilarityIndex_inputs(): input_map = dict( - ANNContinuousVolume=dict(argstr="--ANNContinuousVolume %s", extensions=None,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputManualVolume=dict(argstr="--inputManualVolume %s", extensions=None,), - outputCSVFilename=dict(argstr="--outputCSVFilename %s", extensions=None,), - thresholdInterval=dict(argstr="--thresholdInterval %f",), + ANNContinuousVolume=dict( + argstr="--ANNContinuousVolume %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputManualVolume=dict( + argstr="--inputManualVolume %s", + extensions=None, + ), + outputCSVFilename=dict( + argstr="--outputCSVFilename %s", + extensions=None, + ), + thresholdInterval=dict( + argstr="--thresholdInterval %f", + ), ) inputs = SimilarityIndex.input_spec() diff --git a/nipype/interfaces/semtools/brains/utilities.py b/nipype/interfaces/semtools/brains/utilities.py index 7c6351eaab..3b5596e6d7 100644 --- a/nipype/interfaces/semtools/brains/utilities.py +++ b/nipype/interfaces/semtools/brains/utilities.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -55,11 +47,11 @@ class HistogramMatchingFilterInputSpec(CommandLineInputSpec): ) histogramAlgorithm = traits.Enum( "OtsuHistogramMatching", - desc=" histogram algrithm selection", + desc=" histogram algorithm selection", argstr="--histogramAlgorithm %s", ) verbose = traits.Bool( - desc=" verbose mode running for debbuging", argstr="--verbose " + desc=" verbose mode running for debugging", argstr="--verbose " ) @@ -70,15 +62,14 @@ class HistogramMatchingFilterOutputSpec(TraitedSpec): class HistogramMatchingFilter(SEMLikeCommandLine): """title: Write Out Image Intensities -category: BRAINS.Utilities - -description: For Analysis + category: BRAINS.Utilities -version: 0.1 + description: For Analysis -contributor: University of Iowa Department of Psychiatry, http:://www.psychiatry.uiowa.edu + version: 0.1 -""" + contributor: University of Iowa Department of Psychiatry, http:://www.psychiatry.uiowa.edu + """ input_spec = HistogramMatchingFilterInputSpec output_spec = HistogramMatchingFilterOutputSpec @@ -144,15 +135,14 @@ class GenerateEdgeMapImageOutputSpec(TraitedSpec): class GenerateEdgeMapImage(SEMLikeCommandLine): """title: GenerateEdgeMapImage -category: BRAINS.Utilities + category: BRAINS.Utilities -description: Automatic edgemap generation for edge-guided super-resolution reconstruction + description: Automatic edgemap generation for edge-guided super-resolution reconstruction -version: 1.0 + version: 1.0 -contributor: Ali Ghayoor - -""" + contributor: Ali Ghayoor + """ input_spec = GenerateEdgeMapImageInputSpec output_spec = GenerateEdgeMapImageOutputSpec @@ -175,7 +165,7 @@ class GeneratePurePlugMaskInputSpec(CommandLineInputSpec): ) numberOfSubSamples = InputMultiPath( traits.Int, - desc="Number of continous index samples taken at each direction of lattice space for each plug volume", + desc="Number of continuous index samples taken at each direction of lattice space for each plug volume", sep=",", argstr="--numberOfSubSamples %s", ) @@ -195,15 +185,14 @@ class GeneratePurePlugMaskOutputSpec(TraitedSpec): class GeneratePurePlugMask(SEMLikeCommandLine): """title: GeneratePurePlugMask -category: BRAINS.Utilities - -description: This program gets several modality image files and returns a binary mask that defines the pure plugs + category: BRAINS.Utilities -version: 1.0 + description: This program gets several modality image files and returns a binary mask that defines the pure plugs -contributor: Ali Ghayoor + version: 1.0 -""" + contributor: Ali Ghayoor + """ input_spec = GeneratePurePlugMaskInputSpec output_spec = GeneratePurePlugMaskOutputSpec diff --git a/nipype/interfaces/semtools/converters.py b/nipype/interfaces/semtools/converters.py index f3c1d432f5..091f832b2b 100644 --- a/nipype/interfaces/semtools/converters.py +++ b/nipype/interfaces/semtools/converters.py @@ -1,21 +1,12 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ..base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) @@ -43,21 +34,20 @@ class DWISimpleCompareOutputSpec(TraitedSpec): class DWISimpleCompare(SEMLikeCommandLine): """title: Nrrd DWI comparison -category: Converters - -description: Compares two nrrd format DWI images and verifies that gradient magnitudes, gradient directions, measurement frame, and max B0 value are identicle. Used for testing DWIConvert. + category: Converters -version: 0.1.0.$Revision: 916 $(alpha) + description: Compares two nrrd format DWI images and verifies that gradient magnitudes, gradient directions, measurement frame, and max B0 value are identicle. Used for testing DWIConvert. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DWIConvert + version: 0.1.0.$Revision: 916 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DWIConvert -contributor: Mark Scully (UIowa) + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for DTI data produced on Philips scanners was contributed by Vincent Magnotta and Hans Johnson at the University of Iowa. + contributor: Mark Scully (UIowa) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for DTI data produced on Philips scanners was contributed by Vincent Magnotta and Hans Johnson at the University of Iowa. + """ input_spec = DWISimpleCompareInputSpec output_spec = DWISimpleCompareOutputSpec @@ -86,21 +76,20 @@ class DWICompareOutputSpec(TraitedSpec): class DWICompare(SEMLikeCommandLine): """title: Nrrd DWI comparison -category: Converters - -description: Compares two nrrd format DWI images and verifies that gradient magnitudes, gradient directions, measurement frame, and max B0 value are identicle. Used for testing DWIConvert. + category: Converters -version: 0.1.0.$Revision: 916 $(alpha) + description: Compares two nrrd format DWI images and verifies that gradient magnitudes, gradient directions, measurement frame, and max B0 value are identicle. Used for testing DWIConvert. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DWIConvert + version: 0.1.0.$Revision: 916 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DWIConvert -contributor: Mark Scully (UIowa) + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for DTI data produced on Philips scanners was contributed by Vincent Magnotta and Hans Johnson at the University of Iowa. + contributor: Mark Scully (UIowa) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for DTI data produced on Philips scanners was contributed by Vincent Magnotta and Hans Johnson at the University of Iowa. + """ input_spec = DWICompareInputSpec output_spec = DWICompareOutputSpec diff --git a/nipype/interfaces/semtools/diffusion/__init__.py b/nipype/interfaces/semtools/diffusion/__init__.py index 28044fe337..1f56f11145 100644 --- a/nipype/interfaces/semtools/diffusion/__init__.py +++ b/nipype/interfaces/semtools/diffusion/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .diffusion import dtiaverage, dtiestim, dtiprocess, DWIConvert from .tractography import * from .gtract import ( diff --git a/nipype/interfaces/semtools/diffusion/diffusion.py b/nipype/interfaces/semtools/diffusion/diffusion.py index 90377b8ee0..6a85d5cd7a 100644 --- a/nipype/interfaces/semtools/diffusion/diffusion.py +++ b/nipype/interfaces/semtools/diffusion/diffusion.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -46,24 +39,23 @@ class dtiaverageOutputSpec(TraitedSpec): class dtiaverage(SEMLikeCommandLine): """title: DTIAverage (DTIProcess) -category: Diffusion.Diffusion Tensor Images.CommandLineOnly - -description: dtiaverage is a program that allows to compute the average of an arbitrary number of tensor fields (listed after the --inputs option) This program is used in our pipeline as the last step of the atlas building processing. When all the tensor fields have been deformed in the same space, to create the average tensor field (--tensor_output) we use dtiaverage. - Several average method can be used (specified by the --method option): euclidian, log-euclidian and pga. The default being euclidian. + category: Diffusion.Diffusion Tensor Images.CommandLineOnly -version: 1.0.0 + description: dtiaverage is a program that allows to compute the average of an arbitrary number of tensor fields (listed after the --inputs option) This program is used in our pipeline as the last step of the atlas building processing. When all the tensor fields have been deformed in the same space, to create the average tensor field (--tensor_output) we use dtiaverage. + Several average method can be used (specified by the --method option): euclidean, log-euclidean and pga. The default being euclidean. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess + version: 1.0.0 -license: Copyright (c) Casey Goodlett. All rights reserved. - See http://www.ia.unc.edu/dev/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess -contributor: Casey Goodlett + license: Copyright (c) Casey Goodlett. All rights reserved. + See http://www.ia.unc.edu/dev/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. -""" + contributor: Casey Goodlett + """ input_spec = dtiaverageInputSpec output_spec = dtiaverageOutputSpec @@ -119,7 +111,7 @@ class dtiestimInputSpec(CommandLineInputSpec): "wls", "nls", "ml", - desc="Esitmation method (lls:linear least squares, wls:weighted least squares, nls:non-linear least squares, ml:maximum likelihood)", + desc="Estimation method (lls:linear least squares, wls:weighted least squares, nls:non-linear least squares, ml:maximum likelihood)", argstr="--method %s", ) correction = traits.Enum( @@ -179,45 +171,44 @@ class dtiestimOutputSpec(TraitedSpec): class dtiestim(SEMLikeCommandLine): """title: DTIEstim (DTIProcess) -category: Diffusion.Diffusion Weighted Images - -description: dtiestim is a tool that takes in a set of DWIs (with --dwi_image option) in nrrd format and estimates a tensor field out of it. The output tensor file name is specified with the --tensor_output option -There are several methods to estimate the tensors which you can specify with the option --method lls|wls|nls|ml . Here is a short description of the different methods: + category: Diffusion.Diffusion Weighted Images -lls - Linear least squares. Standard estimation technique that recovers the tensor parameters by multiplying the log of the normalized signal intensities by the pseudo-inverse of the gradient matrix. Default option. + description: dtiestim is a tool that takes in a set of DWIs (with --dwi_image option) in nrrd format and estimates a tensor field out of it. The output tensor file name is specified with the --tensor_output option + There are several methods to estimate the tensors which you can specify with the option --method lls|wls|nls|ml . Here is a short description of the different methods: -wls - Weighted least squares. This method is similar to the linear least squares method except that the gradient matrix is weighted by the original lls estimate. (See Salvador, R., Pena, A., Menon, D. K., Carpenter, T. A., Pickard, J. D., and Bullmore, E. T. Formal characterization and extension of the linearized diffusion tensor model. Human Brain Mapping 24, 2 (Feb. 2005), 144-155. for more information on this method). This method is recommended for most applications. The weight for each iteration can be specified with the --weight_iterations. It is not currently the default due to occasional matrix singularities. -nls - Non-linear least squares. This method does not take the log of the signal and requires an optimization based on levenberg-marquadt to optimize the parameters of the signal. The lls estimate is used as an initialization. For this method the step size can be specified with the --step option. -ml - Maximum likelihood estimation. This method is experimental and is not currently recommended. For this ml method the sigma can be specified with the option --sigma and the step size can be specified with the --step option. + lls + Linear least squares. Standard estimation technique that recovers the tensor parameters by multiplying the log of the normalized signal intensities by the pseudo-inverse of the gradient matrix. Default option. -You can set a threshold (--threshold) to have the tensor estimated to only a subset of voxels. All the baseline voxel value higher than the threshold define the voxels where the tensors are computed. If not specified the threshold is calculated using an OTSU threshold on the baseline image.The masked generated by the -t option or by the otsu value can be saved with the --B0_mask_output option. + wls + Weighted least squares. This method is similar to the linear least squares method except that the gradient matrix is weighted by the original lls estimate. (See Salvador, R., Pena, A., Menon, D. K., Carpenter, T. A., Pickard, J. D., and Bullmore, E. T. Formal characterization and extension of the linearized diffusion tensor model. Human Brain Mapping 24, 2 (Feb. 2005), 144-155. for more information on this method). This method is recommended for most applications. The weight for each iteration can be specified with the --weight_iterations. It is not currently the default due to occasional matrix singularities. + nls + Non-linear least squares. This method does not take the log of the signal and requires an optimization based on levenberg-marquadt to optimize the parameters of the signal. The lls estimate is used as an initialization. For this method the step size can be specified with the --step option. + ml + Maximum likelihood estimation. This method is experimental and is not currently recommended. For this ml method the sigma can be specified with the option --sigma and the step size can be specified with the --step option. -dtiestim also can extract a few scalar images out of the DWI set of images: + You can set a threshold (--threshold) to have the tensor estimated to only a subset of voxels. All the baseline voxel value higher than the threshold define the voxels where the tensors are computed. If not specified the threshold is calculated using an OTSU threshold on the baseline image.The masked generated by the -t option or by the otsu value can be saved with the --B0_mask_output option. - - the average baseline image (--B0) which is the average of all the B0s. - - the IDWI (--idwi)which is the geometric mean of the diffusion images. + dtiestim also can extract a few scalar images out of the DWI set of images: -You can also load a mask if you want to compute the tensors only where the voxels are non-zero (--brain_mask) or a negative mask and the tensors will be estimated where the negative mask has zero values (--bad_region_mask) + - the average baseline image (--B0) which is the average of all the B0s. + - the IDWI (--idwi)which is the geometric mean of the diffusion images. -version: 1.2.0 + You can also load a mask if you want to compute the tensors only where the voxels are non-zero (--brain_mask) or a negative mask and the tensors will be estimated where the negative mask has zero values (--bad_region_mask) -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess + version: 1.2.0 -license: Copyright (c) Casey Goodlett. All rights reserved. - See http://www.ia.unc.edu/dev/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess -contributor: Casey Goodlett, Francois Budin + license: Copyright (c) Casey Goodlett. All rights reserved. + See http://www.ia.unc.edu/dev/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependancies on boost and a fortran compiler. + contributor: Casey Goodlett, Francois Budin -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependencies on boost and a fortran compiler. + """ input_spec = dtiestimInputSpec output_spec = dtiestimOutputSpec @@ -436,35 +427,34 @@ class dtiprocessOutputSpec(TraitedSpec): class dtiprocess(SEMLikeCommandLine): """title: DTIProcess (DTIProcess) -category: Diffusion.Diffusion Tensor Images + category: Diffusion.Diffusion Tensor Images -description: dtiprocess is a tool that handles tensor fields. It takes as an input a tensor field in nrrd format. -It can generate diffusion scalar properties out of the tensor field such as : FA (--fa_output), Gradient FA image (--fa_gradient_output), color FA (--color_fa_output), MD (--md_output), Frobenius norm (--frobenius_norm_output), lbd1, lbd2, lbd3 (--lambda{1,2,3}_output), binary map of voxel where if any of the eigenvalue is negative, the voxel is set to 1 (--negative_eigenvector_output) + description: dtiprocess is a tool that handles tensor fields. It takes as an input a tensor field in nrrd format. + It can generate diffusion scalar properties out of the tensor field such as : FA (--fa_output), Gradient FA image (--fa_gradient_output), color FA (--color_fa_output), MD (--md_output), Frobenius norm (--frobenius_norm_output), lbd1, lbd2, lbd3 (--lambda{1,2,3}_output), binary map of voxel where if any of the eigenvalue is negative, the voxel is set to 1 (--negative_eigenvector_output) -It also creates 4D images out of the tensor field such as: Highest eigenvector map (highest eigenvector at each voxel) (--principal_eigenvector_output) + It also creates 4D images out of the tensor field such as: Highest eigenvector map (highest eigenvector at each voxel) (--principal_eigenvector_output) -Masking capabilities: For any of the processing done with dtiprocess, it's possible to apply it on a masked region of the tensor field. You need to use the --mask option for any of the option to be applied on that tensor field sub-region only. If you want to save the masked tensor field use the option --outmask and specify the new masked tensor field file name. -dtiprocess also allows a range of transformations on the tensor fields. The transformed tensor field file name is specified with the option --deformation_output. There are 3 resampling interpolation methods specified with the tag --interpolation followed by the type to use (nearestneighbor, linear, cubic) Then you have several transformations possible to apply: + Masking capabilities: For any of the processing done with dtiprocess, it's possible to apply it on a masked region of the tensor field. You need to use the --mask option for any of the option to be applied on that tensor field sub-region only. If you want to save the masked tensor field use the option --outmask and specify the new masked tensor field file name. + dtiprocess also allows a range of transformations on the tensor fields. The transformed tensor field file name is specified with the option --deformation_output. There are 3 resampling interpolation methods specified with the tag --interpolation followed by the type to use (nearestneighbor, linear, cubic) Then you have several transformations possible to apply: - - Affine transformations using as an input - - itk affine transformation file (based on the itkAffineTransform class) - - Affine transformations using rview (details and download at http://www.doc.ic.ac.uk/~dr/software/). There are 2 versions of rview both creating transformation files called dof files. The old version of rview outputs text files containing the transformation parameters. It can be read in with the --dof_file option. The new version outputs binary dof files. These dof files can be transformed into human readable file with the dof2mat tool which is part of the rview package. So you need to save the output of dof2mat into a text file which can then be used with the -- newdof_file option. Usage example: dof2mat mynewdoffile.dof >> mynewdoffile.txt dtiprocess --dti_image mytensorfield.nhdr --newdof_file mynewdoffile.txt --rot_output myaffinetensorfield.nhdr + - Affine transformations using as an input + - itk affine transformation file (based on the itkAffineTransform class) + - Affine transformations using rview (details and download at http://www.doc.ic.ac.uk/~dr/software/). There are 2 versions of rview both creating transformation files called dof files. The old version of rview outputs text files containing the transformation parameters. It can be read in with the --dof_file option. The new version outputs binary dof files. These dof files can be transformed into human readable file with the dof2mat tool which is part of the rview package. So you need to save the output of dof2mat into a text file which can then be used with the -- newdof_file option. Usage example: dof2mat mynewdoffile.dof >> mynewdoffile.txt dtiprocess --dti_image mytensorfield.nhdr --newdof_file mynewdoffile.txt --rot_output myaffinetensorfield.nhdr -Non linear transformations as an input: The default transformation file type is d-field (displacement field) in nrrd format. The option to use is --forward with the name of the file. If the transformation file is a h-field you have to add the option --hField. + Non linear transformations as an input: The default transformation file type is d-field (displacement field) in nrrd format. The option to use is --forward with the name of the file. If the transformation file is a h-field you have to add the option --hField. -version: 1.0.1 + version: 1.0.1 -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess -license: Copyright (c) Casey Goodlett. All rights reserved. - See http://www.ia.unc.edu/dev/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. + license: Copyright (c) Casey Goodlett. All rights reserved. + See http://www.ia.unc.edu/dev/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. -contributor: Casey Goodlett - -""" + contributor: Casey Goodlett + """ input_spec = dtiprocessInputSpec output_spec = dtiprocessOutputSpec @@ -556,7 +546,7 @@ class DWIConvertInputSpec(CommandLineInputSpec): argstr="--useIdentityMeaseurementFrame ", ) useBMatrixGradientDirections = traits.Bool( - desc="Fill the nhdr header with the gradient directions and bvalues computed out of the BMatrix. Only changes behavior for Siemens data. In some cases the standard public gradients are not properly computed. The gradients can emperically computed from the private BMatrix fields. In some cases the private BMatrix is consistent with the public grandients, but not in all cases, when it exists BMatrix is usually most robust.", + desc="Fill the nhdr header with the gradient directions and bvalues computed out of the BMatrix. Only changes behavior for Siemens data. In some cases the standard public gradients are not properly computed. The gradients can empirically computed from the private BMatrix fields. In some cases the private BMatrix is consistent with the public grandients, but not in all cases, when it exists BMatrix is usually most robust.", argstr="--useBMatrixGradientDirections ", ) outputDirectory = traits.Either( @@ -606,21 +596,20 @@ class DWIConvertOutputSpec(TraitedSpec): class DWIConvert(SEMLikeCommandLine): """title: DWIConverter -category: Diffusion.Diffusion Data Conversion - -description: Converts diffusion weighted MR images in dicom series into Nrrd format for analysis in Slicer. This program has been tested on only a limited subset of DTI dicom formats available from Siemens, GE, and Phillips scanners. Work in progress to support dicom multi-frame data. The program parses dicom header to extract necessary information about measurement frame, diffusion weighting directions, b-values, etc, and write out a nrrd image. For non-diffusion weighted dicom images, it loads in an entire dicom series and writes out a single dicom volume in a .nhdr/.raw pair. + category: Diffusion.Diffusion Data Conversion -version: Version 1.0 + description: Converts diffusion weighted MR images in dicom series into Nrrd format for analysis in Slicer. This program has been tested on only a limited subset of DTI dicom formats available from Siemens, GE, and Phillips scanners. Work in progress to support dicom multi-frame data. The program parses dicom header to extract necessary information about measurement frame, diffusion weighting directions, b-values, etc, and write out a nrrd image. For non-diffusion weighted dicom images, it loads in an entire dicom series and writes out a single dicom volume in a .nhdr/.raw pair. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DWIConverter + version: Version 1.0 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DWIConverter -contributor: Vince Magnotta (UIowa), Hans Johnson (UIowa), Joy Matsui (UIowa), Kent Williams (UIowa), Mark Scully (Uiowa), Xiaodong Tao (GE) + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for DTI data produced on Philips scanners was contributed by Vincent Magnotta and Hans Johnson at the University of Iowa. + contributor: Vince Magnotta (UIowa), Hans Johnson (UIowa), Joy Matsui (UIowa), Kent Williams (UIowa), Mark Scully (Uiowa), Xiaodong Tao (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for DTI data produced on Philips scanners was contributed by Vincent Magnotta and Hans Johnson at the University of Iowa. + """ input_spec = DWIConvertInputSpec output_spec = DWIConvertOutputSpec diff --git a/nipype/interfaces/semtools/diffusion/gtract.py b/nipype/interfaces/semtools/diffusion/gtract.py index 0ad255b536..58d7264864 100644 --- a/nipype/interfaces/semtools/diffusion/gtract.py +++ b/nipype/interfaces/semtools/diffusion/gtract.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -48,21 +40,20 @@ class gtractTransformToDisplacementFieldOutputSpec(TraitedSpec): class gtractTransformToDisplacementField(SEMLikeCommandLine): """title: Create Displacement Field -category: Diffusion.GTRACT - -description: This program will compute forward deformation from the given Transform. The size of the DF is equal to MNI space + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will compute forward deformation from the given Transform. The size of the DF is equal to MNI space -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta, Madhura Ingalhalikar, and Greg Harris + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta, Madhura Ingalhalikar, and Greg Harris -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractTransformToDisplacementFieldInputSpec output_spec = gtractTransformToDisplacementFieldOutputSpec @@ -110,21 +101,20 @@ class gtractInvertBSplineTransformOutputSpec(TraitedSpec): class gtractInvertBSplineTransform(SEMLikeCommandLine): """title: B-Spline Transform Inversion -category: Diffusion.GTRACT + category: Diffusion.GTRACT -description: This program will invert a B-Spline transform using a thin-plate spline approximation. + description: This program will invert a B-Spline transform using a thin-plate spline approximation. -version: 4.0.0 + version: 4.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 - -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractInvertBSplineTransformInputSpec output_spec = gtractInvertBSplineTransformOutputSpec @@ -166,21 +156,20 @@ class gtractConcatDwiOutputSpec(TraitedSpec): class gtractConcatDwi(SEMLikeCommandLine): """title: Concat DWI Images -category: Diffusion.GTRACT - -description: This program will concatenate two DTI runs together. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will concatenate two DTI runs together. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractConcatDwiInputSpec output_spec = gtractConcatDwiOutputSpec @@ -226,21 +215,20 @@ class gtractAverageBvaluesOutputSpec(TraitedSpec): class gtractAverageBvalues(SEMLikeCommandLine): """title: Average B-Values -category: Diffusion.GTRACT + category: Diffusion.GTRACT -description: This program will directly average together the baseline gradients (b value equals 0) within a DWI scan. This is usually used after gtractCoregBvalues. + description: This program will directly average together the baseline gradients (b value equals 0) within a DWI scan. This is usually used after gtractCoregBvalues. -version: 4.0.0 + version: 4.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 - -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractAverageBvaluesInputSpec output_spec = gtractAverageBvaluesOutputSpec @@ -279,7 +267,7 @@ class gtractCoregBvaluesInputSpec(CommandLineInputSpec): argstr="--outputTransform %s", ) eddyCurrentCorrection = traits.Bool( - desc="Flag to perform eddy current corection in addition to motion correction (recommended)", + desc="Flag to perform eddy current correction in addition to motion correction (recommended)", argstr="--eddyCurrentCorrection ", ) numberOfIterations = traits.Int( @@ -336,21 +324,20 @@ class gtractCoregBvaluesOutputSpec(TraitedSpec): class gtractCoregBvalues(SEMLikeCommandLine): """title: Coregister B-Values -category: Diffusion.GTRACT - -description: This step should be performed after converting DWI scans from DICOM to NRRD format. This program will register all gradients in a NRRD diffusion weighted 4D vector image (moving image) to a specified index in a fixed image. It also supports co-registration with a T2 weighted image or field map in the same plane as the DWI data. The fixed image for the registration should be a b0 image. A mutual information metric cost function is used for the registration because of the differences in signal intensity as a result of the diffusion gradients. The full affine allows the registration procedure to correct for eddy current distortions that may exist in the data. If the eddyCurrentCorrection is enabled, relaxationFactor (0.25) and maximumStepSize (0.1) should be adjusted. + category: Diffusion.GTRACT -version: 4.0.0 + description: This step should be performed after converting DWI scans from DICOM to NRRD format. This program will register all gradients in a NRRD diffusion weighted 4D vector image (moving image) to a specified index in a fixed image. It also supports co-registration with a T2 weighted image or field map in the same plane as the DWI data. The fixed image for the registration should be a b0 image. A mutual information metric cost function is used for the registration because of the differences in signal intensity as a result of the diffusion gradients. The full affine allows the registration procedure to correct for eddy current distortions that may exist in the data. If the eddyCurrentCorrection is enabled, relaxationFactor (0.25) and maximumStepSize (0.1) should be adjusted. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractCoregBvaluesInputSpec output_spec = gtractCoregBvaluesOutputSpec @@ -407,21 +394,20 @@ class gtractResampleAnisotropyOutputSpec(TraitedSpec): class gtractResampleAnisotropy(SEMLikeCommandLine): """title: Resample Anisotropy -category: Diffusion.GTRACT - -description: This program will resample a floating point image using either the Rigid or B-Spline transform. You may want to save the aligned B0 image after each of the anisotropy map co-registration steps with the anatomical image to check the registration quality with another tool. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will resample a floating point image using either the Rigid or B-Spline transform. You may want to save the aligned B0 image after each of the anisotropy map co-registration steps with the anatomical image to check the registration quality with another tool. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractResampleAnisotropyInputSpec output_spec = gtractResampleAnisotropyOutputSpec @@ -478,21 +464,20 @@ class gtractResampleCodeImageOutputSpec(TraitedSpec): class gtractResampleCodeImage(SEMLikeCommandLine): """title: Resample Code Image -category: Diffusion.GTRACT + category: Diffusion.GTRACT -description: This program will resample a short integer code image using either the Rigid or Inverse-B-Spline transform. The reference image is the DTI tensor anisotropy image space, and the input code image is in anatomical space. + description: This program will resample a short integer code image using either the Rigid or Inverse-B-Spline transform. The reference image is the DTI tensor anisotropy image space, and the input code image is in anatomical space. -version: 4.0.0 + version: 4.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 - -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractResampleCodeImageInputSpec output_spec = gtractResampleCodeImageOutputSpec @@ -508,7 +493,7 @@ class gtractCopyImageOrientationInputSpec(CommandLineInputSpec): argstr="--inputVolume %s", ) inputReferenceVolume = File( - desc="Required: input file containing orietation that will be cloned.", + desc="Required: input file containing orientation that will be cloned.", exists=True, argstr="--inputReferenceVolume %s", ) @@ -535,21 +520,20 @@ class gtractCopyImageOrientationOutputSpec(TraitedSpec): class gtractCopyImageOrientation(SEMLikeCommandLine): """title: Copy Image Orientation -category: Diffusion.GTRACT - -description: This program will copy the orientation from the reference image into the moving image. Currently, the registration process requires that the diffusion weighted images and the anatomical images have the same image orientation (i.e. Axial, Coronal, Sagittal). It is suggested that you copy the image orientation from the diffusion weighted images and apply this to the anatomical image. This image can be subsequently removed after the registration step is complete. We anticipate that this limitation will be removed in future versions of the registration programs. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will copy the orientation from the reference image into the moving image. Currently, the registration process requires that the diffusion weighted images and the anatomical images have the same image orientation (i.e. Axial, Coronal, Sagittal). It is suggested that you copy the image orientation from the diffusion weighted images and apply this to the anatomical image. This image can be subsequently removed after the registration step is complete. We anticipate that this limitation will be removed in future versions of the registration programs. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractCopyImageOrientationInputSpec output_spec = gtractCopyImageOrientationOutputSpec @@ -591,21 +575,20 @@ class gtractCreateGuideFiberOutputSpec(TraitedSpec): class gtractCreateGuideFiber(SEMLikeCommandLine): """title: Create Guide Fiber -category: Diffusion.GTRACT - -description: This program will create a guide fiber by averaging fibers from a previously generated tract. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will create a guide fiber by averaging fibers from a previously generated tract. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractCreateGuideFiberInputSpec output_spec = gtractCreateGuideFiberOutputSpec @@ -654,21 +637,20 @@ class gtractAnisotropyMapOutputSpec(TraitedSpec): class gtractAnisotropyMap(SEMLikeCommandLine): """title: Anisotropy Map -category: Diffusion.GTRACT + category: Diffusion.GTRACT -description: This program will generate a scalar map of anisotropy, given a tensor representation. Anisotropy images are used for fiber tracking, but the anisotropy scalars are not defined along the path. Instead, the tensor representation is included as point data allowing all of these metrics to be computed using only the fiber tract point data. The images can be saved in any ITK supported format, but it is suggested that you use an image format that supports the definition of the image origin. This includes NRRD, NifTI, and Meta formats. These images can also be used for scalar analysis including regional anisotropy measures or VBM style analysis. + description: This program will generate a scalar map of anisotropy, given a tensor representation. Anisotropy images are used for fiber tracking, but the anisotropy scalars are not defined along the path. Instead, the tensor representation is included as point data allowing all of these metrics to be computed using only the fiber tract point data. The images can be saved in any ITK supported format, but it is suggested that you use an image format that supports the definition of the image origin. This includes NRRD, NifTI, and Meta formats. These images can also be used for scalar analysis including regional anisotropy measures or VBM style analysis. -version: 4.0.0 + version: 4.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 - -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractAnisotropyMapInputSpec output_spec = gtractAnisotropyMapOutputSpec @@ -710,21 +692,20 @@ class gtractClipAnisotropyOutputSpec(TraitedSpec): class gtractClipAnisotropy(SEMLikeCommandLine): """title: Clip Anisotropy -category: Diffusion.GTRACT - -description: This program will zero the first and/or last slice of an anisotropy image, creating a clipped anisotropy image. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will zero the first and/or last slice of an anisotropy image, creating a clipped anisotropy image. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractClipAnisotropyInputSpec output_spec = gtractClipAnisotropyOutputSpec @@ -782,21 +763,20 @@ class gtractResampleB0OutputSpec(TraitedSpec): class gtractResampleB0(SEMLikeCommandLine): """title: Resample B0 -category: Diffusion.GTRACT - -description: This program will resample a signed short image using either a Rigid or B-Spline transform. The user must specify a template image that will be used to define the origin, orientation, spacing, and size of the resampled image. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will resample a signed short image using either a Rigid or B-Spline transform. The user must specify a template image that will be used to define the origin, orientation, spacing, and size of the resampled image. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractResampleB0InputSpec output_spec = gtractResampleB0OutputSpec @@ -831,21 +811,20 @@ class gtractInvertRigidTransformOutputSpec(TraitedSpec): class gtractInvertRigidTransform(SEMLikeCommandLine): """title: Rigid Transform Inversion -category: Diffusion.GTRACT + category: Diffusion.GTRACT -description: This program will invert a Rigid transform. + description: This program will invert a Rigid transform. -version: 4.0.0 + version: 4.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 - -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractInvertRigidTransformInputSpec output_spec = gtractInvertRigidTransformOutputSpec @@ -888,21 +867,20 @@ class gtractImageConformityOutputSpec(TraitedSpec): class gtractImageConformity(SEMLikeCommandLine): """title: Image Conformity -category: Diffusion.GTRACT - -description: This program will straighten out the Direction and Origin to match the Reference Image. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will straighten out the Direction and Origin to match the Reference Image. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractImageConformityInputSpec output_spec = gtractImageConformityOutputSpec @@ -954,21 +932,20 @@ class compareTractInclusionOutputSpec(TraitedSpec): class compareTractInclusion(SEMLikeCommandLine): """title: Compare Tracts -category: Diffusion.GTRACT - -description: This program will halt with a status code indicating whether a test tract is nearly enough included in a standard tract in the sense that every fiber in the test tract has a low enough sum of squares distance to some fiber in the standard tract modulo spline resampling of every fiber to a fixed number of points. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will halt with a status code indicating whether a test tract is nearly enough included in a standard tract in the sense that every fiber in the test tract has a low enough sum of squares distance to some fiber in the standard tract modulo spline resampling of every fiber to a fixed number of points. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = compareTractInclusionInputSpec output_spec = compareTractInclusionOutputSpec @@ -1048,21 +1025,20 @@ class gtractFastMarchingTrackingOutputSpec(TraitedSpec): class gtractFastMarchingTracking(SEMLikeCommandLine): """title: Fast Marching Tracking -category: Diffusion.GTRACT + category: Diffusion.GTRACT -description: This program will use a fast marching fiber tracking algorithm to identify fiber tracts from a tensor image. This program is the second portion of the algorithm. The user must first run gtractCostFastMarching to generate the vcl_cost image. The second step of the algorithm implemented here is a gradient descent soplution from the defined ending region back to the seed points specified in gtractCostFastMarching. This algorithm is roughly based on the work by G. Parker et al. from IEEE Transactions On Medical Imaging, 21(5): 505-512, 2002. An additional feature of including anisotropy into the vcl_cost function calculation is included. + description: This program will use a fast marching fiber tracking algorithm to identify fiber tracts from a tensor image. This program is the second portion of the algorithm. The user must first run gtractCostFastMarching to generate the vcl_cost image. The second step of the algorithm implemented here is a gradient descent soplution from the defined ending region back to the seed points specified in gtractCostFastMarching. This algorithm is roughly based on the work by G. Parker et al. from IEEE Transactions On Medical Imaging, 21(5): 505-512, 2002. An additional feature of including anisotropy into the vcl_cost function calculation is included. -version: 4.0.0 + version: 4.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -contributor: This tool was developed by Vincent Magnotta and Greg Harris. The original code here was developed by Daisy Espino. + contributor: This tool was developed by Vincent Magnotta and Greg Harris. The original code here was developed by Daisy Espino. -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 - -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractFastMarchingTrackingInputSpec output_spec = gtractFastMarchingTrackingOutputSpec @@ -1106,21 +1082,20 @@ class gtractInvertDisplacementFieldOutputSpec(TraitedSpec): class gtractInvertDisplacementField(SEMLikeCommandLine): """title: Invert Displacement Field -category: Diffusion.GTRACT - -description: This program will invert a deformatrion field. The size of the deformation field is defined by an example image provided by the user + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will invert a deformatrion field. The size of the deformation field is defined by an example image provided by the user -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractInvertDisplacementFieldInputSpec output_spec = gtractInvertDisplacementFieldOutputSpec @@ -1136,7 +1111,7 @@ class gtractCoRegAnatomyInputSpec(CommandLineInputSpec): argstr="--inputVolume %s", ) inputAnatomicalVolume = File( - desc="Required: input anatomical image file name. It is recommended that that the input anatomical image has been skull stripped and has the same orientation as the DWI scan.", + desc="Required: input anatomical image file name. It is recommended that the input anatomical image has been skull stripped and has the same orientation as the DWI scan.", exists=True, argstr="--inputAnatomicalVolume %s", ) @@ -1213,15 +1188,15 @@ class gtractCoRegAnatomyInputSpec(CommandLineInputSpec): argstr="--samplingPercentage %f", ) useMomentsAlign = traits.Bool( - desc="MomentsAlign assumes that the center of mass of the images represent similar structures. Perform a MomentsAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either CenterOfHeadLAlign, GeometryAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", + desc="MomentsAlign assumes that the center of mass of the images represent similar structures. Perform a MomentsAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either CenterOfHeadLAlign, GeometryAlign, or initialTransform file. This family of options supersedes the use of transformType if any of them are set.", argstr="--useMomentsAlign ", ) useGeometryAlign = traits.Bool( - desc="GeometryAlign on assumes that the center of the voxel lattice of the images represent similar structures. Perform a GeometryCenterAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either MomentsAlign, CenterOfHeadAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", + desc="GeometryAlign on assumes that the center of the voxel lattice of the images represent similar structures. Perform a GeometryCenterAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either MomentsAlign, CenterOfHeadAlign, or initialTransform file. This family of options supersedes the use of transformType if any of them are set.", argstr="--useGeometryAlign ", ) useCenterOfHeadAlign = traits.Bool( - desc="CenterOfHeadAlign attempts to find a hemisphere full of foreground voxels from the superior direction as an estimate of where the center of a head shape would be to drive a center of mass estimate. Perform a CenterOfHeadAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either MomentsAlign, GeometryAlign, or initialTransform file. This family of options superceeds the use of transformType if any of them are set.", + desc="CenterOfHeadAlign attempts to find a hemisphere full of foreground voxels from the superior direction as an estimate of where the center of a head shape would be to drive a center of mass estimate. Perform a CenterOfHeadAlign registration as part of the sequential registration steps. This option MUST come first, and CAN NOT be used with either MomentsAlign, GeometryAlign, or initialTransform file. This family of options supersedes the use of transformType if any of them are set.", argstr="--useCenterOfHeadAlign ", ) numberOfThreads = traits.Int( @@ -1239,21 +1214,20 @@ class gtractCoRegAnatomyOutputSpec(TraitedSpec): class gtractCoRegAnatomy(SEMLikeCommandLine): """title: Coregister B0 to Anatomy B-Spline -category: Diffusion.GTRACT - -description: This program will register a Nrrd diffusion weighted 4D vector image to a fixed anatomical image. Two registration methods are supported for alignment with anatomical images: Rigid and B-Spline. The rigid registration performs a rigid body registration with the anatomical images and should be done as well to initialize the B-Spline transform. The B-SPline transform is the deformable transform, where the user can control the amount of deformation based on the number of control points as well as the maximum distance that these points can move. The B-Spline registration places a low dimensional grid in the image, which is deformed. This allows for some susceptibility related distortions to be removed from the diffusion weighted images. In general the amount of motion in the slice selection and read-out directions direction should be kept low. The distortion is in the phase encoding direction in the images. It is recommended that skull stripped (i.e. image containing only brain with skull removed) images shoud be used for image co-registration with the B-Spline transform. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will register a Nrrd diffusion weighted 4D vector image to a fixed anatomical image. Two registration methods are supported for alignment with anatomical images: Rigid and B-Spline. The rigid registration performs a rigid body registration with the anatomical images and should be done as well to initialize the B-Spline transform. The B-SPline transform is the deformable transform, where the user can control the amount of deformation based on the number of control points as well as the maximum distance that these points can move. The B-Spline registration places a low dimensional grid in the image, which is deformed. This allows for some susceptibility related distortions to be removed from the diffusion weighted images. In general the amount of motion in the slice selection and read-out directions direction should be kept low. The distortion is in the phase encoding direction in the images. It is recommended that skull stripped (i.e. image containing only brain with skull removed) images should be used for image co-registration with the B-Spline transform. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractCoRegAnatomyInputSpec output_spec = gtractCoRegAnatomyOutputSpec @@ -1327,21 +1301,20 @@ class gtractResampleDWIInPlaceOutputSpec(TraitedSpec): class gtractResampleDWIInPlace(SEMLikeCommandLine): """title: Resample DWI In Place -category: Diffusion.GTRACT + category: Diffusion.GTRACT -description: Resamples DWI image to structural image. + description: Resamples DWI image to structural image. -version: 4.0.0 + version: 4.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -contributor: This tool was developed by Vincent Magnotta, Greg Harris, Hans Johnson, and Joy Matsui. + contributor: This tool was developed by Vincent Magnotta, Greg Harris, Hans Johnson, and Joy Matsui. -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 - -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractResampleDWIInPlaceInputSpec output_spec = gtractResampleDWIInPlaceOutputSpec @@ -1391,7 +1364,7 @@ class gtractCostFastMarchingInputSpec(CommandLineInputSpec): argstr="--anisotropyWeight %f", ) stoppingValue = traits.Float( - desc="Terminiating value for vcl_cost function estimation", + desc="Terminating value for vcl_cost function estimation", argstr="--stoppingValue %f", ) seedThreshold = traits.Float( @@ -1411,21 +1384,20 @@ class gtractCostFastMarchingOutputSpec(TraitedSpec): class gtractCostFastMarching(SEMLikeCommandLine): """title: Cost Fast Marching -category: Diffusion.GTRACT - -description: This program will use a fast marching fiber tracking algorithm to identify fiber tracts from a tensor image. This program is the first portion of the algorithm. The user must first run gtractFastMarchingTracking to generate the actual fiber tracts. This algorithm is roughly based on the work by G. Parker et al. from IEEE Transactions On Medical Imaging, 21(5): 505-512, 2002. An additional feature of including anisotropy into the vcl_cost function calculation is included. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will use a fast marching fiber tracking algorithm to identify fiber tracts from a tensor image. This program is the first portion of the algorithm. The user must first run gtractFastMarchingTracking to generate the actual fiber tracts. This algorithm is roughly based on the work by G. Parker et al. from IEEE Transactions On Medical Imaging, 21(5): 505-512, 2002. An additional feature of including anisotropy into the vcl_cost function calculation is included. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. The original code here was developed by Daisy Espino. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. The original code here was developed by Daisy Espino. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractCostFastMarchingInputSpec output_spec = gtractCostFastMarchingOutputSpec @@ -1560,21 +1532,20 @@ class gtractFiberTrackingOutputSpec(TraitedSpec): class gtractFiberTracking(SEMLikeCommandLine): """title: Fiber Tracking -category: Diffusion.GTRACT - -description: This program implements four fiber tracking methods (Free, Streamline, GraphSearch, Guided). The output of the fiber tracking is vtkPolyData (i.e. Polylines) that can be loaded into Slicer3 for visualization. The poly data can be saved in either old VTK format files (.vtk) or in the new VTK XML format (.xml). The polylines contain point data that defines ther Tensor at each point along the fiber tract. This can then be used to rendered as glyphs in Slicer3 and can be used to define severeal scalar measures without referencing back to the anisotropy images. (1) Free tracking is a basic streamlines algorithm. This is a direct implementation of the method original proposed by Basser et al. The tracking follows the primarty eigenvector. The tracking begins with seed points in the starting region. Only those voxels above the specified anisotropy threshold in the starting region are used as seed points. Tracking terminates either as a result of maximum fiber length, low ansiotropy, or large curvature. This is a great way to explore your data. (2) The streamlines algorithm is a direct implementation of the method originally proposed by Basser et al. The tracking follows the primary eigenvector. The tracking begins with seed points in the starting region. Only those voxels above the specified anisotropy threshold in the starting region are used as seed points. Tracking terminates either by reaching the ending region or reaching some stopping criteria. Stopping criteria are specified using the following parameters: tracking threshold, curvature threshold, and max length. Only paths terminating in the ending region are kept in this method. The TEND algorithm proposed by Lazar et al. (Human Brain Mapping 18:306-321, 2003) has been instrumented. This can be enabled using the --useTend option while performing Streamlines tracking. This utilizes the entire diffusion tensor to deflect the incoming vector instead of simply following the primary eigenvector. The TEND parameters are set using the --tendF and --tendG options. (3) Graph Search tracking is the first step in the full GTRACT algorithm developed by Cheng et al. (NeuroImage 31(3): 1075-1085, 2006) for finding the tracks in a tensor image. This method was developed to generate fibers in a Tensor representation where crossing fibers occur. The graph search algorithm follows the primary eigenvector in non-ambigous regions and utilizes branching and a graph search algorithm in ambigous regions. Ambiguous tracking regions are defined based on two criteria: Branching Al Threshold (anisotropy values below this value and above the traching threshold) and Curvature Major Eigen (angles of the primary eigenvector direction and the current tracking direction). In regions that meet this criteria, two or three tracking paths are considered. The first is the standard primary eigenvector direction. The second is the seconadary eigenvector direction. This is based on the assumption that these regions may be prolate regions. If the Random Walk option is selected then a third direction is also considered. This direction is defined by a cone pointing from the current position to the centroid of the ending region. The interior angle of the cone is specified by the user with the Branch/Guide Angle parameter. A vector contained inside of the cone is selected at random and used as the third direction. This method can also utilize the TEND option where the primary tracking direction is that specified by the TEND method instead of the primary eigenvector. The parameter '--maximumBranchPoints' allows the tracking to have this number of branches being considered at a time. If this number of branch points is exceeded at any time, then the algorithm will revert back to a streamline alogrithm until the number of branches is reduced. This allows the user to constrain the computational complexity of the algorithm. (4) The second phase of the GTRACT algorithm is Guided Tracking. This method incorporates anatomical information about the track orientation using an initial guess of the fiber track. In the originally proposed GTRACT method, this would be created from the fibers resulting from the Graph Search tracking. However, in practice this can be created using any method and could be defined manually. To create the guide fiber the program gtractCreateGuideFiber can be used. This program will load a fiber tract that has been generated and create a centerline representation of the fiber tract (i.e. a single fiber). In this method, the fiber tracking follows the primary eigenvector direction unless it deviates from the guide fiber track by a angle greater than that specified by the '--guidedCurvatureThreshold' parameter. The user must specify the guide fiber when running this program. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program implements four fiber tracking methods (Free, Streamline, GraphSearch, Guided). The output of the fiber tracking is vtkPolyData (i.e. Polylines) that can be loaded into Slicer3 for visualization. The poly data can be saved in either old VTK format files (.vtk) or in the new VTK XML format (.xml). The polylines contain point data that defines the Tensor at each point along the fiber tract. This can then be used to rendered as glyphs in Slicer3 and can be used to define several scalar measures without referencing back to the anisotropy images. (1) Free tracking is a basic streamlines algorithm. This is a direct implementation of the method original proposed by Basser et al. The tracking follows the primarty eigenvector. The tracking begins with seed points in the starting region. Only those voxels above the specified anisotropy threshold in the starting region are used as seed points. Tracking terminates either as a result of maximum fiber length, low ansiotropy, or large curvature. This is a great way to explore your data. (2) The streamlines algorithm is a direct implementation of the method originally proposed by Basser et al. The tracking follows the primary eigenvector. The tracking begins with seed points in the starting region. Only those voxels above the specified anisotropy threshold in the starting region are used as seed points. Tracking terminates either by reaching the ending region or reaching some stopping criteria. Stopping criteria are specified using the following parameters: tracking threshold, curvature threshold, and max length. Only paths terminating in the ending region are kept in this method. The TEND algorithm proposed by Lazar et al. (Human Brain Mapping 18:306-321, 2003) has been instrumented. This can be enabled using the --useTend option while performing Streamlines tracking. This utilizes the entire diffusion tensor to deflect the incoming vector instead of simply following the primary eigenvector. The TEND parameters are set using the --tendF and --tendG options. (3) Graph Search tracking is the first step in the full GTRACT algorithm developed by Cheng et al. (NeuroImage 31(3): 1075-1085, 2006) for finding the tracks in a tensor image. This method was developed to generate fibers in a Tensor representation where crossing fibers occur. The graph search algorithm follows the primary eigenvector in non-ambiguous regions and utilizes branching and a graph search algorithm in ambiguous regions. Ambiguous tracking regions are defined based on two criteria: Branching Al Threshold (anisotropy values below this value and above the traching threshold) and Curvature Major Eigen (angles of the primary eigenvector direction and the current tracking direction). In regions that meet this criteria, two or three tracking paths are considered. The first is the standard primary eigenvector direction. The second is the seconadary eigenvector direction. This is based on the assumption that these regions may be prolate regions. If the Random Walk option is selected then a third direction is also considered. This direction is defined by a cone pointing from the current position to the centroid of the ending region. The interior angle of the cone is specified by the user with the Branch/Guide Angle parameter. A vector contained inside of the cone is selected at random and used as the third direction. This method can also utilize the TEND option where the primary tracking direction is that specified by the TEND method instead of the primary eigenvector. The parameter '--maximumBranchPoints' allows the tracking to have this number of branches being considered at a time. If this number of branch points is exceeded at any time, then the algorithm will revert back to a streamline algorithm until the number of branches is reduced. This allows the user to constrain the computational complexity of the algorithm. (4) The second phase of the GTRACT algorithm is Guided Tracking. This method incorporates anatomical information about the track orientation using an initial guess of the fiber track. In the originally proposed GTRACT method, this would be created from the fibers resulting from the Graph Search tracking. However, in practice this can be created using any method and could be defined manually. To create the guide fiber the program gtractCreateGuideFiber can be used. This program will load a fiber tract that has been generated and create a centerline representation of the fiber tract (i.e. a single fiber). In this method, the fiber tracking follows the primary eigenvector direction unless it deviates from the guide fiber track by a angle greater than that specified by the '--guidedCurvatureThreshold' parameter. The user must specify the guide fiber when running this program. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta, Greg Harris and Yongqiang Zhao. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta, Greg Harris and Yongqiang Zhao. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractFiberTrackingInputSpec output_spec = gtractFiberTrackingOutputSpec @@ -1623,21 +1594,20 @@ class extractNrrdVectorIndexOutputSpec(TraitedSpec): class extractNrrdVectorIndex(SEMLikeCommandLine): """title: Extract Nrrd Index -category: Diffusion.GTRACT + category: Diffusion.GTRACT -description: This program will extract a 3D image (single vector) from a vector 3D image at a given vector index. + description: This program will extract a 3D image (single vector) from a vector 3D image at a given vector index. -version: 4.0.0 + version: 4.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 - -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = extractNrrdVectorIndexInputSpec output_spec = extractNrrdVectorIndexOutputSpec @@ -1689,21 +1659,20 @@ class gtractResampleFibersOutputSpec(TraitedSpec): class gtractResampleFibers(SEMLikeCommandLine): """title: Resample Fibers -category: Diffusion.GTRACT - -description: This program will resample a fiber tract with respect to a pair of deformation fields that represent the forward and reverse deformation fields. + category: Diffusion.GTRACT -version: 4.0.0 + description: This program will resample a fiber tract with respect to a pair of deformation fields that represent the forward and reverse deformation fields. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractResampleFibersInputSpec output_spec = gtractResampleFibersOutputSpec @@ -1735,7 +1704,7 @@ class gtractTensorInputSpec(CommandLineInputSpec): "NOMASK", "ROIAUTO", "ROI", - desc="ROIAUTO: mask is implicitly defined using a otsu forground and hole filling algorithm. ROI: Uses the masks to define what parts of the image should be used for computing the transform. NOMASK: no mask used", + desc="ROIAUTO: mask is implicitly defined using a otsu foreground and hole filling algorithm. ROI: Uses the masks to define what parts of the image should be used for computing the transform. NOMASK: no mask used", argstr="--maskProcessingMode %s", ) maskVolume = File( @@ -1781,21 +1750,20 @@ class gtractTensorOutputSpec(TraitedSpec): class gtractTensor(SEMLikeCommandLine): """title: Tensor Estimation -category: Diffusion.GTRACT - -description: This step will convert a b-value averaged diffusion tensor image to a 3x3 tensor voxel image. This step takes the diffusion tensor image data and generates a tensor representation of the data based on the signal intensity decay, b values applied, and the diffusion difrections. The apparent diffusion coefficient for a given orientation is computed on a pixel-by-pixel basis by fitting the image data (voxel intensities) to the Stejskal-Tanner equation. If at least 6 diffusion directions are used, then the diffusion tensor can be computed. This program uses itk::DiffusionTensor3DReconstructionImageFilter. The user can adjust background threshold, median filter, and isotropic resampling. + category: Diffusion.GTRACT -version: 4.0.0 + description: This step will convert a b-value averaged diffusion tensor image to a 3x3 tensor voxel image. This step takes the diffusion tensor image data and generates a tensor representation of the data based on the signal intensity decay, b values applied, and the diffusion difrections. The apparent diffusion coefficient for a given orientation is computed on a pixel-by-pixel basis by fitting the image data (voxel intensities) to the Stejskal-Tanner equation. If at least 6 diffusion directions are used, then the diffusion tensor can be computed. This program uses itk::DiffusionTensor3DReconstructionImageFilter. The user can adjust background threshold, median filter, and isotropic resampling. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT + version: 4.0.0 -license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:GTRACT -contributor: This tool was developed by Vincent Magnotta and Greg Harris. + license: http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt -acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + contributor: This tool was developed by Vincent Magnotta and Greg Harris. -""" + acknowledgements: Funding for this version of the GTRACT program was provided by NIH/NINDS R01NS050568-01A2S1 + """ input_spec = gtractTensorInputSpec output_spec = gtractTensorOutputSpec diff --git a/nipype/interfaces/semtools/diffusion/maxcurvature.py b/nipype/interfaces/semtools/diffusion/maxcurvature.py index fdd5057097..86a7580f2d 100644 --- a/nipype/interfaces/semtools/diffusion/maxcurvature.py +++ b/nipype/interfaces/semtools/diffusion/maxcurvature.py @@ -1,21 +1,12 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) @@ -35,25 +26,24 @@ class maxcurvatureOutputSpec(TraitedSpec): class maxcurvature(SEMLikeCommandLine): """title: MaxCurvature-Hessian (DTIProcess) -category: Diffusion - -description: This program computes the Hessian of the FA image (--image). We use this scalar image as a registration input when doing DTI atlas building. For most adult FA we use a sigma of 2 whereas for neonate or primate images and sigma of 1 or 1.5 is more appropriate. For really noisy images, 2.5 - 4 can be considered. The final image (--output) shows the main feature of the input image. + category: Diffusion -version: 1.1.0 + description: This program computes the Hessian of the FA image (--image). We use this scalar image as a registration input when doing DTI atlas building. For most adult FA we use a sigma of 2 whereas for neonate or primate images and sigma of 1 or 1.5 is more appropriate. For really noisy images, 2.5 - 4 can be considered. The final image (--output) shows the main feature of the input image. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess + version: 1.1.0 -license: Copyright (c) Casey Goodlett. All rights reserved. - See http://www.ia.unc.edu/dev/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess -contributor: Casey Goodlett + license: Copyright (c) Casey Goodlett. All rights reserved. + See http://www.ia.unc.edu/dev/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependancies on boost and a fortran compiler. + contributor: Casey Goodlett -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependencies on boost and a fortran compiler. + """ input_spec = maxcurvatureInputSpec output_spec = maxcurvatureOutputSpec diff --git a/nipype/interfaces/semtools/diffusion/tests/__init__.py b/nipype/interfaces/semtools/diffusion/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/diffusion/tests/__init__.py +++ b/nipype/interfaces/semtools/diffusion/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_DWIConvert.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_DWIConvert.py index d1f8c33324..4dfb6943cb 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_DWIConvert.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_DWIConvert.py @@ -4,26 +4,76 @@ def test_DWIConvert_inputs(): input_map = dict( - allowLossyConversion=dict(argstr="--allowLossyConversion ",), - args=dict(argstr="%s",), - conversionMode=dict(argstr="--conversionMode %s",), - environ=dict(nohash=True, usedefault=True,), - fMRI=dict(argstr="--fMRI ",), - fslNIFTIFile=dict(argstr="--fslNIFTIFile %s", extensions=None,), - gradientVectorFile=dict(argstr="--gradientVectorFile %s", hash_files=False,), - inputBValues=dict(argstr="--inputBValues %s", extensions=None,), - inputBVectors=dict(argstr="--inputBVectors %s", extensions=None,), - inputDicomDirectory=dict(argstr="--inputDicomDirectory %s",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputBValues=dict(argstr="--outputBValues %s", hash_files=False,), - outputBVectors=dict(argstr="--outputBVectors %s", hash_files=False,), - outputDirectory=dict(argstr="--outputDirectory %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - smallGradientThreshold=dict(argstr="--smallGradientThreshold %f",), - transposeInputBVectors=dict(argstr="--transposeInputBVectors ",), - useBMatrixGradientDirections=dict(argstr="--useBMatrixGradientDirections ",), - useIdentityMeaseurementFrame=dict(argstr="--useIdentityMeaseurementFrame ",), - writeProtocolGradientsFile=dict(argstr="--writeProtocolGradientsFile ",), + allowLossyConversion=dict( + argstr="--allowLossyConversion ", + ), + args=dict( + argstr="%s", + ), + conversionMode=dict( + argstr="--conversionMode %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fMRI=dict( + argstr="--fMRI ", + ), + fslNIFTIFile=dict( + argstr="--fslNIFTIFile %s", + extensions=None, + ), + gradientVectorFile=dict( + argstr="--gradientVectorFile %s", + hash_files=False, + ), + inputBValues=dict( + argstr="--inputBValues %s", + extensions=None, + ), + inputBVectors=dict( + argstr="--inputBVectors %s", + extensions=None, + ), + inputDicomDirectory=dict( + argstr="--inputDicomDirectory %s", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputBValues=dict( + argstr="--outputBValues %s", + hash_files=False, + ), + outputBVectors=dict( + argstr="--outputBVectors %s", + hash_files=False, + ), + outputDirectory=dict( + argstr="--outputDirectory %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + smallGradientThreshold=dict( + argstr="--smallGradientThreshold %f", + ), + transposeInputBVectors=dict( + argstr="--transposeInputBVectors ", + ), + useBMatrixGradientDirections=dict( + argstr="--useBMatrixGradientDirections ", + ), + useIdentityMeaseurementFrame=dict( + argstr="--useIdentityMeaseurementFrame ", + ), + writeProtocolGradientsFile=dict( + argstr="--writeProtocolGradientsFile ", + ), ) inputs = DWIConvert.input_spec() @@ -34,11 +84,19 @@ def test_DWIConvert_inputs(): def test_DWIConvert_outputs(): output_map = dict( - gradientVectorFile=dict(extensions=None,), - outputBValues=dict(extensions=None,), - outputBVectors=dict(extensions=None,), + gradientVectorFile=dict( + extensions=None, + ), + outputBValues=dict( + extensions=None, + ), + outputBVectors=dict( + extensions=None, + ), outputDirectory=dict(), - outputVolume=dict(extensions=None,), + outputVolume=dict( + extensions=None, + ), ) outputs = DWIConvert.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_compareTractInclusion.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_compareTractInclusion.py index ed184ae4f2..38e8f92b0b 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_compareTractInclusion.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_compareTractInclusion.py @@ -4,16 +4,39 @@ def test_compareTractInclusion_inputs(): input_map = dict( - args=dict(argstr="%s",), - closeness=dict(argstr="--closeness %f",), - environ=dict(nohash=True, usedefault=True,), - numberOfPoints=dict(argstr="--numberOfPoints %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - standardFiber=dict(argstr="--standardFiber %s", extensions=None,), - testFiber=dict(argstr="--testFiber %s", extensions=None,), - testForBijection=dict(argstr="--testForBijection ",), - testForFiberCardinality=dict(argstr="--testForFiberCardinality ",), - writeXMLPolyDataFile=dict(argstr="--writeXMLPolyDataFile ",), + args=dict( + argstr="%s", + ), + closeness=dict( + argstr="--closeness %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + numberOfPoints=dict( + argstr="--numberOfPoints %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + standardFiber=dict( + argstr="--standardFiber %s", + extensions=None, + ), + testFiber=dict( + argstr="--testFiber %s", + extensions=None, + ), + testForBijection=dict( + argstr="--testForBijection ", + ), + testForFiberCardinality=dict( + argstr="--testForFiberCardinality ", + ), + writeXMLPolyDataFile=dict( + argstr="--writeXMLPolyDataFile ", + ), ) inputs = compareTractInclusion.input_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiaverage.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiaverage.py index fe4e00032b..17d4d19b4c 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiaverage.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiaverage.py @@ -4,12 +4,26 @@ def test_dtiaverage_inputs(): input_map = dict( - DTI_double=dict(argstr="--DTI_double ",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputs=dict(argstr="--inputs %s...",), - tensor_output=dict(argstr="--tensor_output %s", hash_files=False,), - verbose=dict(argstr="--verbose ",), + DTI_double=dict( + argstr="--DTI_double ", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputs=dict( + argstr="--inputs %s...", + ), + tensor_output=dict( + argstr="--tensor_output %s", + hash_files=False, + ), + verbose=dict( + argstr="--verbose ", + ), ) inputs = dtiaverage.input_spec() @@ -19,7 +33,11 @@ def test_dtiaverage_inputs(): def test_dtiaverage_outputs(): - output_map = dict(tensor_output=dict(extensions=None,),) + output_map = dict( + tensor_output=dict( + extensions=None, + ), + ) outputs = dtiaverage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiestim.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiestim.py index c7586fc34d..0a36716e87 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiestim.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiestim.py @@ -4,26 +4,75 @@ def test_dtiestim_inputs(): input_map = dict( - B0=dict(argstr="--B0 %s", hash_files=False,), - B0_mask_output=dict(argstr="--B0_mask_output %s", hash_files=False,), - DTI_double=dict(argstr="--DTI_double ",), - args=dict(argstr="%s",), - bad_region_mask=dict(argstr="--bad_region_mask %s", extensions=None,), - brain_mask=dict(argstr="--brain_mask %s", extensions=None,), - correction=dict(argstr="--correction %s",), - defaultTensor=dict(argstr="--defaultTensor %s", sep=",",), - dwi_image=dict(argstr="--dwi_image %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - idwi=dict(argstr="--idwi %s", hash_files=False,), - method=dict(argstr="--method %s",), - shiftNeg=dict(argstr="--shiftNeg ",), - shiftNegCoeff=dict(argstr="--shiftNegCoeff %f",), - sigma=dict(argstr="--sigma %f",), - step=dict(argstr="--step %f",), - tensor_output=dict(argstr="--tensor_output %s", hash_files=False,), - threshold=dict(argstr="--threshold %d",), - verbose=dict(argstr="--verbose ",), - weight_iterations=dict(argstr="--weight_iterations %d",), + B0=dict( + argstr="--B0 %s", + hash_files=False, + ), + B0_mask_output=dict( + argstr="--B0_mask_output %s", + hash_files=False, + ), + DTI_double=dict( + argstr="--DTI_double ", + ), + args=dict( + argstr="%s", + ), + bad_region_mask=dict( + argstr="--bad_region_mask %s", + extensions=None, + ), + brain_mask=dict( + argstr="--brain_mask %s", + extensions=None, + ), + correction=dict( + argstr="--correction %s", + ), + defaultTensor=dict( + argstr="--defaultTensor %s", + sep=",", + ), + dwi_image=dict( + argstr="--dwi_image %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + idwi=dict( + argstr="--idwi %s", + hash_files=False, + ), + method=dict( + argstr="--method %s", + ), + shiftNeg=dict( + argstr="--shiftNeg ", + ), + shiftNegCoeff=dict( + argstr="--shiftNegCoeff %f", + ), + sigma=dict( + argstr="--sigma %f", + ), + step=dict( + argstr="--step %f", + ), + tensor_output=dict( + argstr="--tensor_output %s", + hash_files=False, + ), + threshold=dict( + argstr="--threshold %d", + ), + verbose=dict( + argstr="--verbose ", + ), + weight_iterations=dict( + argstr="--weight_iterations %d", + ), ) inputs = dtiestim.input_spec() @@ -34,10 +83,18 @@ def test_dtiestim_inputs(): def test_dtiestim_outputs(): output_map = dict( - B0=dict(extensions=None,), - B0_mask_output=dict(extensions=None,), - idwi=dict(extensions=None,), - tensor_output=dict(extensions=None,), + B0=dict( + extensions=None, + ), + B0_mask_output=dict( + extensions=None, + ), + idwi=dict( + extensions=None, + ), + tensor_output=dict( + extensions=None, + ), ) outputs = dtiestim.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiprocess.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiprocess.py index 01a53b18cc..24352abbe3 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiprocess.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_dtiprocess.py @@ -4,43 +4,121 @@ def test_dtiprocess_inputs(): input_map = dict( - DTI_double=dict(argstr="--DTI_double ",), - RD_output=dict(argstr="--RD_output %s", hash_files=False,), - affineitk_file=dict(argstr="--affineitk_file %s", extensions=None,), - args=dict(argstr="%s",), - color_fa_output=dict(argstr="--color_fa_output %s", hash_files=False,), - correction=dict(argstr="--correction %s",), - deformation_output=dict(argstr="--deformation_output %s", hash_files=False,), - dof_file=dict(argstr="--dof_file %s", extensions=None,), - dti_image=dict(argstr="--dti_image %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - fa_gradient_output=dict(argstr="--fa_gradient_output %s", hash_files=False,), - fa_gradmag_output=dict(argstr="--fa_gradmag_output %s", hash_files=False,), - fa_output=dict(argstr="--fa_output %s", hash_files=False,), - forward=dict(argstr="--forward %s", extensions=None,), + DTI_double=dict( + argstr="--DTI_double ", + ), + RD_output=dict( + argstr="--RD_output %s", + hash_files=False, + ), + affineitk_file=dict( + argstr="--affineitk_file %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + color_fa_output=dict( + argstr="--color_fa_output %s", + hash_files=False, + ), + correction=dict( + argstr="--correction %s", + ), + deformation_output=dict( + argstr="--deformation_output %s", + hash_files=False, + ), + dof_file=dict( + argstr="--dof_file %s", + extensions=None, + ), + dti_image=dict( + argstr="--dti_image %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fa_gradient_output=dict( + argstr="--fa_gradient_output %s", + hash_files=False, + ), + fa_gradmag_output=dict( + argstr="--fa_gradmag_output %s", + hash_files=False, + ), + fa_output=dict( + argstr="--fa_output %s", + hash_files=False, + ), + forward=dict( + argstr="--forward %s", + extensions=None, + ), frobenius_norm_output=dict( - argstr="--frobenius_norm_output %s", hash_files=False, - ), - hField=dict(argstr="--hField ",), - interpolation=dict(argstr="--interpolation %s",), - lambda1_output=dict(argstr="--lambda1_output %s", hash_files=False,), - lambda2_output=dict(argstr="--lambda2_output %s", hash_files=False,), - lambda3_output=dict(argstr="--lambda3_output %s", hash_files=False,), - mask=dict(argstr="--mask %s", extensions=None,), - md_output=dict(argstr="--md_output %s", hash_files=False,), + argstr="--frobenius_norm_output %s", + hash_files=False, + ), + hField=dict( + argstr="--hField ", + ), + interpolation=dict( + argstr="--interpolation %s", + ), + lambda1_output=dict( + argstr="--lambda1_output %s", + hash_files=False, + ), + lambda2_output=dict( + argstr="--lambda2_output %s", + hash_files=False, + ), + lambda3_output=dict( + argstr="--lambda3_output %s", + hash_files=False, + ), + mask=dict( + argstr="--mask %s", + extensions=None, + ), + md_output=dict( + argstr="--md_output %s", + hash_files=False, + ), negative_eigenvector_output=dict( - argstr="--negative_eigenvector_output %s", hash_files=False, + argstr="--negative_eigenvector_output %s", + hash_files=False, + ), + newdof_file=dict( + argstr="--newdof_file %s", + extensions=None, + ), + outmask=dict( + argstr="--outmask %s", + hash_files=False, ), - newdof_file=dict(argstr="--newdof_file %s", extensions=None,), - outmask=dict(argstr="--outmask %s", hash_files=False,), principal_eigenvector_output=dict( - argstr="--principal_eigenvector_output %s", hash_files=False, + argstr="--principal_eigenvector_output %s", + hash_files=False, + ), + reorientation=dict( + argstr="--reorientation %s", + ), + rot_output=dict( + argstr="--rot_output %s", + hash_files=False, + ), + scalar_float=dict( + argstr="--scalar_float ", + ), + sigma=dict( + argstr="--sigma %f", + ), + verbose=dict( + argstr="--verbose ", ), - reorientation=dict(argstr="--reorientation %s",), - rot_output=dict(argstr="--rot_output %s", hash_files=False,), - scalar_float=dict(argstr="--scalar_float ",), - sigma=dict(argstr="--sigma %f",), - verbose=dict(argstr="--verbose ",), ) inputs = dtiprocess.input_spec() @@ -51,21 +129,51 @@ def test_dtiprocess_inputs(): def test_dtiprocess_outputs(): output_map = dict( - RD_output=dict(extensions=None,), - color_fa_output=dict(extensions=None,), - deformation_output=dict(extensions=None,), - fa_gradient_output=dict(extensions=None,), - fa_gradmag_output=dict(extensions=None,), - fa_output=dict(extensions=None,), - frobenius_norm_output=dict(extensions=None,), - lambda1_output=dict(extensions=None,), - lambda2_output=dict(extensions=None,), - lambda3_output=dict(extensions=None,), - md_output=dict(extensions=None,), - negative_eigenvector_output=dict(extensions=None,), - outmask=dict(extensions=None,), - principal_eigenvector_output=dict(extensions=None,), - rot_output=dict(extensions=None,), + RD_output=dict( + extensions=None, + ), + color_fa_output=dict( + extensions=None, + ), + deformation_output=dict( + extensions=None, + ), + fa_gradient_output=dict( + extensions=None, + ), + fa_gradmag_output=dict( + extensions=None, + ), + fa_output=dict( + extensions=None, + ), + frobenius_norm_output=dict( + extensions=None, + ), + lambda1_output=dict( + extensions=None, + ), + lambda2_output=dict( + extensions=None, + ), + lambda3_output=dict( + extensions=None, + ), + md_output=dict( + extensions=None, + ), + negative_eigenvector_output=dict( + extensions=None, + ), + outmask=dict( + extensions=None, + ), + principal_eigenvector_output=dict( + extensions=None, + ), + rot_output=dict( + extensions=None, + ), ) outputs = dtiprocess.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_extractNrrdVectorIndex.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_extractNrrdVectorIndex.py index 51ec99b1b8..aaa516e9dc 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_extractNrrdVectorIndex.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_extractNrrdVectorIndex.py @@ -4,13 +4,30 @@ def test_extractNrrdVectorIndex_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - setImageOrientation=dict(argstr="--setImageOrientation %s",), - vectorIndex=dict(argstr="--vectorIndex %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + setImageOrientation=dict( + argstr="--setImageOrientation %s", + ), + vectorIndex=dict( + argstr="--vectorIndex %d", + ), ) inputs = extractNrrdVectorIndex.input_spec() @@ -20,7 +37,11 @@ def test_extractNrrdVectorIndex_inputs(): def test_extractNrrdVectorIndex_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = extractNrrdVectorIndex.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAnisotropyMap.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAnisotropyMap.py index 3af3c53648..da3e02c37b 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAnisotropyMap.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAnisotropyMap.py @@ -4,12 +4,27 @@ def test_gtractAnisotropyMap_inputs(): input_map = dict( - anisotropyType=dict(argstr="--anisotropyType %s",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputTensorVolume=dict(argstr="--inputTensorVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + anisotropyType=dict( + argstr="--anisotropyType %s", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputTensorVolume=dict( + argstr="--inputTensorVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = gtractAnisotropyMap.input_spec() @@ -19,7 +34,11 @@ def test_gtractAnisotropyMap_inputs(): def test_gtractAnisotropyMap_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractAnisotropyMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAverageBvalues.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAverageBvalues.py index 1155f11628..a37b0e65ce 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAverageBvalues.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractAverageBvalues.py @@ -4,13 +4,30 @@ def test_gtractAverageBvalues_inputs(): input_map = dict( - args=dict(argstr="%s",), - averageB0only=dict(argstr="--averageB0only ",), - directionsTolerance=dict(argstr="--directionsTolerance %f",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + averageB0only=dict( + argstr="--averageB0only ", + ), + directionsTolerance=dict( + argstr="--directionsTolerance %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = gtractAverageBvalues.input_spec() @@ -20,7 +37,11 @@ def test_gtractAverageBvalues_inputs(): def test_gtractAverageBvalues_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractAverageBvalues.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractClipAnisotropy.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractClipAnisotropy.py index 00fc963f69..3d6e24aee3 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractClipAnisotropy.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractClipAnisotropy.py @@ -4,13 +4,30 @@ def test_gtractClipAnisotropy_inputs(): input_map = dict( - args=dict(argstr="%s",), - clipFirstSlice=dict(argstr="--clipFirstSlice ",), - clipLastSlice=dict(argstr="--clipLastSlice ",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + clipFirstSlice=dict( + argstr="--clipFirstSlice ", + ), + clipLastSlice=dict( + argstr="--clipLastSlice ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = gtractClipAnisotropy.input_spec() @@ -20,7 +37,11 @@ def test_gtractClipAnisotropy_inputs(): def test_gtractClipAnisotropy_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractClipAnisotropy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoRegAnatomy.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoRegAnatomy.py index a5d2337c44..1ab780c1b9 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoRegAnatomy.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoRegAnatomy.py @@ -4,34 +4,90 @@ def test_gtractCoRegAnatomy_inputs(): input_map = dict( - args=dict(argstr="%s",), - borderSize=dict(argstr="--borderSize %d",), - convergence=dict(argstr="--convergence %f",), - environ=dict(nohash=True, usedefault=True,), - gradientTolerance=dict(argstr="--gradientTolerance %f",), - gridSize=dict(argstr="--gridSize %s", sep=",",), + args=dict( + argstr="%s", + ), + borderSize=dict( + argstr="--borderSize %d", + ), + convergence=dict( + argstr="--convergence %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gradientTolerance=dict( + argstr="--gradientTolerance %f", + ), + gridSize=dict( + argstr="--gridSize %s", + sep=",", + ), inputAnatomicalVolume=dict( - argstr="--inputAnatomicalVolume %s", extensions=None, - ), - inputRigidTransform=dict(argstr="--inputRigidTransform %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - maxBSplineDisplacement=dict(argstr="--maxBSplineDisplacement %f",), - maximumStepSize=dict(argstr="--maximumStepSize %f",), - minimumStepSize=dict(argstr="--minimumStepSize %f",), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - numberOfIterations=dict(argstr="--numberOfIterations %d",), - numberOfSamples=dict(argstr="--numberOfSamples %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputTransformName=dict(argstr="--outputTransformName %s", hash_files=False,), - relaxationFactor=dict(argstr="--relaxationFactor %f",), - samplingPercentage=dict(argstr="--samplingPercentage %f",), - spatialScale=dict(argstr="--spatialScale %d",), - transformType=dict(argstr="--transformType %s",), - translationScale=dict(argstr="--translationScale %f",), - useCenterOfHeadAlign=dict(argstr="--useCenterOfHeadAlign ",), - useGeometryAlign=dict(argstr="--useGeometryAlign ",), - useMomentsAlign=dict(argstr="--useMomentsAlign ",), - vectorIndex=dict(argstr="--vectorIndex %d",), + argstr="--inputAnatomicalVolume %s", + extensions=None, + ), + inputRigidTransform=dict( + argstr="--inputRigidTransform %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + maxBSplineDisplacement=dict( + argstr="--maxBSplineDisplacement %f", + ), + maximumStepSize=dict( + argstr="--maximumStepSize %f", + ), + minimumStepSize=dict( + argstr="--minimumStepSize %f", + ), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + numberOfIterations=dict( + argstr="--numberOfIterations %d", + ), + numberOfSamples=dict( + argstr="--numberOfSamples %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputTransformName=dict( + argstr="--outputTransformName %s", + hash_files=False, + ), + relaxationFactor=dict( + argstr="--relaxationFactor %f", + ), + samplingPercentage=dict( + argstr="--samplingPercentage %f", + ), + spatialScale=dict( + argstr="--spatialScale %d", + ), + transformType=dict( + argstr="--transformType %s", + ), + translationScale=dict( + argstr="--translationScale %f", + ), + useCenterOfHeadAlign=dict( + argstr="--useCenterOfHeadAlign ", + ), + useGeometryAlign=dict( + argstr="--useGeometryAlign ", + ), + useMomentsAlign=dict( + argstr="--useMomentsAlign ", + ), + vectorIndex=dict( + argstr="--vectorIndex %d", + ), ) inputs = gtractCoRegAnatomy.input_spec() @@ -41,7 +97,11 @@ def test_gtractCoRegAnatomy_inputs(): def test_gtractCoRegAnatomy_outputs(): - output_map = dict(outputTransformName=dict(extensions=None,),) + output_map = dict( + outputTransformName=dict( + extensions=None, + ), + ) outputs = gtractCoRegAnatomy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractConcatDwi.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractConcatDwi.py index 8fd46f9ab6..d2a6ca3288 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractConcatDwi.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractConcatDwi.py @@ -4,12 +4,26 @@ def test_gtractConcatDwi_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - ignoreOrigins=dict(argstr="--ignoreOrigins ",), - inputVolume=dict(argstr="--inputVolume %s...",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + ignoreOrigins=dict( + argstr="--ignoreOrigins ", + ), + inputVolume=dict( + argstr="--inputVolume %s...", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = gtractConcatDwi.input_spec() @@ -19,7 +33,11 @@ def test_gtractConcatDwi_inputs(): def test_gtractConcatDwi_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractConcatDwi.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCopyImageOrientation.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCopyImageOrientation.py index 4ce50c9faa..ba03837015 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCopyImageOrientation.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCopyImageOrientation.py @@ -4,12 +4,28 @@ def test_gtractCopyImageOrientation_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputReferenceVolume=dict(argstr="--inputReferenceVolume %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputReferenceVolume=dict( + argstr="--inputReferenceVolume %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = gtractCopyImageOrientation.input_spec() @@ -19,7 +35,11 @@ def test_gtractCopyImageOrientation_inputs(): def test_gtractCopyImageOrientation_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractCopyImageOrientation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoregBvalues.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoregBvalues.py index 639dc8cd69..0122bf7636 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoregBvalues.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCoregBvalues.py @@ -4,24 +4,65 @@ def test_gtractCoregBvalues_inputs(): input_map = dict( - args=dict(argstr="%s",), - debugLevel=dict(argstr="--debugLevel %d",), - eddyCurrentCorrection=dict(argstr="--eddyCurrentCorrection ",), - environ=dict(nohash=True, usedefault=True,), - fixedVolume=dict(argstr="--fixedVolume %s", extensions=None,), - fixedVolumeIndex=dict(argstr="--fixedVolumeIndex %d",), - maximumStepSize=dict(argstr="--maximumStepSize %f",), - minimumStepSize=dict(argstr="--minimumStepSize %f",), - movingVolume=dict(argstr="--movingVolume %s", extensions=None,), - numberOfIterations=dict(argstr="--numberOfIterations %d",), - numberOfSpatialSamples=dict(argstr="--numberOfSpatialSamples %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputTransform=dict(argstr="--outputTransform %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - registerB0Only=dict(argstr="--registerB0Only ",), - relaxationFactor=dict(argstr="--relaxationFactor %f",), - samplingPercentage=dict(argstr="--samplingPercentage %f",), - spatialScale=dict(argstr="--spatialScale %f",), + args=dict( + argstr="%s", + ), + debugLevel=dict( + argstr="--debugLevel %d", + ), + eddyCurrentCorrection=dict( + argstr="--eddyCurrentCorrection ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedVolume=dict( + argstr="--fixedVolume %s", + extensions=None, + ), + fixedVolumeIndex=dict( + argstr="--fixedVolumeIndex %d", + ), + maximumStepSize=dict( + argstr="--maximumStepSize %f", + ), + minimumStepSize=dict( + argstr="--minimumStepSize %f", + ), + movingVolume=dict( + argstr="--movingVolume %s", + extensions=None, + ), + numberOfIterations=dict( + argstr="--numberOfIterations %d", + ), + numberOfSpatialSamples=dict( + argstr="--numberOfSpatialSamples %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputTransform=dict( + argstr="--outputTransform %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + registerB0Only=dict( + argstr="--registerB0Only ", + ), + relaxationFactor=dict( + argstr="--relaxationFactor %f", + ), + samplingPercentage=dict( + argstr="--samplingPercentage %f", + ), + spatialScale=dict( + argstr="--spatialScale %f", + ), ) inputs = gtractCoregBvalues.input_spec() @@ -32,7 +73,12 @@ def test_gtractCoregBvalues_inputs(): def test_gtractCoregBvalues_outputs(): output_map = dict( - outputTransform=dict(extensions=None,), outputVolume=dict(extensions=None,), + outputTransform=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), ) outputs = gtractCoregBvalues.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCostFastMarching.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCostFastMarching.py index cd5d34952d..7d086cd7c0 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCostFastMarching.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCostFastMarching.py @@ -4,22 +4,48 @@ def test_gtractCostFastMarching_inputs(): input_map = dict( - anisotropyWeight=dict(argstr="--anisotropyWeight %f",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + anisotropyWeight=dict( + argstr="--anisotropyWeight %f", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputAnisotropyVolume=dict( - argstr="--inputAnisotropyVolume %s", extensions=None, + argstr="--inputAnisotropyVolume %s", + extensions=None, ), inputStartingSeedsLabelMapVolume=dict( - argstr="--inputStartingSeedsLabelMapVolume %s", extensions=None, - ), - inputTensorVolume=dict(argstr="--inputTensorVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputCostVolume=dict(argstr="--outputCostVolume %s", hash_files=False,), - outputSpeedVolume=dict(argstr="--outputSpeedVolume %s", hash_files=False,), - seedThreshold=dict(argstr="--seedThreshold %f",), - startingSeedsLabel=dict(argstr="--startingSeedsLabel %d",), - stoppingValue=dict(argstr="--stoppingValue %f",), + argstr="--inputStartingSeedsLabelMapVolume %s", + extensions=None, + ), + inputTensorVolume=dict( + argstr="--inputTensorVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputCostVolume=dict( + argstr="--outputCostVolume %s", + hash_files=False, + ), + outputSpeedVolume=dict( + argstr="--outputSpeedVolume %s", + hash_files=False, + ), + seedThreshold=dict( + argstr="--seedThreshold %f", + ), + startingSeedsLabel=dict( + argstr="--startingSeedsLabel %d", + ), + stoppingValue=dict( + argstr="--stoppingValue %f", + ), ) inputs = gtractCostFastMarching.input_spec() @@ -30,8 +56,12 @@ def test_gtractCostFastMarching_inputs(): def test_gtractCostFastMarching_outputs(): output_map = dict( - outputCostVolume=dict(extensions=None,), - outputSpeedVolume=dict(extensions=None,), + outputCostVolume=dict( + extensions=None, + ), + outputSpeedVolume=dict( + extensions=None, + ), ) outputs = gtractCostFastMarching.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCreateGuideFiber.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCreateGuideFiber.py index 6b2b0a31e5..1990cc2057 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCreateGuideFiber.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractCreateGuideFiber.py @@ -4,13 +4,30 @@ def test_gtractCreateGuideFiber_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputFiber=dict(argstr="--inputFiber %s", extensions=None,), - numberOfPoints=dict(argstr="--numberOfPoints %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputFiber=dict(argstr="--outputFiber %s", hash_files=False,), - writeXMLPolyDataFile=dict(argstr="--writeXMLPolyDataFile ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputFiber=dict( + argstr="--inputFiber %s", + extensions=None, + ), + numberOfPoints=dict( + argstr="--numberOfPoints %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputFiber=dict( + argstr="--outputFiber %s", + hash_files=False, + ), + writeXMLPolyDataFile=dict( + argstr="--writeXMLPolyDataFile ", + ), ) inputs = gtractCreateGuideFiber.input_spec() @@ -20,7 +37,11 @@ def test_gtractCreateGuideFiber_inputs(): def test_gtractCreateGuideFiber_outputs(): - output_map = dict(outputFiber=dict(extensions=None,),) + output_map = dict( + outputFiber=dict( + extensions=None, + ), + ) outputs = gtractCreateGuideFiber.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFastMarchingTracking.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFastMarchingTracking.py index 15ee3053f0..4059d45f6a 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFastMarchingTracking.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFastMarchingTracking.py @@ -4,26 +4,60 @@ def test_gtractFastMarchingTracking_inputs(): input_map = dict( - args=dict(argstr="%s",), - costStepSize=dict(argstr="--costStepSize %f",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + costStepSize=dict( + argstr="--costStepSize %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputAnisotropyVolume=dict( - argstr="--inputAnisotropyVolume %s", extensions=None, + argstr="--inputAnisotropyVolume %s", + extensions=None, + ), + inputCostVolume=dict( + argstr="--inputCostVolume %s", + extensions=None, ), - inputCostVolume=dict(argstr="--inputCostVolume %s", extensions=None,), inputStartingSeedsLabelMapVolume=dict( - argstr="--inputStartingSeedsLabelMapVolume %s", extensions=None, - ), - inputTensorVolume=dict(argstr="--inputTensorVolume %s", extensions=None,), - maximumStepSize=dict(argstr="--maximumStepSize %f",), - minimumStepSize=dict(argstr="--minimumStepSize %f",), - numberOfIterations=dict(argstr="--numberOfIterations %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputTract=dict(argstr="--outputTract %s", hash_files=False,), - seedThreshold=dict(argstr="--seedThreshold %f",), - startingSeedsLabel=dict(argstr="--startingSeedsLabel %d",), - trackingThreshold=dict(argstr="--trackingThreshold %f",), - writeXMLPolyDataFile=dict(argstr="--writeXMLPolyDataFile ",), + argstr="--inputStartingSeedsLabelMapVolume %s", + extensions=None, + ), + inputTensorVolume=dict( + argstr="--inputTensorVolume %s", + extensions=None, + ), + maximumStepSize=dict( + argstr="--maximumStepSize %f", + ), + minimumStepSize=dict( + argstr="--minimumStepSize %f", + ), + numberOfIterations=dict( + argstr="--numberOfIterations %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputTract=dict( + argstr="--outputTract %s", + hash_files=False, + ), + seedThreshold=dict( + argstr="--seedThreshold %f", + ), + startingSeedsLabel=dict( + argstr="--startingSeedsLabel %d", + ), + trackingThreshold=dict( + argstr="--trackingThreshold %f", + ), + writeXMLPolyDataFile=dict( + argstr="--writeXMLPolyDataFile ", + ), ) inputs = gtractFastMarchingTracking.input_spec() @@ -33,7 +67,11 @@ def test_gtractFastMarchingTracking_inputs(): def test_gtractFastMarchingTracking_outputs(): - output_map = dict(outputTract=dict(extensions=None,),) + output_map = dict( + outputTract=dict( + extensions=None, + ), + ) outputs = gtractFastMarchingTracking.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFiberTracking.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFiberTracking.py index 510c00013a..9837774d3e 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFiberTracking.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractFiberTracking.py @@ -4,42 +4,103 @@ def test_gtractFiberTracking_inputs(): input_map = dict( - args=dict(argstr="%s",), - branchingAngle=dict(argstr="--branchingAngle %f",), - branchingThreshold=dict(argstr="--branchingThreshold %f",), - curvatureThreshold=dict(argstr="--curvatureThreshold %f",), - endingSeedsLabel=dict(argstr="--endingSeedsLabel %d",), - environ=dict(nohash=True, usedefault=True,), - guidedCurvatureThreshold=dict(argstr="--guidedCurvatureThreshold %f",), + args=dict( + argstr="%s", + ), + branchingAngle=dict( + argstr="--branchingAngle %f", + ), + branchingThreshold=dict( + argstr="--branchingThreshold %f", + ), + curvatureThreshold=dict( + argstr="--curvatureThreshold %f", + ), + endingSeedsLabel=dict( + argstr="--endingSeedsLabel %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + guidedCurvatureThreshold=dict( + argstr="--guidedCurvatureThreshold %f", + ), inputAnisotropyVolume=dict( - argstr="--inputAnisotropyVolume %s", extensions=None, + argstr="--inputAnisotropyVolume %s", + extensions=None, ), inputEndingSeedsLabelMapVolume=dict( - argstr="--inputEndingSeedsLabelMapVolume %s", extensions=None, + argstr="--inputEndingSeedsLabelMapVolume %s", + extensions=None, ), inputStartingSeedsLabelMapVolume=dict( - argstr="--inputStartingSeedsLabelMapVolume %s", extensions=None, - ), - inputTensorVolume=dict(argstr="--inputTensorVolume %s", extensions=None,), - inputTract=dict(argstr="--inputTract %s", extensions=None,), - maximumBranchPoints=dict(argstr="--maximumBranchPoints %d",), - maximumGuideDistance=dict(argstr="--maximumGuideDistance %f",), - maximumLength=dict(argstr="--maximumLength %f",), - minimumLength=dict(argstr="--minimumLength %f",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputTract=dict(argstr="--outputTract %s", hash_files=False,), - randomSeed=dict(argstr="--randomSeed %d",), - seedThreshold=dict(argstr="--seedThreshold %f",), - startingSeedsLabel=dict(argstr="--startingSeedsLabel %d",), - stepSize=dict(argstr="--stepSize %f",), - tendF=dict(argstr="--tendF %f",), - tendG=dict(argstr="--tendG %f",), - trackingMethod=dict(argstr="--trackingMethod %s",), - trackingThreshold=dict(argstr="--trackingThreshold %f",), - useLoopDetection=dict(argstr="--useLoopDetection ",), - useRandomWalk=dict(argstr="--useRandomWalk ",), - useTend=dict(argstr="--useTend ",), - writeXMLPolyDataFile=dict(argstr="--writeXMLPolyDataFile ",), + argstr="--inputStartingSeedsLabelMapVolume %s", + extensions=None, + ), + inputTensorVolume=dict( + argstr="--inputTensorVolume %s", + extensions=None, + ), + inputTract=dict( + argstr="--inputTract %s", + extensions=None, + ), + maximumBranchPoints=dict( + argstr="--maximumBranchPoints %d", + ), + maximumGuideDistance=dict( + argstr="--maximumGuideDistance %f", + ), + maximumLength=dict( + argstr="--maximumLength %f", + ), + minimumLength=dict( + argstr="--minimumLength %f", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputTract=dict( + argstr="--outputTract %s", + hash_files=False, + ), + randomSeed=dict( + argstr="--randomSeed %d", + ), + seedThreshold=dict( + argstr="--seedThreshold %f", + ), + startingSeedsLabel=dict( + argstr="--startingSeedsLabel %d", + ), + stepSize=dict( + argstr="--stepSize %f", + ), + tendF=dict( + argstr="--tendF %f", + ), + tendG=dict( + argstr="--tendG %f", + ), + trackingMethod=dict( + argstr="--trackingMethod %s", + ), + trackingThreshold=dict( + argstr="--trackingThreshold %f", + ), + useLoopDetection=dict( + argstr="--useLoopDetection ", + ), + useRandomWalk=dict( + argstr="--useRandomWalk ", + ), + useTend=dict( + argstr="--useTend ", + ), + writeXMLPolyDataFile=dict( + argstr="--writeXMLPolyDataFile ", + ), ) inputs = gtractFiberTracking.input_spec() @@ -49,7 +110,11 @@ def test_gtractFiberTracking_inputs(): def test_gtractFiberTracking_outputs(): - output_map = dict(outputTract=dict(extensions=None,),) + output_map = dict( + outputTract=dict( + extensions=None, + ), + ) outputs = gtractFiberTracking.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractImageConformity.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractImageConformity.py index b382e97133..64b896e0ca 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractImageConformity.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractImageConformity.py @@ -4,12 +4,28 @@ def test_gtractImageConformity_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputReferenceVolume=dict(argstr="--inputReferenceVolume %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputReferenceVolume=dict( + argstr="--inputReferenceVolume %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = gtractImageConformity.input_spec() @@ -19,7 +35,11 @@ def test_gtractImageConformity_inputs(): def test_gtractImageConformity_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractImageConformity.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py index 9affd39654..ed43c90dc6 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertBSplineTransform.py @@ -4,13 +4,32 @@ def test_gtractInvertBSplineTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputReferenceVolume=dict(argstr="--inputReferenceVolume %s", extensions=None,), - inputTransform=dict(argstr="--inputTransform %s", extensions=None,), - landmarkDensity=dict(argstr="--landmarkDensity %s", sep=",",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputTransform=dict(argstr="--outputTransform %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputReferenceVolume=dict( + argstr="--inputReferenceVolume %s", + extensions=None, + ), + inputTransform=dict( + argstr="--inputTransform %s", + extensions=None, + ), + landmarkDensity=dict( + argstr="--landmarkDensity %s", + sep=",", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputTransform=dict( + argstr="--outputTransform %s", + hash_files=False, + ), ) inputs = gtractInvertBSplineTransform.input_spec() @@ -20,7 +39,11 @@ def test_gtractInvertBSplineTransform_inputs(): def test_gtractInvertBSplineTransform_outputs(): - output_map = dict(outputTransform=dict(extensions=None,),) + output_map = dict( + outputTransform=dict( + extensions=None, + ), + ) outputs = gtractInvertBSplineTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertDisplacementField.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertDisplacementField.py index 2ec1e53e42..83129902aa 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertDisplacementField.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertDisplacementField.py @@ -4,13 +4,31 @@ def test_gtractInvertDisplacementField_inputs(): input_map = dict( - args=dict(argstr="%s",), - baseImage=dict(argstr="--baseImage %s", extensions=None,), - deformationImage=dict(argstr="--deformationImage %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - subsamplingFactor=dict(argstr="--subsamplingFactor %d",), + args=dict( + argstr="%s", + ), + baseImage=dict( + argstr="--baseImage %s", + extensions=None, + ), + deformationImage=dict( + argstr="--deformationImage %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + subsamplingFactor=dict( + argstr="--subsamplingFactor %d", + ), ) inputs = gtractInvertDisplacementField.input_spec() @@ -20,7 +38,11 @@ def test_gtractInvertDisplacementField_inputs(): def test_gtractInvertDisplacementField_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractInvertDisplacementField.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertRigidTransform.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertRigidTransform.py index bbf3b5b260..73ba9c576f 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertRigidTransform.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractInvertRigidTransform.py @@ -4,11 +4,24 @@ def test_gtractInvertRigidTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputTransform=dict(argstr="--inputTransform %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputTransform=dict(argstr="--outputTransform %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputTransform=dict( + argstr="--inputTransform %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputTransform=dict( + argstr="--outputTransform %s", + hash_files=False, + ), ) inputs = gtractInvertRigidTransform.input_spec() @@ -18,7 +31,11 @@ def test_gtractInvertRigidTransform_inputs(): def test_gtractInvertRigidTransform_outputs(): - output_map = dict(outputTransform=dict(extensions=None,),) + output_map = dict( + outputTransform=dict( + extensions=None, + ), + ) outputs = gtractInvertRigidTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleAnisotropy.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleAnisotropy.py index dd30cda525..7b38abe0b5 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleAnisotropy.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleAnisotropy.py @@ -4,18 +4,35 @@ def test_gtractResampleAnisotropy_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputAnatomicalVolume=dict( - argstr="--inputAnatomicalVolume %s", extensions=None, + argstr="--inputAnatomicalVolume %s", + extensions=None, ), inputAnisotropyVolume=dict( - argstr="--inputAnisotropyVolume %s", extensions=None, + argstr="--inputAnisotropyVolume %s", + extensions=None, + ), + inputTransform=dict( + argstr="--inputTransform %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + transformType=dict( + argstr="--transformType %s", ), - inputTransform=dict(argstr="--inputTransform %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - transformType=dict(argstr="--transformType %s",), ) inputs = gtractResampleAnisotropy.input_spec() @@ -25,7 +42,11 @@ def test_gtractResampleAnisotropy_inputs(): def test_gtractResampleAnisotropy_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractResampleAnisotropy.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleB0.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleB0.py index e512fed7b5..7271e8a42a 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleB0.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleB0.py @@ -4,17 +4,38 @@ def test_gtractResampleB0_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputAnatomicalVolume=dict( - argstr="--inputAnatomicalVolume %s", extensions=None, - ), - inputTransform=dict(argstr="--inputTransform %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - transformType=dict(argstr="--transformType %s",), - vectorIndex=dict(argstr="--vectorIndex %d",), + argstr="--inputAnatomicalVolume %s", + extensions=None, + ), + inputTransform=dict( + argstr="--inputTransform %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + transformType=dict( + argstr="--transformType %s", + ), + vectorIndex=dict( + argstr="--vectorIndex %d", + ), ) inputs = gtractResampleB0.input_spec() @@ -24,7 +45,11 @@ def test_gtractResampleB0_inputs(): def test_gtractResampleB0_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractResampleB0.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleCodeImage.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleCodeImage.py index 4cc5c30e4f..6649ecfc1f 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleCodeImage.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleCodeImage.py @@ -4,14 +4,35 @@ def test_gtractResampleCodeImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputCodeVolume=dict(argstr="--inputCodeVolume %s", extensions=None,), - inputReferenceVolume=dict(argstr="--inputReferenceVolume %s", extensions=None,), - inputTransform=dict(argstr="--inputTransform %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - transformType=dict(argstr="--transformType %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputCodeVolume=dict( + argstr="--inputCodeVolume %s", + extensions=None, + ), + inputReferenceVolume=dict( + argstr="--inputReferenceVolume %s", + extensions=None, + ), + inputTransform=dict( + argstr="--inputTransform %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + transformType=dict( + argstr="--transformType %s", + ), ) inputs = gtractResampleCodeImage.input_spec() @@ -21,7 +42,11 @@ def test_gtractResampleCodeImage_inputs(): def test_gtractResampleCodeImage_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractResampleCodeImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleDWIInPlace.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleDWIInPlace.py index f87aa364cc..3b61312e54 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleDWIInPlace.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleDWIInPlace.py @@ -4,17 +4,47 @@ def test_gtractResampleDWIInPlace_inputs(): input_map = dict( - args=dict(argstr="%s",), - debugLevel=dict(argstr="--debugLevel %d",), - environ=dict(nohash=True, usedefault=True,), - imageOutputSize=dict(argstr="--imageOutputSize %s", sep=",",), - inputTransform=dict(argstr="--inputTransform %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputResampledB0=dict(argstr="--outputResampledB0 %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - referenceVolume=dict(argstr="--referenceVolume %s", extensions=None,), - warpDWITransform=dict(argstr="--warpDWITransform %s", extensions=None,), + args=dict( + argstr="%s", + ), + debugLevel=dict( + argstr="--debugLevel %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + imageOutputSize=dict( + argstr="--imageOutputSize %s", + sep=",", + ), + inputTransform=dict( + argstr="--inputTransform %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputResampledB0=dict( + argstr="--outputResampledB0 %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + referenceVolume=dict( + argstr="--referenceVolume %s", + extensions=None, + ), + warpDWITransform=dict( + argstr="--warpDWITransform %s", + extensions=None, + ), ) inputs = gtractResampleDWIInPlace.input_spec() @@ -25,7 +55,12 @@ def test_gtractResampleDWIInPlace_inputs(): def test_gtractResampleDWIInPlace_outputs(): output_map = dict( - outputResampledB0=dict(extensions=None,), outputVolume=dict(extensions=None,), + outputResampledB0=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), ) outputs = gtractResampleDWIInPlace.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleFibers.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleFibers.py index 3c7a6b33b8..d64d2d8581 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleFibers.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractResampleFibers.py @@ -4,18 +4,35 @@ def test_gtractResampleFibers_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputForwardDeformationFieldVolume=dict( - argstr="--inputForwardDeformationFieldVolume %s", extensions=None, + argstr="--inputForwardDeformationFieldVolume %s", + extensions=None, ), inputReverseDeformationFieldVolume=dict( - argstr="--inputReverseDeformationFieldVolume %s", extensions=None, + argstr="--inputReverseDeformationFieldVolume %s", + extensions=None, + ), + inputTract=dict( + argstr="--inputTract %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputTract=dict( + argstr="--outputTract %s", + hash_files=False, + ), + writeXMLPolyDataFile=dict( + argstr="--writeXMLPolyDataFile ", ), - inputTract=dict(argstr="--inputTract %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputTract=dict(argstr="--outputTract %s", hash_files=False,), - writeXMLPolyDataFile=dict(argstr="--writeXMLPolyDataFile ",), ) inputs = gtractResampleFibers.input_spec() @@ -25,7 +42,11 @@ def test_gtractResampleFibers_inputs(): def test_gtractResampleFibers_outputs(): - output_map = dict(outputTract=dict(extensions=None,),) + output_map = dict( + outputTract=dict( + extensions=None, + ), + ) outputs = gtractResampleFibers.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTensor.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTensor.py index 2372b9599f..eabe7c6f50 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTensor.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTensor.py @@ -4,22 +4,54 @@ def test_gtractTensor_inputs(): input_map = dict( - applyMeasurementFrame=dict(argstr="--applyMeasurementFrame ",), - args=dict(argstr="%s",), - b0Index=dict(argstr="--b0Index %d",), + applyMeasurementFrame=dict( + argstr="--applyMeasurementFrame ", + ), + args=dict( + argstr="%s", + ), + b0Index=dict( + argstr="--b0Index %d", + ), backgroundSuppressingThreshold=dict( argstr="--backgroundSuppressingThreshold %d", ), - environ=dict(nohash=True, usedefault=True,), - ignoreIndex=dict(argstr="--ignoreIndex %s", sep=",",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - maskProcessingMode=dict(argstr="--maskProcessingMode %s",), - maskVolume=dict(argstr="--maskVolume %s", extensions=None,), - medianFilterSize=dict(argstr="--medianFilterSize %s", sep=",",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - resampleIsotropic=dict(argstr="--resampleIsotropic ",), - size=dict(argstr="--size %f",), + environ=dict( + nohash=True, + usedefault=True, + ), + ignoreIndex=dict( + argstr="--ignoreIndex %s", + sep=",", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + maskProcessingMode=dict( + argstr="--maskProcessingMode %s", + ), + maskVolume=dict( + argstr="--maskVolume %s", + extensions=None, + ), + medianFilterSize=dict( + argstr="--medianFilterSize %s", + sep=",", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + resampleIsotropic=dict( + argstr="--resampleIsotropic ", + ), + size=dict( + argstr="--size %f", + ), ) inputs = gtractTensor.input_spec() @@ -29,7 +61,11 @@ def test_gtractTensor_inputs(): def test_gtractTensor_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = gtractTensor.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTransformToDisplacementField.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTransformToDisplacementField.py index 3999871191..64daec32fb 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTransformToDisplacementField.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_gtractTransformToDisplacementField.py @@ -4,13 +4,27 @@ def test_gtractTransformToDisplacementField_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputReferenceVolume=dict(argstr="--inputReferenceVolume %s", extensions=None,), - inputTransform=dict(argstr="--inputTransform %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputReferenceVolume=dict( + argstr="--inputReferenceVolume %s", + extensions=None, + ), + inputTransform=dict( + argstr="--inputTransform %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), outputDeformationFieldVolume=dict( - argstr="--outputDeformationFieldVolume %s", hash_files=False, + argstr="--outputDeformationFieldVolume %s", + hash_files=False, ), ) inputs = gtractTransformToDisplacementField.input_spec() @@ -21,7 +35,11 @@ def test_gtractTransformToDisplacementField_inputs(): def test_gtractTransformToDisplacementField_outputs(): - output_map = dict(outputDeformationFieldVolume=dict(extensions=None,),) + output_map = dict( + outputDeformationFieldVolume=dict( + extensions=None, + ), + ) outputs = gtractTransformToDisplacementField.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tests/test_auto_maxcurvature.py b/nipype/interfaces/semtools/diffusion/tests/test_auto_maxcurvature.py index 9ec247675e..6638ef34cd 100644 --- a/nipype/interfaces/semtools/diffusion/tests/test_auto_maxcurvature.py +++ b/nipype/interfaces/semtools/diffusion/tests/test_auto_maxcurvature.py @@ -4,12 +4,27 @@ def test_maxcurvature_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - image=dict(argstr="--image %s", extensions=None,), - output=dict(argstr="--output %s", hash_files=False,), - sigma=dict(argstr="--sigma %f",), - verbose=dict(argstr="--verbose ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + image=dict( + argstr="--image %s", + extensions=None, + ), + output=dict( + argstr="--output %s", + hash_files=False, + ), + sigma=dict( + argstr="--sigma %f", + ), + verbose=dict( + argstr="--verbose ", + ), ) inputs = maxcurvature.input_spec() @@ -19,7 +34,11 @@ def test_maxcurvature_inputs(): def test_maxcurvature_outputs(): - output_map = dict(output=dict(extensions=None,),) + output_map = dict( + output=dict( + extensions=None, + ), + ) outputs = maxcurvature.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tractography/__init__.py b/nipype/interfaces/semtools/diffusion/tractography/__init__.py index ac45b2050f..809910cf28 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/__init__.py +++ b/nipype/interfaces/semtools/diffusion/tractography/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .commandlineonly import fiberstats from .fiberprocess import fiberprocess from .fibertrack import fibertrack diff --git a/nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py b/nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py index becf1466e9..e03c8fde9e 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py +++ b/nipype/interfaces/semtools/diffusion/tractography/commandlineonly.py @@ -1,21 +1,12 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ....base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) @@ -31,25 +22,24 @@ class fiberstatsOutputSpec(TraitedSpec): class fiberstats(SEMLikeCommandLine): """title: FiberStats (DTIProcess) -category: Diffusion.Tractography.CommandLineOnly - -description: Obsolete tool - Not used anymore + category: Diffusion.Tractography.CommandLineOnly -version: 1.1.0 + description: Obsolete tool - Not used anymore -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess + version: 1.1.0 -license: Copyright (c) Casey Goodlett. All rights reserved. - See http://www.ia.unc.edu/dev/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess -contributor: Casey Goodlett + license: Copyright (c) Casey Goodlett. All rights reserved. + See http://www.ia.unc.edu/dev/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependancies on boost and a fortran compiler. + contributor: Casey Goodlett -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependencies on boost and a fortran compiler. + """ input_spec = fiberstatsInputSpec output_spec = fiberstatsOutputSpec diff --git a/nipype/interfaces/semtools/diffusion/tractography/fiberprocess.py b/nipype/interfaces/semtools/diffusion/tractography/fiberprocess.py index 1798ead449..7efb9c9e23 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/fiberprocess.py +++ b/nipype/interfaces/semtools/diffusion/tractography/fiberprocess.py @@ -1,21 +1,12 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ....base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) @@ -90,25 +81,24 @@ class fiberprocessOutputSpec(TraitedSpec): class fiberprocess(SEMLikeCommandLine): """title: FiberProcess (DTIProcess) -category: Diffusion.Tractography - -description: fiberprocess is a tool that manage fiber files extracted from the fibertrack tool or any fiber tracking algorithm. It takes as an input .fib and .vtk files (--fiber_file) and saves the changed fibers (--fiber_output) into the 2 same formats. The main purpose of this tool is to deform the fiber file with a transformation field as an input (--displacement_field or --h_field depending if you deal with dfield or hfield). To use that option you need to specify the tensor field from which the fiber file was extracted with the option --tensor_volume. The transformation applied on the fiber file is the inverse of the one input. If the transformation is from one case to an atlas, fiberprocess assumes that the fiber file is in the atlas space and you want it in the original case space, so it's the inverse of the transformation which has been computed. -You have 2 options for fiber modification. You can either deform the fibers (their geometry) into the space OR you can keep the same geometry but map the diffusion properties (fa, md, lbd's...) of the original tensor field along the fibers at the corresponding locations. This is triggered by the --no_warp option. To use the previous example: when you have a tensor field in the original space and the deformed tensor field in the atlas space, you want to track the fibers in the atlas space, keeping this geometry but with the original case diffusion properties. Then you can specify the transformations field (from original case -> atlas) and the original tensor field with the --tensor_volume option. -With fiberprocess you can also binarize a fiber file. Using the --voxelize option will create an image where each voxel through which a fiber is passing is set to 1. The output is going to be a binary image with the values 0 or 1 by default but the 1 value voxel can be set to any number with the --voxel_label option. Finally you can create an image where the value at the voxel is the number of fiber passing through. (--voxelize_count_fibers) + category: Diffusion.Tractography -version: 1.0.0 + description: fiberprocess is a tool that manage fiber files extracted from the fibertrack tool or any fiber tracking algorithm. It takes as an input .fib and .vtk files (--fiber_file) and saves the changed fibers (--fiber_output) into the 2 same formats. The main purpose of this tool is to deform the fiber file with a transformation field as an input (--displacement_field or --h_field depending if you deal with dfield or hfield). To use that option you need to specify the tensor field from which the fiber file was extracted with the option --tensor_volume. The transformation applied on the fiber file is the inverse of the one input. If the transformation is from one case to an atlas, fiberprocess assumes that the fiber file is in the atlas space and you want it in the original case space, so it's the inverse of the transformation which has been computed. + You have 2 options for fiber modification. You can either deform the fibers (their geometry) into the space OR you can keep the same geometry but map the diffusion properties (fa, md, lbd's...) of the original tensor field along the fibers at the corresponding locations. This is triggered by the --no_warp option. To use the previous example: when you have a tensor field in the original space and the deformed tensor field in the atlas space, you want to track the fibers in the atlas space, keeping this geometry but with the original case diffusion properties. Then you can specify the transformations field (from original case -> atlas) and the original tensor field with the --tensor_volume option. + With fiberprocess you can also binarize a fiber file. Using the --voxelize option will create an image where each voxel through which a fiber is passing is set to 1. The output is going to be a binary image with the values 0 or 1 by default but the 1 value voxel can be set to any number with the --voxel_label option. Finally you can create an image where the value at the voxel is the number of fiber passing through. (--voxelize_count_fibers) -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess + version: 1.0.0 -license: Copyright (c) Casey Goodlett. All rights reserved. - See http://www.ia.unc.edu/dev/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess -contributor: Casey Goodlett + license: Copyright (c) Casey Goodlett. All rights reserved. + See http://www.ia.unc.edu/dev/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. -""" + contributor: Casey Goodlett + """ input_spec = fiberprocessInputSpec output_spec = fiberprocessOutputSpec diff --git a/nipype/interfaces/semtools/diffusion/tractography/fibertrack.py b/nipype/interfaces/semtools/diffusion/tractography/fibertrack.py index c6eb7f13e0..1fa64180d5 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/fibertrack.py +++ b/nipype/interfaces/semtools/diffusion/tractography/fibertrack.py @@ -1,21 +1,12 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ....base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) @@ -74,28 +65,27 @@ class fibertrackOutputSpec(TraitedSpec): class fibertrack(SEMLikeCommandLine): """title: FiberTrack (DTIProcess) -category: Diffusion.Tractography - -description: This program implements a simple streamline tractography method based on the principal eigenvector of the tensor field. A fourth order Runge-Kutta integration rule used to advance the streamlines. -As a first parameter you have to input the tensor field (with the --input_tensor_file option). Then the region of interest image file is set with the --input_roi_file. Next you want to set the output fiber file name after the --output_fiber_file option. -You can specify the label value in the input_roi_file with the --target_label, --source_label and --fobidden_label options. By default target label is 1, source label is 2 and forbidden label is 0. The source label is where the streamlines are seeded, the target label defines the voxels through which the fibers must pass by to be kept in the final fiber file and the forbidden label defines the voxels where the streamlines are stopped if they pass through it. There is also a --whole_brain option which, if enabled, consider both target and source labels of the roi image as target labels and all the voxels of the image are considered as sources. -During the tractography, the --fa_min parameter is used as the minimum value needed at different voxel for the tracking to keep going along a streamline. The --step_size parameter is used for each iteration of the tracking algorithm and defines the length of each step. The --max_angle option defines the maximum angle allowed between two successive segments along the tracked fiber. + category: Diffusion.Tractography -version: 1.1.0 + description: This program implements a simple streamline tractography method based on the principal eigenvector of the tensor field. A fourth order Runge-Kutta integration rule used to advance the streamlines. + As a first parameter you have to input the tensor field (with the --input_tensor_file option). Then the region of interest image file is set with the --input_roi_file. Next you want to set the output fiber file name after the --output_fiber_file option. + You can specify the label value in the input_roi_file with the --target_label, --source_label and --fobidden_label options. By default target label is 1, source label is 2 and forbidden label is 0. The source label is where the streamlines are seeded, the target label defines the voxels through which the fibers must pass by to be kept in the final fiber file and the forbidden label defines the voxels where the streamlines are stopped if they pass through it. There is also a --whole_brain option which, if enabled, consider both target and source labels of the roi image as target labels and all the voxels of the image are considered as sources. + During the tractography, the --fa_min parameter is used as the minimum value needed at different voxel for the tracking to keep going along a streamline. The --step_size parameter is used for each iteration of the tracking algorithm and defines the length of each step. The --max_angle option defines the maximum angle allowed between two successive segments along the tracked fiber. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess + version: 1.1.0 -license: Copyright (c) Casey Goodlett. All rights reserved. - See http://www.ia.unc.edu/dev/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess -contributor: Casey Goodlett + license: Copyright (c) Casey Goodlett. All rights reserved. + See http://www.ia.unc.edu/dev/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependancies on boost and a fortran compiler. + contributor: Casey Goodlett -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering) provided conversions to make DTIProcess compatible with Slicer execution, and simplified the stand-alone build requirements by removing the dependencies on boost and a fortran compiler. + """ input_spec = fibertrackInputSpec output_spec = fibertrackOutputSpec diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/__init__.py b/nipype/interfaces/semtools/diffusion/tractography/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/__init__.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_UKFTractography.py b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_UKFTractography.py index a7e86c79b8..92050c6e43 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_UKFTractography.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_UKFTractography.py @@ -4,43 +4,118 @@ def test_UKFTractography_inputs(): input_map = dict( - Ql=dict(argstr="--Ql %f",), - Qm=dict(argstr="--Qm %f",), - Qw=dict(argstr="--Qw %f",), - Rs=dict(argstr="--Rs %f",), - args=dict(argstr="%s",), - dwiFile=dict(argstr="--dwiFile %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - freeWater=dict(argstr="--freeWater ",), - fullTensorModel=dict(argstr="--fullTensorModel ",), - labels=dict(argstr="--labels %s", sep=",",), - maskFile=dict(argstr="--maskFile %s", extensions=None,), - maxBranchingAngle=dict(argstr="--maxBranchingAngle %f",), - maxHalfFiberLength=dict(argstr="--maxHalfFiberLength %f",), - minBranchingAngle=dict(argstr="--minBranchingAngle %f",), - minFA=dict(argstr="--minFA %f",), - minGA=dict(argstr="--minGA %f",), - numTensor=dict(argstr="--numTensor %s",), - numThreads=dict(argstr="--numThreads %d",), - recordCovariance=dict(argstr="--recordCovariance ",), - recordFA=dict(argstr="--recordFA ",), - recordFreeWater=dict(argstr="--recordFreeWater ",), - recordLength=dict(argstr="--recordLength %f",), - recordNMSE=dict(argstr="--recordNMSE ",), - recordState=dict(argstr="--recordState ",), - recordTensors=dict(argstr="--recordTensors ",), - recordTrace=dict(argstr="--recordTrace ",), - seedFALimit=dict(argstr="--seedFALimit %f",), - seedsFile=dict(argstr="--seedsFile %s", extensions=None,), - seedsPerVoxel=dict(argstr="--seedsPerVoxel %d",), - stepLength=dict(argstr="--stepLength %f",), - storeGlyphs=dict(argstr="--storeGlyphs ",), - tracts=dict(argstr="--tracts %s", hash_files=False,), + Ql=dict( + argstr="--Ql %f", + ), + Qm=dict( + argstr="--Qm %f", + ), + Qw=dict( + argstr="--Qw %f", + ), + Rs=dict( + argstr="--Rs %f", + ), + args=dict( + argstr="%s", + ), + dwiFile=dict( + argstr="--dwiFile %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + freeWater=dict( + argstr="--freeWater ", + ), + fullTensorModel=dict( + argstr="--fullTensorModel ", + ), + labels=dict( + argstr="--labels %s", + sep=",", + ), + maskFile=dict( + argstr="--maskFile %s", + extensions=None, + ), + maxBranchingAngle=dict( + argstr="--maxBranchingAngle %f", + ), + maxHalfFiberLength=dict( + argstr="--maxHalfFiberLength %f", + ), + minBranchingAngle=dict( + argstr="--minBranchingAngle %f", + ), + minFA=dict( + argstr="--minFA %f", + ), + minGA=dict( + argstr="--minGA %f", + ), + numTensor=dict( + argstr="--numTensor %s", + ), + numThreads=dict( + argstr="--numThreads %d", + ), + recordCovariance=dict( + argstr="--recordCovariance ", + ), + recordFA=dict( + argstr="--recordFA ", + ), + recordFreeWater=dict( + argstr="--recordFreeWater ", + ), + recordLength=dict( + argstr="--recordLength %f", + ), + recordNMSE=dict( + argstr="--recordNMSE ", + ), + recordState=dict( + argstr="--recordState ", + ), + recordTensors=dict( + argstr="--recordTensors ", + ), + recordTrace=dict( + argstr="--recordTrace ", + ), + seedFALimit=dict( + argstr="--seedFALimit %f", + ), + seedsFile=dict( + argstr="--seedsFile %s", + extensions=None, + ), + seedsPerVoxel=dict( + argstr="--seedsPerVoxel %d", + ), + stepLength=dict( + argstr="--stepLength %f", + ), + storeGlyphs=dict( + argstr="--storeGlyphs ", + ), + tracts=dict( + argstr="--tracts %s", + hash_files=False, + ), tractsWithSecondTensor=dict( - argstr="--tractsWithSecondTensor %s", hash_files=False, + argstr="--tractsWithSecondTensor %s", + hash_files=False, + ), + writeAsciiTracts=dict( + argstr="--writeAsciiTracts ", + ), + writeUncompressedTracts=dict( + argstr="--writeUncompressedTracts ", ), - writeAsciiTracts=dict(argstr="--writeAsciiTracts ",), - writeUncompressedTracts=dict(argstr="--writeUncompressedTracts ",), ) inputs = UKFTractography.input_spec() @@ -51,7 +126,12 @@ def test_UKFTractography_inputs(): def test_UKFTractography_outputs(): output_map = dict( - tracts=dict(extensions=None,), tractsWithSecondTensor=dict(extensions=None,), + tracts=dict( + extensions=None, + ), + tractsWithSecondTensor=dict( + extensions=None, + ), ) outputs = UKFTractography.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberprocess.py b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberprocess.py index d25c1a10ca..506d3f8f90 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberprocess.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberprocess.py @@ -4,22 +4,61 @@ def test_fiberprocess_inputs(): input_map = dict( - args=dict(argstr="%s",), - displacement_field=dict(argstr="--displacement_field %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - fiber_file=dict(argstr="--fiber_file %s", extensions=None,), - fiber_output=dict(argstr="--fiber_output %s", hash_files=False,), - fiber_radius=dict(argstr="--fiber_radius %f",), - h_field=dict(argstr="--h_field %s", extensions=None,), - index_space=dict(argstr="--index_space ",), - noDataChange=dict(argstr="--noDataChange ",), - no_warp=dict(argstr="--no_warp ",), - saveProperties=dict(argstr="--saveProperties ",), - tensor_volume=dict(argstr="--tensor_volume %s", extensions=None,), - verbose=dict(argstr="--verbose ",), - voxel_label=dict(argstr="--voxel_label %d",), - voxelize=dict(argstr="--voxelize %s", hash_files=False,), - voxelize_count_fibers=dict(argstr="--voxelize_count_fibers ",), + args=dict( + argstr="%s", + ), + displacement_field=dict( + argstr="--displacement_field %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fiber_file=dict( + argstr="--fiber_file %s", + extensions=None, + ), + fiber_output=dict( + argstr="--fiber_output %s", + hash_files=False, + ), + fiber_radius=dict( + argstr="--fiber_radius %f", + ), + h_field=dict( + argstr="--h_field %s", + extensions=None, + ), + index_space=dict( + argstr="--index_space ", + ), + noDataChange=dict( + argstr="--noDataChange ", + ), + no_warp=dict( + argstr="--no_warp ", + ), + saveProperties=dict( + argstr="--saveProperties ", + ), + tensor_volume=dict( + argstr="--tensor_volume %s", + extensions=None, + ), + verbose=dict( + argstr="--verbose ", + ), + voxel_label=dict( + argstr="--voxel_label %d", + ), + voxelize=dict( + argstr="--voxelize %s", + hash_files=False, + ), + voxelize_count_fibers=dict( + argstr="--voxelize_count_fibers ", + ), ) inputs = fiberprocess.input_spec() @@ -30,7 +69,12 @@ def test_fiberprocess_inputs(): def test_fiberprocess_outputs(): output_map = dict( - fiber_output=dict(extensions=None,), voxelize=dict(extensions=None,), + fiber_output=dict( + extensions=None, + ), + voxelize=dict( + extensions=None, + ), ) outputs = fiberprocess.output_spec() diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberstats.py b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberstats.py index 570ea316c7..a9df738d28 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberstats.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fiberstats.py @@ -4,10 +4,20 @@ def test_fiberstats_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fiber_file=dict(argstr="--fiber_file %s", extensions=None,), - verbose=dict(argstr="--verbose ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fiber_file=dict( + argstr="--fiber_file %s", + extensions=None, + ), + verbose=dict( + argstr="--verbose ", + ), ) inputs = fiberstats.input_spec() diff --git a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fibertrack.py b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fibertrack.py index d3994690d1..28798b14ff 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fibertrack.py +++ b/nipype/interfaces/semtools/diffusion/tractography/tests/test_auto_fibertrack.py @@ -4,21 +4,55 @@ def test_fibertrack_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - forbidden_label=dict(argstr="--forbidden_label %d",), - force=dict(argstr="--force ",), - input_roi_file=dict(argstr="--input_roi_file %s", extensions=None,), - input_tensor_file=dict(argstr="--input_tensor_file %s", extensions=None,), - max_angle=dict(argstr="--max_angle %f",), - min_fa=dict(argstr="--min_fa %f",), - output_fiber_file=dict(argstr="--output_fiber_file %s", hash_files=False,), - really_verbose=dict(argstr="--really_verbose ",), - source_label=dict(argstr="--source_label %d",), - step_size=dict(argstr="--step_size %f",), - target_label=dict(argstr="--target_label %d",), - verbose=dict(argstr="--verbose ",), - whole_brain=dict(argstr="--whole_brain ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + forbidden_label=dict( + argstr="--forbidden_label %d", + ), + force=dict( + argstr="--force ", + ), + input_roi_file=dict( + argstr="--input_roi_file %s", + extensions=None, + ), + input_tensor_file=dict( + argstr="--input_tensor_file %s", + extensions=None, + ), + max_angle=dict( + argstr="--max_angle %f", + ), + min_fa=dict( + argstr="--min_fa %f", + ), + output_fiber_file=dict( + argstr="--output_fiber_file %s", + hash_files=False, + ), + really_verbose=dict( + argstr="--really_verbose ", + ), + source_label=dict( + argstr="--source_label %d", + ), + step_size=dict( + argstr="--step_size %f", + ), + target_label=dict( + argstr="--target_label %d", + ), + verbose=dict( + argstr="--verbose ", + ), + whole_brain=dict( + argstr="--whole_brain ", + ), ) inputs = fibertrack.input_spec() @@ -28,7 +62,11 @@ def test_fibertrack_inputs(): def test_fibertrack_outputs(): - output_map = dict(output_fiber_file=dict(extensions=None,),) + output_map = dict( + output_fiber_file=dict( + extensions=None, + ), + ) outputs = fibertrack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/diffusion/tractography/ukftractography.py b/nipype/interfaces/semtools/diffusion/tractography/ukftractography.py index 228d162560..fc8035762d 100644 --- a/nipype/interfaces/semtools/diffusion/tractography/ukftractography.py +++ b/nipype/interfaces/semtools/diffusion/tractography/ukftractography.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ....base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -57,7 +49,7 @@ class UKFTractographyInputSpec(CommandLineInputSpec): "1", "2", desc="Number of tensors used", argstr="--numTensor %s" ) freeWater = traits.Bool( - desc="Adds a term for free water difusion to the model. (Note for experts: if checked, the 1T simple model is forced) ", + desc="Adds a term for free water diffusion to the model. (Note for experts: if checked, the 1T simple model is forced) ", argstr="--freeWater ", ) recordFA = traits.Bool( @@ -126,7 +118,7 @@ class UKFTractographyInputSpec(CommandLineInputSpec): ) Rs = traits.Float(desc="Measurement noise", argstr="--Rs %f") maxBranchingAngle = traits.Float( - desc="Maximum branching angle, in degrees. When using multiple tensors, a new branch will be created when the tensors' major directions form an angle between (minBranchingAngle, maxBranchingAngle). Branching is supressed when this maxBranchingAngle is set to 0.0", + desc="Maximum branching angle, in degrees. When using multiple tensors, a new branch will be created when the tensors' major directions form an angle between (minBranchingAngle, maxBranchingAngle). Branching is suppressed when this maxBranchingAngle is set to 0.0", argstr="--maxBranchingAngle %f", ) minBranchingAngle = traits.Float( @@ -157,19 +149,18 @@ class UKFTractographyOutputSpec(TraitedSpec): class UKFTractography(SEMLikeCommandLine): """title: UKF Tractography -category: Diffusion.Tractography - -description: This module traces fibers in a DWI Volume using the multiple tensor unscented Kalman Filter methology. For more informations check the documentation. + category: Diffusion.Tractography -version: 1.0 + description: This module traces fibers in a DWI Volume using the multiple tensor unscented Kalman Filter methology. For more information check the documentation. -documentation-url: http://www.nitrc.org/plugins/mwiki/index.php/ukftractography:MainPage + version: 1.0 -contributor: Yogesh Rathi, Stefan Lienhard, Yinpeng Li, Martin Styner, Ipek Oguz, Yundi Shi, Christian Baumgartner, Kent Williams, Hans Johnson, Peter Savadjiev, Carl-Fredrik Westin. + documentation-url: http://www.nitrc.org/plugins/mwiki/index.php/ukftractography:MainPage -acknowledgements: The development of this module was supported by NIH grants R01 MH097979 (PI Rathi), R01 MH092862 (PIs Westin and Verma), U01 NS083223 (PI Westin), R01 MH074794 (PI Westin) and P41 EB015902 (PI Kikinis). + contributor: Yogesh Rathi, Stefan Lienhard, Yinpeng Li, Martin Styner, Ipek Oguz, Yundi Shi, Christian Baumgartner, Kent Williams, Hans Johnson, Peter Savadjiev, Carl-Fredrik Westin. -""" + acknowledgements: The development of this module was supported by NIH grants R01 MH097979 (PI Rathi), R01 MH092862 (PIs Westin and Verma), U01 NS083223 (PI Westin), R01 MH074794 (PI Westin) and P41 EB015902 (PI Kikinis). + """ input_spec = UKFTractographyInputSpec output_spec = UKFTractographyOutputSpec diff --git a/nipype/interfaces/semtools/featurecreator.py b/nipype/interfaces/semtools/featurecreator.py index f02d19fda8..08482853a5 100644 --- a/nipype/interfaces/semtools/featurecreator.py +++ b/nipype/interfaces/semtools/featurecreator.py @@ -1,21 +1,12 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ..base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) @@ -41,19 +32,18 @@ class GenerateCsfClippedFromClassifiedImageOutputSpec(TraitedSpec): class GenerateCsfClippedFromClassifiedImage(SEMLikeCommandLine): """title: GenerateCsfClippedFromClassifiedImage -category: FeatureCreator - -description: Get the distance from a voxel to the nearest voxel of a given tissue type. + category: FeatureCreator -version: 0.1.0.$Revision: 1 $(alpha) + description: Get the distance from a voxel to the nearest voxel of a given tissue type. -documentation-url: http:://www.na-mic.org/ + version: 0.1.0.$Revision: 1 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http:://www.na-mic.org/ -contributor: This tool was written by Hans J. Johnson. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: This tool was written by Hans J. Johnson. + """ input_spec = GenerateCsfClippedFromClassifiedImageInputSpec output_spec = GenerateCsfClippedFromClassifiedImageOutputSpec diff --git a/nipype/interfaces/semtools/filtering/__init__.py b/nipype/interfaces/semtools/filtering/__init__.py index b5b7eccb20..159dc2c490 100644 --- a/nipype/interfaces/semtools/filtering/__init__.py +++ b/nipype/interfaces/semtools/filtering/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .denoising import UnbiasedNonLocalMeans from .featuredetection import ( GenerateSummedGradientImage, diff --git a/nipype/interfaces/semtools/filtering/denoising.py b/nipype/interfaces/semtools/filtering/denoising.py index 2ca6840128..9afd9184fa 100644 --- a/nipype/interfaces/semtools/filtering/denoising.py +++ b/nipype/interfaces/semtools/filtering/denoising.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -62,27 +54,26 @@ class UnbiasedNonLocalMeansOutputSpec(TraitedSpec): class UnbiasedNonLocalMeans(SEMLikeCommandLine): """title: Unbiased NLM for MRI -category: Filtering.Denoising - -description: This module implements a fast version of the popular Non-Local Means filter for image denoising. This algorithm filters each pixel as a weighted average of its neighbors in a large vicinity. The weights are computed based on the similarity of each neighbor with the voxel to be denoised. - In the original formulation a patch with a certain radius is centered in each of the voxels, and the Mean Squared Error between each pair of corresponding voxels is computed. In this implementation, only the mean value and gradient components are compared. This, together with an efficient memory management, can attain a speed-up of nearly 20x. Besides, the filtering is more accurate than the original with poor SNR. - This code is intended for its use with MRI (or any other Rician-distributed modality): the second order moment is estimated, then we subtract twice the squared power of noise, and finally we take the square root of the result to remove the Rician bias. - The original implementation of the NLM filter may be found in: - A. Buades, B. Coll, J. Morel, "A review of image denoising algorithms, with a new one", Multiscale Modelling and Simulation 4(2): 490-530. 2005. - The correction of the Rician bias is described in the following reference (among others): - S. Aja-Fernandez, K. Krissian, "An unbiased Non-Local Means scheme for DWI filtering", in: Proceedings of the MICCAI Workshop on Computational Diffusion MRI, 2008, pp. 277-284. - The whole description of this version may be found in the following paper (please, cite it if you are willing to use this software): - A. Tristan-Vega, V. Garcia Perez, S. Aja-Fenandez, and C.-F. Westin, "Efficient and Robust Nonlocal Means Denoising of MR Data Based on Salient Features Matching", Computer Methods and Programs in Biomedicine. (Accepted for publication) 2011. + category: Filtering.Denoising -version: 0.0.1.$Revision: 1 $(beta) + description: This module implements a fast version of the popular Non-Local Means filter for image denoising. This algorithm filters each pixel as a weighted average of its neighbors in a large vicinity. The weights are computed based on the similarity of each neighbor with the voxel to be denoised. + In the original formulation a patch with a certain radius is centered in each of the voxels, and the Mean Squared Error between each pair of corresponding voxels is computed. In this implementation, only the mean value and gradient components are compared. This, together with an efficient memory management, can attain a speed-up of nearly 20x. Besides, the filtering is more accurate than the original with poor SNR. + This code is intended for its use with MRI (or any other Rician-distributed modality): the second order moment is estimated, then we subtract twice the squared power of noise, and finally we take the square root of the result to remove the Rician bias. + The original implementation of the NLM filter may be found in: + A. Buades, B. Coll, J. Morel, "A review of image denoising algorithms, with a new one", Multiscale Modelling and Simulation 4(2): 490-530. 2005. + The correction of the Rician bias is described in the following reference (among others): + S. Aja-Fernandez, K. Krissian, "An unbiased Non-Local Means scheme for DWI filtering", in: Proceedings of the MICCAI Workshop on Computational Diffusion MRI, 2008, pp. 277-284. + The whole description of this version may be found in the following paper (please, cite it if you are willing to use this software): + A. Tristan-Vega, V. Garcia Perez, S. Aja-Fenandez, and C.-F. Westin, "Efficient and Robust Nonlocal Means Denoising of MR Data Based on Salient Features Matching", Computer Methods and Programs in Biomedicine. (Accepted for publication) 2011. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Modules:UnbiasedNonLocalMeans-Documentation-3.6 + version: 0.0.1.$Revision: 1 $(beta) -contributor: Antonio Tristan Vega, Veronica Garcia-Perez, Santiago Aja-Fernandez, Carl-Fredrik Westin + documentation-url: http://www.slicer.org/slicerWiki/index.php/Modules:UnbiasedNonLocalMeans-Documentation-3.6 -acknowledgements: Supported by grant number FMECD-2010/71131616E from the Spanish Ministry of Education/Fulbright Committee + contributor: Antonio Tristan Vega, Veronica Garcia-Perez, Santiago Aja-Fernandez, Carl-Fredrik Westin -""" + acknowledgements: Supported by grant number FMECD-2010/71131616E from the Spanish Ministry of Education/Fulbright Committee + """ input_spec = UnbiasedNonLocalMeansInputSpec output_spec = UnbiasedNonLocalMeansOutputSpec diff --git a/nipype/interfaces/semtools/filtering/featuredetection.py b/nipype/interfaces/semtools/filtering/featuredetection.py index e15e1de6b0..b61cf59a11 100644 --- a/nipype/interfaces/semtools/filtering/featuredetection.py +++ b/nipype/interfaces/semtools/filtering/featuredetection.py @@ -1,30 +1,22 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) class GenerateSummedGradientImageInputSpec(CommandLineInputSpec): inputVolume1 = File( - desc="input volume 1, usally t1 image", exists=True, argstr="--inputVolume1 %s" + desc="input volume 1, usually t1 image", exists=True, argstr="--inputVolume1 %s" ) inputVolume2 = File( - desc="input volume 2, usally t2 image", exists=True, argstr="--inputVolume2 %s" + desc="input volume 2, usually t2 image", exists=True, argstr="--inputVolume2 %s" ) outputFileName = traits.Either( traits.Bool, @@ -50,17 +42,16 @@ class GenerateSummedGradientImageOutputSpec(TraitedSpec): class GenerateSummedGradientImage(SEMLikeCommandLine): """title: GenerateSummedGradient -category: Filtering.FeatureDetection - -description: Automatic FeatureImages using neural networks + category: Filtering.FeatureDetection -version: 1.0 + description: Automatic FeatureImages using neural networks -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 1.0 -contributor: Greg Harris, Eun Young Kim + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: Greg Harris, Eun Young Kim + """ input_spec = GenerateSummedGradientImageInputSpec output_spec = GenerateSummedGradientImageOutputSpec @@ -101,19 +92,18 @@ class CannySegmentationLevelSetImageFilterOutputSpec(TraitedSpec): class CannySegmentationLevelSetImageFilter(SEMLikeCommandLine): """title: Canny Level Set Image Filter -category: Filtering.FeatureDetection - -description: The CannySegmentationLevelSet is commonly used to refine a manually generated manual mask. + category: Filtering.FeatureDetection -version: 0.3.0 + description: The CannySegmentationLevelSet is commonly used to refine a manually generated manual mask. -license: CC + version: 0.3.0 -contributor: Regina Kim + license: CC -acknowledgements: This command module was derived from Insight/Examples/Segmentation/CannySegmentationLevelSetImageFilter.cxx (copyright) Insight Software Consortium. See http://wiki.na-mic.org/Wiki/index.php/Slicer3:Execution_Model_Documentation for more detailed descriptions. + contributor: Regina Kim -""" + acknowledgements: This command module was derived from Insight/Examples/Segmentation/CannySegmentationLevelSetImageFilter.cxx (copyright) Insight Software Consortium. See http://wiki.na-mic.org/Wiki/index.php/Slicer3:Execution_Model_Documentation for more detailed descriptions. + """ input_spec = CannySegmentationLevelSetImageFilterInputSpec output_spec = CannySegmentationLevelSetImageFilterOutputSpec @@ -153,19 +143,18 @@ class DilateImageOutputSpec(TraitedSpec): class DilateImage(SEMLikeCommandLine): """title: Dilate Image -category: Filtering.FeatureDetection + category: Filtering.FeatureDetection -description: Uses mathematical morphology to dilate the input images. + description: Uses mathematical morphology to dilate the input images. -version: 0.1.0.$Revision: 1 $(alpha) + version: 0.1.0.$Revision: 1 $(alpha) -documentation-url: http:://www.na-mic.org/ + documentation-url: http:://www.na-mic.org/ -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. - -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = DilateImageInputSpec output_spec = DilateImageOutputSpec @@ -197,19 +186,18 @@ class TextureFromNoiseImageFilterOutputSpec(TraitedSpec): class TextureFromNoiseImageFilter(SEMLikeCommandLine): """title: TextureFromNoiseImageFilter -category: Filtering.FeatureDetection - -description: Calculate the local noise in an image. + category: Filtering.FeatureDetection -version: 0.1.0.$Revision: 1 $(alpha) + description: Calculate the local noise in an image. -documentation-url: http:://www.na-mic.org/ + version: 0.1.0.$Revision: 1 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http:://www.na-mic.org/ -contributor: This tool was developed by Eunyoung Regina Kim + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: This tool was developed by Eunyoung Regina Kim + """ input_spec = TextureFromNoiseImageFilterInputSpec output_spec = TextureFromNoiseImageFilterOutputSpec @@ -243,19 +231,18 @@ class FlippedDifferenceOutputSpec(TraitedSpec): class FlippedDifference(SEMLikeCommandLine): """title: Flip Image -category: Filtering.FeatureDetection + category: Filtering.FeatureDetection -description: Difference between an image and the axially flipped version of that image. + description: Difference between an image and the axially flipped version of that image. -version: 0.1.0.$Revision: 1 $(alpha) + version: 0.1.0.$Revision: 1 $(alpha) -documentation-url: http:://www.na-mic.org/ + documentation-url: http:://www.na-mic.org/ -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. - -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = FlippedDifferenceInputSpec output_spec = FlippedDifferenceOutputSpec @@ -292,19 +279,18 @@ class ErodeImageOutputSpec(TraitedSpec): class ErodeImage(SEMLikeCommandLine): """title: Erode Image -category: Filtering.FeatureDetection - -description: Uses mathematical morphology to erode the input images. + category: Filtering.FeatureDetection -version: 0.1.0.$Revision: 1 $(alpha) + description: Uses mathematical morphology to erode the input images. -documentation-url: http:://www.na-mic.org/ + version: 0.1.0.$Revision: 1 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http:://www.na-mic.org/ -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = ErodeImageInputSpec output_spec = ErodeImageOutputSpec @@ -315,10 +301,10 @@ class ErodeImage(SEMLikeCommandLine): class GenerateBrainClippedImageInputSpec(CommandLineInputSpec): inputImg = File( - desc="input volume 1, usally t1 image", exists=True, argstr="--inputImg %s" + desc="input volume 1, usually t1 image", exists=True, argstr="--inputImg %s" ) inputMsk = File( - desc="input volume 2, usally t2 image", exists=True, argstr="--inputMsk %s" + desc="input volume 2, usually t2 image", exists=True, argstr="--inputMsk %s" ) outputFileName = traits.Either( traits.Bool, @@ -340,17 +326,16 @@ class GenerateBrainClippedImageOutputSpec(TraitedSpec): class GenerateBrainClippedImage(SEMLikeCommandLine): """title: GenerateBrainClippedImage -category: Filtering.FeatureDetection - -description: Automatic FeatureImages using neural networks + category: Filtering.FeatureDetection -version: 1.0 + description: Automatic FeatureImages using neural networks -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 1.0 -contributor: Eun Young Kim + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: Eun Young Kim + """ input_spec = GenerateBrainClippedImageInputSpec output_spec = GenerateBrainClippedImageOutputSpec @@ -387,19 +372,18 @@ class NeighborhoodMedianOutputSpec(TraitedSpec): class NeighborhoodMedian(SEMLikeCommandLine): """title: Neighborhood Median -category: Filtering.FeatureDetection + category: Filtering.FeatureDetection -description: Calculates the median, for the given neighborhood size, at each voxel of the input image. + description: Calculates the median, for the given neighborhood size, at each voxel of the input image. -version: 0.1.0.$Revision: 1 $(alpha) + version: 0.1.0.$Revision: 1 $(alpha) -documentation-url: http:://www.na-mic.org/ + documentation-url: http:://www.na-mic.org/ -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. - -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = NeighborhoodMedianInputSpec output_spec = NeighborhoodMedianOutputSpec @@ -410,7 +394,7 @@ class NeighborhoodMedian(SEMLikeCommandLine): class GenerateTestImageInputSpec(CommandLineInputSpec): inputVolume = File( - desc="input volume 1, usally t1 image", exists=True, argstr="--inputVolume %s" + desc="input volume 1, usually t1 image", exists=True, argstr="--inputVolume %s" ) outputVolume = traits.Either( traits.Bool, @@ -433,17 +417,16 @@ class GenerateTestImageOutputSpec(TraitedSpec): class GenerateTestImage(SEMLikeCommandLine): """title: DownSampleImage -category: Filtering.FeatureDetection - -description: Down sample image for testing + category: Filtering.FeatureDetection -version: 1.0 + description: Down sample image for testing -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 1.0 -contributor: Eun Young Kim + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: Eun Young Kim + """ input_spec = GenerateTestImageInputSpec output_spec = GenerateTestImageOutputSpec @@ -480,19 +463,18 @@ class NeighborhoodMeanOutputSpec(TraitedSpec): class NeighborhoodMean(SEMLikeCommandLine): """title: Neighborhood Mean -category: Filtering.FeatureDetection + category: Filtering.FeatureDetection -description: Calculates the mean, for the given neighborhood size, at each voxel of the T1, T2, and FLAIR. + description: Calculates the mean, for the given neighborhood size, at each voxel of the T1, T2, and FLAIR. -version: 0.1.0.$Revision: 1 $(alpha) + version: 0.1.0.$Revision: 1 $(alpha) -documentation-url: http:://www.na-mic.org/ + documentation-url: http:://www.na-mic.org/ -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. - -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = NeighborhoodMeanInputSpec output_spec = NeighborhoodMeanOutputSpec @@ -532,19 +514,18 @@ class HammerAttributeCreatorOutputSpec(TraitedSpec): class HammerAttributeCreator(SEMLikeCommandLine): """title: HAMMER Feature Vectors -category: Filtering.FeatureDetection - -description: Create the feature vectors used by HAMMER. + category: Filtering.FeatureDetection -version: 0.1.0.$Revision: 1 $(alpha) + description: Create the feature vectors used by HAMMER. -documentation-url: http:://www.na-mic.org/ + version: 0.1.0.$Revision: 1 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http:://www.na-mic.org/ -contributor: This was extracted from the Hammer Registration source code, and wrapped up by Hans J. Johnson. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: This was extracted from the Hammer Registration source code, and wrapped up by Hans J. Johnson. + """ input_spec = HammerAttributeCreatorInputSpec output_spec = HammerAttributeCreatorOutputSpec @@ -570,19 +551,18 @@ class TextureMeasureFilterOutputSpec(TraitedSpec): class TextureMeasureFilter(SEMLikeCommandLine): """title: Canny Level Set Image Filter -category: Filtering.FeatureDetection - -description: The CannySegmentationLevelSet is commonly used to refine a manually generated manual mask. + category: Filtering.FeatureDetection -version: 0.3.0 + description: The CannySegmentationLevelSet is commonly used to refine a manually generated manual mask. -license: CC + version: 0.3.0 -contributor: Regina Kim + license: CC -acknowledgements: This command module was derived from Insight/Examples/Segmentation/CannySegmentationLevelSetImageFilter.cxx (copyright) Insight Software Consortium. See http://wiki.na-mic.org/Wiki/index.php/Slicer3:Execution_Model_Documentation for more detailed descriptions. + contributor: Regina Kim -""" + acknowledgements: This command module was derived from Insight/Examples/Segmentation/CannySegmentationLevelSetImageFilter.cxx (copyright) Insight Software Consortium. See http://wiki.na-mic.org/Wiki/index.php/Slicer3:Execution_Model_Documentation for more detailed descriptions. + """ input_spec = TextureMeasureFilterInputSpec output_spec = TextureMeasureFilterOutputSpec @@ -623,19 +603,18 @@ class DilateMaskOutputSpec(TraitedSpec): class DilateMask(SEMLikeCommandLine): """title: Dilate Image -category: Filtering.FeatureDetection + category: Filtering.FeatureDetection -description: Uses mathematical morphology to dilate the input images. + description: Uses mathematical morphology to dilate the input images. -version: 0.1.0.$Revision: 1 $(alpha) + version: 0.1.0.$Revision: 1 $(alpha) -documentation-url: http:://www.na-mic.org/ + documentation-url: http:://www.na-mic.org/ -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. - -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = DilateMaskInputSpec output_spec = DilateMaskOutputSpec @@ -664,19 +643,18 @@ class DumpBinaryTrainingVectorsOutputSpec(TraitedSpec): class DumpBinaryTrainingVectors(SEMLikeCommandLine): """title: Erode Image -category: Filtering.FeatureDetection - -description: Uses mathematical morphology to erode the input images. + category: Filtering.FeatureDetection -version: 0.1.0.$Revision: 1 $(alpha) + description: Uses mathematical morphology to erode the input images. -documentation-url: http:://www.na-mic.org/ + version: 0.1.0.$Revision: 1 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http:://www.na-mic.org/ -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = DumpBinaryTrainingVectorsInputSpec output_spec = DumpBinaryTrainingVectorsOutputSpec @@ -716,19 +694,18 @@ class DistanceMapsOutputSpec(TraitedSpec): class DistanceMaps(SEMLikeCommandLine): """title: Mauerer Distance -category: Filtering.FeatureDetection + category: Filtering.FeatureDetection -description: Get the distance from a voxel to the nearest voxel of a given tissue type. + description: Get the distance from a voxel to the nearest voxel of a given tissue type. -version: 0.1.0.$Revision: 1 $(alpha) + version: 0.1.0.$Revision: 1 $(alpha) -documentation-url: http:://www.na-mic.org/ + documentation-url: http:://www.na-mic.org/ -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. - -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = DistanceMapsInputSpec output_spec = DistanceMapsOutputSpec @@ -762,19 +739,18 @@ class STAPLEAnalysisOutputSpec(TraitedSpec): class STAPLEAnalysis(SEMLikeCommandLine): """title: Dilate Image -category: Filtering.FeatureDetection - -description: Uses mathematical morphology to dilate the input images. + category: Filtering.FeatureDetection -version: 0.1.0.$Revision: 1 $(alpha) + description: Uses mathematical morphology to dilate the input images. -documentation-url: http:://www.na-mic.org/ + version: 0.1.0.$Revision: 1 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http:://www.na-mic.org/ -contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: This tool was developed by Mark Scully and Jeremy Bockholt. + """ input_spec = STAPLEAnalysisInputSpec output_spec = STAPLEAnalysisOutputSpec @@ -812,13 +788,12 @@ class GradientAnisotropicDiffusionImageFilterOutputSpec(TraitedSpec): class GradientAnisotropicDiffusionImageFilter(SEMLikeCommandLine): """title: GradientAnisopropicDiffusionFilter -category: Filtering.FeatureDetection + category: Filtering.FeatureDetection -description: Image Smoothing using Gradient Anisotropic Diffuesion Filer + description: Image Smoothing using Gradient Anisotropic Diffuesion Filer -contributor: This tool was developed by Eun Young Kim by modifying ITK Example - -""" + contributor: This tool was developed by Eun Young Kim by modifying ITK Example + """ input_spec = GradientAnisotropicDiffusionImageFilterInputSpec output_spec = GradientAnisotropicDiffusionImageFilterOutputSpec @@ -861,19 +836,18 @@ class CannyEdgeOutputSpec(TraitedSpec): class CannyEdge(SEMLikeCommandLine): """title: Canny Edge Detection -category: Filtering.FeatureDetection - -description: Get the distance from a voxel to the nearest voxel of a given tissue type. + category: Filtering.FeatureDetection -version: 0.1.0.(alpha) + description: Get the distance from a voxel to the nearest voxel of a given tissue type. -documentation-url: http:://www.na-mic.org/ + version: 0.1.0.(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http:://www.na-mic.org/ -contributor: This tool was written by Hans J. Johnson. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: This tool was written by Hans J. Johnson. + """ input_spec = CannyEdgeInputSpec output_spec = CannyEdgeOutputSpec diff --git a/nipype/interfaces/semtools/filtering/tests/__init__.py b/nipype/interfaces/semtools/filtering/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/filtering/tests/__init__.py +++ b/nipype/interfaces/semtools/filtering/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_CannyEdge.py b/nipype/interfaces/semtools/filtering/tests/test_auto_CannyEdge.py index 66d4da8a6c..222c460279 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_CannyEdge.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_CannyEdge.py @@ -4,13 +4,30 @@ def test_CannyEdge_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - lowerThreshold=dict(argstr="--lowerThreshold %f",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - upperThreshold=dict(argstr="--upperThreshold %f",), - variance=dict(argstr="--variance %f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + lowerThreshold=dict( + argstr="--lowerThreshold %f", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + upperThreshold=dict( + argstr="--upperThreshold %f", + ), + variance=dict( + argstr="--variance %f", + ), ) inputs = CannyEdge.input_spec() @@ -20,7 +37,11 @@ def test_CannyEdge_inputs(): def test_CannyEdge_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = CannyEdge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_CannySegmentationLevelSetImageFilter.py b/nipype/interfaces/semtools/filtering/tests/test_auto_CannySegmentationLevelSetImageFilter.py index f77517fbb5..21f8e5da6f 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_CannySegmentationLevelSetImageFilter.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_CannySegmentationLevelSetImageFilter.py @@ -4,17 +4,44 @@ def test_CannySegmentationLevelSetImageFilter_inputs(): input_map = dict( - advectionWeight=dict(argstr="--advectionWeight %f",), - args=dict(argstr="%s",), - cannyThreshold=dict(argstr="--cannyThreshold %f",), - cannyVariance=dict(argstr="--cannyVariance %f",), - environ=dict(nohash=True, usedefault=True,), - initialModel=dict(argstr="--initialModel %s", extensions=None,), - initialModelIsovalue=dict(argstr="--initialModelIsovalue %f",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - maxIterations=dict(argstr="--maxIterations %d",), - outputSpeedVolume=dict(argstr="--outputSpeedVolume %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + advectionWeight=dict( + argstr="--advectionWeight %f", + ), + args=dict( + argstr="%s", + ), + cannyThreshold=dict( + argstr="--cannyThreshold %f", + ), + cannyVariance=dict( + argstr="--cannyVariance %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + initialModel=dict( + argstr="--initialModel %s", + extensions=None, + ), + initialModelIsovalue=dict( + argstr="--initialModelIsovalue %f", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + maxIterations=dict( + argstr="--maxIterations %d", + ), + outputSpeedVolume=dict( + argstr="--outputSpeedVolume %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = CannySegmentationLevelSetImageFilter.input_spec() @@ -25,7 +52,12 @@ def test_CannySegmentationLevelSetImageFilter_inputs(): def test_CannySegmentationLevelSetImageFilter_outputs(): output_map = dict( - outputSpeedVolume=dict(extensions=None,), outputVolume=dict(extensions=None,), + outputSpeedVolume=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), ) outputs = CannySegmentationLevelSetImageFilter.output_spec() diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_DilateImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_DilateImage.py index 901aef8d82..2be2940aeb 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_DilateImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_DilateImage.py @@ -4,12 +4,28 @@ def test_DilateImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMaskVolume=dict(argstr="--inputMaskVolume %s", extensions=None,), - inputRadius=dict(argstr="--inputRadius %d",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict( + argstr="--inputMaskVolume %s", + extensions=None, + ), + inputRadius=dict( + argstr="--inputRadius %d", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = DilateImage.input_spec() @@ -19,7 +35,11 @@ def test_DilateImage_inputs(): def test_DilateImage_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = DilateImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_DilateMask.py b/nipype/interfaces/semtools/filtering/tests/test_auto_DilateMask.py index 0311b115fb..66cc444a94 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_DilateMask.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_DilateMask.py @@ -4,13 +4,31 @@ def test_DilateMask_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputBinaryVolume=dict(argstr="--inputBinaryVolume %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - lowerThreshold=dict(argstr="--lowerThreshold %f",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - sizeStructuralElement=dict(argstr="--sizeStructuralElement %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputBinaryVolume=dict( + argstr="--inputBinaryVolume %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + lowerThreshold=dict( + argstr="--lowerThreshold %f", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + sizeStructuralElement=dict( + argstr="--sizeStructuralElement %d", + ), ) inputs = DilateMask.input_spec() @@ -20,7 +38,11 @@ def test_DilateMask_inputs(): def test_DilateMask_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = DilateMask.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_DistanceMaps.py b/nipype/interfaces/semtools/filtering/tests/test_auto_DistanceMaps.py index 730644e779..255145cfc6 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_DistanceMaps.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_DistanceMaps.py @@ -4,12 +4,28 @@ def test_DistanceMaps_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputLabelVolume=dict(argstr="--inputLabelVolume %s", extensions=None,), - inputMaskVolume=dict(argstr="--inputMaskVolume %s", extensions=None,), - inputTissueLabel=dict(argstr="--inputTissueLabel %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputLabelVolume=dict( + argstr="--inputLabelVolume %s", + extensions=None, + ), + inputMaskVolume=dict( + argstr="--inputMaskVolume %s", + extensions=None, + ), + inputTissueLabel=dict( + argstr="--inputTissueLabel %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = DistanceMaps.input_spec() @@ -19,7 +35,11 @@ def test_DistanceMaps_inputs(): def test_DistanceMaps_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = DistanceMaps.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py b/nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py index 0d7df6bf80..b62a21fdbe 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_DumpBinaryTrainingVectors.py @@ -4,10 +4,21 @@ def test_DumpBinaryTrainingVectors_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputHeaderFilename=dict(argstr="--inputHeaderFilename %s", extensions=None,), - inputVectorFilename=dict(argstr="--inputVectorFilename %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputHeaderFilename=dict( + argstr="--inputHeaderFilename %s", + extensions=None, + ), + inputVectorFilename=dict( + argstr="--inputVectorFilename %s", + extensions=None, + ), ) inputs = DumpBinaryTrainingVectors.input_spec() diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_ErodeImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_ErodeImage.py index 568cafee66..ae7140754f 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_ErodeImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_ErodeImage.py @@ -4,12 +4,28 @@ def test_ErodeImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMaskVolume=dict(argstr="--inputMaskVolume %s", extensions=None,), - inputRadius=dict(argstr="--inputRadius %d",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict( + argstr="--inputMaskVolume %s", + extensions=None, + ), + inputRadius=dict( + argstr="--inputRadius %d", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = ErodeImage.input_spec() @@ -19,7 +35,11 @@ def test_ErodeImage_inputs(): def test_ErodeImage_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = ErodeImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_FlippedDifference.py b/nipype/interfaces/semtools/filtering/tests/test_auto_FlippedDifference.py index 5498ea004d..704bc01820 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_FlippedDifference.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_FlippedDifference.py @@ -4,11 +4,25 @@ def test_FlippedDifference_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMaskVolume=dict(argstr="--inputMaskVolume %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict( + argstr="--inputMaskVolume %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = FlippedDifference.input_spec() @@ -18,7 +32,11 @@ def test_FlippedDifference_inputs(): def test_FlippedDifference_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = FlippedDifference.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateBrainClippedImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateBrainClippedImage.py index 661bd6c1af..e48d622ab3 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateBrainClippedImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateBrainClippedImage.py @@ -4,12 +4,28 @@ def test_GenerateBrainClippedImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputImg=dict(argstr="--inputImg %s", extensions=None,), - inputMsk=dict(argstr="--inputMsk %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputFileName=dict(argstr="--outputFileName %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputImg=dict( + argstr="--inputImg %s", + extensions=None, + ), + inputMsk=dict( + argstr="--inputMsk %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputFileName=dict( + argstr="--outputFileName %s", + hash_files=False, + ), ) inputs = GenerateBrainClippedImage.input_spec() @@ -19,7 +35,11 @@ def test_GenerateBrainClippedImage_inputs(): def test_GenerateBrainClippedImage_outputs(): - output_map = dict(outputFileName=dict(extensions=None,),) + output_map = dict( + outputFileName=dict( + extensions=None, + ), + ) outputs = GenerateBrainClippedImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateSummedGradientImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateSummedGradientImage.py index 2eedb1831c..b53396f396 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateSummedGradientImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateSummedGradientImage.py @@ -4,13 +4,31 @@ def test_GenerateSummedGradientImage_inputs(): input_map = dict( - MaximumGradient=dict(argstr="--MaximumGradient ",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume1=dict(argstr="--inputVolume1 %s", extensions=None,), - inputVolume2=dict(argstr="--inputVolume2 %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputFileName=dict(argstr="--outputFileName %s", hash_files=False,), + MaximumGradient=dict( + argstr="--MaximumGradient ", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr="--inputVolume1 %s", + extensions=None, + ), + inputVolume2=dict( + argstr="--inputVolume2 %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputFileName=dict( + argstr="--outputFileName %s", + hash_files=False, + ), ) inputs = GenerateSummedGradientImage.input_spec() @@ -20,7 +38,11 @@ def test_GenerateSummedGradientImage_inputs(): def test_GenerateSummedGradientImage_outputs(): - output_map = dict(outputFileName=dict(extensions=None,),) + output_map = dict( + outputFileName=dict( + extensions=None, + ), + ) outputs = GenerateSummedGradientImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateTestImage.py b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateTestImage.py index 364ef50be4..c6e8fdfb12 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateTestImage.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_GenerateTestImage.py @@ -4,13 +4,30 @@ def test_GenerateTestImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - lowerBoundOfOutputVolume=dict(argstr="--lowerBoundOfOutputVolume %f",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - outputVolumeSize=dict(argstr="--outputVolumeSize %f",), - upperBoundOfOutputVolume=dict(argstr="--upperBoundOfOutputVolume %f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + lowerBoundOfOutputVolume=dict( + argstr="--lowerBoundOfOutputVolume %f", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + outputVolumeSize=dict( + argstr="--outputVolumeSize %f", + ), + upperBoundOfOutputVolume=dict( + argstr="--upperBoundOfOutputVolume %f", + ), ) inputs = GenerateTestImage.input_spec() @@ -20,7 +37,11 @@ def test_GenerateTestImage_inputs(): def test_GenerateTestImage_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = GenerateTestImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_GradientAnisotropicDiffusionImageFilter.py b/nipype/interfaces/semtools/filtering/tests/test_auto_GradientAnisotropicDiffusionImageFilter.py index 383a836a20..c7828aaccc 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_GradientAnisotropicDiffusionImageFilter.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_GradientAnisotropicDiffusionImageFilter.py @@ -4,13 +4,30 @@ def test_GradientAnisotropicDiffusionImageFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - conductance=dict(argstr="--conductance %f",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfIterations=dict(argstr="--numberOfIterations %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - timeStep=dict(argstr="--timeStep %f",), + args=dict( + argstr="%s", + ), + conductance=dict( + argstr="--conductance %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfIterations=dict( + argstr="--numberOfIterations %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + timeStep=dict( + argstr="--timeStep %f", + ), ) inputs = GradientAnisotropicDiffusionImageFilter.input_spec() @@ -20,7 +37,11 @@ def test_GradientAnisotropicDiffusionImageFilter_inputs(): def test_GradientAnisotropicDiffusionImageFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = GradientAnisotropicDiffusionImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_HammerAttributeCreator.py b/nipype/interfaces/semtools/filtering/tests/test_auto_HammerAttributeCreator.py index 9e77140c41..8188ad0432 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_HammerAttributeCreator.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_HammerAttributeCreator.py @@ -4,14 +4,34 @@ def test_HammerAttributeCreator_inputs(): input_map = dict( - Scale=dict(argstr="--Scale %d",), - Strength=dict(argstr="--Strength %f",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputCSFVolume=dict(argstr="--inputCSFVolume %s", extensions=None,), - inputGMVolume=dict(argstr="--inputGMVolume %s", extensions=None,), - inputWMVolume=dict(argstr="--inputWMVolume %s", extensions=None,), - outputVolumeBase=dict(argstr="--outputVolumeBase %s",), + Scale=dict( + argstr="--Scale %d", + ), + Strength=dict( + argstr="--Strength %f", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputCSFVolume=dict( + argstr="--inputCSFVolume %s", + extensions=None, + ), + inputGMVolume=dict( + argstr="--inputGMVolume %s", + extensions=None, + ), + inputWMVolume=dict( + argstr="--inputWMVolume %s", + extensions=None, + ), + outputVolumeBase=dict( + argstr="--outputVolumeBase %s", + ), ) inputs = HammerAttributeCreator.input_spec() diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMean.py b/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMean.py index 9b4652a60c..839bfe5f11 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMean.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMean.py @@ -4,12 +4,28 @@ def test_NeighborhoodMean_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMaskVolume=dict(argstr="--inputMaskVolume %s", extensions=None,), - inputRadius=dict(argstr="--inputRadius %d",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict( + argstr="--inputMaskVolume %s", + extensions=None, + ), + inputRadius=dict( + argstr="--inputRadius %d", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = NeighborhoodMean.input_spec() @@ -19,7 +35,11 @@ def test_NeighborhoodMean_inputs(): def test_NeighborhoodMean_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = NeighborhoodMean.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMedian.py b/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMedian.py index ae1fc8266d..476a93595e 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMedian.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_NeighborhoodMedian.py @@ -4,12 +4,28 @@ def test_NeighborhoodMedian_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMaskVolume=dict(argstr="--inputMaskVolume %s", extensions=None,), - inputRadius=dict(argstr="--inputRadius %d",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict( + argstr="--inputMaskVolume %s", + extensions=None, + ), + inputRadius=dict( + argstr="--inputRadius %d", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = NeighborhoodMedian.input_spec() @@ -19,7 +35,11 @@ def test_NeighborhoodMedian_inputs(): def test_NeighborhoodMedian_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = NeighborhoodMedian.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_STAPLEAnalysis.py b/nipype/interfaces/semtools/filtering/tests/test_auto_STAPLEAnalysis.py index 9d841a6052..f6ee369414 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_STAPLEAnalysis.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_STAPLEAnalysis.py @@ -4,11 +4,23 @@ def test_STAPLEAnalysis_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputDimension=dict(argstr="--inputDimension %d",), - inputLabelVolume=dict(argstr="--inputLabelVolume %s...",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputDimension=dict( + argstr="--inputDimension %d", + ), + inputLabelVolume=dict( + argstr="--inputLabelVolume %s...", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = STAPLEAnalysis.input_spec() @@ -18,7 +30,11 @@ def test_STAPLEAnalysis_inputs(): def test_STAPLEAnalysis_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = STAPLEAnalysis.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_TextureFromNoiseImageFilter.py b/nipype/interfaces/semtools/filtering/tests/test_auto_TextureFromNoiseImageFilter.py index 9d820afb58..e16d7a9522 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_TextureFromNoiseImageFilter.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_TextureFromNoiseImageFilter.py @@ -4,11 +4,24 @@ def test_TextureFromNoiseImageFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputRadius=dict(argstr="--inputRadius %d",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputRadius=dict( + argstr="--inputRadius %d", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = TextureFromNoiseImageFilter.input_spec() @@ -18,7 +31,11 @@ def test_TextureFromNoiseImageFilter_inputs(): def test_TextureFromNoiseImageFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = TextureFromNoiseImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_TextureMeasureFilter.py b/nipype/interfaces/semtools/filtering/tests/test_auto_TextureMeasureFilter.py index ea9e8843d5..7e6c4f6263 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_TextureMeasureFilter.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_TextureMeasureFilter.py @@ -4,13 +4,31 @@ def test_TextureMeasureFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - distance=dict(argstr="--distance %d",), - environ=dict(nohash=True, usedefault=True,), - inputMaskVolume=dict(argstr="--inputMaskVolume %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - insideROIValue=dict(argstr="--insideROIValue %f",), - outputFilename=dict(argstr="--outputFilename %s", hash_files=False,), + args=dict( + argstr="%s", + ), + distance=dict( + argstr="--distance %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMaskVolume=dict( + argstr="--inputMaskVolume %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + insideROIValue=dict( + argstr="--insideROIValue %f", + ), + outputFilename=dict( + argstr="--outputFilename %s", + hash_files=False, + ), ) inputs = TextureMeasureFilter.input_spec() @@ -20,7 +38,11 @@ def test_TextureMeasureFilter_inputs(): def test_TextureMeasureFilter_outputs(): - output_map = dict(outputFilename=dict(extensions=None,),) + output_map = dict( + outputFilename=dict( + extensions=None, + ), + ) outputs = TextureMeasureFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/filtering/tests/test_auto_UnbiasedNonLocalMeans.py b/nipype/interfaces/semtools/filtering/tests/test_auto_UnbiasedNonLocalMeans.py index 113d9607c2..194d556a8e 100644 --- a/nipype/interfaces/semtools/filtering/tests/test_auto_UnbiasedNonLocalMeans.py +++ b/nipype/interfaces/semtools/filtering/tests/test_auto_UnbiasedNonLocalMeans.py @@ -4,15 +4,40 @@ def test_UnbiasedNonLocalMeans_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - hp=dict(argstr="--hp %f",), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - ps=dict(argstr="--ps %f",), - rc=dict(argstr="--rc %s", sep=",",), - rs=dict(argstr="--rs %s", sep=",",), - sigma=dict(argstr="--sigma %f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hp=dict( + argstr="--hp %f", + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + ps=dict( + argstr="--ps %f", + ), + rc=dict( + argstr="--rc %s", + sep=",", + ), + rs=dict( + argstr="--rs %s", + sep=",", + ), + sigma=dict( + argstr="--sigma %f", + ), ) inputs = UnbiasedNonLocalMeans.input_spec() @@ -22,7 +47,12 @@ def test_UnbiasedNonLocalMeans_inputs(): def test_UnbiasedNonLocalMeans_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = UnbiasedNonLocalMeans.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/legacy/__init__.py b/nipype/interfaces/semtools/legacy/__init__.py index 343704adb7..de11d37760 100644 --- a/nipype/interfaces/semtools/legacy/__init__.py +++ b/nipype/interfaces/semtools/legacy/__init__.py @@ -1,2 +1 @@ -# -*- coding: utf-8 -*- from .registration import scalartransform diff --git a/nipype/interfaces/semtools/legacy/registration.py b/nipype/interfaces/semtools/legacy/registration.py index 9835889040..b0755aff40 100644 --- a/nipype/interfaces/semtools/legacy/registration.py +++ b/nipype/interfaces/semtools/legacy/registration.py @@ -1,26 +1,19 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) class scalartransformInputSpec(CommandLineInputSpec): - input_image = File(desc="Image to tranform", exists=True, argstr="--input_image %s") + input_image = File( + desc="Image to transform", exists=True, argstr="--input_image %s" + ) output_image = traits.Either( traits.Bool, File(), @@ -35,7 +28,7 @@ class scalartransformInputSpec(CommandLineInputSpec): desc="Output file for transformation parameters", argstr="--transformation %s", ) - invert = traits.Bool(desc="Invert tranform before applying.", argstr="--invert ") + invert = traits.Bool(desc="Invert transform before applying.", argstr="--invert ") deformation = File( desc="Deformation field.", exists=True, argstr="--deformation %s" ) @@ -57,21 +50,20 @@ class scalartransformOutputSpec(TraitedSpec): class scalartransform(SEMLikeCommandLine): """title: ScalarTransform (DTIProcess) -category: Legacy.Registration - -version: 1.0.0 + category: Legacy.Registration -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess + version: 1.0.0 -license: Copyright (c) Casey Goodlett. All rights reserved. - See http://www.ia.unc.edu/dev/Copyright.htm for details. - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notices for more information. + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/Nightly/Extensions/DTIProcess -contributor: Casey Goodlett + license: Copyright (c) Casey Goodlett. All rights reserved. + See http://www.ia.unc.edu/dev/Copyright.htm for details. + This software is distributed WITHOUT ANY WARRANTY; without even + the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the above copyright notices for more information. -""" + contributor: Casey Goodlett + """ input_spec = scalartransformInputSpec output_spec = scalartransformOutputSpec diff --git a/nipype/interfaces/semtools/legacy/tests/__init__.py b/nipype/interfaces/semtools/legacy/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/legacy/tests/__init__.py +++ b/nipype/interfaces/semtools/legacy/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/legacy/tests/test_auto_scalartransform.py b/nipype/interfaces/semtools/legacy/tests/test_auto_scalartransform.py index 248c98df3d..6af2e14039 100644 --- a/nipype/interfaces/semtools/legacy/tests/test_auto_scalartransform.py +++ b/nipype/interfaces/semtools/legacy/tests/test_auto_scalartransform.py @@ -4,15 +4,38 @@ def test_scalartransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - deformation=dict(argstr="--deformation %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - h_field=dict(argstr="--h_field ",), - input_image=dict(argstr="--input_image %s", extensions=None,), - interpolation=dict(argstr="--interpolation %s",), - invert=dict(argstr="--invert ",), - output_image=dict(argstr="--output_image %s", hash_files=False,), - transformation=dict(argstr="--transformation %s", hash_files=False,), + args=dict( + argstr="%s", + ), + deformation=dict( + argstr="--deformation %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + h_field=dict( + argstr="--h_field ", + ), + input_image=dict( + argstr="--input_image %s", + extensions=None, + ), + interpolation=dict( + argstr="--interpolation %s", + ), + invert=dict( + argstr="--invert ", + ), + output_image=dict( + argstr="--output_image %s", + hash_files=False, + ), + transformation=dict( + argstr="--transformation %s", + hash_files=False, + ), ) inputs = scalartransform.input_spec() @@ -23,7 +46,12 @@ def test_scalartransform_inputs(): def test_scalartransform_outputs(): output_map = dict( - output_image=dict(extensions=None,), transformation=dict(extensions=None,), + output_image=dict( + extensions=None, + ), + transformation=dict( + extensions=None, + ), ) outputs = scalartransform.output_spec() diff --git a/nipype/interfaces/semtools/registration/__init__.py b/nipype/interfaces/semtools/registration/__init__.py index 6d52169ab3..808e0f67eb 100644 --- a/nipype/interfaces/semtools/registration/__init__.py +++ b/nipype/interfaces/semtools/registration/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .specialized import VBRAINSDemonWarp, BRAINSDemonWarp, BRAINSTransformFromFiducials from .brainsresample import BRAINSResample from .brainsfit import BRAINSFit diff --git a/nipype/interfaces/semtools/registration/brainsfit.py b/nipype/interfaces/semtools/registration/brainsfit.py index 343edd2155..0ed5dd2be9 100644 --- a/nipype/interfaces/semtools/registration/brainsfit.py +++ b/nipype/interfaces/semtools/registration/brainsfit.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -291,7 +283,7 @@ class BRAINSFitInputSpec(CommandLineInputSpec): argstr="--outputTransform %s", ) initializeRegistrationByCurrentGenericTransform = traits.Bool( - desc="If this flag is ON, the current generic composite transform, resulted from the linear registration stages, is set to initialize the follow nonlinear registration process. However, by the default behaviour, the moving image is first warped based on the existant transform before it is passed to the BSpline registration filter. It is done to speed up the BSpline registration by reducing the computations of composite transform Jacobian.", + desc="If this flag is ON, the current generic composite transform, resulted from the linear registration stages, is set to initialize the follow nonlinear registration process. However, by the default behaviour, the moving image is first warped based on the existent transform before it is passed to the BSpline registration filter. It is done to speed up the BSpline registration by reducing the computations of composite transform Jacobian.", argstr="--initializeRegistrationByCurrentGenericTransform ", ) failureExitCode = traits.Int( @@ -327,7 +319,7 @@ class BRAINSFitInputSpec(CommandLineInputSpec): argstr="--maximumNumberOfCorrections %d", ) gui = traits.Bool( - desc="Display intermediate image volumes for debugging. NOTE: This is not part of the standard build sytem, and probably does nothing on your installation.", + desc="Display intermediate image volumes for debugging. NOTE: This is not part of the standard build system, and probably does nothing on your installation.", argstr="--gui ", ) promptUser = traits.Bool( @@ -390,21 +382,20 @@ class BRAINSFitOutputSpec(TraitedSpec): class BRAINSFit(SEMLikeCommandLine): """title: General Registration (BRAINS) -category: Registration - -description: Register a three-dimensional volume to a reference volume (Mattes Mutual Information by default). Full documentation avalable here: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSFit. Method described in BRAINSFit: Mutual Information Registrations of Whole-Brain 3D Images, Using the Insight Toolkit, Johnson H.J., Harris G., Williams K., The Insight Journal, 2007. http://hdl.handle.net/1926/1291 + category: Registration -version: 3.0.0 + description: Register a three-dimensional volume to a reference volume (Mattes Mutual Information by default). Full documentation available here: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSFit. Method described in BRAINSFit: Mutual Information Registrations of Whole-Brain 3D Images, Using the Insight Toolkit, Johnson H.J., Harris G., Williams K., The Insight Journal, 2007. http://hdl.handle.net/1926/1291 -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSFit + version: 3.0.0 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSFit -contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://www.psychiatry.uiowa.edu + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); Gregory Harris(1), Vincent Magnotta(1,2,3); Andriy Fedorov(5) 1=University of Iowa Department of Psychiatry, 2=University of Iowa Department of Radiology, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering, 5=Surgical Planning Lab, Harvard + contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://www.psychiatry.uiowa.edu -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); Gregory Harris(1), Vincent Magnotta(1,2,3); Andriy Fedorov(5) 1=University of Iowa Department of Psychiatry, 2=University of Iowa Department of Radiology, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering, 5=Surgical Planning Lab, Harvard + """ input_spec = BRAINSFitInputSpec output_spec = BRAINSFitOutputSpec diff --git a/nipype/interfaces/semtools/registration/brainsresample.py b/nipype/interfaces/semtools/registration/brainsresample.py index 0eb6b5f29c..37f2eeb69b 100644 --- a/nipype/interfaces/semtools/registration/brainsresample.py +++ b/nipype/interfaces/semtools/registration/brainsresample.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -75,7 +67,7 @@ class BRAINSResampleInputSpec(CommandLineInputSpec): defaultValue = traits.Float(desc="Default voxel value", argstr="--defaultValue %f") gridSpacing = InputMultiPath( traits.Int, - desc="Add warped grid to output image to help show the deformation that occured with specified spacing. A spacing of 0 in a dimension indicates that grid lines should be rendered to fall exactly (i.e. do not allow displacements off that plane). This is useful for makeing a 2D image of grid lines from the 3D space", + desc="Add warped grid to output image to help show the deformation that occurred with specified spacing. A spacing of 0 in a dimension indicates that grid lines should be rendered to fall exactly (i.e. do not allow displacements off that plane). This is useful for making a 2D image of grid lines from the 3D space", sep=",", argstr="--gridSpacing %s", ) @@ -92,21 +84,20 @@ class BRAINSResampleOutputSpec(TraitedSpec): class BRAINSResample(SEMLikeCommandLine): """title: Resample Image (BRAINS) -category: Registration - -description: This program collects together three common image processing tasks that all involve resampling an image volume: Resampling to a new resolution and spacing, applying a transformation (using an ITK transform IO mechanisms) and Warping (using a vector image deformation field). Full documentation available here: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSResample. + category: Registration -version: 3.0.0 + description: This program collects together three common image processing tasks that all involve resampling an image volume: Resampling to a new resolution and spacing, applying a transformation (using an ITK transform IO mechanisms) and Warping (using a vector image deformation field). Full documentation available here: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSResample. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSResample + version: 3.0.0 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSResample -contributor: This tool was developed by Vincent Magnotta, Greg Harris, and Hans Johnson. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + contributor: This tool was developed by Vincent Magnotta, Greg Harris, and Hans Johnson. -""" + acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + """ input_spec = BRAINSResampleInputSpec output_spec = BRAINSResampleOutputSpec diff --git a/nipype/interfaces/semtools/registration/brainsresize.py b/nipype/interfaces/semtools/registration/brainsresize.py index a81ee204b5..f86d7d9e62 100644 --- a/nipype/interfaces/semtools/registration/brainsresize.py +++ b/nipype/interfaces/semtools/registration/brainsresize.py @@ -1,21 +1,12 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) @@ -51,19 +42,18 @@ class BRAINSResizeOutputSpec(TraitedSpec): class BRAINSResize(SEMLikeCommandLine): """title: Resize Image (BRAINS) -category: Registration - -description: This program is useful for downsampling an image by a constant scale factor. + category: Registration -version: 3.0.0 + description: This program is useful for downsampling an image by a constant scale factor. -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 3.0.0 -contributor: This tool was developed by Hans Johnson. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + contributor: This tool was developed by Hans Johnson. -""" + acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + """ input_spec = BRAINSResizeInputSpec output_spec = BRAINSResizeOutputSpec diff --git a/nipype/interfaces/semtools/registration/specialized.py b/nipype/interfaces/semtools/registration/specialized.py index 5a6daf5250..68a6a0b993 100644 --- a/nipype/interfaces/semtools/registration/specialized.py +++ b/nipype/interfaces/semtools/registration/specialized.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) @@ -86,7 +78,7 @@ class VBRAINSDemonWarpInputSpec(CommandLineInputSpec): argstr="--registrationFilterType %s", ) smoothDisplacementFieldSigma = traits.Float( - desc="A gaussian smoothing value to be applied to the deformation feild at each iteration.", + desc="A gaussian smoothing value to be applied to the deformation field at each iteration.", argstr="--smoothDisplacementFieldSigma %f", ) numberOfPyramidLevels = traits.Int( @@ -257,21 +249,20 @@ class VBRAINSDemonWarpOutputSpec(TraitedSpec): class VBRAINSDemonWarp(SEMLikeCommandLine): """title: Vector Demon Registration (BRAINS) -category: Registration.Specialized - -description: This program finds a deformation field to warp a moving image onto a fixed image. The images must be of the same signal kind, and contain an image of the same kind of object. This program uses the Thirion Demons warp software in ITK, the Insight Toolkit. Additional information is available at: http://www.nitrc.org/projects/brainsdemonwarp. + category: Registration.Specialized -version: 3.0.0 + description: This program finds a deformation field to warp a moving image onto a fixed image. The images must be of the same signal kind, and contain an image of the same kind of object. This program uses the Thirion Demons warp software in ITK, the Insight Toolkit. Additional information is available at: http://www.nitrc.org/projects/brainsdemonwarp. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSDemonWarp + version: 3.0.0 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSDemonWarp -contributor: This tool was developed by Hans J. Johnson and Greg Harris. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + contributor: This tool was developed by Hans J. Johnson and Greg Harris. -""" + acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + """ input_spec = VBRAINSDemonWarpInputSpec output_spec = VBRAINSDemonWarpOutputSpec @@ -347,7 +338,7 @@ class BRAINSDemonWarpInputSpec(CommandLineInputSpec): argstr="--registrationFilterType %s", ) smoothDisplacementFieldSigma = traits.Float( - desc="A gaussian smoothing value to be applied to the deformation feild at each iteration.", + desc="A gaussian smoothing value to be applied to the deformation field at each iteration.", argstr="--smoothDisplacementFieldSigma %f", ) numberOfPyramidLevels = traits.Int( @@ -404,7 +395,7 @@ class BRAINSDemonWarpInputSpec(CommandLineInputSpec): "ROIAUTO", "ROI", "BOBF", - desc="What mode to use for using the masks: NOMASK|ROIAUTO|ROI|BOBF. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. Where the Region Of Interest mode uses the masks to define what parts of the image should be used for computing the deformation field. Brain Only Background Fill uses the masks to pre-process the input images by clipping and filling in the background with a predefined value.", + desc="What mode to use for using the masks: NOMASK|ROIAUTO|ROI|BOBF. If ROIAUTO is chosen, then the mask is implicitly defined using a otsu foreground and hole filling algorithm. Where the Region Of Interest mode uses the masks to define what parts of the image should be used for computing the deformation field. Brain Only Background Fill uses the masks to pre-process the input images by clipping and filling in the background with a predefined value.", argstr="--maskProcessingMode %s", ) fixedBinaryVolume = File( @@ -516,21 +507,20 @@ class BRAINSDemonWarpOutputSpec(TraitedSpec): class BRAINSDemonWarp(SEMLikeCommandLine): """title: Demon Registration (BRAINS) -category: Registration.Specialized + category: Registration.Specialized -description: This program finds a deformation field to warp a moving image onto a fixed image. The images must be of the same signal kind, and contain an image of the same kind of object. This program uses the Thirion Demons warp software in ITK, the Insight Toolkit. Additional information is available at: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSDemonWarp. + description: This program finds a deformation field to warp a moving image onto a fixed image. The images must be of the same signal kind, and contain an image of the same kind of object. This program uses the Thirion Demons warp software in ITK, the Insight Toolkit. Additional information is available at: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSDemonWarp. -version: 3.0.0 + version: 3.0.0 -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSDemonWarp + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BRAINSDemonWarp -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Hans J. Johnson and Greg Harris. + contributor: This tool was developed by Hans J. Johnson and Greg Harris. -acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. - -""" + acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + """ input_spec = BRAINSDemonWarpInputSpec output_spec = BRAINSDemonWarpOutputSpec @@ -593,19 +583,18 @@ class BRAINSTransformFromFiducialsOutputSpec(TraitedSpec): class BRAINSTransformFromFiducials(SEMLikeCommandLine): """title: Fiducial Registration (BRAINS) -category: Registration.Specialized - -description: Computes a rigid, similarity or affine transform from a matched list of fiducials + category: Registration.Specialized -version: 0.1.0.$Revision$ + description: Computes a rigid, similarity or affine transform from a matched list of fiducials -documentation-url: http://www.slicer.org/slicerWiki/index.php/Modules:TransformFromFiducials-Documentation-3.6 + version: 0.1.0.$Revision$ -contributor: Casey B Goodlett + documentation-url: http://www.slicer.org/slicerWiki/index.php/Modules:TransformFromFiducials-Documentation-3.6 -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Casey B Goodlett -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = BRAINSTransformFromFiducialsInputSpec output_spec = BRAINSTransformFromFiducialsOutputSpec diff --git a/nipype/interfaces/semtools/registration/tests/__init__.py b/nipype/interfaces/semtools/registration/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/registration/tests/__init__.py +++ b/nipype/interfaces/semtools/registration/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSDemonWarp.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSDemonWarp.py index 4136c8105d..d1c8055df3 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSDemonWarp.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSDemonWarp.py @@ -4,64 +4,149 @@ def test_BRAINSDemonWarp_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), arrayOfPyramidLevelIterations=dict( - argstr="--arrayOfPyramidLevelIterations %s", sep=",", + argstr="--arrayOfPyramidLevelIterations %s", + sep=",", + ), + backgroundFillValue=dict( + argstr="--backgroundFillValue %d", ), - backgroundFillValue=dict(argstr="--backgroundFillValue %d",), checkerboardPatternSubdivisions=dict( - argstr="--checkerboardPatternSubdivisions %s", sep=",", - ), - environ=dict(nohash=True, usedefault=True,), - fixedBinaryVolume=dict(argstr="--fixedBinaryVolume %s", extensions=None,), - fixedVolume=dict(argstr="--fixedVolume %s", extensions=None,), - gradient_type=dict(argstr="--gradient_type %s",), - gui=dict(argstr="--gui ",), - histogramMatch=dict(argstr="--histogramMatch ",), + argstr="--checkerboardPatternSubdivisions %s", + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedBinaryVolume=dict( + argstr="--fixedBinaryVolume %s", + extensions=None, + ), + fixedVolume=dict( + argstr="--fixedVolume %s", + extensions=None, + ), + gradient_type=dict( + argstr="--gradient_type %s", + ), + gui=dict( + argstr="--gui ", + ), + histogramMatch=dict( + argstr="--histogramMatch ", + ), initializeWithDisplacementField=dict( - argstr="--initializeWithDisplacementField %s", extensions=None, + argstr="--initializeWithDisplacementField %s", + extensions=None, ), initializeWithTransform=dict( - argstr="--initializeWithTransform %s", extensions=None, - ), - inputPixelType=dict(argstr="--inputPixelType %s",), - interpolationMode=dict(argstr="--interpolationMode %s",), - lowerThresholdForBOBF=dict(argstr="--lowerThresholdForBOBF %d",), - maskProcessingMode=dict(argstr="--maskProcessingMode %s",), - max_step_length=dict(argstr="--max_step_length %f",), - medianFilterSize=dict(argstr="--medianFilterSize %s", sep=",",), - minimumFixedPyramid=dict(argstr="--minimumFixedPyramid %s", sep=",",), - minimumMovingPyramid=dict(argstr="--minimumMovingPyramid %s", sep=",",), - movingBinaryVolume=dict(argstr="--movingBinaryVolume %s", extensions=None,), - movingVolume=dict(argstr="--movingVolume %s", extensions=None,), - neighborhoodForBOBF=dict(argstr="--neighborhoodForBOBF %s", sep=",",), + argstr="--initializeWithTransform %s", + extensions=None, + ), + inputPixelType=dict( + argstr="--inputPixelType %s", + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + lowerThresholdForBOBF=dict( + argstr="--lowerThresholdForBOBF %d", + ), + maskProcessingMode=dict( + argstr="--maskProcessingMode %s", + ), + max_step_length=dict( + argstr="--max_step_length %f", + ), + medianFilterSize=dict( + argstr="--medianFilterSize %s", + sep=",", + ), + minimumFixedPyramid=dict( + argstr="--minimumFixedPyramid %s", + sep=",", + ), + minimumMovingPyramid=dict( + argstr="--minimumMovingPyramid %s", + sep=",", + ), + movingBinaryVolume=dict( + argstr="--movingBinaryVolume %s", + extensions=None, + ), + movingVolume=dict( + argstr="--movingVolume %s", + extensions=None, + ), + neighborhoodForBOBF=dict( + argstr="--neighborhoodForBOBF %s", + sep=",", + ), numberOfBCHApproximationTerms=dict( argstr="--numberOfBCHApproximationTerms %d", ), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - numberOfMatchPoints=dict(argstr="--numberOfMatchPoints %d",), - numberOfPyramidLevels=dict(argstr="--numberOfPyramidLevels %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + numberOfMatchPoints=dict( + argstr="--numberOfMatchPoints %d", + ), + numberOfPyramidLevels=dict( + argstr="--numberOfPyramidLevels %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), outputCheckerboardVolume=dict( - argstr="--outputCheckerboardVolume %s", hash_files=False, + argstr="--outputCheckerboardVolume %s", + hash_files=False, + ), + outputDebug=dict( + argstr="--outputDebug ", ), - outputDebug=dict(argstr="--outputDebug ",), outputDisplacementFieldPrefix=dict( argstr="--outputDisplacementFieldPrefix %s", ), outputDisplacementFieldVolume=dict( - argstr="--outputDisplacementFieldVolume %s", hash_files=False, - ), - outputNormalized=dict(argstr="--outputNormalized ",), - outputPixelType=dict(argstr="--outputPixelType %s",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - promptUser=dict(argstr="--promptUser ",), - registrationFilterType=dict(argstr="--registrationFilterType %s",), - seedForBOBF=dict(argstr="--seedForBOBF %s", sep=",",), - smoothDisplacementFieldSigma=dict(argstr="--smoothDisplacementFieldSigma %f",), - upFieldSmoothing=dict(argstr="--upFieldSmoothing %f",), - upperThresholdForBOBF=dict(argstr="--upperThresholdForBOBF %d",), - use_vanilla_dem=dict(argstr="--use_vanilla_dem ",), + argstr="--outputDisplacementFieldVolume %s", + hash_files=False, + ), + outputNormalized=dict( + argstr="--outputNormalized ", + ), + outputPixelType=dict( + argstr="--outputPixelType %s", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + promptUser=dict( + argstr="--promptUser ", + ), + registrationFilterType=dict( + argstr="--registrationFilterType %s", + ), + seedForBOBF=dict( + argstr="--seedForBOBF %s", + sep=",", + ), + smoothDisplacementFieldSigma=dict( + argstr="--smoothDisplacementFieldSigma %f", + ), + upFieldSmoothing=dict( + argstr="--upFieldSmoothing %f", + ), + upperThresholdForBOBF=dict( + argstr="--upperThresholdForBOBF %d", + ), + use_vanilla_dem=dict( + argstr="--use_vanilla_dem ", + ), ) inputs = BRAINSDemonWarp.input_spec() @@ -72,9 +157,15 @@ def test_BRAINSDemonWarp_inputs(): def test_BRAINSDemonWarp_outputs(): output_map = dict( - outputCheckerboardVolume=dict(extensions=None,), - outputDisplacementFieldVolume=dict(extensions=None,), - outputVolume=dict(extensions=None,), + outputCheckerboardVolume=dict( + extensions=None, + ), + outputDisplacementFieldVolume=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), ) outputs = BRAINSDemonWarp.output_spec() diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSFit.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSFit.py index 683d34694b..69111d9212 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSFit.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSFit.py @@ -4,83 +4,228 @@ def test_BRAINSFit_inputs(): input_map = dict( - ROIAutoClosingSize=dict(argstr="--ROIAutoClosingSize %f",), - ROIAutoDilateSize=dict(argstr="--ROIAutoDilateSize %f",), - args=dict(argstr="%s",), - backgroundFillValue=dict(argstr="--backgroundFillValue %f",), - bsplineTransform=dict(argstr="--bsplineTransform %s", hash_files=False,), + ROIAutoClosingSize=dict( + argstr="--ROIAutoClosingSize %f", + ), + ROIAutoDilateSize=dict( + argstr="--ROIAutoDilateSize %f", + ), + args=dict( + argstr="%s", + ), + backgroundFillValue=dict( + argstr="--backgroundFillValue %f", + ), + bsplineTransform=dict( + argstr="--bsplineTransform %s", + hash_files=False, + ), costFunctionConvergenceFactor=dict( argstr="--costFunctionConvergenceFactor %f", ), - costMetric=dict(argstr="--costMetric %s",), - debugLevel=dict(argstr="--debugLevel %d",), - environ=dict(nohash=True, usedefault=True,), - failureExitCode=dict(argstr="--failureExitCode %d",), - fixedBinaryVolume=dict(argstr="--fixedBinaryVolume %s", extensions=None,), - fixedVolume=dict(argstr="--fixedVolume %s", extensions=None,), - fixedVolume2=dict(argstr="--fixedVolume2 %s", extensions=None,), - fixedVolumeTimeIndex=dict(argstr="--fixedVolumeTimeIndex %d",), - gui=dict(argstr="--gui ",), - histogramMatch=dict(argstr="--histogramMatch ",), - initialTransform=dict(argstr="--initialTransform %s", extensions=None,), + costMetric=dict( + argstr="--costMetric %s", + ), + debugLevel=dict( + argstr="--debugLevel %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + failureExitCode=dict( + argstr="--failureExitCode %d", + ), + fixedBinaryVolume=dict( + argstr="--fixedBinaryVolume %s", + extensions=None, + ), + fixedVolume=dict( + argstr="--fixedVolume %s", + extensions=None, + ), + fixedVolume2=dict( + argstr="--fixedVolume2 %s", + extensions=None, + ), + fixedVolumeTimeIndex=dict( + argstr="--fixedVolumeTimeIndex %d", + ), + gui=dict( + argstr="--gui ", + ), + histogramMatch=dict( + argstr="--histogramMatch ", + ), + initialTransform=dict( + argstr="--initialTransform %s", + extensions=None, + ), initializeRegistrationByCurrentGenericTransform=dict( argstr="--initializeRegistrationByCurrentGenericTransform ", ), - initializeTransformMode=dict(argstr="--initializeTransformMode %s",), - interpolationMode=dict(argstr="--interpolationMode %s",), - linearTransform=dict(argstr="--linearTransform %s", hash_files=False,), - logFileReport=dict(argstr="--logFileReport %s", hash_files=False,), - maskInferiorCutOffFromCenter=dict(argstr="--maskInferiorCutOffFromCenter %f",), - maskProcessingMode=dict(argstr="--maskProcessingMode %s",), - maxBSplineDisplacement=dict(argstr="--maxBSplineDisplacement %f",), - maximumNumberOfCorrections=dict(argstr="--maximumNumberOfCorrections %d",), - maximumNumberOfEvaluations=dict(argstr="--maximumNumberOfEvaluations %d",), - maximumStepLength=dict(argstr="--maximumStepLength %f",), - medianFilterSize=dict(argstr="--medianFilterSize %s", sep=",",), - metricSamplingStrategy=dict(argstr="--metricSamplingStrategy %s",), - minimumStepLength=dict(argstr="--minimumStepLength %s", sep=",",), - movingBinaryVolume=dict(argstr="--movingBinaryVolume %s", extensions=None,), - movingVolume=dict(argstr="--movingVolume %s", extensions=None,), - movingVolume2=dict(argstr="--movingVolume2 %s", extensions=None,), - movingVolumeTimeIndex=dict(argstr="--movingVolumeTimeIndex %d",), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - numberOfIterations=dict(argstr="--numberOfIterations %s", sep=",",), - numberOfMatchPoints=dict(argstr="--numberOfMatchPoints %d",), - numberOfSamples=dict(argstr="--numberOfSamples %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + initializeTransformMode=dict( + argstr="--initializeTransformMode %s", + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + linearTransform=dict( + argstr="--linearTransform %s", + hash_files=False, + ), + logFileReport=dict( + argstr="--logFileReport %s", + hash_files=False, + ), + maskInferiorCutOffFromCenter=dict( + argstr="--maskInferiorCutOffFromCenter %f", + ), + maskProcessingMode=dict( + argstr="--maskProcessingMode %s", + ), + maxBSplineDisplacement=dict( + argstr="--maxBSplineDisplacement %f", + ), + maximumNumberOfCorrections=dict( + argstr="--maximumNumberOfCorrections %d", + ), + maximumNumberOfEvaluations=dict( + argstr="--maximumNumberOfEvaluations %d", + ), + maximumStepLength=dict( + argstr="--maximumStepLength %f", + ), + medianFilterSize=dict( + argstr="--medianFilterSize %s", + sep=",", + ), + metricSamplingStrategy=dict( + argstr="--metricSamplingStrategy %s", + ), + minimumStepLength=dict( + argstr="--minimumStepLength %s", + sep=",", + ), + movingBinaryVolume=dict( + argstr="--movingBinaryVolume %s", + extensions=None, + ), + movingVolume=dict( + argstr="--movingVolume %s", + extensions=None, + ), + movingVolume2=dict( + argstr="--movingVolume2 %s", + extensions=None, + ), + movingVolumeTimeIndex=dict( + argstr="--movingVolumeTimeIndex %d", + ), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + numberOfIterations=dict( + argstr="--numberOfIterations %s", + sep=",", + ), + numberOfMatchPoints=dict( + argstr="--numberOfMatchPoints %d", + ), + numberOfSamples=dict( + argstr="--numberOfSamples %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), outputFixedVolumeROI=dict( - argstr="--outputFixedVolumeROI %s", hash_files=False, + argstr="--outputFixedVolumeROI %s", + hash_files=False, ), outputMovingVolumeROI=dict( - argstr="--outputMovingVolumeROI %s", hash_files=False, - ), - outputTransform=dict(argstr="--outputTransform %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - outputVolumePixelType=dict(argstr="--outputVolumePixelType %s",), - projectedGradientTolerance=dict(argstr="--projectedGradientTolerance %f",), - promptUser=dict(argstr="--promptUser ",), - relaxationFactor=dict(argstr="--relaxationFactor %f",), - removeIntensityOutliers=dict(argstr="--removeIntensityOutliers %f",), - reproportionScale=dict(argstr="--reproportionScale %f",), - samplingPercentage=dict(argstr="--samplingPercentage %f",), - scaleOutputValues=dict(argstr="--scaleOutputValues ",), - skewScale=dict(argstr="--skewScale %f",), - splineGridSize=dict(argstr="--splineGridSize %s", sep=",",), + argstr="--outputMovingVolumeROI %s", + hash_files=False, + ), + outputTransform=dict( + argstr="--outputTransform %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + outputVolumePixelType=dict( + argstr="--outputVolumePixelType %s", + ), + projectedGradientTolerance=dict( + argstr="--projectedGradientTolerance %f", + ), + promptUser=dict( + argstr="--promptUser ", + ), + relaxationFactor=dict( + argstr="--relaxationFactor %f", + ), + removeIntensityOutliers=dict( + argstr="--removeIntensityOutliers %f", + ), + reproportionScale=dict( + argstr="--reproportionScale %f", + ), + samplingPercentage=dict( + argstr="--samplingPercentage %f", + ), + scaleOutputValues=dict( + argstr="--scaleOutputValues ", + ), + skewScale=dict( + argstr="--skewScale %f", + ), + splineGridSize=dict( + argstr="--splineGridSize %s", + sep=",", + ), strippedOutputTransform=dict( - argstr="--strippedOutputTransform %s", hash_files=False, - ), - transformType=dict(argstr="--transformType %s", sep=",",), - translationScale=dict(argstr="--translationScale %f",), - useAffine=dict(argstr="--useAffine ",), - useBSpline=dict(argstr="--useBSpline ",), - useComposite=dict(argstr="--useComposite ",), - useROIBSpline=dict(argstr="--useROIBSpline ",), - useRigid=dict(argstr="--useRigid ",), - useScaleSkewVersor3D=dict(argstr="--useScaleSkewVersor3D ",), - useScaleVersor3D=dict(argstr="--useScaleVersor3D ",), - useSyN=dict(argstr="--useSyN ",), - writeOutputTransformInFloat=dict(argstr="--writeOutputTransformInFloat ",), - writeTransformOnFailure=dict(argstr="--writeTransformOnFailure ",), + argstr="--strippedOutputTransform %s", + hash_files=False, + ), + transformType=dict( + argstr="--transformType %s", + sep=",", + ), + translationScale=dict( + argstr="--translationScale %f", + ), + useAffine=dict( + argstr="--useAffine ", + ), + useBSpline=dict( + argstr="--useBSpline ", + ), + useComposite=dict( + argstr="--useComposite ", + ), + useROIBSpline=dict( + argstr="--useROIBSpline ", + ), + useRigid=dict( + argstr="--useRigid ", + ), + useScaleSkewVersor3D=dict( + argstr="--useScaleSkewVersor3D ", + ), + useScaleVersor3D=dict( + argstr="--useScaleVersor3D ", + ), + useSyN=dict( + argstr="--useSyN ", + ), + writeOutputTransformInFloat=dict( + argstr="--writeOutputTransformInFloat ", + ), + writeTransformOnFailure=dict( + argstr="--writeTransformOnFailure ", + ), ) inputs = BRAINSFit.input_spec() @@ -91,14 +236,30 @@ def test_BRAINSFit_inputs(): def test_BRAINSFit_outputs(): output_map = dict( - bsplineTransform=dict(extensions=None,), - linearTransform=dict(extensions=None,), - logFileReport=dict(extensions=None,), - outputFixedVolumeROI=dict(extensions=None,), - outputMovingVolumeROI=dict(extensions=None,), - outputTransform=dict(extensions=None,), - outputVolume=dict(extensions=None,), - strippedOutputTransform=dict(extensions=None,), + bsplineTransform=dict( + extensions=None, + ), + linearTransform=dict( + extensions=None, + ), + logFileReport=dict( + extensions=None, + ), + outputFixedVolumeROI=dict( + extensions=None, + ), + outputMovingVolumeROI=dict( + extensions=None, + ), + outputTransform=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), + strippedOutputTransform=dict( + extensions=None, + ), ) outputs = BRAINSFit.output_spec() diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResample.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResample.py index 2d94f19a5f..46d175da07 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResample.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResample.py @@ -4,19 +4,52 @@ def test_BRAINSResample_inputs(): input_map = dict( - args=dict(argstr="%s",), - defaultValue=dict(argstr="--defaultValue %f",), - deformationVolume=dict(argstr="--deformationVolume %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - gridSpacing=dict(argstr="--gridSpacing %s", sep=",",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - interpolationMode=dict(argstr="--interpolationMode %s",), - inverseTransform=dict(argstr="--inverseTransform ",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - pixelType=dict(argstr="--pixelType %s",), - referenceVolume=dict(argstr="--referenceVolume %s", extensions=None,), - warpTransform=dict(argstr="--warpTransform %s", extensions=None,), + args=dict( + argstr="%s", + ), + defaultValue=dict( + argstr="--defaultValue %f", + ), + deformationVolume=dict( + argstr="--deformationVolume %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gridSpacing=dict( + argstr="--gridSpacing %s", + sep=",", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + inverseTransform=dict( + argstr="--inverseTransform ", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + pixelType=dict( + argstr="--pixelType %s", + ), + referenceVolume=dict( + argstr="--referenceVolume %s", + extensions=None, + ), + warpTransform=dict( + argstr="--warpTransform %s", + extensions=None, + ), ) inputs = BRAINSResample.input_spec() @@ -26,7 +59,11 @@ def test_BRAINSResample_inputs(): def test_BRAINSResample_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResize.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResize.py index db477b2593..52d24e6fff 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResize.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSResize.py @@ -4,12 +4,27 @@ def test_BRAINSResize_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - pixelType=dict(argstr="--pixelType %s",), - scaleFactor=dict(argstr="--scaleFactor %f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + pixelType=dict( + argstr="--pixelType %s", + ), + scaleFactor=dict( + argstr="--scaleFactor %f", + ), ) inputs = BRAINSResize.input_spec() @@ -19,7 +34,11 @@ def test_BRAINSResize_inputs(): def test_BRAINSResize_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSResize.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSTransformFromFiducials.py b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSTransformFromFiducials.py index 4e5c6ae239..bc98fc2763 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSTransformFromFiducials.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_BRAINSTransformFromFiducials.py @@ -4,15 +4,37 @@ def test_BRAINSTransformFromFiducials_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixedLandmarks=dict(argstr="--fixedLandmarks %s...",), - fixedLandmarksFile=dict(argstr="--fixedLandmarksFile %s", extensions=None,), - movingLandmarks=dict(argstr="--movingLandmarks %s...",), - movingLandmarksFile=dict(argstr="--movingLandmarksFile %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - saveTransform=dict(argstr="--saveTransform %s", hash_files=False,), - transformType=dict(argstr="--transformType %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedLandmarks=dict( + argstr="--fixedLandmarks %s...", + ), + fixedLandmarksFile=dict( + argstr="--fixedLandmarksFile %s", + extensions=None, + ), + movingLandmarks=dict( + argstr="--movingLandmarks %s...", + ), + movingLandmarksFile=dict( + argstr="--movingLandmarksFile %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + saveTransform=dict( + argstr="--saveTransform %s", + hash_files=False, + ), + transformType=dict( + argstr="--transformType %s", + ), ) inputs = BRAINSTransformFromFiducials.input_spec() @@ -22,7 +44,11 @@ def test_BRAINSTransformFromFiducials_inputs(): def test_BRAINSTransformFromFiducials_outputs(): - output_map = dict(saveTransform=dict(extensions=None,),) + output_map = dict( + saveTransform=dict( + extensions=None, + ), + ) outputs = BRAINSTransformFromFiducials.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/registration/tests/test_auto_VBRAINSDemonWarp.py b/nipype/interfaces/semtools/registration/tests/test_auto_VBRAINSDemonWarp.py index 098360c1e3..af8bac8680 100644 --- a/nipype/interfaces/semtools/registration/tests/test_auto_VBRAINSDemonWarp.py +++ b/nipype/interfaces/semtools/registration/tests/test_auto_VBRAINSDemonWarp.py @@ -4,65 +4,151 @@ def test_VBRAINSDemonWarp_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), arrayOfPyramidLevelIterations=dict( - argstr="--arrayOfPyramidLevelIterations %s", sep=",", + argstr="--arrayOfPyramidLevelIterations %s", + sep=",", + ), + backgroundFillValue=dict( + argstr="--backgroundFillValue %d", ), - backgroundFillValue=dict(argstr="--backgroundFillValue %d",), checkerboardPatternSubdivisions=dict( - argstr="--checkerboardPatternSubdivisions %s", sep=",", - ), - environ=dict(nohash=True, usedefault=True,), - fixedBinaryVolume=dict(argstr="--fixedBinaryVolume %s", extensions=None,), - fixedVolume=dict(argstr="--fixedVolume %s...",), - gradient_type=dict(argstr="--gradient_type %s",), - gui=dict(argstr="--gui ",), - histogramMatch=dict(argstr="--histogramMatch ",), + argstr="--checkerboardPatternSubdivisions %s", + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedBinaryVolume=dict( + argstr="--fixedBinaryVolume %s", + extensions=None, + ), + fixedVolume=dict( + argstr="--fixedVolume %s...", + ), + gradient_type=dict( + argstr="--gradient_type %s", + ), + gui=dict( + argstr="--gui ", + ), + histogramMatch=dict( + argstr="--histogramMatch ", + ), initializeWithDisplacementField=dict( - argstr="--initializeWithDisplacementField %s", extensions=None, + argstr="--initializeWithDisplacementField %s", + extensions=None, ), initializeWithTransform=dict( - argstr="--initializeWithTransform %s", extensions=None, - ), - inputPixelType=dict(argstr="--inputPixelType %s",), - interpolationMode=dict(argstr="--interpolationMode %s",), - lowerThresholdForBOBF=dict(argstr="--lowerThresholdForBOBF %d",), - makeBOBF=dict(argstr="--makeBOBF ",), - max_step_length=dict(argstr="--max_step_length %f",), - medianFilterSize=dict(argstr="--medianFilterSize %s", sep=",",), - minimumFixedPyramid=dict(argstr="--minimumFixedPyramid %s", sep=",",), - minimumMovingPyramid=dict(argstr="--minimumMovingPyramid %s", sep=",",), - movingBinaryVolume=dict(argstr="--movingBinaryVolume %s", extensions=None,), - movingVolume=dict(argstr="--movingVolume %s...",), - neighborhoodForBOBF=dict(argstr="--neighborhoodForBOBF %s", sep=",",), + argstr="--initializeWithTransform %s", + extensions=None, + ), + inputPixelType=dict( + argstr="--inputPixelType %s", + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + lowerThresholdForBOBF=dict( + argstr="--lowerThresholdForBOBF %d", + ), + makeBOBF=dict( + argstr="--makeBOBF ", + ), + max_step_length=dict( + argstr="--max_step_length %f", + ), + medianFilterSize=dict( + argstr="--medianFilterSize %s", + sep=",", + ), + minimumFixedPyramid=dict( + argstr="--minimumFixedPyramid %s", + sep=",", + ), + minimumMovingPyramid=dict( + argstr="--minimumMovingPyramid %s", + sep=",", + ), + movingBinaryVolume=dict( + argstr="--movingBinaryVolume %s", + extensions=None, + ), + movingVolume=dict( + argstr="--movingVolume %s...", + ), + neighborhoodForBOBF=dict( + argstr="--neighborhoodForBOBF %s", + sep=",", + ), numberOfBCHApproximationTerms=dict( argstr="--numberOfBCHApproximationTerms %d", ), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - numberOfMatchPoints=dict(argstr="--numberOfMatchPoints %d",), - numberOfPyramidLevels=dict(argstr="--numberOfPyramidLevels %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + numberOfMatchPoints=dict( + argstr="--numberOfMatchPoints %d", + ), + numberOfPyramidLevels=dict( + argstr="--numberOfPyramidLevels %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), outputCheckerboardVolume=dict( - argstr="--outputCheckerboardVolume %s", hash_files=False, + argstr="--outputCheckerboardVolume %s", + hash_files=False, + ), + outputDebug=dict( + argstr="--outputDebug ", ), - outputDebug=dict(argstr="--outputDebug ",), outputDisplacementFieldPrefix=dict( argstr="--outputDisplacementFieldPrefix %s", ), outputDisplacementFieldVolume=dict( - argstr="--outputDisplacementFieldVolume %s", hash_files=False, - ), - outputNormalized=dict(argstr="--outputNormalized ",), - outputPixelType=dict(argstr="--outputPixelType %s",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - promptUser=dict(argstr="--promptUser ",), - registrationFilterType=dict(argstr="--registrationFilterType %s",), - seedForBOBF=dict(argstr="--seedForBOBF %s", sep=",",), - smoothDisplacementFieldSigma=dict(argstr="--smoothDisplacementFieldSigma %f",), - upFieldSmoothing=dict(argstr="--upFieldSmoothing %f",), - upperThresholdForBOBF=dict(argstr="--upperThresholdForBOBF %d",), - use_vanilla_dem=dict(argstr="--use_vanilla_dem ",), - weightFactors=dict(argstr="--weightFactors %s", sep=",",), + argstr="--outputDisplacementFieldVolume %s", + hash_files=False, + ), + outputNormalized=dict( + argstr="--outputNormalized ", + ), + outputPixelType=dict( + argstr="--outputPixelType %s", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + promptUser=dict( + argstr="--promptUser ", + ), + registrationFilterType=dict( + argstr="--registrationFilterType %s", + ), + seedForBOBF=dict( + argstr="--seedForBOBF %s", + sep=",", + ), + smoothDisplacementFieldSigma=dict( + argstr="--smoothDisplacementFieldSigma %f", + ), + upFieldSmoothing=dict( + argstr="--upFieldSmoothing %f", + ), + upperThresholdForBOBF=dict( + argstr="--upperThresholdForBOBF %d", + ), + use_vanilla_dem=dict( + argstr="--use_vanilla_dem ", + ), + weightFactors=dict( + argstr="--weightFactors %s", + sep=",", + ), ) inputs = VBRAINSDemonWarp.input_spec() @@ -73,9 +159,15 @@ def test_VBRAINSDemonWarp_inputs(): def test_VBRAINSDemonWarp_outputs(): output_map = dict( - outputCheckerboardVolume=dict(extensions=None,), - outputDisplacementFieldVolume=dict(extensions=None,), - outputVolume=dict(extensions=None,), + outputCheckerboardVolume=dict( + extensions=None, + ), + outputDisplacementFieldVolume=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), ) outputs = VBRAINSDemonWarp.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/__init__.py b/nipype/interfaces/semtools/segmentation/__init__.py index 0cc6090203..8d11e465ef 100644 --- a/nipype/interfaces/semtools/segmentation/__init__.py +++ b/nipype/interfaces/semtools/segmentation/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .specialized import ( BRAINSCut, BRAINSROIAuto, diff --git a/nipype/interfaces/semtools/segmentation/specialized.py b/nipype/interfaces/semtools/segmentation/specialized.py index 483b5470fe..d4f1ab1b07 100644 --- a/nipype/interfaces/semtools/segmentation/specialized.py +++ b/nipype/interfaces/semtools/segmentation/specialized.py @@ -1,19 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, - isdefined, InputMultiPath, OutputMultiPath, ) @@ -37,11 +31,11 @@ class BRAINSCutInputSpec(CommandLineInputSpec): desc="print out some debugging information", argstr="--verbose %d" ) multiStructureThreshold = traits.Bool( - desc="multiStructureThreshold module to deal with overlaping area", + desc="multiStructureThreshold module to deal with overlapping area", argstr="--multiStructureThreshold ", ) histogramEqualization = traits.Bool( - desc="A Histogram Equalization process could be added to the creating/applying process from Subject To Atlas. Default is false, which genreate input vectors without Histogram Equalization. ", + desc="A Histogram Equalization process could be added to the creating/applying process from Subject To Atlas. Default is false, which generate input vectors without Histogram Equalization. ", argstr="--histogramEqualization ", ) computeSSEOn = traits.Bool( @@ -86,17 +80,16 @@ class BRAINSCutOutputSpec(TraitedSpec): class BRAINSCut(SEMLikeCommandLine): """title: BRAINSCut (BRAINS) -category: Segmentation.Specialized - -description: Automatic Segmentation using neural networks + category: Segmentation.Specialized -version: 1.0 + description: Automatic Segmentation using neural networks -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 1.0 -contributor: Vince Magnotta, Hans Johnson, Greg Harris, Kent Williams, Eunyoung Regina Kim + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: Vince Magnotta, Hans Johnson, Greg Harris, Kent Williams, Eunyoung Regina Kim + """ input_spec = BRAINSCutInputSpec output_spec = BRAINSCutOutputSpec @@ -145,7 +138,7 @@ class BRAINSROIAutoInputSpec(CommandLineInputSpec): argstr="--closingSize %f", ) ROIAutoDilateSize = traits.Float( - desc="This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", + desc="This flag is only relevant when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", argstr="--ROIAutoDilateSize %f", ) outputVolumePixelType = traits.Enum( @@ -177,19 +170,18 @@ class BRAINSROIAutoOutputSpec(TraitedSpec): class BRAINSROIAuto(SEMLikeCommandLine): """title: Foreground masking (BRAINS) -category: Segmentation.Specialized - -description: This program is used to create a mask over the most prominant forground region in an image. This is accomplished via a combination of otsu thresholding and a closing operation. More documentation is available here: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ForegroundMasking. + category: Segmentation.Specialized -version: 2.4.1 + description: This program is used to create a mask over the most prominent foreground region in an image. This is accomplished via a combination of otsu thresholding and a closing operation. More documentation is available here: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ForegroundMasking. -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 2.4.1 -contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://www.psychiatry.uiowa.edu + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); Gregory Harris(1), Vincent Magnotta(1,2,3); Andriy Fedorov(5), fedorov -at- bwh.harvard.edu (Slicer integration); (1=University of Iowa Department of Psychiatry, 2=University of Iowa Department of Radiology, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering, 5=Surgical Planning Lab, Harvard) + contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://www.psychiatry.uiowa.edu -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); Gregory Harris(1), Vincent Magnotta(1,2,3); Andriy Fedorov(5), fedorov -at- bwh.harvard.edu (Slicer integration); (1=University of Iowa Department of Psychiatry, 2=University of Iowa Department of Radiology, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering, 5=Surgical Planning Lab, Harvard) + """ input_spec = BRAINSROIAutoInputSpec output_spec = BRAINSROIAutoOutputSpec @@ -271,7 +263,7 @@ class BRAINSConstellationDetectorInputSpec(CommandLineInputSpec): argstr="--outputVerificationScript %s", ) mspQualityLevel = traits.Int( - desc=", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds), NOTE: -1= Prealigned so no estimate!., ", + desc=", Flag controls how aggressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds), NOTE: -1= Prealigned so no estimate!., ", argstr="--mspQualityLevel %d", ) otsuPercentileThreshold = traits.Float( @@ -393,7 +385,7 @@ class BRAINSConstellationDetectorInputSpec(CommandLineInputSpec): traits.Bool, Directory(), hash_files=False, - desc=", The directory for the debuging images to be written., ", + desc=", The directory for the debugging images to be written., ", argstr="--resultsDir %s", ) writedebuggingImagesLevel = traits.Int( @@ -459,7 +451,7 @@ class BRAINSConstellationDetectorOutputSpec(TraitedSpec): exists=True, ) resultsDir = Directory( - desc=", The directory for the debuging images to be written., ", + desc=", The directory for the debugging images to be written., ", exists=True, ) @@ -467,15 +459,14 @@ class BRAINSConstellationDetectorOutputSpec(TraitedSpec): class BRAINSConstellationDetector(SEMLikeCommandLine): """title: Brain Landmark Constellation Detector (BRAINS) -category: Segmentation.Specialized + category: Segmentation.Specialized -description: This program will find the mid-sagittal plane, a constellation of landmarks in a volume, and create an AC/PC aligned data set with the AC point at the center of the voxel lattice (labeled at the origin of the image physical space.) Part of this work is an extention of the algorithms originally described by Dr. Babak A. Ardekani, Alvin H. Bachman, Model-based automatic detection of the anterior and posterior commissures on MRI scans, NeuroImage, Volume 46, Issue 3, 1 July 2009, Pages 677-682, ISSN 1053-8119, DOI: 10.1016/j.neuroimage.2009.02.030. (http://www.sciencedirect.com/science/article/B6WNP-4VRP25C-4/2/8207b962a38aa83c822c6379bc43fe4c) + description: This program will find the mid-sagittal plane, a constellation of landmarks in a volume, and create an AC/PC aligned data set with the AC point at the center of the voxel lattice (labeled at the origin of the image physical space.) Part of this work is an extension of the algorithms originally described by Dr. Babak A. Ardekani, Alvin H. Bachman, Model-based automatic detection of the anterior and posterior commissures on MRI scans, NeuroImage, Volume 46, Issue 3, 1 July 2009, Pages 677-682, ISSN 1053-8119, DOI: 10.1016/j.neuroimage.2009.02.030. (http://www.sciencedirect.com/science/article/B6WNP-4VRP25C-4/2/8207b962a38aa83c822c6379bc43fe4c) -version: 1.0 + version: 1.0 -documentation-url: http://www.nitrc.org/projects/brainscdetector/ - -""" + documentation-url: http://www.nitrc.org/projects/brainscdetector/ + """ input_spec = BRAINSConstellationDetectorInputSpec output_spec = BRAINSConstellationDetectorOutputSpec @@ -545,11 +536,10 @@ class BRAINSCreateLabelMapFromProbabilityMapsOutputSpec(TraitedSpec): class BRAINSCreateLabelMapFromProbabilityMaps(SEMLikeCommandLine): """title: Create Label Map From Probability Maps (BRAINS) -category: Segmentation.Specialized - -description: Given A list of Probability Maps, generate a LabelMap. + category: Segmentation.Specialized -""" + description: Given A list of Probability Maps, generate a LabelMap. + """ input_spec = BRAINSCreateLabelMapFromProbabilityMapsInputSpec output_spec = BRAINSCreateLabelMapFromProbabilityMapsOutputSpec @@ -593,7 +583,7 @@ class BinaryMaskEditorBasedOnLandmarksInputSpec(CommandLineInputSpec): ) setCutDirectionForObliquePlane = InputMultiPath( traits.Str, - desc="If this is true, the mask will be thresholded out to the direction of inferior, posterior, and/or left. Default behavrior is that cutting out to the direction of superior, anterior and/or right. ", + desc="If this is true, the mask will be thresholded out to the direction of inferior, posterior, and/or left. Default behavior is that cutting out to the direction of superior, anterior and/or right. ", sep=",", argstr="--setCutDirectionForObliquePlane %s", ) @@ -614,13 +604,12 @@ class BinaryMaskEditorBasedOnLandmarksOutputSpec(TraitedSpec): class BinaryMaskEditorBasedOnLandmarks(SEMLikeCommandLine): """title: BRAINS Binary Mask Editor Based On Landmarks(BRAINS) -category: Segmentation.Specialized + category: Segmentation.Specialized -version: 1.0 + version: 1.0 -documentation-url: http://www.nitrc.org/projects/brainscdetector/ - -""" + documentation-url: http://www.nitrc.org/projects/brainscdetector/ + """ input_spec = BinaryMaskEditorBasedOnLandmarksInputSpec output_spec = BinaryMaskEditorBasedOnLandmarksOutputSpec @@ -631,7 +620,7 @@ class BinaryMaskEditorBasedOnLandmarks(SEMLikeCommandLine): class BRAINSMultiSTAPLEInputSpec(CommandLineInputSpec): inputCompositeT1Volume = File( - desc="Composite T1, all label maps transofrmed into the space for this image.", + desc="Composite T1, all label maps transformed into the space for this image.", exists=True, argstr="--inputCompositeT1Volume %s", ) @@ -681,11 +670,10 @@ class BRAINSMultiSTAPLEOutputSpec(TraitedSpec): class BRAINSMultiSTAPLE(SEMLikeCommandLine): """title: Create best representative label map) -category: Segmentation.Specialized - -description: given a list of label map images, create a representative/average label map. + category: Segmentation.Specialized -""" + description: given a list of label map images, create a representative/average label map. + """ input_spec = BRAINSMultiSTAPLEInputSpec output_spec = BRAINSMultiSTAPLEOutputSpec @@ -730,7 +718,7 @@ class BRAINSABCInputSpec(CommandLineInputSpec): traits.Bool, Directory(), hash_files=False, - desc="Ouput directory", + desc="Output directory", argstr="--outputDir %s", ) atlasToSubjectTransformType = traits.Enum( @@ -766,7 +754,7 @@ class BRAINSABCInputSpec(CommandLineInputSpec): ) outputVolumes = traits.Either( traits.Bool, - InputMultiPath(File(),), + InputMultiPath(File()), hash_files=False, desc="Corrected Output Images: should specify the same number of images as inputVolume, if only one element is given, then it is used as a file pattern where %s is replaced by the imageVolumeType, and %d by the index list location.", argstr="--outputVolumes %s...", @@ -838,7 +826,7 @@ class BRAINSABCInputSpec(CommandLineInputSpec): ) numberOfSubSamplesInEachPlugArea = InputMultiPath( traits.Int, - desc="Number of continous index samples taken at each direction of lattice space for each plug volume.", + desc="Number of continuous index samples taken at each direction of lattice space for each plug volume.", sep=",", argstr="--numberOfSubSamplesInEachPlugArea %s", ) @@ -854,7 +842,7 @@ class BRAINSABCInputSpec(CommandLineInputSpec): defaultSuffix = traits.Str(argstr="--defaultSuffix %s") implicitOutputs = traits.Either( traits.Bool, - InputMultiPath(File(),), + InputMultiPath(File()), hash_files=False, desc="Outputs to be made available to NiPype. Needed because not all BRAINSABC outputs have command line arguments.", argstr="--implicitOutputs %s...", @@ -878,7 +866,7 @@ class BRAINSABCOutputSpec(TraitedSpec): desc="(optional) Filename to which save the final state of the registration", exists=True, ) - outputDir = Directory(desc="Ouput directory", exists=True) + outputDir = Directory(desc="Output directory", exists=True) atlasToSubjectTransform = File( desc="The transform from atlas to the subject", exists=True ) @@ -900,11 +888,10 @@ class BRAINSABCOutputSpec(TraitedSpec): class BRAINSABC(SEMLikeCommandLine): """title: Intra-subject registration, bias Correction, and tissue classification (BRAINS) -category: Segmentation.Specialized + category: Segmentation.Specialized -description: Atlas-based tissue segmentation method. This is an algorithmic extension of work done by XXXX at UNC and Utah XXXX need more description here. - -""" + description: Atlas-based tissue segmentation method. This is an algorithmic extension of work done by XXXX at UNC and Utah XXXX need more description here. + """ input_spec = BRAINSABCInputSpec output_spec = BRAINSABCOutputSpec @@ -965,11 +952,10 @@ class ESLROutputSpec(TraitedSpec): class ESLR(SEMLikeCommandLine): """title: Clean Contiguous Label Map (BRAINS) -category: Segmentation.Specialized - -description: From a range of label map values, extract the largest contiguous region of those labels + category: Segmentation.Specialized -""" + description: From a range of label map values, extract the largest contiguous region of those labels + """ input_spec = ESLRInputSpec output_spec = ESLROutputSpec diff --git a/nipype/interfaces/semtools/segmentation/tests/__init__.py b/nipype/interfaces/semtools/segmentation/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/segmentation/tests/__init__.py +++ b/nipype/interfaces/semtools/segmentation/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSABC.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSABC.py index e43cdf412c..5e66b2d82c 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSABC.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSABC.py @@ -4,48 +4,123 @@ def test_BRAINSABC_inputs(): input_map = dict( - args=dict(argstr="%s",), - atlasDefinition=dict(argstr="--atlasDefinition %s", extensions=None,), + args=dict( + argstr="%s", + ), + atlasDefinition=dict( + argstr="--atlasDefinition %s", + extensions=None, + ), atlasToSubjectInitialTransform=dict( - argstr="--atlasToSubjectInitialTransform %s", hash_files=False, + argstr="--atlasToSubjectInitialTransform %s", + hash_files=False, ), atlasToSubjectTransform=dict( - argstr="--atlasToSubjectTransform %s", hash_files=False, - ), - atlasToSubjectTransformType=dict(argstr="--atlasToSubjectTransformType %s",), - atlasWarpingOff=dict(argstr="--atlasWarpingOff ",), - debuglevel=dict(argstr="--debuglevel %d",), - defaultSuffix=dict(argstr="--defaultSuffix %s",), - environ=dict(nohash=True, usedefault=True,), - filterIteration=dict(argstr="--filterIteration %d",), - filterMethod=dict(argstr="--filterMethod %s",), - filterTimeStep=dict(argstr="--filterTimeStep %f",), - gridSize=dict(argstr="--gridSize %s", sep=",",), - implicitOutputs=dict(argstr="--implicitOutputs %s...", hash_files=False,), - inputVolumeTypes=dict(argstr="--inputVolumeTypes %s", sep=",",), - inputVolumes=dict(argstr="--inputVolumes %s...",), - interpolationMode=dict(argstr="--interpolationMode %s",), - maxBiasDegree=dict(argstr="--maxBiasDegree %d",), - maxIterations=dict(argstr="--maxIterations %d",), - medianFilterSize=dict(argstr="--medianFilterSize %s", sep=",",), + argstr="--atlasToSubjectTransform %s", + hash_files=False, + ), + atlasToSubjectTransformType=dict( + argstr="--atlasToSubjectTransformType %s", + ), + atlasWarpingOff=dict( + argstr="--atlasWarpingOff ", + ), + debuglevel=dict( + argstr="--debuglevel %d", + ), + defaultSuffix=dict( + argstr="--defaultSuffix %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filterIteration=dict( + argstr="--filterIteration %d", + ), + filterMethod=dict( + argstr="--filterMethod %s", + ), + filterTimeStep=dict( + argstr="--filterTimeStep %f", + ), + gridSize=dict( + argstr="--gridSize %s", + sep=",", + ), + implicitOutputs=dict( + argstr="--implicitOutputs %s...", + hash_files=False, + ), + inputVolumeTypes=dict( + argstr="--inputVolumeTypes %s", + sep=",", + ), + inputVolumes=dict( + argstr="--inputVolumes %s...", + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + maxBiasDegree=dict( + argstr="--maxBiasDegree %d", + ), + maxIterations=dict( + argstr="--maxIterations %d", + ), + medianFilterSize=dict( + argstr="--medianFilterSize %s", + sep=",", + ), numberOfSubSamplesInEachPlugArea=dict( - argstr="--numberOfSubSamplesInEachPlugArea %s", sep=",", - ), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputDir=dict(argstr="--outputDir %s", hash_files=False,), - outputDirtyLabels=dict(argstr="--outputDirtyLabels %s", hash_files=False,), - outputFormat=dict(argstr="--outputFormat %s",), - outputLabels=dict(argstr="--outputLabels %s", hash_files=False,), - outputVolumes=dict(argstr="--outputVolumes %s...", hash_files=False,), - posteriorTemplate=dict(argstr="--posteriorTemplate %s",), - purePlugsThreshold=dict(argstr="--purePlugsThreshold %f",), - restoreState=dict(argstr="--restoreState %s", extensions=None,), - saveState=dict(argstr="--saveState %s", hash_files=False,), + argstr="--numberOfSubSamplesInEachPlugArea %s", + sep=",", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputDir=dict( + argstr="--outputDir %s", + hash_files=False, + ), + outputDirtyLabels=dict( + argstr="--outputDirtyLabels %s", + hash_files=False, + ), + outputFormat=dict( + argstr="--outputFormat %s", + ), + outputLabels=dict( + argstr="--outputLabels %s", + hash_files=False, + ), + outputVolumes=dict( + argstr="--outputVolumes %s...", + hash_files=False, + ), + posteriorTemplate=dict( + argstr="--posteriorTemplate %s", + ), + purePlugsThreshold=dict( + argstr="--purePlugsThreshold %f", + ), + restoreState=dict( + argstr="--restoreState %s", + extensions=None, + ), + saveState=dict( + argstr="--saveState %s", + hash_files=False, + ), subjectIntermodeTransformType=dict( argstr="--subjectIntermodeTransformType %s", ), - useKNN=dict(argstr="--useKNN ",), - writeLess=dict(argstr="--writeLess ",), + useKNN=dict( + argstr="--useKNN ", + ), + writeLess=dict( + argstr="--writeLess ", + ), ) inputs = BRAINSABC.input_spec() @@ -56,14 +131,24 @@ def test_BRAINSABC_inputs(): def test_BRAINSABC_outputs(): output_map = dict( - atlasToSubjectInitialTransform=dict(extensions=None,), - atlasToSubjectTransform=dict(extensions=None,), + atlasToSubjectInitialTransform=dict( + extensions=None, + ), + atlasToSubjectTransform=dict( + extensions=None, + ), implicitOutputs=dict(), outputDir=dict(), - outputDirtyLabels=dict(extensions=None,), - outputLabels=dict(extensions=None,), + outputDirtyLabels=dict( + extensions=None, + ), + outputLabels=dict( + extensions=None, + ), outputVolumes=dict(), - saveState=dict(extensions=None,), + saveState=dict( + extensions=None, + ), ) outputs = BRAINSABC.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSConstellationDetector.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSConstellationDetector.py index a2eb766db3..2f77f419e7 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSConstellationDetector.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSConstellationDetector.py @@ -4,62 +4,155 @@ def test_BRAINSConstellationDetector_inputs(): input_map = dict( - BackgroundFillValue=dict(argstr="--BackgroundFillValue %s",), - LLSModel=dict(argstr="--LLSModel %s", extensions=None,), - acLowerBound=dict(argstr="--acLowerBound %f",), - args=dict(argstr="%s",), - atlasLandmarkWeights=dict(argstr="--atlasLandmarkWeights %s", extensions=None,), - atlasLandmarks=dict(argstr="--atlasLandmarks %s", extensions=None,), - atlasVolume=dict(argstr="--atlasVolume %s", extensions=None,), - cutOutHeadInOutputVolume=dict(argstr="--cutOutHeadInOutputVolume ",), - debug=dict(argstr="--debug ",), - environ=dict(nohash=True, usedefault=True,), - forceACPoint=dict(argstr="--forceACPoint %s", sep=",",), + BackgroundFillValue=dict( + argstr="--BackgroundFillValue %s", + ), + LLSModel=dict( + argstr="--LLSModel %s", + extensions=None, + ), + acLowerBound=dict( + argstr="--acLowerBound %f", + ), + args=dict( + argstr="%s", + ), + atlasLandmarkWeights=dict( + argstr="--atlasLandmarkWeights %s", + extensions=None, + ), + atlasLandmarks=dict( + argstr="--atlasLandmarks %s", + extensions=None, + ), + atlasVolume=dict( + argstr="--atlasVolume %s", + extensions=None, + ), + cutOutHeadInOutputVolume=dict( + argstr="--cutOutHeadInOutputVolume ", + ), + debug=dict( + argstr="--debug ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + forceACPoint=dict( + argstr="--forceACPoint %s", + sep=",", + ), forceHoughEyeDetectorReportFailure=dict( argstr="--forceHoughEyeDetectorReportFailure ", ), - forcePCPoint=dict(argstr="--forcePCPoint %s", sep=",",), - forceRPPoint=dict(argstr="--forceRPPoint %s", sep=",",), - forceVN4Point=dict(argstr="--forceVN4Point %s", sep=",",), - houghEyeDetectorMode=dict(argstr="--houghEyeDetectorMode %d",), - inputLandmarksEMSP=dict(argstr="--inputLandmarksEMSP %s", extensions=None,), - inputTemplateModel=dict(argstr="--inputTemplateModel %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - interpolationMode=dict(argstr="--interpolationMode %s",), - mspQualityLevel=dict(argstr="--mspQualityLevel %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - otsuPercentileThreshold=dict(argstr="--otsuPercentileThreshold %f",), + forcePCPoint=dict( + argstr="--forcePCPoint %s", + sep=",", + ), + forceRPPoint=dict( + argstr="--forceRPPoint %s", + sep=",", + ), + forceVN4Point=dict( + argstr="--forceVN4Point %s", + sep=",", + ), + houghEyeDetectorMode=dict( + argstr="--houghEyeDetectorMode %d", + ), + inputLandmarksEMSP=dict( + argstr="--inputLandmarksEMSP %s", + extensions=None, + ), + inputTemplateModel=dict( + argstr="--inputTemplateModel %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + mspQualityLevel=dict( + argstr="--mspQualityLevel %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + otsuPercentileThreshold=dict( + argstr="--otsuPercentileThreshold %f", + ), outputLandmarksInACPCAlignedSpace=dict( - argstr="--outputLandmarksInACPCAlignedSpace %s", hash_files=False, + argstr="--outputLandmarksInACPCAlignedSpace %s", + hash_files=False, ), outputLandmarksInInputSpace=dict( - argstr="--outputLandmarksInInputSpace %s", hash_files=False, + argstr="--outputLandmarksInInputSpace %s", + hash_files=False, + ), + outputMRML=dict( + argstr="--outputMRML %s", + hash_files=False, ), - outputMRML=dict(argstr="--outputMRML %s", hash_files=False,), outputResampledVolume=dict( - argstr="--outputResampledVolume %s", hash_files=False, + argstr="--outputResampledVolume %s", + hash_files=False, + ), + outputTransform=dict( + argstr="--outputTransform %s", + hash_files=False, ), - outputTransform=dict(argstr="--outputTransform %s", hash_files=False,), outputUntransformedClippedVolume=dict( - argstr="--outputUntransformedClippedVolume %s", hash_files=False, + argstr="--outputUntransformedClippedVolume %s", + hash_files=False, ), outputVerificationScript=dict( - argstr="--outputVerificationScript %s", hash_files=False, + argstr="--outputVerificationScript %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + rVN4=dict( + argstr="--rVN4 %f", + ), + rac=dict( + argstr="--rac %f", + ), + rescaleIntensities=dict( + argstr="--rescaleIntensities ", ), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - rVN4=dict(argstr="--rVN4 %f",), - rac=dict(argstr="--rac %f",), - rescaleIntensities=dict(argstr="--rescaleIntensities ",), rescaleIntensitiesOutputRange=dict( - argstr="--rescaleIntensitiesOutputRange %s", sep=",", - ), - resultsDir=dict(argstr="--resultsDir %s", hash_files=False,), - rmpj=dict(argstr="--rmpj %f",), - rpc=dict(argstr="--rpc %f",), - trimRescaledIntensities=dict(argstr="--trimRescaledIntensities %f",), - verbose=dict(argstr="--verbose ",), - writeBranded2DImage=dict(argstr="--writeBranded2DImage %s", hash_files=False,), - writedebuggingImagesLevel=dict(argstr="--writedebuggingImagesLevel %d",), + argstr="--rescaleIntensitiesOutputRange %s", + sep=",", + ), + resultsDir=dict( + argstr="--resultsDir %s", + hash_files=False, + ), + rmpj=dict( + argstr="--rmpj %f", + ), + rpc=dict( + argstr="--rpc %f", + ), + trimRescaledIntensities=dict( + argstr="--trimRescaledIntensities %f", + ), + verbose=dict( + argstr="--verbose ", + ), + writeBranded2DImage=dict( + argstr="--writeBranded2DImage %s", + hash_files=False, + ), + writedebuggingImagesLevel=dict( + argstr="--writedebuggingImagesLevel %d", + ), ) inputs = BRAINSConstellationDetector.input_spec() @@ -70,16 +163,34 @@ def test_BRAINSConstellationDetector_inputs(): def test_BRAINSConstellationDetector_outputs(): output_map = dict( - outputLandmarksInACPCAlignedSpace=dict(extensions=None,), - outputLandmarksInInputSpace=dict(extensions=None,), - outputMRML=dict(extensions=None,), - outputResampledVolume=dict(extensions=None,), - outputTransform=dict(extensions=None,), - outputUntransformedClippedVolume=dict(extensions=None,), - outputVerificationScript=dict(extensions=None,), - outputVolume=dict(extensions=None,), + outputLandmarksInACPCAlignedSpace=dict( + extensions=None, + ), + outputLandmarksInInputSpace=dict( + extensions=None, + ), + outputMRML=dict( + extensions=None, + ), + outputResampledVolume=dict( + extensions=None, + ), + outputTransform=dict( + extensions=None, + ), + outputUntransformedClippedVolume=dict( + extensions=None, + ), + outputVerificationScript=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), resultsDir=dict(), - writeBranded2DImage=dict(extensions=None,), + writeBranded2DImage=dict( + extensions=None, + ), ) outputs = BRAINSConstellationDetector.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCreateLabelMapFromProbabilityMaps.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCreateLabelMapFromProbabilityMaps.py index 06bf0165ca..4a395fbc14 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCreateLabelMapFromProbabilityMaps.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCreateLabelMapFromProbabilityMaps.py @@ -4,15 +4,39 @@ def test_BRAINSCreateLabelMapFromProbabilityMaps_inputs(): input_map = dict( - args=dict(argstr="%s",), - cleanLabelVolume=dict(argstr="--cleanLabelVolume %s", hash_files=False,), - dirtyLabelVolume=dict(argstr="--dirtyLabelVolume %s", hash_files=False,), - environ=dict(nohash=True, usedefault=True,), - foregroundPriors=dict(argstr="--foregroundPriors %s", sep=",",), - inclusionThreshold=dict(argstr="--inclusionThreshold %f",), - inputProbabilityVolume=dict(argstr="--inputProbabilityVolume %s...",), - nonAirRegionMask=dict(argstr="--nonAirRegionMask %s", extensions=None,), - priorLabelCodes=dict(argstr="--priorLabelCodes %s", sep=",",), + args=dict( + argstr="%s", + ), + cleanLabelVolume=dict( + argstr="--cleanLabelVolume %s", + hash_files=False, + ), + dirtyLabelVolume=dict( + argstr="--dirtyLabelVolume %s", + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + foregroundPriors=dict( + argstr="--foregroundPriors %s", + sep=",", + ), + inclusionThreshold=dict( + argstr="--inclusionThreshold %f", + ), + inputProbabilityVolume=dict( + argstr="--inputProbabilityVolume %s...", + ), + nonAirRegionMask=dict( + argstr="--nonAirRegionMask %s", + extensions=None, + ), + priorLabelCodes=dict( + argstr="--priorLabelCodes %s", + sep=",", + ), ) inputs = BRAINSCreateLabelMapFromProbabilityMaps.input_spec() @@ -23,8 +47,12 @@ def test_BRAINSCreateLabelMapFromProbabilityMaps_inputs(): def test_BRAINSCreateLabelMapFromProbabilityMaps_outputs(): output_map = dict( - cleanLabelVolume=dict(extensions=None,), - dirtyLabelVolume=dict(extensions=None,), + cleanLabelVolume=dict( + extensions=None, + ), + dirtyLabelVolume=dict( + extensions=None, + ), ) outputs = BRAINSCreateLabelMapFromProbabilityMaps.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCut.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCut.py index c72579c470..e101cde2cc 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCut.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSCut.py @@ -4,27 +4,66 @@ def test_BRAINSCut_inputs(): input_map = dict( - NoTrainingVectorShuffling=dict(argstr="--NoTrainingVectorShuffling ",), - applyModel=dict(argstr="--applyModel ",), - args=dict(argstr="%s",), - computeSSEOn=dict(argstr="--computeSSEOn ",), - createVectors=dict(argstr="--createVectors ",), - environ=dict(nohash=True, usedefault=True,), - generateProbability=dict(argstr="--generateProbability ",), - histogramEqualization=dict(argstr="--histogramEqualization ",), - method=dict(argstr="--method %s",), + NoTrainingVectorShuffling=dict( + argstr="--NoTrainingVectorShuffling ", + ), + applyModel=dict( + argstr="--applyModel ", + ), + args=dict( + argstr="%s", + ), + computeSSEOn=dict( + argstr="--computeSSEOn ", + ), + createVectors=dict( + argstr="--createVectors ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + generateProbability=dict( + argstr="--generateProbability ", + ), + histogramEqualization=dict( + argstr="--histogramEqualization ", + ), + method=dict( + argstr="--method %s", + ), modelConfigurationFilename=dict( - argstr="--modelConfigurationFilename %s", extensions=None, - ), - modelFilename=dict(argstr="--modelFilename %s",), - multiStructureThreshold=dict(argstr="--multiStructureThreshold ",), - netConfiguration=dict(argstr="--netConfiguration %s", extensions=None,), - numberOfTrees=dict(argstr="--numberOfTrees %d",), - randomTreeDepth=dict(argstr="--randomTreeDepth %d",), - trainModel=dict(argstr="--trainModel ",), - trainModelStartIndex=dict(argstr="--trainModelStartIndex %d",), - validate=dict(argstr="--validate ",), - verbose=dict(argstr="--verbose %d",), + argstr="--modelConfigurationFilename %s", + extensions=None, + ), + modelFilename=dict( + argstr="--modelFilename %s", + ), + multiStructureThreshold=dict( + argstr="--multiStructureThreshold ", + ), + netConfiguration=dict( + argstr="--netConfiguration %s", + extensions=None, + ), + numberOfTrees=dict( + argstr="--numberOfTrees %d", + ), + randomTreeDepth=dict( + argstr="--randomTreeDepth %d", + ), + trainModel=dict( + argstr="--trainModel ", + ), + trainModelStartIndex=dict( + argstr="--trainModelStartIndex %d", + ), + validate=dict( + argstr="--validate ", + ), + verbose=dict( + argstr="--verbose %d", + ), ) inputs = BRAINSCut.input_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSMultiSTAPLE.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSMultiSTAPLE.py index 7f91e4e803..6ff468ba47 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSMultiSTAPLE.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSMultiSTAPLE.py @@ -4,20 +4,40 @@ def test_BRAINSMultiSTAPLE_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputCompositeT1Volume=dict( - argstr="--inputCompositeT1Volume %s", extensions=None, + argstr="--inputCompositeT1Volume %s", + extensions=None, + ), + inputLabelVolume=dict( + argstr="--inputLabelVolume %s...", + ), + inputTransform=dict( + argstr="--inputTransform %s...", + ), + labelForUndecidedPixels=dict( + argstr="--labelForUndecidedPixels %d", ), - inputLabelVolume=dict(argstr="--inputLabelVolume %s...",), - inputTransform=dict(argstr="--inputTransform %s...",), - labelForUndecidedPixels=dict(argstr="--labelForUndecidedPixels %d",), outputConfusionMatrix=dict( - argstr="--outputConfusionMatrix %s", hash_files=False, + argstr="--outputConfusionMatrix %s", + hash_files=False, + ), + outputMultiSTAPLE=dict( + argstr="--outputMultiSTAPLE %s", + hash_files=False, + ), + resampledVolumePrefix=dict( + argstr="--resampledVolumePrefix %s", + ), + skipResampling=dict( + argstr="--skipResampling ", ), - outputMultiSTAPLE=dict(argstr="--outputMultiSTAPLE %s", hash_files=False,), - resampledVolumePrefix=dict(argstr="--resampledVolumePrefix %s",), - skipResampling=dict(argstr="--skipResampling ",), ) inputs = BRAINSMultiSTAPLE.input_spec() @@ -28,8 +48,12 @@ def test_BRAINSMultiSTAPLE_inputs(): def test_BRAINSMultiSTAPLE_outputs(): output_map = dict( - outputConfusionMatrix=dict(extensions=None,), - outputMultiSTAPLE=dict(extensions=None,), + outputConfusionMatrix=dict( + extensions=None, + ), + outputMultiSTAPLE=dict( + extensions=None, + ), ) outputs = BRAINSMultiSTAPLE.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSROIAuto.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSROIAuto.py index 69562cc9ce..f65c8c9b88 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSROIAuto.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BRAINSROIAuto.py @@ -4,19 +4,49 @@ def test_BRAINSROIAuto_inputs(): input_map = dict( - ROIAutoDilateSize=dict(argstr="--ROIAutoDilateSize %f",), - args=dict(argstr="%s",), - closingSize=dict(argstr="--closingSize %f",), - cropOutput=dict(argstr="--cropOutput ",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - maskOutput=dict(argstr="--maskOutput ",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - otsuPercentileThreshold=dict(argstr="--otsuPercentileThreshold %f",), - outputROIMaskVolume=dict(argstr="--outputROIMaskVolume %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - outputVolumePixelType=dict(argstr="--outputVolumePixelType %s",), - thresholdCorrectionFactor=dict(argstr="--thresholdCorrectionFactor %f",), + ROIAutoDilateSize=dict( + argstr="--ROIAutoDilateSize %f", + ), + args=dict( + argstr="%s", + ), + closingSize=dict( + argstr="--closingSize %f", + ), + cropOutput=dict( + argstr="--cropOutput ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + maskOutput=dict( + argstr="--maskOutput ", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + otsuPercentileThreshold=dict( + argstr="--otsuPercentileThreshold %f", + ), + outputROIMaskVolume=dict( + argstr="--outputROIMaskVolume %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + outputVolumePixelType=dict( + argstr="--outputVolumePixelType %s", + ), + thresholdCorrectionFactor=dict( + argstr="--thresholdCorrectionFactor %f", + ), ) inputs = BRAINSROIAuto.input_spec() @@ -27,7 +57,12 @@ def test_BRAINSROIAuto_inputs(): def test_BRAINSROIAuto_outputs(): output_map = dict( - outputROIMaskVolume=dict(extensions=None,), outputVolume=dict(extensions=None,), + outputROIMaskVolume=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), ) outputs = BRAINSROIAuto.output_spec() diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_BinaryMaskEditorBasedOnLandmarks.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_BinaryMaskEditorBasedOnLandmarks.py index fd28644cdc..1dd20adecd 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_BinaryMaskEditorBasedOnLandmarks.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_BinaryMaskEditorBasedOnLandmarks.py @@ -4,22 +4,40 @@ def test_BinaryMaskEditorBasedOnLandmarks_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputBinaryVolume=dict(argstr="--inputBinaryVolume %s", extensions=None,), - inputLandmarkNames=dict(argstr="--inputLandmarkNames %s", sep=",",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputBinaryVolume=dict( + argstr="--inputBinaryVolume %s", + extensions=None, + ), + inputLandmarkNames=dict( + argstr="--inputLandmarkNames %s", + sep=",", + ), inputLandmarkNamesForObliquePlane=dict( - argstr="--inputLandmarkNamesForObliquePlane %s", sep=",", + argstr="--inputLandmarkNamesForObliquePlane %s", + sep=",", ), inputLandmarksFilename=dict( - argstr="--inputLandmarksFilename %s", extensions=None, + argstr="--inputLandmarksFilename %s", + extensions=None, + ), + outputBinaryVolume=dict( + argstr="--outputBinaryVolume %s", + hash_files=False, ), - outputBinaryVolume=dict(argstr="--outputBinaryVolume %s", hash_files=False,), setCutDirectionForLandmark=dict( - argstr="--setCutDirectionForLandmark %s", sep=",", + argstr="--setCutDirectionForLandmark %s", + sep=",", ), setCutDirectionForObliquePlane=dict( - argstr="--setCutDirectionForObliquePlane %s", sep=",", + argstr="--setCutDirectionForObliquePlane %s", + sep=",", ), ) inputs = BinaryMaskEditorBasedOnLandmarks.input_spec() @@ -30,7 +48,11 @@ def test_BinaryMaskEditorBasedOnLandmarks_inputs(): def test_BinaryMaskEditorBasedOnLandmarks_outputs(): - output_map = dict(outputBinaryVolume=dict(extensions=None,),) + output_map = dict( + outputBinaryVolume=dict( + extensions=None, + ), + ) outputs = BinaryMaskEditorBasedOnLandmarks.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/segmentation/tests/test_auto_ESLR.py b/nipype/interfaces/semtools/segmentation/tests/test_auto_ESLR.py index 2fe0fc16ce..272327f4db 100644 --- a/nipype/interfaces/semtools/segmentation/tests/test_auto_ESLR.py +++ b/nipype/interfaces/semtools/segmentation/tests/test_auto_ESLR.py @@ -4,17 +4,42 @@ def test_ESLR_inputs(): input_map = dict( - args=dict(argstr="%s",), - closingSize=dict(argstr="--closingSize %d",), - environ=dict(nohash=True, usedefault=True,), - high=dict(argstr="--high %d",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - low=dict(argstr="--low %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - openingSize=dict(argstr="--openingSize %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - preserveOutside=dict(argstr="--preserveOutside ",), - safetySize=dict(argstr="--safetySize %d",), + args=dict( + argstr="%s", + ), + closingSize=dict( + argstr="--closingSize %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + high=dict( + argstr="--high %d", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + low=dict( + argstr="--low %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + openingSize=dict( + argstr="--openingSize %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + preserveOutside=dict( + argstr="--preserveOutside ", + ), + safetySize=dict( + argstr="--safetySize %d", + ), ) inputs = ESLR.input_spec() @@ -24,7 +49,11 @@ def test_ESLR_inputs(): def test_ESLR_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = ESLR.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/testing/__init__.py b/nipype/interfaces/semtools/testing/__init__.py index d06a7ea2df..aa4b5619c8 100644 --- a/nipype/interfaces/semtools/testing/__init__.py +++ b/nipype/interfaces/semtools/testing/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .featuredetection import SphericalCoordinateGeneration from .landmarkscompare import LandmarksCompare from .generateaveragelmkfile import GenerateAverageLmkFile diff --git a/nipype/interfaces/semtools/testing/featuredetection.py b/nipype/interfaces/semtools/testing/featuredetection.py index 19e5076b0a..67aa38746d 100644 --- a/nipype/interfaces/semtools/testing/featuredetection.py +++ b/nipype/interfaces/semtools/testing/featuredetection.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class SphericalCoordinateGenerationInputSpec(CommandLineInputSpec): @@ -34,15 +26,14 @@ class SphericalCoordinateGenerationOutputSpec(TraitedSpec): class SphericalCoordinateGeneration(SEMLikeCommandLine): """title: Spherical Coordinate Generation -category: Testing.FeatureDetection + category: Testing.FeatureDetection -description: get the atlas image as input and generates the rho, phi and theta images. + description: get the atlas image as input and generates the rho, phi and theta images. -version: 0.1.0.$Revision: 1 $(alpha) + version: 0.1.0.$Revision: 1 $(alpha) -contributor: Ali Ghayoor - -""" + contributor: Ali Ghayoor + """ input_spec = SphericalCoordinateGenerationInputSpec output_spec = SphericalCoordinateGenerationOutputSpec diff --git a/nipype/interfaces/semtools/testing/generateaveragelmkfile.py b/nipype/interfaces/semtools/testing/generateaveragelmkfile.py index 3995a9b73d..9235e63dd2 100644 --- a/nipype/interfaces/semtools/testing/generateaveragelmkfile.py +++ b/nipype/interfaces/semtools/testing/generateaveragelmkfile.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class GenerateAverageLmkFileInputSpec(CommandLineInputSpec): @@ -29,14 +22,14 @@ class GenerateAverageLmkFileInputSpec(CommandLineInputSpec): traits.Bool, File(), hash_files=False, - desc="Ouput landmark file name that includes average values for landmarks (.fcsv or .wts)", + desc="Output landmark file name that includes average values for landmarks (.fcsv or .wts)", argstr="--outputLandmarkFile %s", ) class GenerateAverageLmkFileOutputSpec(TraitedSpec): outputLandmarkFile = File( - desc="Ouput landmark file name that includes average values for landmarks (.fcsv or .wts)", + desc="Output landmark file name that includes average values for landmarks (.fcsv or .wts)", exists=True, ) @@ -44,13 +37,12 @@ class GenerateAverageLmkFileOutputSpec(TraitedSpec): class GenerateAverageLmkFile(SEMLikeCommandLine): """title: Average Fiducials -category: Testing + category: Testing -description: This program gets several fcsv file each one contains several landmarks with the same name but slightly different coordinates. For EACH landmark we compute the average coordination. + description: This program gets several fcsv file each one contains several landmarks with the same name but slightly different coordinates. For EACH landmark we compute the average coordination. -contributor: Ali Ghayoor - -""" + contributor: Ali Ghayoor + """ input_spec = GenerateAverageLmkFileInputSpec output_spec = GenerateAverageLmkFileOutputSpec diff --git a/nipype/interfaces/semtools/testing/landmarkscompare.py b/nipype/interfaces/semtools/testing/landmarkscompare.py index 066a92f24b..7d628518a8 100644 --- a/nipype/interfaces/semtools/testing/landmarkscompare.py +++ b/nipype/interfaces/semtools/testing/landmarkscompare.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class LandmarksCompareInputSpec(CommandLineInputSpec): @@ -42,13 +34,12 @@ class LandmarksCompareOutputSpec(TraitedSpec): class LandmarksCompare(SEMLikeCommandLine): """title: Compare Fiducials -category: Testing + category: Testing -description: Compares two .fcsv or .wts text files and verifies that they are identicle. Used for testing landmarks files. + description: Compares two .fcsv or .wts text files and verifies that they are identicle. Used for testing landmarks files. -contributor: Ali Ghayoor - -""" + contributor: Ali Ghayoor + """ input_spec = LandmarksCompareInputSpec output_spec = LandmarksCompareOutputSpec diff --git a/nipype/interfaces/semtools/tests/__init__.py b/nipype/interfaces/semtools/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/tests/__init__.py +++ b/nipype/interfaces/semtools/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/tests/test_auto_DWICompare.py b/nipype/interfaces/semtools/tests/test_auto_DWICompare.py index a9a270d6a5..b691c097a8 100644 --- a/nipype/interfaces/semtools/tests/test_auto_DWICompare.py +++ b/nipype/interfaces/semtools/tests/test_auto_DWICompare.py @@ -4,10 +4,21 @@ def test_DWICompare_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume1=dict(argstr="--inputVolume1 %s", extensions=None,), - inputVolume2=dict(argstr="--inputVolume2 %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr="--inputVolume1 %s", + extensions=None, + ), + inputVolume2=dict( + argstr="--inputVolume2 %s", + extensions=None, + ), ) inputs = DWICompare.input_spec() diff --git a/nipype/interfaces/semtools/tests/test_auto_DWISimpleCompare.py b/nipype/interfaces/semtools/tests/test_auto_DWISimpleCompare.py index f8f099104d..ad4dcb12d4 100644 --- a/nipype/interfaces/semtools/tests/test_auto_DWISimpleCompare.py +++ b/nipype/interfaces/semtools/tests/test_auto_DWISimpleCompare.py @@ -4,11 +4,24 @@ def test_DWISimpleCompare_inputs(): input_map = dict( - args=dict(argstr="%s",), - checkDWIData=dict(argstr="--checkDWIData ",), - environ=dict(nohash=True, usedefault=True,), - inputVolume1=dict(argstr="--inputVolume1 %s", extensions=None,), - inputVolume2=dict(argstr="--inputVolume2 %s", extensions=None,), + args=dict( + argstr="%s", + ), + checkDWIData=dict( + argstr="--checkDWIData ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr="--inputVolume1 %s", + extensions=None, + ), + inputVolume2=dict( + argstr="--inputVolume2 %s", + extensions=None, + ), ) inputs = DWISimpleCompare.input_spec() diff --git a/nipype/interfaces/semtools/tests/test_auto_GenerateCsfClippedFromClassifiedImage.py b/nipype/interfaces/semtools/tests/test_auto_GenerateCsfClippedFromClassifiedImage.py index 99d8d5d226..3f857d8085 100644 --- a/nipype/interfaces/semtools/tests/test_auto_GenerateCsfClippedFromClassifiedImage.py +++ b/nipype/interfaces/semtools/tests/test_auto_GenerateCsfClippedFromClassifiedImage.py @@ -4,10 +4,21 @@ def test_GenerateCsfClippedFromClassifiedImage_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputCassifiedVolume=dict(argstr="--inputCassifiedVolume %s", extensions=None,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputCassifiedVolume=dict( + argstr="--inputCassifiedVolume %s", + extensions=None, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = GenerateCsfClippedFromClassifiedImage.input_spec() @@ -17,7 +28,11 @@ def test_GenerateCsfClippedFromClassifiedImage_inputs(): def test_GenerateCsfClippedFromClassifiedImage_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = GenerateCsfClippedFromClassifiedImage.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/__init__.py b/nipype/interfaces/semtools/utilities/__init__.py index 2209064909..02a5540951 100644 --- a/nipype/interfaces/semtools/utilities/__init__.py +++ b/nipype/interfaces/semtools/utilities/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .brains import ( BRAINSConstellationModeler, landmarksConstellationWeights, diff --git a/nipype/interfaces/semtools/utilities/brains.py b/nipype/interfaces/semtools/utilities/brains.py index 59a61a1137..de38a52fc2 100644 --- a/nipype/interfaces/semtools/utilities/brains.py +++ b/nipype/interfaces/semtools/utilities/brains.py @@ -1,19 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" -import os - from ...base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, - isdefined, InputMultiPath, OutputMultiPath, ) @@ -52,7 +46,7 @@ class BRAINSConstellationModelerInputSpec(CommandLineInputSpec): argstr="--resultsDir %s", ) mspQualityLevel = traits.Int( - desc=", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds)., ", + desc=", Flag controls how aggressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds)., ", argstr="--mspQualityLevel %d", ) rescaleIntensities = traits.Bool( @@ -97,11 +91,10 @@ class BRAINSConstellationModelerOutputSpec(TraitedSpec): class BRAINSConstellationModeler(SEMLikeCommandLine): """title: Generate Landmarks Model (BRAINS) -category: Utilities.BRAINS - -description: Train up a model for BRAINSConstellationDetector + category: Utilities.BRAINS -""" + description: Train up a model for BRAINSConstellationDetector + """ input_spec = BRAINSConstellationModelerInputSpec output_spec = BRAINSConstellationModelerOutputSpec @@ -145,11 +138,10 @@ class landmarksConstellationWeightsOutputSpec(TraitedSpec): class landmarksConstellationWeights(SEMLikeCommandLine): """title: Generate Landmarks Weights (BRAINS) -category: Utilities.BRAINS - -description: Train up a list of Weights for the Landmarks in BRAINSConstellationDetector + category: Utilities.BRAINS -""" + description: Train up a list of Weights for the Landmarks in BRAINSConstellationDetector + """ input_spec = landmarksConstellationWeightsInputSpec output_spec = landmarksConstellationWeightsOutputSpec @@ -207,15 +199,14 @@ class BRAINSTrimForegroundInDirectionOutputSpec(TraitedSpec): class BRAINSTrimForegroundInDirection(SEMLikeCommandLine): """title: Trim Foreground In Direction (BRAINS) -category: Utilities.BRAINS + category: Utilities.BRAINS -description: This program will trim off the neck and also air-filling noise from the inputImage. + description: This program will trim off the neck and also air-filling noise from the inputImage. -version: 0.1 + version: 0.1 -documentation-url: http://www.nitrc.org/projects/art/ - -""" + documentation-url: http://www.nitrc.org/projects/art/ + """ input_spec = BRAINSTrimForegroundInDirectionInputSpec output_spec = BRAINSTrimForegroundInDirectionOutputSpec @@ -278,15 +269,14 @@ class BRAINSLmkTransformOutputSpec(TraitedSpec): class BRAINSLmkTransform(SEMLikeCommandLine): """title: Landmark Transform (BRAINS) -category: Utilities.BRAINS - -description: This utility program estimates the affine transform to align the fixed landmarks to the moving landmarks, and then generate the resampled moving image to the same physical space as that of the reference image. + category: Utilities.BRAINS -version: 1.0 + description: This utility program estimates the affine transform to align the fixed landmarks to the moving landmarks, and then generate the resampled moving image to the same physical space as that of the reference image. -documentation-url: http://www.nitrc.org/projects/brainscdetector/ + version: 1.0 -""" + documentation-url: http://www.nitrc.org/projects/brainscdetector/ + """ input_spec = BRAINSLmkTransformInputSpec output_spec = BRAINSLmkTransformOutputSpec @@ -396,21 +386,20 @@ class BRAINSMushOutputSpec(TraitedSpec): class BRAINSMush(SEMLikeCommandLine): """title: Brain Extraction from T1/T2 image (BRAINS) -category: Utilities.BRAINS - -description: This program: 1) generates a weighted mixture image optimizing the mean and variance and 2) produces a mask of the brain volume + category: Utilities.BRAINS -version: 0.1.0.$Revision: 1.4 $(alpha) + description: This program: 1) generates a weighted mixture image optimizing the mean and variance and 2) produces a mask of the brain volume -documentation-url: http:://mri.radiology.uiowa.edu + version: 0.1.0.$Revision: 1.4 $(alpha) -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http:://mri.radiology.uiowa.edu -contributor: This tool is a modification by Steven Dunn of a program developed by Greg Harris and Ron Pierson. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: This work was developed by the University of Iowa Departments of Radiology and Psychiatry. This software was supported in part of NIH/NINDS award NS050568. + contributor: This tool is a modification by Steven Dunn of a program developed by Greg Harris and Ron Pierson. -""" + acknowledgements: This work was developed by the University of Iowa Departments of Radiology and Psychiatry. This software was supported in part of NIH/NINDS award NS050568. + """ input_spec = BRAINSMushInputSpec output_spec = BRAINSMushOutputSpec @@ -458,19 +447,18 @@ class BRAINSTransformConvertOutputSpec(TraitedSpec): class BRAINSTransformConvert(SEMLikeCommandLine): """title: BRAINS Transform Convert -category: Utilities.BRAINS + category: Utilities.BRAINS -description: Convert ITK transforms to higher order transforms + description: Convert ITK transforms to higher order transforms -version: 1.0 + version: 1.0 -documentation-url: A utility to convert between transform file formats. + documentation-url: A utility to convert between transform file formats. -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: Hans J. Johnson,Kent Williams, Ali Ghayoor - -""" + contributor: Hans J. Johnson,Kent Williams, Ali Ghayoor + """ input_spec = BRAINSTransformConvertInputSpec output_spec = BRAINSTransformConvertOutputSpec @@ -504,13 +492,12 @@ class landmarksConstellationAlignerOutputSpec(TraitedSpec): class landmarksConstellationAligner(SEMLikeCommandLine): """title: MidACPC Landmark Insertion -category: Utilities.BRAINS - -description: This program converts the original landmark files to the acpc-aligned landmark files + category: Utilities.BRAINS -contributor: Ali Ghayoor + description: This program converts the original landmark files to the acpc-aligned landmark files -""" + contributor: Ali Ghayoor + """ input_spec = landmarksConstellationAlignerInputSpec output_spec = landmarksConstellationAlignerOutputSpec @@ -542,13 +529,12 @@ class BRAINSEyeDetectorOutputSpec(TraitedSpec): class BRAINSEyeDetector(SEMLikeCommandLine): """title: Eye Detector (BRAINS) -category: Utilities.BRAINS - -version: 1.0 + category: Utilities.BRAINS -documentation-url: http://www.nitrc.org/projects/brainscdetector/ + version: 1.0 -""" + documentation-url: http://www.nitrc.org/projects/brainscdetector/ + """ input_spec = BRAINSEyeDetectorInputSpec output_spec = BRAINSEyeDetectorOutputSpec @@ -576,15 +562,14 @@ class BRAINSLinearModelerEPCAOutputSpec(TraitedSpec): class BRAINSLinearModelerEPCA(SEMLikeCommandLine): """title: Landmark Linear Modeler (BRAINS) -category: Utilities.BRAINS + category: Utilities.BRAINS -description: Training linear model using EPCA. Implementation based on my MS thesis, "A METHOD FOR AUTOMATED LANDMARK CONSTELLATION DETECTION USING EVOLUTIONARY PRINCIPAL COMPONENTS AND STATISTICAL SHAPE MODELS" + description: Training linear model using EPCA. Implementation based on my MS thesis, "A METHOD FOR AUTOMATED LANDMARK CONSTELLATION DETECTION USING EVOLUTIONARY PRINCIPAL COMPONENTS AND STATISTICAL SHAPE MODELS" -version: 1.0 + version: 1.0 -documentation-url: http://www.nitrc.org/projects/brainscdetector/ - -""" + documentation-url: http://www.nitrc.org/projects/brainscdetector/ + """ input_spec = BRAINSLinearModelerEPCAInputSpec output_spec = BRAINSLinearModelerEPCAOutputSpec @@ -630,19 +615,18 @@ class BRAINSInitializedControlPointsOutputSpec(TraitedSpec): class BRAINSInitializedControlPoints(SEMLikeCommandLine): """title: Initialized Control Points (BRAINS) -category: Utilities.BRAINS - -description: Outputs bspline control points as landmarks + category: Utilities.BRAINS -version: 0.1.0.$Revision: 916 $(alpha) + description: Outputs bspline control points as landmarks -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 0.1.0.$Revision: 916 $(alpha) -contributor: Mark Scully + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for Mark Scully and Hans Johnson at the University of Iowa. + contributor: Mark Scully -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for Mark Scully and Hans Johnson at the University of Iowa. + """ input_spec = BRAINSInitializedControlPointsInputSpec output_spec = BRAINSInitializedControlPointsOutputSpec @@ -659,7 +643,7 @@ class CleanUpOverlapLabelsInputSpec(CommandLineInputSpec): ) outputBinaryVolumes = traits.Either( traits.Bool, - InputMultiPath(File(),), + InputMultiPath(File()), hash_files=False, desc="The output label map images, with integer values in it. Each label value specified in the inputLabels is combined into this output label map volume", argstr="--outputBinaryVolumes %s...", @@ -676,15 +660,14 @@ class CleanUpOverlapLabelsOutputSpec(TraitedSpec): class CleanUpOverlapLabels(SEMLikeCommandLine): """title: Clean Up Overla Labels -category: Utilities.BRAINS - -description: Take a series of input binary images and clean up for those overlapped area. Binary volumes given first always wins out + category: Utilities.BRAINS -version: 0.1.0 + description: Take a series of input binary images and clean up for those overlapped area. Binary volumes given first always wins out -contributor: Eun Young Kim + version: 0.1.0 -""" + contributor: Eun Young Kim + """ input_spec = CleanUpOverlapLabelsInputSpec output_spec = CleanUpOverlapLabelsOutputSpec @@ -730,13 +713,12 @@ class BRAINSClipInferiorOutputSpec(TraitedSpec): class BRAINSClipInferior(SEMLikeCommandLine): """title: Clip Inferior of Center of Brain (BRAINS) -category: Utilities.BRAINS + category: Utilities.BRAINS -description: This program will read the inputVolume as a short int image, write the BackgroundFillValue everywhere inferior to the lower bound, and write the resulting clipped short int image in the outputVolume. + description: This program will read the inputVolume as a short int image, write the BackgroundFillValue everywhere inferior to the lower bound, and write the resulting clipped short int image in the outputVolume. -version: 1.0 - -""" + version: 1.0 + """ input_spec = BRAINSClipInferiorInputSpec output_spec = BRAINSClipInferiorOutputSpec @@ -748,7 +730,7 @@ class BRAINSClipInferior(SEMLikeCommandLine): class GenerateLabelMapFromProbabilityMapInputSpec(CommandLineInputSpec): inputVolumes = InputMultiPath( File(exists=True), - desc="The Input probaiblity images to be computed for lable maps", + desc="The Input probaiblity images to be computed for label maps", argstr="--inputVolumes %s...", ) outputLabelVolume = traits.Either( @@ -773,15 +755,14 @@ class GenerateLabelMapFromProbabilityMapOutputSpec(TraitedSpec): class GenerateLabelMapFromProbabilityMap(SEMLikeCommandLine): """title: Label Map from Probability Images -category: Utilities.BRAINS - -description: Given a list of probability maps for labels, create a discrete label map where only the highest probability region is used for the labeling. + category: Utilities.BRAINS -version: 0.1 + description: Given a list of probability maps for labels, create a discrete label map where only the highest probability region is used for the labeling. -contributor: University of Iowa Department of Psychiatry, http:://www.psychiatry.uiowa.edu + version: 0.1 -""" + contributor: University of Iowa Department of Psychiatry, http:://www.psychiatry.uiowa.edu + """ input_spec = GenerateLabelMapFromProbabilityMapInputSpec output_spec = GenerateLabelMapFromProbabilityMapOutputSpec @@ -818,7 +799,7 @@ class BRAINSAlignMSPInputSpec(CommandLineInputSpec): argstr="--writedebuggingImagesLevel %d", ) mspQualityLevel = traits.Int( - desc=", Flag cotrols how agressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds)., ", + desc=", Flag controls how aggressive the MSP is estimated. 0=quick estimate (9 seconds), 1=normal estimate (11 seconds), 2=great estimate (22 seconds), 3=best estimate (58 seconds)., ", argstr="--mspQualityLevel %d", ) rescaleIntensities = traits.Bool( @@ -870,13 +851,12 @@ class BRAINSAlignMSPOutputSpec(TraitedSpec): class BRAINSAlignMSP(SEMLikeCommandLine): - """title: Align Mid Saggital Brain (BRAINS) - -category: Utilities.BRAINS + """title: Align Mid Sagittal Brain (BRAINS) -description: Resample an image into ACPC alignement ACPCDetect + category: Utilities.BRAINS -""" + description: Resample an image into ACPC alignment ACPCDetect + """ input_spec = BRAINSAlignMSPInputSpec output_spec = BRAINSAlignMSPOutputSpec @@ -900,7 +880,7 @@ class BRAINSLandmarkInitializerInputSpec(CommandLineInputSpec): argstr="--inputMovingLandmarkFilename %s", ) inputWeightFilename = File( - desc="Input weight file name for landmarks. Higher weighted landmark will be considered more heavily. Weights are propotional, that is the magnitude of weights will be normalized by its minimum and maximum value. ", + desc="Input weight file name for landmarks. Higher weighted landmark will be considered more heavily. Weights are proportional, that is the magnitude of weights will be normalized by its minimum and maximum value. ", exists=True, argstr="--inputWeightFilename %s", ) @@ -922,17 +902,16 @@ class BRAINSLandmarkInitializerOutputSpec(TraitedSpec): class BRAINSLandmarkInitializer(SEMLikeCommandLine): """title: BRAINSLandmarkInitializer -category: Utilities.BRAINS + category: Utilities.BRAINS -description: Create transformation file (*mat) from a pair of landmarks (*fcsv) files. + description: Create transformation file (*mat) from a pair of landmarks (*fcsv) files. -version: 1.0 + version: 1.0 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: Eunyoung Regina Kim - -""" + contributor: Eunyoung Regina Kim + """ input_spec = BRAINSLandmarkInitializerInputSpec output_spec = BRAINSLandmarkInitializerOutputSpec @@ -961,13 +940,12 @@ class insertMidACPCpointOutputSpec(TraitedSpec): class insertMidACPCpoint(SEMLikeCommandLine): """title: MidACPC Landmark Insertion -category: Utilities.BRAINS - -description: This program gets a landmark fcsv file and adds a new landmark as the midpoint between AC and PC points to the output landmark fcsv file + category: Utilities.BRAINS -contributor: Ali Ghayoor + description: This program gets a landmark fcsv file and adds a new landmark as the midpoint between AC and PC points to the output landmark fcsv file -""" + contributor: Ali Ghayoor + """ input_spec = insertMidACPCpointInputSpec output_spec = insertMidACPCpointOutputSpec @@ -1007,7 +985,7 @@ class BRAINSSnapShotWriterInputSpec(CommandLineInputSpec): ) inputPlaneDirection = InputMultiPath( traits.Int, - desc="Plane to display. In general, 0=saggital, 1=coronal, and 2=axial plane.", + desc="Plane to display. In general, 0=sagittal, 1=coronal, and 2=axial plane.", sep=",", argstr="--inputPlaneDirection %s", ) @@ -1027,17 +1005,16 @@ class BRAINSSnapShotWriterOutputSpec(TraitedSpec): class BRAINSSnapShotWriter(SEMLikeCommandLine): """title: BRAINSSnapShotWriter -category: Utilities.BRAINS - -description: Create 2D snapshot of input images. Mask images are color-coded + category: Utilities.BRAINS -version: 1.0 + description: Create 2D snapshot of input images. Mask images are color-coded -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 1.0 -contributor: Eunyoung Regina Kim + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: Eunyoung Regina Kim + """ input_spec = BRAINSSnapShotWriterInputSpec output_spec = BRAINSSnapShotWriterOutputSpec @@ -1083,15 +1060,14 @@ class JointHistogramOutputSpec(TraitedSpec): class JointHistogram(SEMLikeCommandLine): """title: Write Out Image Intensities -category: Utilities.BRAINS + category: Utilities.BRAINS -description: For Analysis + description: For Analysis -version: 0.1 + version: 0.1 -contributor: University of Iowa Department of Psychiatry, http:://www.psychiatry.uiowa.edu - -""" + contributor: University of Iowa Department of Psychiatry, http:://www.psychiatry.uiowa.edu + """ input_spec = JointHistogramInputSpec output_spec = JointHistogramOutputSpec @@ -1129,17 +1105,16 @@ class ShuffleVectorsModuleOutputSpec(TraitedSpec): class ShuffleVectorsModule(SEMLikeCommandLine): """title: ShuffleVectors -category: Utilities.BRAINS - -description: Automatic Segmentation using neural networks + category: Utilities.BRAINS -version: 1.0 + description: Automatic Segmentation using neural networks -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 1.0 -contributor: Hans Johnson + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -""" + contributor: Hans Johnson + """ input_spec = ShuffleVectorsModuleInputSpec output_spec = ShuffleVectorsModuleOutputSpec @@ -1193,15 +1168,14 @@ class ImageRegionPlotterOutputSpec(TraitedSpec): class ImageRegionPlotter(SEMLikeCommandLine): """title: Write Out Image Intensities -category: Utilities.BRAINS - -description: For Analysis + category: Utilities.BRAINS -version: 0.1 + description: For Analysis -contributor: University of Iowa Department of Psychiatry, http:://www.psychiatry.uiowa.edu + version: 0.1 -""" + contributor: University of Iowa Department of Psychiatry, http:://www.psychiatry.uiowa.edu + """ input_spec = ImageRegionPlotterInputSpec output_spec = ImageRegionPlotterOutputSpec @@ -1256,11 +1230,10 @@ class fcsv_to_hdf5OutputSpec(TraitedSpec): class fcsv_to_hdf5(SEMLikeCommandLine): """title: fcsv_to_hdf5 (BRAINS) -category: Utilities.BRAINS + category: Utilities.BRAINS -description: Convert a collection of fcsv files to a HDF5 format file - -""" + description: Convert a collection of fcsv files to a HDF5 format file + """ input_spec = fcsv_to_hdf5InputSpec output_spec = fcsv_to_hdf5OutputSpec @@ -1322,19 +1295,18 @@ class FindCenterOfBrainOutputSpec(TraitedSpec): class FindCenterOfBrain(SEMLikeCommandLine): """title: Center Of Brain (BRAINS) -category: Utilities.BRAINS - -description: Finds the center point of a brain + category: Utilities.BRAINS -version: 3.0.0 + description: Finds the center point of a brain -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 3.0.0 -contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://wwww.psychiatry.uiowa.edu + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering + contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://wwww.psychiatry.uiowa.edu -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); (1=University of Iowa Department of Psychiatry, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering + """ input_spec = FindCenterOfBrainInputSpec output_spec = FindCenterOfBrainOutputSpec diff --git a/nipype/interfaces/semtools/utilities/tests/__init__.py b/nipype/interfaces/semtools/utilities/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/semtools/utilities/tests/__init__.py +++ b/nipype/interfaces/semtools/utilities/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSAlignMSP.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSAlignMSP.py index 2dabdd4b6d..81fee98e93 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSAlignMSP.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSAlignMSP.py @@ -4,22 +4,53 @@ def test_BRAINSAlignMSP_inputs(): input_map = dict( - BackgroundFillValue=dict(argstr="--BackgroundFillValue %s",), - OutputresampleMSP=dict(argstr="--OutputresampleMSP %s", hash_files=False,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - interpolationMode=dict(argstr="--interpolationMode %s",), - mspQualityLevel=dict(argstr="--mspQualityLevel %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - rescaleIntensities=dict(argstr="--rescaleIntensities ",), + BackgroundFillValue=dict( + argstr="--BackgroundFillValue %s", + ), + OutputresampleMSP=dict( + argstr="--OutputresampleMSP %s", + hash_files=False, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + mspQualityLevel=dict( + argstr="--mspQualityLevel %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + rescaleIntensities=dict( + argstr="--rescaleIntensities ", + ), rescaleIntensitiesOutputRange=dict( - argstr="--rescaleIntensitiesOutputRange %s", sep=",", + argstr="--rescaleIntensitiesOutputRange %s", + sep=",", + ), + resultsDir=dict( + argstr="--resultsDir %s", + hash_files=False, + ), + trimRescaledIntensities=dict( + argstr="--trimRescaledIntensities %f", + ), + verbose=dict( + argstr="--verbose ", + ), + writedebuggingImagesLevel=dict( + argstr="--writedebuggingImagesLevel %d", ), - resultsDir=dict(argstr="--resultsDir %s", hash_files=False,), - trimRescaledIntensities=dict(argstr="--trimRescaledIntensities %f",), - verbose=dict(argstr="--verbose ",), - writedebuggingImagesLevel=dict(argstr="--writedebuggingImagesLevel %d",), ) inputs = BRAINSAlignMSP.input_spec() @@ -29,7 +60,12 @@ def test_BRAINSAlignMSP_inputs(): def test_BRAINSAlignMSP_outputs(): - output_map = dict(OutputresampleMSP=dict(extensions=None,), resultsDir=dict(),) + output_map = dict( + OutputresampleMSP=dict( + extensions=None, + ), + resultsDir=dict(), + ) outputs = BRAINSAlignMSP.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSClipInferior.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSClipInferior.py index 76958e0b2f..92e45758b1 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSClipInferior.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSClipInferior.py @@ -4,13 +4,30 @@ def test_BRAINSClipInferior_inputs(): input_map = dict( - BackgroundFillValue=dict(argstr="--BackgroundFillValue %s",), - acLowerBound=dict(argstr="--acLowerBound %f",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + BackgroundFillValue=dict( + argstr="--BackgroundFillValue %s", + ), + acLowerBound=dict( + argstr="--acLowerBound %f", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = BRAINSClipInferior.input_spec() @@ -20,7 +37,11 @@ def test_BRAINSClipInferior_inputs(): def test_BRAINSClipInferior_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSClipInferior.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSConstellationModeler.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSConstellationModeler.py index 61129f62cc..2e26a91e05 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSConstellationModeler.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSConstellationModeler.py @@ -4,25 +4,56 @@ def test_BRAINSConstellationModeler_inputs(): input_map = dict( - BackgroundFillValue=dict(argstr="--BackgroundFillValue %s",), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputTrainingList=dict(argstr="--inputTrainingList %s", extensions=None,), - mspQualityLevel=dict(argstr="--mspQualityLevel %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + BackgroundFillValue=dict( + argstr="--BackgroundFillValue %s", + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputTrainingList=dict( + argstr="--inputTrainingList %s", + extensions=None, + ), + mspQualityLevel=dict( + argstr="--mspQualityLevel %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), optimizedLandmarksFilenameExtender=dict( argstr="--optimizedLandmarksFilenameExtender %s", ), - outputModel=dict(argstr="--outputModel %s", hash_files=False,), - rescaleIntensities=dict(argstr="--rescaleIntensities ",), + outputModel=dict( + argstr="--outputModel %s", + hash_files=False, + ), + rescaleIntensities=dict( + argstr="--rescaleIntensities ", + ), rescaleIntensitiesOutputRange=dict( - argstr="--rescaleIntensitiesOutputRange %s", sep=",", + argstr="--rescaleIntensitiesOutputRange %s", + sep=",", + ), + resultsDir=dict( + argstr="--resultsDir %s", + hash_files=False, + ), + saveOptimizedLandmarks=dict( + argstr="--saveOptimizedLandmarks ", + ), + trimRescaledIntensities=dict( + argstr="--trimRescaledIntensities %f", + ), + verbose=dict( + argstr="--verbose ", + ), + writedebuggingImagesLevel=dict( + argstr="--writedebuggingImagesLevel %d", ), - resultsDir=dict(argstr="--resultsDir %s", hash_files=False,), - saveOptimizedLandmarks=dict(argstr="--saveOptimizedLandmarks ",), - trimRescaledIntensities=dict(argstr="--trimRescaledIntensities %f",), - verbose=dict(argstr="--verbose ",), - writedebuggingImagesLevel=dict(argstr="--writedebuggingImagesLevel %d",), ) inputs = BRAINSConstellationModeler.input_spec() @@ -32,7 +63,12 @@ def test_BRAINSConstellationModeler_inputs(): def test_BRAINSConstellationModeler_outputs(): - output_map = dict(outputModel=dict(extensions=None,), resultsDir=dict(),) + output_map = dict( + outputModel=dict( + extensions=None, + ), + resultsDir=dict(), + ) outputs = BRAINSConstellationModeler.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSEyeDetector.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSEyeDetector.py index 8ac3c8a21a..c511be64c5 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSEyeDetector.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSEyeDetector.py @@ -4,12 +4,27 @@ def test_BRAINSEyeDetector_inputs(): input_map = dict( - args=dict(argstr="%s",), - debugDir=dict(argstr="--debugDir %s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + debugDir=dict( + argstr="--debugDir %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = BRAINSEyeDetector.input_spec() @@ -19,7 +34,11 @@ def test_BRAINSEyeDetector_inputs(): def test_BRAINSEyeDetector_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSEyeDetector.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py index cf20b5a37b..05ba1ae7d6 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSInitializedControlPoints.py @@ -4,14 +4,35 @@ def test_BRAINSInitializedControlPoints_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputLandmarksFile=dict(argstr="--outputLandmarksFile %s",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - permuteOrder=dict(argstr="--permuteOrder %s", sep=",",), - splineGridSize=dict(argstr="--splineGridSize %s", sep=",",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputLandmarksFile=dict( + argstr="--outputLandmarksFile %s", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + permuteOrder=dict( + argstr="--permuteOrder %s", + sep=",", + ), + splineGridSize=dict( + argstr="--splineGridSize %s", + sep=",", + ), ) inputs = BRAINSInitializedControlPoints.input_spec() @@ -21,7 +42,11 @@ def test_BRAINSInitializedControlPoints_inputs(): def test_BRAINSInitializedControlPoints_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSInitializedControlPoints.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLandmarkInitializer.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLandmarkInitializer.py index cdb17c6232..efaa484008 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLandmarkInitializer.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLandmarkInitializer.py @@ -4,17 +4,28 @@ def test_BRAINSLandmarkInitializer_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputFixedLandmarkFilename=dict( - argstr="--inputFixedLandmarkFilename %s", extensions=None, + argstr="--inputFixedLandmarkFilename %s", + extensions=None, ), inputMovingLandmarkFilename=dict( - argstr="--inputMovingLandmarkFilename %s", extensions=None, + argstr="--inputMovingLandmarkFilename %s", + extensions=None, + ), + inputWeightFilename=dict( + argstr="--inputWeightFilename %s", + extensions=None, ), - inputWeightFilename=dict(argstr="--inputWeightFilename %s", extensions=None,), outputTransformFilename=dict( - argstr="--outputTransformFilename %s", hash_files=False, + argstr="--outputTransformFilename %s", + hash_files=False, ), ) inputs = BRAINSLandmarkInitializer.input_spec() @@ -25,7 +36,11 @@ def test_BRAINSLandmarkInitializer_inputs(): def test_BRAINSLandmarkInitializer_outputs(): - output_map = dict(outputTransformFilename=dict(extensions=None,),) + output_map = dict( + outputTransformFilename=dict( + extensions=None, + ), + ) outputs = BRAINSLandmarkInitializer.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLinearModelerEPCA.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLinearModelerEPCA.py index a9fdee554b..beb7a5f664 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLinearModelerEPCA.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLinearModelerEPCA.py @@ -4,10 +4,20 @@ def test_BRAINSLinearModelerEPCA_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputTrainingList=dict(argstr="--inputTrainingList %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputTrainingList=dict( + argstr="--inputTrainingList %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), ) inputs = BRAINSLinearModelerEPCA.input_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLmkTransform.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLmkTransform.py index f459589580..d0cdc8cc7f 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLmkTransform.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSLmkTransform.py @@ -4,18 +4,39 @@ def test_BRAINSLmkTransform_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputFixedLandmarks=dict(argstr="--inputFixedLandmarks %s", extensions=None,), - inputMovingLandmarks=dict(argstr="--inputMovingLandmarks %s", extensions=None,), - inputMovingVolume=dict(argstr="--inputMovingVolume %s", extensions=None,), - inputReferenceVolume=dict(argstr="--inputReferenceVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputFixedLandmarks=dict( + argstr="--inputFixedLandmarks %s", + extensions=None, + ), + inputMovingLandmarks=dict( + argstr="--inputMovingLandmarks %s", + extensions=None, + ), + inputMovingVolume=dict( + argstr="--inputMovingVolume %s", + extensions=None, + ), + inputReferenceVolume=dict( + argstr="--inputReferenceVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), outputAffineTransform=dict( - argstr="--outputAffineTransform %s", hash_files=False, + argstr="--outputAffineTransform %s", + hash_files=False, ), outputResampledVolume=dict( - argstr="--outputResampledVolume %s", hash_files=False, + argstr="--outputResampledVolume %s", + hash_files=False, ), ) inputs = BRAINSLmkTransform.input_spec() @@ -27,8 +48,12 @@ def test_BRAINSLmkTransform_inputs(): def test_BRAINSLmkTransform_outputs(): output_map = dict( - outputAffineTransform=dict(extensions=None,), - outputResampledVolume=dict(extensions=None,), + outputAffineTransform=dict( + extensions=None, + ), + outputResampledVolume=dict( + extensions=None, + ), ) outputs = BRAINSLmkTransform.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSMush.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSMush.py index b16829ef8f..e6eac9cf2d 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSMush.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSMush.py @@ -4,24 +4,70 @@ def test_BRAINSMush_inputs(): input_map = dict( - args=dict(argstr="%s",), - boundingBoxSize=dict(argstr="--boundingBoxSize %s", sep=",",), - boundingBoxStart=dict(argstr="--boundingBoxStart %s", sep=",",), - desiredMean=dict(argstr="--desiredMean %f",), - desiredVariance=dict(argstr="--desiredVariance %f",), - environ=dict(nohash=True, usedefault=True,), - inputFirstVolume=dict(argstr="--inputFirstVolume %s", extensions=None,), - inputMaskVolume=dict(argstr="--inputMaskVolume %s", extensions=None,), - inputSecondVolume=dict(argstr="--inputSecondVolume %s", extensions=None,), - lowerThresholdFactor=dict(argstr="--lowerThresholdFactor %f",), - lowerThresholdFactorPre=dict(argstr="--lowerThresholdFactorPre %f",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputMask=dict(argstr="--outputMask %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - outputWeightsFile=dict(argstr="--outputWeightsFile %s", hash_files=False,), - seed=dict(argstr="--seed %s", sep=",",), - upperThresholdFactor=dict(argstr="--upperThresholdFactor %f",), - upperThresholdFactorPre=dict(argstr="--upperThresholdFactorPre %f",), + args=dict( + argstr="%s", + ), + boundingBoxSize=dict( + argstr="--boundingBoxSize %s", + sep=",", + ), + boundingBoxStart=dict( + argstr="--boundingBoxStart %s", + sep=",", + ), + desiredMean=dict( + argstr="--desiredMean %f", + ), + desiredVariance=dict( + argstr="--desiredVariance %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputFirstVolume=dict( + argstr="--inputFirstVolume %s", + extensions=None, + ), + inputMaskVolume=dict( + argstr="--inputMaskVolume %s", + extensions=None, + ), + inputSecondVolume=dict( + argstr="--inputSecondVolume %s", + extensions=None, + ), + lowerThresholdFactor=dict( + argstr="--lowerThresholdFactor %f", + ), + lowerThresholdFactorPre=dict( + argstr="--lowerThresholdFactorPre %f", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputMask=dict( + argstr="--outputMask %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + outputWeightsFile=dict( + argstr="--outputWeightsFile %s", + hash_files=False, + ), + seed=dict( + argstr="--seed %s", + sep=",", + ), + upperThresholdFactor=dict( + argstr="--upperThresholdFactor %f", + ), + upperThresholdFactorPre=dict( + argstr="--upperThresholdFactorPre %f", + ), ) inputs = BRAINSMush.input_spec() @@ -32,9 +78,15 @@ def test_BRAINSMush_inputs(): def test_BRAINSMush_outputs(): output_map = dict( - outputMask=dict(extensions=None,), - outputVolume=dict(extensions=None,), - outputWeightsFile=dict(extensions=None,), + outputMask=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), + outputWeightsFile=dict( + extensions=None, + ), ) outputs = BRAINSMush.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSSnapShotWriter.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSSnapShotWriter.py index 30bf49a6ad..a120b062a4 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSSnapShotWriter.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSSnapShotWriter.py @@ -4,21 +4,39 @@ def test_BRAINSSnapShotWriter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputBinaryVolumes=dict(argstr="--inputBinaryVolumes %s...",), - inputPlaneDirection=dict(argstr="--inputPlaneDirection %s", sep=",",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputBinaryVolumes=dict( + argstr="--inputBinaryVolumes %s...", + ), + inputPlaneDirection=dict( + argstr="--inputPlaneDirection %s", + sep=",", + ), inputSliceToExtractInIndex=dict( - argstr="--inputSliceToExtractInIndex %s", sep=",", + argstr="--inputSliceToExtractInIndex %s", + sep=",", ), inputSliceToExtractInPercent=dict( - argstr="--inputSliceToExtractInPercent %s", sep=",", + argstr="--inputSliceToExtractInPercent %s", + sep=",", ), inputSliceToExtractInPhysicalPoint=dict( - argstr="--inputSliceToExtractInPhysicalPoint %s", sep=",", + argstr="--inputSliceToExtractInPhysicalPoint %s", + sep=",", + ), + inputVolumes=dict( + argstr="--inputVolumes %s...", + ), + outputFilename=dict( + argstr="--outputFilename %s", + hash_files=False, ), - inputVolumes=dict(argstr="--inputVolumes %s...",), - outputFilename=dict(argstr="--outputFilename %s", hash_files=False,), ) inputs = BRAINSSnapShotWriter.input_spec() @@ -28,7 +46,11 @@ def test_BRAINSSnapShotWriter_inputs(): def test_BRAINSSnapShotWriter_outputs(): - output_map = dict(outputFilename=dict(extensions=None,),) + output_map = dict( + outputFilename=dict( + extensions=None, + ), + ) outputs = BRAINSSnapShotWriter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTransformConvert.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTransformConvert.py index 4316f4561b..1eebbb0cec 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTransformConvert.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTransformConvert.py @@ -4,14 +4,35 @@ def test_BRAINSTransformConvert_inputs(): input_map = dict( - args=dict(argstr="%s",), - displacementVolume=dict(argstr="--displacementVolume %s", hash_files=False,), - environ=dict(nohash=True, usedefault=True,), - inputTransform=dict(argstr="--inputTransform %s", extensions=None,), - outputPrecisionType=dict(argstr="--outputPrecisionType %s",), - outputTransform=dict(argstr="--outputTransform %s", hash_files=False,), - outputTransformType=dict(argstr="--outputTransformType %s",), - referenceVolume=dict(argstr="--referenceVolume %s", extensions=None,), + args=dict( + argstr="%s", + ), + displacementVolume=dict( + argstr="--displacementVolume %s", + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputTransform=dict( + argstr="--inputTransform %s", + extensions=None, + ), + outputPrecisionType=dict( + argstr="--outputPrecisionType %s", + ), + outputTransform=dict( + argstr="--outputTransform %s", + hash_files=False, + ), + outputTransformType=dict( + argstr="--outputTransformType %s", + ), + referenceVolume=dict( + argstr="--referenceVolume %s", + extensions=None, + ), ) inputs = BRAINSTransformConvert.input_spec() @@ -22,8 +43,12 @@ def test_BRAINSTransformConvert_inputs(): def test_BRAINSTransformConvert_outputs(): output_map = dict( - displacementVolume=dict(extensions=None,), - outputTransform=dict(extensions=None,), + displacementVolume=dict( + extensions=None, + ), + outputTransform=dict( + extensions=None, + ), ) outputs = BRAINSTransformConvert.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTrimForegroundInDirection.py b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTrimForegroundInDirection.py index ed3180746c..fa68f51e21 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTrimForegroundInDirection.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_BRAINSTrimForegroundInDirection.py @@ -4,16 +4,39 @@ def test_BRAINSTrimForegroundInDirection_inputs(): input_map = dict( - BackgroundFillValue=dict(argstr="--BackgroundFillValue %s",), - args=dict(argstr="%s",), - closingSize=dict(argstr="--closingSize %d",), - directionCode=dict(argstr="--directionCode %d",), - environ=dict(nohash=True, usedefault=True,), - headSizeLimit=dict(argstr="--headSizeLimit %f",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - otsuPercentileThreshold=dict(argstr="--otsuPercentileThreshold %f",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), + BackgroundFillValue=dict( + argstr="--BackgroundFillValue %s", + ), + args=dict( + argstr="%s", + ), + closingSize=dict( + argstr="--closingSize %d", + ), + directionCode=dict( + argstr="--directionCode %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + headSizeLimit=dict( + argstr="--headSizeLimit %f", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + otsuPercentileThreshold=dict( + argstr="--otsuPercentileThreshold %f", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), ) inputs = BRAINSTrimForegroundInDirection.input_spec() @@ -23,7 +46,11 @@ def test_BRAINSTrimForegroundInDirection_inputs(): def test_BRAINSTrimForegroundInDirection_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSTrimForegroundInDirection.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_CleanUpOverlapLabels.py b/nipype/interfaces/semtools/utilities/tests/test_auto_CleanUpOverlapLabels.py index b7a9167092..14ec09298c 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_CleanUpOverlapLabels.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_CleanUpOverlapLabels.py @@ -4,11 +4,19 @@ def test_CleanUpOverlapLabels_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputBinaryVolumes=dict(argstr="--inputBinaryVolumes %s...",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputBinaryVolumes=dict( + argstr="--inputBinaryVolumes %s...", + ), outputBinaryVolumes=dict( - argstr="--outputBinaryVolumes %s...", hash_files=False, + argstr="--outputBinaryVolumes %s...", + hash_files=False, ), ) inputs = CleanUpOverlapLabels.input_spec() @@ -19,7 +27,9 @@ def test_CleanUpOverlapLabels_inputs(): def test_CleanUpOverlapLabels_outputs(): - output_map = dict(outputBinaryVolumes=dict(),) + output_map = dict( + outputBinaryVolumes=dict(), + ) outputs = CleanUpOverlapLabels.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_FindCenterOfBrain.py b/nipype/interfaces/semtools/utilities/tests/test_auto_FindCenterOfBrain.py index bf2d9ab03d..4a0d7c89c2 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_FindCenterOfBrain.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_FindCenterOfBrain.py @@ -4,28 +4,69 @@ def test_FindCenterOfBrain_inputs(): input_map = dict( - args=dict(argstr="%s",), - axis=dict(argstr="--axis %d",), - backgroundValue=dict(argstr="--backgroundValue %d",), - clippedImageMask=dict(argstr="--clippedImageMask %s", hash_files=False,), - closingSize=dict(argstr="--closingSize %d",), + args=dict( + argstr="%s", + ), + axis=dict( + argstr="--axis %d", + ), + backgroundValue=dict( + argstr="--backgroundValue %d", + ), + clippedImageMask=dict( + argstr="--clippedImageMask %s", + hash_files=False, + ), + closingSize=dict( + argstr="--closingSize %d", + ), debugAfterGridComputationsForegroundImage=dict( - argstr="--debugAfterGridComputationsForegroundImage %s", hash_files=False, + argstr="--debugAfterGridComputationsForegroundImage %s", + hash_files=False, ), debugClippedImageMask=dict( - argstr="--debugClippedImageMask %s", hash_files=False, - ), - debugDistanceImage=dict(argstr="--debugDistanceImage %s", hash_files=False,), - debugGridImage=dict(argstr="--debugGridImage %s", hash_files=False,), - debugTrimmedImage=dict(argstr="--debugTrimmedImage %s", hash_files=False,), - environ=dict(nohash=True, usedefault=True,), - generateDebugImages=dict(argstr="--generateDebugImages ",), - headSizeEstimate=dict(argstr="--headSizeEstimate %f",), - headSizeLimit=dict(argstr="--headSizeLimit %f",), - imageMask=dict(argstr="--imageMask %s", extensions=None,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - maximize=dict(argstr="--maximize ",), - otsuPercentileThreshold=dict(argstr="--otsuPercentileThreshold %f",), + argstr="--debugClippedImageMask %s", + hash_files=False, + ), + debugDistanceImage=dict( + argstr="--debugDistanceImage %s", + hash_files=False, + ), + debugGridImage=dict( + argstr="--debugGridImage %s", + hash_files=False, + ), + debugTrimmedImage=dict( + argstr="--debugTrimmedImage %s", + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + generateDebugImages=dict( + argstr="--generateDebugImages ", + ), + headSizeEstimate=dict( + argstr="--headSizeEstimate %f", + ), + headSizeLimit=dict( + argstr="--headSizeLimit %f", + ), + imageMask=dict( + argstr="--imageMask %s", + extensions=None, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + maximize=dict( + argstr="--maximize ", + ), + otsuPercentileThreshold=dict( + argstr="--otsuPercentileThreshold %f", + ), ) inputs = FindCenterOfBrain.input_spec() @@ -36,12 +77,24 @@ def test_FindCenterOfBrain_inputs(): def test_FindCenterOfBrain_outputs(): output_map = dict( - clippedImageMask=dict(extensions=None,), - debugAfterGridComputationsForegroundImage=dict(extensions=None,), - debugClippedImageMask=dict(extensions=None,), - debugDistanceImage=dict(extensions=None,), - debugGridImage=dict(extensions=None,), - debugTrimmedImage=dict(extensions=None,), + clippedImageMask=dict( + extensions=None, + ), + debugAfterGridComputationsForegroundImage=dict( + extensions=None, + ), + debugClippedImageMask=dict( + extensions=None, + ), + debugDistanceImage=dict( + extensions=None, + ), + debugGridImage=dict( + extensions=None, + ), + debugTrimmedImage=dict( + extensions=None, + ), ) outputs = FindCenterOfBrain.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_GenerateLabelMapFromProbabilityMap.py b/nipype/interfaces/semtools/utilities/tests/test_auto_GenerateLabelMapFromProbabilityMap.py index 289473e902..d3840ec7bd 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_GenerateLabelMapFromProbabilityMap.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_GenerateLabelMapFromProbabilityMap.py @@ -4,11 +4,23 @@ def test_GenerateLabelMapFromProbabilityMap_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolumes=dict(argstr="--inputVolumes %s...",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputLabelVolume=dict(argstr="--outputLabelVolume %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolumes=dict( + argstr="--inputVolumes %s...", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputLabelVolume=dict( + argstr="--outputLabelVolume %s", + hash_files=False, + ), ) inputs = GenerateLabelMapFromProbabilityMap.input_spec() @@ -18,7 +30,11 @@ def test_GenerateLabelMapFromProbabilityMap_inputs(): def test_GenerateLabelMapFromProbabilityMap_outputs(): - output_map = dict(outputLabelVolume=dict(extensions=None,),) + output_map = dict( + outputLabelVolume=dict( + extensions=None, + ), + ) outputs = GenerateLabelMapFromProbabilityMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_ImageRegionPlotter.py b/nipype/interfaces/semtools/utilities/tests/test_auto_ImageRegionPlotter.py index 7d9f72aedb..5b71204a67 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_ImageRegionPlotter.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_ImageRegionPlotter.py @@ -4,17 +4,44 @@ def test_ImageRegionPlotter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputBinaryROIVolume=dict(argstr="--inputBinaryROIVolume %s", extensions=None,), - inputLabelVolume=dict(argstr="--inputLabelVolume %s", extensions=None,), - inputVolume1=dict(argstr="--inputVolume1 %s", extensions=None,), - inputVolume2=dict(argstr="--inputVolume2 %s", extensions=None,), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - outputJointHistogramData=dict(argstr="--outputJointHistogramData %s",), - useIntensityForHistogram=dict(argstr="--useIntensityForHistogram ",), - useROIAUTO=dict(argstr="--useROIAUTO ",), - verbose=dict(argstr="--verbose ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputBinaryROIVolume=dict( + argstr="--inputBinaryROIVolume %s", + extensions=None, + ), + inputLabelVolume=dict( + argstr="--inputLabelVolume %s", + extensions=None, + ), + inputVolume1=dict( + argstr="--inputVolume1 %s", + extensions=None, + ), + inputVolume2=dict( + argstr="--inputVolume2 %s", + extensions=None, + ), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + outputJointHistogramData=dict( + argstr="--outputJointHistogramData %s", + ), + useIntensityForHistogram=dict( + argstr="--useIntensityForHistogram ", + ), + useROIAUTO=dict( + argstr="--useROIAUTO ", + ), + verbose=dict( + argstr="--verbose ", + ), ) inputs = ImageRegionPlotter.input_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_JointHistogram.py b/nipype/interfaces/semtools/utilities/tests/test_auto_JointHistogram.py index 6ac46c3695..d5e61c867a 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_JointHistogram.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_JointHistogram.py @@ -4,18 +4,35 @@ def test_JointHistogram_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputMaskVolumeInXAxis=dict( - argstr="--inputMaskVolumeInXAxis %s", extensions=None, + argstr="--inputMaskVolumeInXAxis %s", + extensions=None, ), inputMaskVolumeInYAxis=dict( - argstr="--inputMaskVolumeInYAxis %s", extensions=None, + argstr="--inputMaskVolumeInYAxis %s", + extensions=None, + ), + inputVolumeInXAxis=dict( + argstr="--inputVolumeInXAxis %s", + extensions=None, + ), + inputVolumeInYAxis=dict( + argstr="--inputVolumeInYAxis %s", + extensions=None, + ), + outputJointHistogramImage=dict( + argstr="--outputJointHistogramImage %s", + ), + verbose=dict( + argstr="--verbose ", ), - inputVolumeInXAxis=dict(argstr="--inputVolumeInXAxis %s", extensions=None,), - inputVolumeInYAxis=dict(argstr="--inputVolumeInYAxis %s", extensions=None,), - outputJointHistogramImage=dict(argstr="--outputJointHistogramImage %s",), - verbose=dict(argstr="--verbose ",), ) inputs = JointHistogram.input_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_ShuffleVectorsModule.py b/nipype/interfaces/semtools/utilities/tests/test_auto_ShuffleVectorsModule.py index f3541344a0..4b7d3431bd 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_ShuffleVectorsModule.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_ShuffleVectorsModule.py @@ -4,15 +4,24 @@ def test_ShuffleVectorsModule_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), inputVectorFileBaseName=dict( - argstr="--inputVectorFileBaseName %s", extensions=None, + argstr="--inputVectorFileBaseName %s", + extensions=None, ), outputVectorFileBaseName=dict( - argstr="--outputVectorFileBaseName %s", hash_files=False, + argstr="--outputVectorFileBaseName %s", + hash_files=False, + ), + resampleProportion=dict( + argstr="--resampleProportion %f", ), - resampleProportion=dict(argstr="--resampleProportion %f",), ) inputs = ShuffleVectorsModule.input_spec() @@ -22,7 +31,11 @@ def test_ShuffleVectorsModule_inputs(): def test_ShuffleVectorsModule_outputs(): - output_map = dict(outputVectorFileBaseName=dict(extensions=None,),) + output_map = dict( + outputVectorFileBaseName=dict( + extensions=None, + ), + ) outputs = ShuffleVectorsModule.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_fcsv_to_hdf5.py b/nipype/interfaces/semtools/utilities/tests/test_auto_fcsv_to_hdf5.py index f64c302328..896f630839 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_fcsv_to_hdf5.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_fcsv_to_hdf5.py @@ -4,16 +4,34 @@ def test_fcsv_to_hdf5_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - landmarkGlobPattern=dict(argstr="--landmarkGlobPattern %s",), - landmarkTypesList=dict(argstr="--landmarkTypesList %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + landmarkGlobPattern=dict( + argstr="--landmarkGlobPattern %s", + ), + landmarkTypesList=dict( + argstr="--landmarkTypesList %s", + extensions=None, + ), landmarksInformationFile=dict( - argstr="--landmarksInformationFile %s", hash_files=False, + argstr="--landmarksInformationFile %s", + hash_files=False, + ), + modelFile=dict( + argstr="--modelFile %s", + hash_files=False, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + versionID=dict( + argstr="--versionID %s", ), - modelFile=dict(argstr="--modelFile %s", hash_files=False,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - versionID=dict(argstr="--versionID %s",), ) inputs = fcsv_to_hdf5.input_spec() @@ -24,8 +42,12 @@ def test_fcsv_to_hdf5_inputs(): def test_fcsv_to_hdf5_outputs(): output_map = dict( - landmarksInformationFile=dict(extensions=None,), - modelFile=dict(extensions=None,), + landmarksInformationFile=dict( + extensions=None, + ), + modelFile=dict( + extensions=None, + ), ) outputs = fcsv_to_hdf5.output_spec() diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_insertMidACPCpoint.py b/nipype/interfaces/semtools/utilities/tests/test_auto_insertMidACPCpoint.py index 7e02bfc9e1..05aa2a3910 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_insertMidACPCpoint.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_insertMidACPCpoint.py @@ -4,10 +4,21 @@ def test_insertMidACPCpoint_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputLandmarkFile=dict(argstr="--inputLandmarkFile %s", extensions=None,), - outputLandmarkFile=dict(argstr="--outputLandmarkFile %s", hash_files=False,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputLandmarkFile=dict( + argstr="--inputLandmarkFile %s", + extensions=None, + ), + outputLandmarkFile=dict( + argstr="--outputLandmarkFile %s", + hash_files=False, + ), ) inputs = insertMidACPCpoint.input_spec() @@ -17,7 +28,11 @@ def test_insertMidACPCpoint_inputs(): def test_insertMidACPCpoint_outputs(): - output_map = dict(outputLandmarkFile=dict(extensions=None,),) + output_map = dict( + outputLandmarkFile=dict( + extensions=None, + ), + ) outputs = insertMidACPCpoint.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationAligner.py b/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationAligner.py index 79fedd5b68..472a1326e0 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationAligner.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationAligner.py @@ -4,11 +4,20 @@ def test_landmarksConstellationAligner_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputLandmarksPaired=dict(argstr="--inputLandmarksPaired %s", extensions=None,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputLandmarksPaired=dict( + argstr="--inputLandmarksPaired %s", + extensions=None, + ), outputLandmarksPaired=dict( - argstr="--outputLandmarksPaired %s", hash_files=False, + argstr="--outputLandmarksPaired %s", + hash_files=False, ), ) inputs = landmarksConstellationAligner.input_spec() @@ -19,7 +28,11 @@ def test_landmarksConstellationAligner_inputs(): def test_landmarksConstellationAligner_outputs(): - output_map = dict(outputLandmarksPaired=dict(extensions=None,),) + output_map = dict( + outputLandmarksPaired=dict( + extensions=None, + ), + ) outputs = landmarksConstellationAligner.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationWeights.py b/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationWeights.py index 5bd27aa957..c14fdff775 100644 --- a/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationWeights.py +++ b/nipype/interfaces/semtools/utilities/tests/test_auto_landmarksConstellationWeights.py @@ -4,12 +4,29 @@ def test_landmarksConstellationWeights_inputs(): input_map = dict( - LLSModel=dict(argstr="--LLSModel %s", extensions=None,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputTemplateModel=dict(argstr="--inputTemplateModel %s", extensions=None,), - inputTrainingList=dict(argstr="--inputTrainingList %s", extensions=None,), - outputWeightsList=dict(argstr="--outputWeightsList %s", hash_files=False,), + LLSModel=dict( + argstr="--LLSModel %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputTemplateModel=dict( + argstr="--inputTemplateModel %s", + extensions=None, + ), + inputTrainingList=dict( + argstr="--inputTrainingList %s", + extensions=None, + ), + outputWeightsList=dict( + argstr="--outputWeightsList %s", + hash_files=False, + ), ) inputs = landmarksConstellationWeights.input_spec() @@ -19,7 +36,11 @@ def test_landmarksConstellationWeights_inputs(): def test_landmarksConstellationWeights_outputs(): - output_map = dict(outputWeightsList=dict(extensions=None,),) + output_map = dict( + outputWeightsList=dict( + extensions=None, + ), + ) outputs = landmarksConstellationWeights.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/__init__.py b/nipype/interfaces/slicer/__init__.py index 91c56b131f..ca191b99df 100644 --- a/nipype/interfaces/slicer/__init__.py +++ b/nipype/interfaces/slicer/__init__.py @@ -1,10 +1,10 @@ -# -*- coding: utf-8 -*- """ 3D Slicer is a platform for medical image informatics processing and visualization. For an EXPERIMENTAL implementation of an interface for the ``3dSlicer`` full framework, please check `"dynamic" Slicer `__. """ + from .diffusion import * from .segmentation import * from .filtering import * diff --git a/nipype/interfaces/slicer/base.py b/nipype/interfaces/slicer/base.py index aae54ec00b..de00883265 100644 --- a/nipype/interfaces/slicer/base.py +++ b/nipype/interfaces/slicer/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from ..base import SEMLikeCommandLine diff --git a/nipype/interfaces/slicer/converters.py b/nipype/interfaces/slicer/converters.py index cc477e99d0..1be9651f55 100644 --- a/nipype/interfaces/slicer/converters.py +++ b/nipype/interfaces/slicer/converters.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class DicomToNrrdConverterInputSpec(CommandLineInputSpec): @@ -61,21 +54,20 @@ class DicomToNrrdConverterOutputSpec(TraitedSpec): class DicomToNrrdConverter(SEMLikeCommandLine): """title: DICOM to NRRD Converter -category: Converters + category: Converters -description: Converts diffusion weighted MR images in dicom series into Nrrd format for analysis in Slicer. This program has been tested on only a limited subset of DTI dicom formats available from Siemens, GE, and Phillips scanners. Work in progress to support dicom multi-frame data. The program parses dicom header to extract necessary information about measurement frame, diffusion weighting directions, b-values, etc, and write out a nrrd image. For non-diffusion weighted dicom images, it loads in an entire dicom series and writes out a single dicom volume in a .nhdr/.raw pair. + description: Converts diffusion weighted MR images in dicom series into Nrrd format for analysis in Slicer. This program has been tested on only a limited subset of DTI dicom formats available from Siemens, GE, and Phillips scanners. Work in progress to support dicom multi-frame data. The program parses dicom header to extract necessary information about measurement frame, diffusion weighting directions, b-values, etc, and write out a nrrd image. For non-diffusion weighted dicom images, it loads in an entire dicom series and writes out a single dicom volume in a .nhdr/.raw pair. -version: 0.2.0.$Revision: 916 $(alpha) + version: 0.2.0.$Revision: 916 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DicomToNrrdConverter + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DicomToNrrdConverter -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: Xiaodong Tao (GE), Vince Magnotta (UIowa), Hans Johnson (UIowa) + contributor: Xiaodong Tao (GE), Vince Magnotta (UIowa), Hans Johnson (UIowa) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for DTI data produced on Philips scanners was contributed by Vincent Magnotta and Hans Johnson at the University of Iowa. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Additional support for DTI data produced on Philips scanners was contributed by Vincent Magnotta and Hans Johnson at the University of Iowa. + """ input_spec = DicomToNrrdConverterInputSpec output_spec = DicomToNrrdConverterOutputSpec @@ -157,19 +149,18 @@ class OrientScalarVolumeOutputSpec(TraitedSpec): class OrientScalarVolume(SEMLikeCommandLine): """title: Orient Scalar Volume -category: Converters - -description: Orients an output volume. Rearranges the slices in a volume according to the selected orientation. The slices are not interpolated. They are just reordered and/or permuted. The resulting volume will cover the original volume. NOTE: since Slicer takes into account the orientation of a volume, the re-oriented volume will not show any difference from the original volume, To see the difference, save the volume and display it with a system that either ignores the orientation of the image (e.g. Paraview) or displays individual images. + category: Converters -version: 0.1.0.$Revision: 19608 $(alpha) + description: Orients an output volume. Rearranges the slices in a volume according to the selected orientation. The slices are not interpolated. They are just reordered and/or permuted. The resulting volume will cover the original volume. NOTE: since Slicer takes into account the orientation of a volume, the re-oriented volume will not show any difference from the original volume, To see the difference, save the volume and display it with a system that either ignores the orientation of the image (e.g. Paraview) or displays individual images. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/OrientImage + version: 0.1.0.$Revision: 19608 $(alpha) -contributor: Bill Lorensen (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/OrientImage -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Bill Lorensen (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = OrientScalarVolumeInputSpec output_spec = OrientScalarVolumeOutputSpec diff --git a/nipype/interfaces/slicer/diffusion/__init__.py b/nipype/interfaces/slicer/diffusion/__init__.py index d7f3089de5..807fecdde2 100644 --- a/nipype/interfaces/slicer/diffusion/__init__.py +++ b/nipype/interfaces/slicer/diffusion/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .diffusion import ( ResampleDTIVolume, DWIRicianLMMSEFilter, diff --git a/nipype/interfaces/slicer/diffusion/diffusion.py b/nipype/interfaces/slicer/diffusion/diffusion.py index 8fc0f0c6c9..3238981562 100644 --- a/nipype/interfaces/slicer/diffusion/diffusion.py +++ b/nipype/interfaces/slicer/diffusion/diffusion.py @@ -1,21 +1,15 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class ResampleDTIVolumeInputSpec(CommandLineInputSpec): @@ -52,7 +46,7 @@ class ResampleDTIVolumeInputSpec(CommandLineInputSpec): "nn", "ws", "bs", - desc="Sampling algorithm (linear , nn (nearest neighborhoor), ws (WindowedSinc), bs (BSpline) )", + desc="Sampling algorithm (linear , nn (nearest neighbor), ws (WindowedSinc), bs (BSpline) )", argstr="--interpolation %s", ) correction = traits.Enum( @@ -162,19 +156,18 @@ class ResampleDTIVolumeOutputSpec(TraitedSpec): class ResampleDTIVolume(SEMLikeCommandLine): """title: Resample DTI Volume -category: Diffusion.Diffusion Tensor Images + category: Diffusion.Diffusion Tensor Images -description: Resampling an image is a very important task in image analysis. It is especially important in the frame of image registration. This module implements DT image resampling through the use of itk Transforms. The resampling is controlled by the Output Spacing. "Resampling" is performed in space coordinates, not pixel/grid coordinates. It is quite important to ensure that image spacing is properly set on the images involved. The interpolator is required since the mapping from one space to the other will often require evaluation of the intensity of the image at non-grid positions. + description: Resampling an image is a very important task in image analysis. It is especially important in the frame of image registration. This module implements DT image resampling through the use of itk Transforms. The resampling is controlled by the Output Spacing. "Resampling" is performed in space coordinates, not pixel/grid coordinates. It is quite important to ensure that image spacing is properly set on the images involved. The interpolator is required since the mapping from one space to the other will often require evaluation of the intensity of the image at non-grid positions. -version: 0.1 + version: 0.1 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ResampleDTI + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ResampleDTI -contributor: Francois Budin (UNC) + contributor: Francois Budin (UNC) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Information on the National Centers for Biomedical Computing can be obtained from http://nihroadmap.nih.gov/bioinformatics - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Information on the National Centers for Biomedical Computing can be obtained from http://nihroadmap.nih.gov/bioinformatics + """ input_spec = ResampleDTIVolumeInputSpec output_spec = ResampleDTIVolumeOutputSpec @@ -232,22 +225,21 @@ class DWIRicianLMMSEFilterOutputSpec(TraitedSpec): class DWIRicianLMMSEFilter(SEMLikeCommandLine): """title: DWI Rician LMMSE Filter -category: Diffusion.Diffusion Weighted Images - -description: This module reduces noise (or unwanted detail) on a set of diffusion weighted images. For this, it filters the image in the mean squared error sense using a Rician noise model. Images corresponding to each gradient direction, including baseline, are processed individually. The noise parameter is automatically estimated (noise estimation improved but slower). -Note that this is a general purpose filter for MRi images. The module jointLMMSE has been specifically designed for DWI volumes and shows a better performance, so its use is recommended instead. -A complete description of the algorithm in this module can be found in: -S. Aja-Fernandez, M. Niethammer, M. Kubicki, M. Shenton, and C.-F. Westin. Restoration of DWI data using a Rician LMMSE estimator. IEEE Transactions on Medical Imaging, 27(10): pp. 1389-1403, Oct. 2008. + category: Diffusion.Diffusion Weighted Images -version: 0.1.1.$Revision: 1 $(alpha) + description: This module reduces noise (or unwanted detail) on a set of diffusion weighted images. For this, it filters the image in the mean squared error sense using a Rician noise model. Images corresponding to each gradient direction, including baseline, are processed individually. The noise parameter is automatically estimated (noise estimation improved but slower). + Note that this is a general purpose filter for MRi images. The module jointLMMSE has been specifically designed for DWI volumes and shows a better performance, so its use is recommended instead. + A complete description of the algorithm in this module can be found in: + S. Aja-Fernandez, M. Niethammer, M. Kubicki, M. Shenton, and C.-F. Westin. Restoration of DWI data using a Rician LMMSE estimator. IEEE Transactions on Medical Imaging, 27(10): pp. 1389-1403, Oct. 2008. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/RicianLMMSEImageFilter + version: 0.1.1.$Revision: 1 $(alpha) -contributor: Antonio Tristan Vega (UVa), Santiago Aja Fernandez (UVa), Marc Niethammer (UNC) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/RicianLMMSEImageFilter -acknowledgements: Partially founded by grant number TEC2007-67073/TCM from the Comision Interministerial de Ciencia y Tecnologia (Spain). + contributor: Antonio Tristan Vega (UVa), Santiago Aja Fernandez (UVa), Marc Niethammer (UNC) -""" + acknowledgements: Partially founded by grant number TEC2007-67073/TCM from the Comision Interministerial de Ciencia y Tecnologia (Spain). + """ input_spec = DWIRicianLMMSEFilterInputSpec output_spec = DWIRicianLMMSEFilterOutputSpec @@ -330,21 +322,20 @@ class TractographyLabelMapSeedingOutputSpec(TraitedSpec): class TractographyLabelMapSeeding(SEMLikeCommandLine): """title: Tractography Label Map Seeding -category: Diffusion.Diffusion Tensor Images - -description: Seed tracts on a Diffusion Tensor Image (DT) from a label map + category: Diffusion.Diffusion Tensor Images -version: 0.1.0.$Revision: 1892 $(alpha) + description: Seed tracts on a Diffusion Tensor Image (DT) from a label map -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Seeding + version: 0.1.0.$Revision: 1892 $(alpha) -license: slicer3 + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Seeding -contributor: Raul San Jose (SPL, BWH), Demian Wassermann (SPL, BWH) + license: slicer3 -acknowledgements: Laboratory of Mathematics in Imaging. This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Raul San Jose (SPL, BWH), Demian Wassermann (SPL, BWH) -""" + acknowledgements: Laboratory of Mathematics in Imaging. This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = TractographyLabelMapSeedingInputSpec output_spec = TractographyLabelMapSeedingOutputSpec @@ -386,22 +377,21 @@ class DWIJointRicianLMMSEFilterOutputSpec(TraitedSpec): class DWIJointRicianLMMSEFilter(SEMLikeCommandLine): """title: DWI Joint Rician LMMSE Filter -category: Diffusion.Diffusion Weighted Images + category: Diffusion.Diffusion Weighted Images -description: This module reduces Rician noise (or unwanted detail) on a set of diffusion weighted images. For this, it filters the image in the mean squared error sense using a Rician noise model. The N closest gradient directions to the direction being processed are filtered together to improve the results: the noise-free signal is seen as an n-diemensional vector which has to be estimated with the LMMSE method from a set of corrupted measurements. To that end, the covariance matrix of the noise-free vector and the cross covariance between this signal and the noise have to be estimated, which is done taking into account the image formation process. -The noise parameter is automatically estimated from a rough segmentation of the background of the image. In this area the signal is simply 0, so that Rician statistics reduce to Rayleigh and the noise power can be easily estimated from the mode of the histogram. -A complete description of the algorithm may be found in: -Antonio Tristan-Vega and Santiago Aja-Fernandez, DWI filtering using joint information for DTI and HARDI, Medical Image Analysis, Volume 14, Issue 2, Pages 205-218. 2010. + description: This module reduces Rician noise (or unwanted detail) on a set of diffusion weighted images. For this, it filters the image in the mean squared error sense using a Rician noise model. The N closest gradient directions to the direction being processed are filtered together to improve the results: the noise-free signal is seen as an n-diemensional vector which has to be estimated with the LMMSE method from a set of corrupted measurements. To that end, the covariance matrix of the noise-free vector and the cross covariance between this signal and the noise have to be estimated, which is done taking into account the image formation process. + The noise parameter is automatically estimated from a rough segmentation of the background of the image. In this area the signal is simply 0, so that Rician statistics reduce to Rayleigh and the noise power can be easily estimated from the mode of the histogram. + A complete description of the algorithm may be found in: + Antonio Tristan-Vega and Santiago Aja-Fernandez, DWI filtering using joint information for DTI and HARDI, Medical Image Analysis, Volume 14, Issue 2, Pages 205-218. 2010. -version: 0.1.1.$Revision: 1 $(alpha) + version: 0.1.1.$Revision: 1 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/JointRicianLMMSEImageFilter + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/JointRicianLMMSEImageFilter -contributor: Antonio Tristan Vega (UVa), Santiago Aja Fernandez (UVa) + contributor: Antonio Tristan Vega (UVa), Santiago Aja Fernandez (UVa) -acknowledgements: Partially founded by grant number TEC2007-67073/TCM from the Comision Interministerial de Ciencia y Tecnologia (Spain). - -""" + acknowledgements: Partially founded by grant number TEC2007-67073/TCM from the Comision Interministerial de Ciencia y Tecnologia (Spain). + """ input_spec = DWIJointRicianLMMSEFilterInputSpec output_spec = DWIJointRicianLMMSEFilterOutputSpec @@ -428,7 +418,7 @@ class DiffusionWeightedVolumeMaskingInputSpec(CommandLineInputSpec): argstr="%s", ) otsuomegathreshold = traits.Float( - desc="Control the sharpness of the threshold in the Otsu computation. 0: lower threshold, 1: higher threhold", + desc="Control the sharpness of the threshold in the Otsu computation. 0: lower threshold, 1: higher threshold", argstr="--otsuomegathreshold %f", ) removeislands = traits.Bool( @@ -444,19 +434,18 @@ class DiffusionWeightedVolumeMaskingOutputSpec(TraitedSpec): class DiffusionWeightedVolumeMasking(SEMLikeCommandLine): """title: Diffusion Weighted Volume Masking -category: Diffusion.Diffusion Weighted Images - -description:

Performs a mask calculation from a diffusion weighted (DW) image.

Starting from a dw image, this module computes the baseline image averaging all the images without diffusion weighting and then applies the otsu segmentation algorithm in order to produce a mask. this mask can then be used when estimating the diffusion tensor (dt) image, not to estimate tensors all over the volume.

+ category: Diffusion.Diffusion Weighted Images -version: 0.1.0.$Revision: 1892 $(alpha) + description:

Performs a mask calculation from a diffusion weighted (DW) image.

Starting from a dw image, this module computes the baseline image averaging all the images without diffusion weighting and then applies the otsu segmentation algorithm in order to produce a mask. this mask can then be used when estimating the diffusion tensor (dt) image, not to estimate tensors all over the volume.

-documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DiffusionWeightedMasking + version: 0.1.0.$Revision: 1892 $(alpha) -license: slicer3 + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DiffusionWeightedMasking -contributor: Demian Wassermann (SPL, BWH) + license: slicer3 -""" + contributor: Demian Wassermann (SPL, BWH) + """ input_spec = DiffusionWeightedVolumeMaskingInputSpec output_spec = DiffusionWeightedVolumeMaskingOutputSpec @@ -490,19 +479,18 @@ class DTIimportOutputSpec(TraitedSpec): class DTIimport(SEMLikeCommandLine): """title: DTIimport -category: Diffusion.Diffusion Data Conversion + category: Diffusion.Diffusion Data Conversion -description: Import tensor datasets from various formats, including the NifTi file format + description: Import tensor datasets from various formats, including the NifTi file format -version: 1.0 + version: 1.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DTIImport + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DTIImport -contributor: Sonia Pujol (SPL, BWH) + contributor: Sonia Pujol (SPL, BWH) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NA-MIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NA-MIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = DTIimportInputSpec output_spec = DTIimportOutputSpec @@ -551,23 +539,22 @@ class DWIToDTIEstimationOutputSpec(TraitedSpec): class DWIToDTIEstimation(SEMLikeCommandLine): """title: DWI to DTI Estimation -category: Diffusion.Diffusion Weighted Images - -description: Performs a tensor model estimation from diffusion weighted images. + category: Diffusion.Diffusion Weighted Images -There are three estimation methods available: least squares, weigthed least squares and non-linear estimation. The first method is the traditional method for tensor estimation and the fastest one. Weighted least squares takes into account the noise characteristics of the MRI images to weight the DWI samples used in the estimation based on its intensity magnitude. The last method is the more complex. + description: Performs a tensor model estimation from diffusion weighted images. -version: 0.1.0.$Revision: 1892 $(alpha) + There are three estimation methods available: least squares, weighted least squares and non-linear estimation. The first method is the traditional method for tensor estimation and the fastest one. Weighted least squares takes into account the noise characteristics of the MRI images to weight the DWI samples used in the estimation based on its intensity magnitude. The last method is the more complex. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DiffusionTensorEstimation + version: 0.1.0.$Revision: 1892 $(alpha) -license: slicer3 + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DiffusionTensorEstimation -contributor: Raul San Jose (SPL, BWH) + license: slicer3 -acknowledgements: This command module is based on the estimation functionality provided by the Teem library. This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Raul San Jose (SPL, BWH) -""" + acknowledgements: This command module is based on the estimation functionality provided by the Teem library. This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = DWIToDTIEstimationInputSpec output_spec = DWIToDTIEstimationOutputSpec @@ -628,19 +615,18 @@ class DiffusionTensorScalarMeasurementsOutputSpec(TraitedSpec): class DiffusionTensorScalarMeasurements(SEMLikeCommandLine): """title: Diffusion Tensor Scalar Measurements -category: Diffusion.Diffusion Tensor Images + category: Diffusion.Diffusion Tensor Images -description: Compute a set of different scalar measurements from a tensor field, specially oriented for Diffusion Tensors where some rotationally invariant measurements, like Fractional Anisotropy, are highly used to describe the anistropic behaviour of the tensor. + description: Compute a set of different scalar measurements from a tensor field, specially oriented for Diffusion Tensors where some rotationally invariant measurements, like Fractional Anisotropy, are highly used to describe the anistropic behaviour of the tensor. -version: 0.1.0.$Revision: 1892 $(alpha) + version: 0.1.0.$Revision: 1892 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DiffusionTensorMathematics + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DiffusionTensorMathematics -contributor: Raul San Jose (SPL, BWH) + contributor: Raul San Jose (SPL, BWH) -acknowledgements: LMI - -""" + acknowledgements: LMI + """ input_spec = DiffusionTensorScalarMeasurementsInputSpec output_spec = DiffusionTensorScalarMeasurementsOutputSpec @@ -667,19 +653,18 @@ class DTIexportOutputSpec(TraitedSpec): class DTIexport(SEMLikeCommandLine): """title: DTIexport -category: Diffusion.Diffusion Data Conversion - -description: Export DTI data to various file formats + category: Diffusion.Diffusion Data Conversion -version: 1.0 + description: Export DTI data to various file formats -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DTIExport + version: 1.0 -contributor: Sonia Pujol (SPL, BWH) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/DTIExport -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NA-MIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Sonia Pujol (SPL, BWH) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NA-MIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = DTIexportInputSpec output_spec = DTIexportOutputSpec diff --git a/nipype/interfaces/slicer/diffusion/tests/__init__.py b/nipype/interfaces/slicer/diffusion/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/slicer/diffusion/tests/__init__.py +++ b/nipype/interfaces/slicer/diffusion/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIexport.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIexport.py index 7c7f02cacc..9017db6760 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIexport.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIexport.py @@ -4,10 +4,23 @@ def test_DTIexport_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputTensor=dict(argstr="%s", extensions=None, position=-2,), - outputFile=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputTensor=dict( + argstr="%s", + extensions=None, + position=-2, + ), + outputFile=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = DTIexport.input_spec() @@ -17,7 +30,12 @@ def test_DTIexport_inputs(): def test_DTIexport_outputs(): - output_map = dict(outputFile=dict(extensions=None, position=-1,),) + output_map = dict( + outputFile=dict( + extensions=None, + position=-1, + ), + ) outputs = DTIexport.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIimport.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIimport.py index 65ed035819..802d4ce9bc 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIimport.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DTIimport.py @@ -4,11 +4,26 @@ def test_DTIimport_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputFile=dict(argstr="%s", extensions=None, position=-2,), - outputTensor=dict(argstr="%s", hash_files=False, position=-1,), - testingmode=dict(argstr="--testingmode ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputFile=dict( + argstr="%s", + extensions=None, + position=-2, + ), + outputTensor=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + testingmode=dict( + argstr="--testingmode ", + ), ) inputs = DTIimport.input_spec() @@ -18,7 +33,12 @@ def test_DTIimport_inputs(): def test_DTIimport_outputs(): - output_map = dict(outputTensor=dict(extensions=None, position=-1,),) + output_map = dict( + outputTensor=dict( + extensions=None, + position=-1, + ), + ) outputs = DTIimport.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIJointRicianLMMSEFilter.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIJointRicianLMMSEFilter.py index 3c0d7c8861..e004599c12 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIJointRicianLMMSEFilter.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIJointRicianLMMSEFilter.py @@ -4,14 +4,37 @@ def test_DWIJointRicianLMMSEFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - compressOutput=dict(argstr="--compressOutput ",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - ng=dict(argstr="--ng %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - re=dict(argstr="--re %s", sep=",",), - rf=dict(argstr="--rf %s", sep=",",), + args=dict( + argstr="%s", + ), + compressOutput=dict( + argstr="--compressOutput ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + ng=dict( + argstr="--ng %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + re=dict( + argstr="--re %s", + sep=",", + ), + rf=dict( + argstr="--rf %s", + sep=",", + ), ) inputs = DWIJointRicianLMMSEFilter.input_spec() @@ -21,7 +44,12 @@ def test_DWIJointRicianLMMSEFilter_inputs(): def test_DWIJointRicianLMMSEFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = DWIJointRicianLMMSEFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIRicianLMMSEFilter.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIRicianLMMSEFilter.py index 8dda7d3105..3c38117737 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIRicianLMMSEFilter.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIRicianLMMSEFilter.py @@ -4,20 +4,55 @@ def test_DWIRicianLMMSEFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - compressOutput=dict(argstr="--compressOutput ",), - environ=dict(nohash=True, usedefault=True,), - hrf=dict(argstr="--hrf %f",), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - iter=dict(argstr="--iter %d",), - maxnstd=dict(argstr="--maxnstd %d",), - minnstd=dict(argstr="--minnstd %d",), - mnve=dict(argstr="--mnve %d",), - mnvf=dict(argstr="--mnvf %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - re=dict(argstr="--re %s", sep=",",), - rf=dict(argstr="--rf %s", sep=",",), - uav=dict(argstr="--uav ",), + args=dict( + argstr="%s", + ), + compressOutput=dict( + argstr="--compressOutput ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hrf=dict( + argstr="--hrf %f", + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + iter=dict( + argstr="--iter %d", + ), + maxnstd=dict( + argstr="--maxnstd %d", + ), + minnstd=dict( + argstr="--minnstd %d", + ), + mnve=dict( + argstr="--mnve %d", + ), + mnvf=dict( + argstr="--mnvf %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + re=dict( + argstr="--re %s", + sep=",", + ), + rf=dict( + argstr="--rf %s", + sep=",", + ), + uav=dict( + argstr="--uav ", + ), ) inputs = DWIRicianLMMSEFilter.input_spec() @@ -27,7 +62,12 @@ def test_DWIRicianLMMSEFilter_inputs(): def test_DWIRicianLMMSEFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = DWIRicianLMMSEFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIToDTIEstimation.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIToDTIEstimation.py index ecb618c2ff..76b305283c 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIToDTIEstimation.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DWIToDTIEstimation.py @@ -4,14 +4,38 @@ def test_DWIToDTIEstimation_inputs(): input_map = dict( - args=dict(argstr="%s",), - enumeration=dict(argstr="--enumeration %s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-3,), - mask=dict(argstr="--mask %s", extensions=None,), - outputBaseline=dict(argstr="%s", hash_files=False, position=-1,), - outputTensor=dict(argstr="%s", hash_files=False, position=-2,), - shiftNeg=dict(argstr="--shiftNeg ",), + args=dict( + argstr="%s", + ), + enumeration=dict( + argstr="--enumeration %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-3, + ), + mask=dict( + argstr="--mask %s", + extensions=None, + ), + outputBaseline=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + outputTensor=dict( + argstr="%s", + hash_files=False, + position=-2, + ), + shiftNeg=dict( + argstr="--shiftNeg ", + ), ) inputs = DWIToDTIEstimation.input_spec() @@ -22,8 +46,14 @@ def test_DWIToDTIEstimation_inputs(): def test_DWIToDTIEstimation_outputs(): output_map = dict( - outputBaseline=dict(extensions=None, position=-1,), - outputTensor=dict(extensions=None, position=-2,), + outputBaseline=dict( + extensions=None, + position=-1, + ), + outputTensor=dict( + extensions=None, + position=-2, + ), ) outputs = DWIToDTIEstimation.output_spec() diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionTensorScalarMeasurements.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionTensorScalarMeasurements.py index 70df302ae6..143194f493 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionTensorScalarMeasurements.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionTensorScalarMeasurements.py @@ -4,11 +4,26 @@ def test_DiffusionTensorScalarMeasurements_inputs(): input_map = dict( - args=dict(argstr="%s",), - enumeration=dict(argstr="--enumeration %s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-3,), - outputScalar=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + enumeration=dict( + argstr="--enumeration %s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-3, + ), + outputScalar=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = DiffusionTensorScalarMeasurements.input_spec() @@ -18,7 +33,12 @@ def test_DiffusionTensorScalarMeasurements_inputs(): def test_DiffusionTensorScalarMeasurements_outputs(): - output_map = dict(outputScalar=dict(extensions=None, position=-1,),) + output_map = dict( + outputScalar=dict( + extensions=None, + position=-1, + ), + ) outputs = DiffusionTensorScalarMeasurements.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionWeightedVolumeMasking.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionWeightedVolumeMasking.py index 659f86a642..5b11d2f578 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionWeightedVolumeMasking.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_DiffusionWeightedVolumeMasking.py @@ -4,13 +4,34 @@ def test_DiffusionWeightedVolumeMasking_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-4,), - otsuomegathreshold=dict(argstr="--otsuomegathreshold %f",), - outputBaseline=dict(argstr="%s", hash_files=False, position=-2,), - removeislands=dict(argstr="--removeislands ",), - thresholdMask=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-4, + ), + otsuomegathreshold=dict( + argstr="--otsuomegathreshold %f", + ), + outputBaseline=dict( + argstr="%s", + hash_files=False, + position=-2, + ), + removeislands=dict( + argstr="--removeislands ", + ), + thresholdMask=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = DiffusionWeightedVolumeMasking.input_spec() @@ -21,8 +42,14 @@ def test_DiffusionWeightedVolumeMasking_inputs(): def test_DiffusionWeightedVolumeMasking_outputs(): output_map = dict( - outputBaseline=dict(extensions=None, position=-2,), - thresholdMask=dict(extensions=None, position=-1,), + outputBaseline=dict( + extensions=None, + position=-2, + ), + thresholdMask=dict( + extensions=None, + position=-1, + ), ) outputs = DiffusionWeightedVolumeMasking.output_spec() diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_ResampleDTIVolume.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_ResampleDTIVolume.py index 8db387f985..c52bb5357d 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_ResampleDTIVolume.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_ResampleDTIVolume.py @@ -4,34 +4,102 @@ def test_ResampleDTIVolume_inputs(): input_map = dict( - Inverse_ITK_Transformation=dict(argstr="--Inverse_ITK_Transformation ",), - Reference=dict(argstr="--Reference %s", extensions=None,), - args=dict(argstr="%s",), - centered_transform=dict(argstr="--centered_transform ",), - correction=dict(argstr="--correction %s",), - defField=dict(argstr="--defField %s", extensions=None,), - default_pixel_value=dict(argstr="--default_pixel_value %f",), - direction_matrix=dict(argstr="--direction_matrix %s", sep=",",), - environ=dict(nohash=True, usedefault=True,), - hfieldtype=dict(argstr="--hfieldtype %s",), - image_center=dict(argstr="--image_center %s",), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - interpolation=dict(argstr="--interpolation %s",), - notbulk=dict(argstr="--notbulk ",), - number_of_thread=dict(argstr="--number_of_thread %d",), - origin=dict(argstr="--origin %s",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - rotation_point=dict(argstr="--rotation_point %s",), - size=dict(argstr="--size %s", sep=",",), - spaceChange=dict(argstr="--spaceChange ",), - spacing=dict(argstr="--spacing %s", sep=",",), - spline_order=dict(argstr="--spline_order %d",), - transform=dict(argstr="--transform %s",), - transform_matrix=dict(argstr="--transform_matrix %s", sep=",",), - transform_order=dict(argstr="--transform_order %s",), - transform_tensor_method=dict(argstr="--transform_tensor_method %s",), - transformationFile=dict(argstr="--transformationFile %s", extensions=None,), - window_function=dict(argstr="--window_function %s",), + Inverse_ITK_Transformation=dict( + argstr="--Inverse_ITK_Transformation ", + ), + Reference=dict( + argstr="--Reference %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + centered_transform=dict( + argstr="--centered_transform ", + ), + correction=dict( + argstr="--correction %s", + ), + defField=dict( + argstr="--defField %s", + extensions=None, + ), + default_pixel_value=dict( + argstr="--default_pixel_value %f", + ), + direction_matrix=dict( + argstr="--direction_matrix %s", + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hfieldtype=dict( + argstr="--hfieldtype %s", + ), + image_center=dict( + argstr="--image_center %s", + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + interpolation=dict( + argstr="--interpolation %s", + ), + notbulk=dict( + argstr="--notbulk ", + ), + number_of_thread=dict( + argstr="--number_of_thread %d", + ), + origin=dict( + argstr="--origin %s", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + rotation_point=dict( + argstr="--rotation_point %s", + ), + size=dict( + argstr="--size %s", + sep=",", + ), + spaceChange=dict( + argstr="--spaceChange ", + ), + spacing=dict( + argstr="--spacing %s", + sep=",", + ), + spline_order=dict( + argstr="--spline_order %d", + ), + transform=dict( + argstr="--transform %s", + ), + transform_matrix=dict( + argstr="--transform_matrix %s", + sep=",", + ), + transform_order=dict( + argstr="--transform_order %s", + ), + transform_tensor_method=dict( + argstr="--transform_tensor_method %s", + ), + transformationFile=dict( + argstr="--transformationFile %s", + extensions=None, + ), + window_function=dict( + argstr="--window_function %s", + ), ) inputs = ResampleDTIVolume.input_spec() @@ -41,7 +109,12 @@ def test_ResampleDTIVolume_inputs(): def test_ResampleDTIVolume_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = ResampleDTIVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/diffusion/tests/test_auto_TractographyLabelMapSeeding.py b/nipype/interfaces/slicer/diffusion/tests/test_auto_TractographyLabelMapSeeding.py index 6f36ac2a63..f8b1a3ddff 100644 --- a/nipype/interfaces/slicer/diffusion/tests/test_auto_TractographyLabelMapSeeding.py +++ b/nipype/interfaces/slicer/diffusion/tests/test_auto_TractographyLabelMapSeeding.py @@ -4,25 +4,70 @@ def test_TractographyLabelMapSeeding_inputs(): input_map = dict( - InputVolume=dict(argstr="%s", extensions=None, position=-2,), - OutputFibers=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - clthreshold=dict(argstr="--clthreshold %f",), - environ=dict(nohash=True, usedefault=True,), - inputroi=dict(argstr="--inputroi %s", extensions=None,), - integrationsteplength=dict(argstr="--integrationsteplength %f",), - label=dict(argstr="--label %d",), - maximumlength=dict(argstr="--maximumlength %f",), - minimumlength=dict(argstr="--minimumlength %f",), - name=dict(argstr="--name %s",), - outputdirectory=dict(argstr="--outputdirectory %s", hash_files=False,), - randomgrid=dict(argstr="--randomgrid ",), - seedspacing=dict(argstr="--seedspacing %f",), - stoppingcurvature=dict(argstr="--stoppingcurvature %f",), - stoppingmode=dict(argstr="--stoppingmode %s",), - stoppingvalue=dict(argstr="--stoppingvalue %f",), - useindexspace=dict(argstr="--useindexspace ",), - writetofile=dict(argstr="--writetofile ",), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + OutputFibers=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + clthreshold=dict( + argstr="--clthreshold %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputroi=dict( + argstr="--inputroi %s", + extensions=None, + ), + integrationsteplength=dict( + argstr="--integrationsteplength %f", + ), + label=dict( + argstr="--label %d", + ), + maximumlength=dict( + argstr="--maximumlength %f", + ), + minimumlength=dict( + argstr="--minimumlength %f", + ), + name=dict( + argstr="--name %s", + ), + outputdirectory=dict( + argstr="--outputdirectory %s", + hash_files=False, + ), + randomgrid=dict( + argstr="--randomgrid ", + ), + seedspacing=dict( + argstr="--seedspacing %f", + ), + stoppingcurvature=dict( + argstr="--stoppingcurvature %f", + ), + stoppingmode=dict( + argstr="--stoppingmode %s", + ), + stoppingvalue=dict( + argstr="--stoppingvalue %f", + ), + useindexspace=dict( + argstr="--useindexspace ", + ), + writetofile=dict( + argstr="--writetofile ", + ), ) inputs = TractographyLabelMapSeeding.input_spec() @@ -33,7 +78,11 @@ def test_TractographyLabelMapSeeding_inputs(): def test_TractographyLabelMapSeeding_outputs(): output_map = dict( - OutputFibers=dict(extensions=None, position=-1,), outputdirectory=dict(), + OutputFibers=dict( + extensions=None, + position=-1, + ), + outputdirectory=dict(), ) outputs = TractographyLabelMapSeeding.output_spec() diff --git a/nipype/interfaces/slicer/filtering/__init__.py b/nipype/interfaces/slicer/filtering/__init__.py index 13b79f8705..8d7a6c0da4 100644 --- a/nipype/interfaces/slicer/filtering/__init__.py +++ b/nipype/interfaces/slicer/filtering/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .morphology import GrayscaleGrindPeakImageFilter, GrayscaleFillHoleImageFilter from .denoising import ( GradientAnisotropicDiffusion, diff --git a/nipype/interfaces/slicer/filtering/arithmetic.py b/nipype/interfaces/slicer/filtering/arithmetic.py index 64d60feef3..8b729d8c6a 100644 --- a/nipype/interfaces/slicer/filtering/arithmetic.py +++ b/nipype/interfaces/slicer/filtering/arithmetic.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class MultiplyScalarVolumesInputSpec(CommandLineInputSpec): @@ -46,19 +38,18 @@ class MultiplyScalarVolumesOutputSpec(TraitedSpec): class MultiplyScalarVolumes(SEMLikeCommandLine): """title: Multiply Scalar Volumes -category: Filtering.Arithmetic + category: Filtering.Arithmetic -description: Multiplies two images. Although all image types are supported on input, only signed types are produced. The two images do not have to have the same dimensions. + description: Multiplies two images. Although all image types are supported on input, only signed types are produced. The two images do not have to have the same dimensions. -version: 0.1.0.$Revision: 8595 $(alpha) + version: 0.1.0.$Revision: 8595 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Multiply + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Multiply -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = MultiplyScalarVolumesInputSpec output_spec = MultiplyScalarVolumesOutputSpec @@ -101,19 +92,18 @@ class MaskScalarVolumeOutputSpec(TraitedSpec): class MaskScalarVolume(SEMLikeCommandLine): """title: Mask Scalar Volume -category: Filtering.Arithmetic - -description: Masks two images. The output image is set to 0 everywhere except where the chosen label from the mask volume is present, at which point it will retain it's original values. Although all image types are supported on input, only signed types are produced. The two images do not have to have the same dimensions. + category: Filtering.Arithmetic -version: 0.1.0.$Revision: 8595 $(alpha) + description: Masks two images. The output image is set to 0 everywhere except where the chosen label from the mask volume is present, at which point it will retain it's original values. Although all image types are supported on input, only signed types are produced. The two images do not have to have the same dimensions. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Mask + version: 0.1.0.$Revision: 8595 $(alpha) -contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Mask -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = MaskScalarVolumeInputSpec output_spec = MaskScalarVolumeOutputSpec @@ -149,19 +139,18 @@ class SubtractScalarVolumesOutputSpec(TraitedSpec): class SubtractScalarVolumes(SEMLikeCommandLine): """title: Subtract Scalar Volumes -category: Filtering.Arithmetic - -description: Subtracts two images. Although all image types are supported on input, only signed types are produced. The two images do not have to have the same dimensions. + category: Filtering.Arithmetic -version: 0.1.0.$Revision: 19608 $(alpha) + description: Subtracts two images. Although all image types are supported on input, only signed types are produced. The two images do not have to have the same dimensions. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Subtract + version: 0.1.0.$Revision: 19608 $(alpha) -contributor: Bill Lorensen (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Subtract -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Bill Lorensen (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = SubtractScalarVolumesInputSpec output_spec = SubtractScalarVolumesOutputSpec @@ -197,19 +186,18 @@ class AddScalarVolumesOutputSpec(TraitedSpec): class AddScalarVolumes(SEMLikeCommandLine): """title: Add Scalar Volumes -category: Filtering.Arithmetic + category: Filtering.Arithmetic -description: Adds two images. Although all image types are supported on input, only signed types are produced. The two images do not have to have the same dimensions. + description: Adds two images. Although all image types are supported on input, only signed types are produced. The two images do not have to have the same dimensions. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Add + documentation-url: http://slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Add -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = AddScalarVolumesInputSpec output_spec = AddScalarVolumesOutputSpec @@ -252,21 +240,20 @@ class CastScalarVolumeOutputSpec(TraitedSpec): class CastScalarVolume(SEMLikeCommandLine): """title: Cast Scalar Volume -category: Filtering.Arithmetic - -description: Cast a volume to a given data type. -Use at your own risk when casting an input volume into a lower precision type! -Allows casting to the same type as the input volume. + category: Filtering.Arithmetic -version: 0.1.0.$Revision: 2104 $(alpha) + description: Cast a volume to a given data type. + Use at your own risk when casting an input volume into a lower precision type! + Allows casting to the same type as the input volume. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Cast + version: 0.1.0.$Revision: 2104 $(alpha) -contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Cast -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = CastScalarVolumeInputSpec output_spec = CastScalarVolumeOutputSpec diff --git a/nipype/interfaces/slicer/filtering/checkerboardfilter.py b/nipype/interfaces/slicer/filtering/checkerboardfilter.py index 1789359e7d..336d0b13d7 100644 --- a/nipype/interfaces/slicer/filtering/checkerboardfilter.py +++ b/nipype/interfaces/slicer/filtering/checkerboardfilter.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class CheckerBoardFilterInputSpec(CommandLineInputSpec): @@ -48,19 +41,18 @@ class CheckerBoardFilterOutputSpec(TraitedSpec): class CheckerBoardFilter(SEMLikeCommandLine): """title: CheckerBoard Filter -category: Filtering + category: Filtering -description: Create a checkerboard volume of two volumes. The output volume will show the two inputs alternating according to the user supplied checkerPattern. This filter is often used to compare the results of image registration. Note that the second input is resampled to the same origin, spacing and direction before it is composed with the first input. The scalar type of the output volume will be the same as the input image scalar type. + description: Create a checkerboard volume of two volumes. The output volume will show the two inputs alternating according to the user supplied checkerPattern. This filter is often used to compare the results of image registration. Note that the second input is resampled to the same origin, spacing and direction before it is composed with the first input. The scalar type of the output volume will be the same as the input image scalar type. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/CheckerBoard + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/CheckerBoard -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = CheckerBoardFilterInputSpec output_spec = CheckerBoardFilterOutputSpec diff --git a/nipype/interfaces/slicer/filtering/denoising.py b/nipype/interfaces/slicer/filtering/denoising.py index 6c26b74618..e5d1135038 100644 --- a/nipype/interfaces/slicer/filtering/denoising.py +++ b/nipype/interfaces/slicer/filtering/denoising.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class GradientAnisotropicDiffusionInputSpec(CommandLineInputSpec): @@ -51,21 +44,20 @@ class GradientAnisotropicDiffusionOutputSpec(TraitedSpec): class GradientAnisotropicDiffusion(SEMLikeCommandLine): """title: Gradient Anisotropic Diffusion -category: Filtering.Denoising + category: Filtering.Denoising -description: Runs gradient anisotropic diffusion on a volume. + description: Runs gradient anisotropic diffusion on a volume. -Anisotropic diffusion methods reduce noise (or unwanted detail) in images while preserving specific image features, like edges. For many applications, there is an assumption that light-dark transitions (edges) are interesting. Standard isotropic diffusion methods move and blur light-dark boundaries. Anisotropic diffusion methods are formulated to specifically preserve edges. The conductance term for this implementation is a function of the gradient magnitude of the image at each point, reducing the strength of diffusion at edges. The numerical implementation of this equation is similar to that described in the Perona-Malik paper, but uses a more robust technique for gradient magnitude estimation and has been generalized to N-dimensions. + Anisotropic diffusion methods reduce noise (or unwanted detail) in images while preserving specific image features, like edges. For many applications, there is an assumption that light-dark transitions (edges) are interesting. Standard isotropic diffusion methods move and blur light-dark boundaries. Anisotropic diffusion methods are formulated to specifically preserve edges. The conductance term for this implementation is a function of the gradient magnitude of the image at each point, reducing the strength of diffusion at edges. The numerical implementation of this equation is similar to that described in the Perona-Malik paper, but uses a more robust technique for gradient magnitude estimation and has been generalized to N-dimensions. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GradientAnisotropicDiffusion + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GradientAnisotropicDiffusion -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This command module was derived from Insight/Examples (copyright) Insight Software Consortium - -""" + acknowledgements: This command module was derived from Insight/Examples (copyright) Insight Software Consortium + """ input_spec = GradientAnisotropicDiffusionInputSpec output_spec = GradientAnisotropicDiffusionOutputSpec @@ -106,23 +98,22 @@ class CurvatureAnisotropicDiffusionOutputSpec(TraitedSpec): class CurvatureAnisotropicDiffusion(SEMLikeCommandLine): """title: Curvature Anisotropic Diffusion -category: Filtering.Denoising - -description: Performs anisotropic diffusion on an image using a modified curvature diffusion equation (MCDE). + category: Filtering.Denoising -MCDE does not exhibit the edge enhancing properties of classic anisotropic diffusion, which can under certain conditions undergo a 'negative' diffusion, which enhances the contrast of edges. Equations of the form of MCDE always undergo positive diffusion, with the conductance term only varying the strength of that diffusion. + description: Performs anisotropic diffusion on an image using a modified curvature diffusion equation (MCDE). - Qualitatively, MCDE compares well with other non-linear diffusion techniques. It is less sensitive to contrast than classic Perona-Malik style diffusion, and preserves finer detailed structures in images. There is a potential speed trade-off for using this function in place of Gradient Anisotropic Diffusion. Each iteration of the solution takes roughly twice as long. Fewer iterations, however, may be required to reach an acceptable solution. + MCDE does not exhibit the edge enhancing properties of classic anisotropic diffusion, which can under certain conditions undergo a 'negative' diffusion, which enhances the contrast of edges. Equations of the form of MCDE always undergo positive diffusion, with the conductance term only varying the strength of that diffusion. -version: 0.1.0.$Revision: 19608 $(alpha) + Qualitatively, MCDE compares well with other non-linear diffusion techniques. It is less sensitive to contrast than classic Perona-Malik style diffusion, and preserves finer detailed structures in images. There is a potential speed trade-off for using this function in place of Gradient Anisotropic Diffusion. Each iteration of the solution takes roughly twice as long. Fewer iterations, however, may be required to reach an acceptable solution. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/CurvatureAnisotropicDiffusion + version: 0.1.0.$Revision: 19608 $(alpha) -contributor: Bill Lorensen (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/CurvatureAnisotropicDiffusion -acknowledgements: This command module was derived from Insight/Examples (copyright) Insight Software Consortium + contributor: Bill Lorensen (GE) -""" + acknowledgements: This command module was derived from Insight/Examples (copyright) Insight Software Consortium + """ input_spec = CurvatureAnisotropicDiffusionInputSpec output_spec = CurvatureAnisotropicDiffusionOutputSpec @@ -153,19 +144,18 @@ class GaussianBlurImageFilterOutputSpec(TraitedSpec): class GaussianBlurImageFilter(SEMLikeCommandLine): """title: Gaussian Blur Image Filter -category: Filtering.Denoising + category: Filtering.Denoising -description: Apply a gaussian blurr to an image + description: Apply a gaussian blur to an image -version: 0.1.0.$Revision: 1.1 $(alpha) + version: 0.1.0.$Revision: 1.1 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GaussianBlurImageFilter + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GaussianBlurImageFilter -contributor: Julien Jomier (Kitware), Stephen Aylward (Kitware) + contributor: Julien Jomier (Kitware), Stephen Aylward (Kitware) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = GaussianBlurImageFilterInputSpec output_spec = GaussianBlurImageFilterOutputSpec @@ -200,19 +190,18 @@ class MedianImageFilterOutputSpec(TraitedSpec): class MedianImageFilter(SEMLikeCommandLine): """title: Median Image Filter -category: Filtering.Denoising - -description: The MedianImageFilter is commonly used as a robust approach for noise reduction. This filter is particularly efficient against "salt-and-pepper" noise. In other words, it is robust to the presence of gray-level outliers. MedianImageFilter computes the value of each output pixel as the statistical median of the neighborhood of values around the corresponding input pixel. + category: Filtering.Denoising -version: 0.1.0.$Revision: 19608 $(alpha) + description: The MedianImageFilter is commonly used as a robust approach for noise reduction. This filter is particularly efficient against "salt-and-pepper" noise. In other words, it is robust to the presence of gray-level outliers. MedianImageFilter computes the value of each output pixel as the statistical median of the neighborhood of values around the corresponding input pixel. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/MedianImageFilter + version: 0.1.0.$Revision: 19608 $(alpha) -contributor: Bill Lorensen (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/MedianImageFilter -acknowledgements: This command module was derived from Insight/Examples/Filtering/MedianImageFilter (copyright) Insight Software Consortium + contributor: Bill Lorensen (GE) -""" + acknowledgements: This command module was derived from Insight/Examples/Filtering/MedianImageFilter (copyright) Insight Software Consortium + """ input_spec = MedianImageFilterInputSpec output_spec = MedianImageFilterOutputSpec diff --git a/nipype/interfaces/slicer/filtering/extractskeleton.py b/nipype/interfaces/slicer/filtering/extractskeleton.py index 7900be472c..8b873bad98 100644 --- a/nipype/interfaces/slicer/filtering/extractskeleton.py +++ b/nipype/interfaces/slicer/filtering/extractskeleton.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class ExtractSkeletonInputSpec(CommandLineInputSpec): @@ -53,19 +45,18 @@ class ExtractSkeletonOutputSpec(TraitedSpec): class ExtractSkeleton(SEMLikeCommandLine): """title: Extract Skeleton -category: Filtering + category: Filtering -description: Extract the skeleton of a binary object. The skeleton can be limited to being a 1D curve or allowed to be a full 2D manifold. The branches of the skeleton can be pruned so that only the maximal center skeleton is returned. + description: Extract the skeleton of a binary object. The skeleton can be limited to being a 1D curve or allowed to be a full 2D manifold. The branches of the skeleton can be pruned so that only the maximal center skeleton is returned. -version: 0.1.0.$Revision: 2104 $(alpha) + version: 0.1.0.$Revision: 2104 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ExtractSkeleton + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ExtractSkeleton -contributor: Pierre Seroul (UNC), Martin Styner (UNC), Guido Gerig (UNC), Stephen Aylward (Kitware) + contributor: Pierre Seroul (UNC), Martin Styner (UNC), Guido Gerig (UNC), Stephen Aylward (Kitware) -acknowledgements: The original implementation of this method was provided by ETH Zurich, Image Analysis Laboratory of Profs Olaf Kuebler, Gabor Szekely and Guido Gerig. Martin Styner at UNC, Chapel Hill made enhancements. Wrapping for Slicer was provided by Pierre Seroul and Stephen Aylward at Kitware, Inc. - -""" + acknowledgements: The original implementation of this method was provided by ETH Zurich, Image Analysis Laboratory of Profs Olaf Kuebler, Gabor Szekely and Guido Gerig. Martin Styner at UNC, Chapel Hill made enhancements. Wrapping for Slicer was provided by Pierre Seroul and Stephen Aylward at Kitware, Inc. + """ input_spec = ExtractSkeletonInputSpec output_spec = ExtractSkeletonOutputSpec diff --git a/nipype/interfaces/slicer/filtering/histogrammatching.py b/nipype/interfaces/slicer/filtering/histogrammatching.py index 9b6cb17813..df1d87bd2f 100644 --- a/nipype/interfaces/slicer/filtering/histogrammatching.py +++ b/nipype/interfaces/slicer/filtering/histogrammatching.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class HistogramMatchingInputSpec(CommandLineInputSpec): @@ -60,25 +52,24 @@ class HistogramMatchingOutputSpec(TraitedSpec): class HistogramMatching(SEMLikeCommandLine): """title: Histogram Matching -category: Filtering + category: Filtering -description: Normalizes the grayscale values of a source image based on the grayscale values of a reference image. This filter uses a histogram matching technique where the histograms of the two images are matched only at a specified number of quantile values. + description: Normalizes the grayscale values of a source image based on the grayscale values of a reference image. This filter uses a histogram matching technique where the histograms of the two images are matched only at a specified number of quantile values. -The filter was orginally designed to normalize MR images of the sameMR protocol and same body part. The algorithm works best if background pixels are excluded from both the source and reference histograms. A simple background exclusion method is to exclude all pixels whose grayscale values are smaller than the mean grayscale value. ThresholdAtMeanIntensity switches on this simple background exclusion method. + The filter was originally designed to normalize MR images of the sameMR protocol and same body part. The algorithm works best if background pixels are excluded from both the source and reference histograms. A simple background exclusion method is to exclude all pixels whose grayscale values are smaller than the mean grayscale value. ThresholdAtMeanIntensity switches on this simple background exclusion method. -Number of match points governs the number of quantile values to be matched. + Number of match points governs the number of quantile values to be matched. -The filter assumes that both the source and reference are of the same type and that the input and output image type have the same number of dimension and have scalar pixel types. + The filter assumes that both the source and reference are of the same type and that the input and output image type have the same number of dimension and have scalar pixel types. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/HistogramMatching + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/HistogramMatching -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = HistogramMatchingInputSpec output_spec = HistogramMatchingOutputSpec diff --git a/nipype/interfaces/slicer/filtering/imagelabelcombine.py b/nipype/interfaces/slicer/filtering/imagelabelcombine.py index 666385845d..6941ff05fe 100644 --- a/nipype/interfaces/slicer/filtering/imagelabelcombine.py +++ b/nipype/interfaces/slicer/filtering/imagelabelcombine.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class ImageLabelCombineInputSpec(CommandLineInputSpec): @@ -46,17 +38,16 @@ class ImageLabelCombineOutputSpec(TraitedSpec): class ImageLabelCombine(SEMLikeCommandLine): """title: Image Label Combine -category: Filtering + category: Filtering -description: Combine two label maps into one + description: Combine two label maps into one -version: 0.1.0 + version: 0.1.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ImageLabelCombine + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ImageLabelCombine -contributor: Alex Yarmarkovich (SPL, BWH) - -""" + contributor: Alex Yarmarkovich (SPL, BWH) + """ input_spec = ImageLabelCombineInputSpec output_spec = ImageLabelCombineOutputSpec diff --git a/nipype/interfaces/slicer/filtering/morphology.py b/nipype/interfaces/slicer/filtering/morphology.py index b33d3e9c6d..bd1232dece 100644 --- a/nipype/interfaces/slicer/filtering/morphology.py +++ b/nipype/interfaces/slicer/filtering/morphology.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class GrayscaleGrindPeakImageFilterInputSpec(CommandLineInputSpec): @@ -39,29 +31,28 @@ class GrayscaleGrindPeakImageFilterOutputSpec(TraitedSpec): class GrayscaleGrindPeakImageFilter(SEMLikeCommandLine): """title: Grayscale Grind Peak Image Filter -category: Filtering.Morphology + category: Filtering.Morphology -description: GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a peak are extrapolated through the peak. + description: GrayscaleGrindPeakImageFilter removes peaks in a grayscale image. Peaks are local maxima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a peak are extrapolated through the peak. -This filter is used to smooth over local maxima without affecting the values of local minima. If you take the difference between the output of this filter and the original image (and perhaps threshold the difference above a small value), you'll obtain a map of the local maxima. + This filter is used to smooth over local maxima without affecting the values of local minima. If you take the difference between the output of this filter and the original image (and perhaps threshold the difference above a small value), you'll obtain a map of the local maxima. -This filter uses the GrayscaleGeodesicDilateImageFilter. It provides its own input as the "mask" input to the geodesic erosion. The "marker" image for the geodesic erosion is constructed such that boundary pixels match the boundary pixels of the input image and the interior pixels are set to the minimum pixel value in the input image. + This filter uses the GrayscaleGeodesicDilateImageFilter. It provides its own input as the "mask" input to the geodesic erosion. The "marker" image for the geodesic erosion is constructed such that boundary pixels match the boundary pixels of the input image and the interior pixels are set to the minimum pixel value in the input image. -This filter is the dual to the GrayscaleFillholeImageFilter which implements the Fillhole algorithm. Since it is a dual, it is somewhat superfluous but is provided as a convenience. + This filter is the dual to the GrayscaleFillholeImageFilter which implements the Fillhole algorithm. Since it is a dual, it is somewhat superfluous but is provided as a convenience. -Geodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book "Morphological Image Analysis: Principles and Applications", Second Edition, Springer, 2003. + Geodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book "Morphological Image Analysis: Principles and Applications", Second Edition, Springer, 2003. -A companion filter, Grayscale Fill Hole, fills holes in grayscale images. + A companion filter, Grayscale Fill Hole, fills holes in grayscale images. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GrayscaleGrindPeakImageFilter + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GrayscaleGrindPeakImageFilter -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = GrayscaleGrindPeakImageFilterInputSpec output_spec = GrayscaleGrindPeakImageFilterOutputSpec @@ -90,27 +81,26 @@ class GrayscaleFillHoleImageFilterOutputSpec(TraitedSpec): class GrayscaleFillHoleImageFilter(SEMLikeCommandLine): """title: Grayscale Fill Hole Image Filter -category: Filtering.Morphology - -description: GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a hole are extrapolated across the hole. + category: Filtering.Morphology -This filter is used to smooth over local minima without affecting the values of local maxima. If you take the difference between the output of this filter and the original image (and perhaps threshold the difference above a small value), you'll obtain a map of the local minima. + description: GrayscaleFillholeImageFilter fills holes in a grayscale image. Holes are local minima in the grayscale topography that are not connected to boundaries of the image. Gray level values adjacent to a hole are extrapolated across the hole. -This filter uses the itkGrayscaleGeodesicErodeImageFilter. It provides its own input as the "mask" input to the geodesic erosion. The "marker" image for the geodesic erosion is constructed such that boundary pixels match the boundary pixels of the input image and the interior pixels are set to the maximum pixel value in the input image. + This filter is used to smooth over local minima without affecting the values of local maxima. If you take the difference between the output of this filter and the original image (and perhaps threshold the difference above a small value), you'll obtain a map of the local minima. - Geodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book "Morphological Image Analysis: Principles and Applications", Second Edition, Springer, 2003. + This filter uses the itkGrayscaleGeodesicErodeImageFilter. It provides its own input as the "mask" input to the geodesic erosion. The "marker" image for the geodesic erosion is constructed such that boundary pixels match the boundary pixels of the input image and the interior pixels are set to the maximum pixel value in the input image. - A companion filter, Grayscale Grind Peak, removes peaks in grayscale images. + Geodesic morphology and the Fillhole algorithm is described in Chapter 6 of Pierre Soille's book "Morphological Image Analysis: Principles and Applications", Second Edition, Springer, 2003. -version: 0.1.0.$Revision: 19608 $(alpha) + A companion filter, Grayscale Grind Peak, removes peaks in grayscale images. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GrayscaleFillHoleImageFilter + version: 0.1.0.$Revision: 19608 $(alpha) -contributor: Bill Lorensen (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GrayscaleFillHoleImageFilter -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Bill Lorensen (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = GrayscaleFillHoleImageFilterInputSpec output_spec = GrayscaleFillHoleImageFilterOutputSpec diff --git a/nipype/interfaces/slicer/filtering/n4itkbiasfieldcorrection.py b/nipype/interfaces/slicer/filtering/n4itkbiasfieldcorrection.py index b1243160b5..69768e3b7e 100644 --- a/nipype/interfaces/slicer/filtering/n4itkbiasfieldcorrection.py +++ b/nipype/interfaces/slicer/filtering/n4itkbiasfieldcorrection.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class N4ITKBiasFieldCorrectionInputSpec(CommandLineInputSpec): @@ -88,19 +81,18 @@ class N4ITKBiasFieldCorrectionOutputSpec(TraitedSpec): class N4ITKBiasFieldCorrection(SEMLikeCommandLine): """title: N4ITK MRI Bias correction -category: Filtering + category: Filtering -description: Performs image bias correction using N4 algorithm. This module is based on the ITK filters contributed in the following publication: Tustison N, Gee J "N4ITK: Nick's N3 ITK Implementation For MRI Bias Field Correction", The Insight Journal 2009 January-June, http://hdl.handle.net/10380/3053 + description: Performs image bias correction using N4 algorithm. This module is based on the ITK filters contributed in the following publication: Tustison N, Gee J "N4ITK: Nick's N3 ITK Implementation For MRI Bias Field Correction", The Insight Journal 2009 January-June, http://hdl.handle.net/10380/3053 -version: 9 + version: 9 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/N4ITKBiasFieldCorrection + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/N4ITKBiasFieldCorrection -contributor: Nick Tustison (UPenn), Andrey Fedorov (SPL, BWH), Ron Kikinis (SPL, BWH) + contributor: Nick Tustison (UPenn), Andrey Fedorov (SPL, BWH), Ron Kikinis (SPL, BWH) -acknowledgements: The development of this module was partially supported by NIH grants R01 AA016748-01, R01 CA111288 and U01 CA151261 as well as by NA-MIC, NAC, NCIGT and the Slicer community. - -""" + acknowledgements: The development of this module was partially supported by NIH grants R01 AA016748-01, R01 CA111288 and U01 CA151261 as well as by NA-MIC, NAC, NCIGT and the Slicer community. + """ input_spec = N4ITKBiasFieldCorrectionInputSpec output_spec = N4ITKBiasFieldCorrectionOutputSpec diff --git a/nipype/interfaces/slicer/filtering/resamplescalarvectordwivolume.py b/nipype/interfaces/slicer/filtering/resamplescalarvectordwivolume.py index c41827cb39..e9d6a8271f 100644 --- a/nipype/interfaces/slicer/filtering/resamplescalarvectordwivolume.py +++ b/nipype/interfaces/slicer/filtering/resamplescalarvectordwivolume.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class ResampleScalarVectorDWIVolumeInputSpec(CommandLineInputSpec): @@ -52,7 +45,7 @@ class ResampleScalarVectorDWIVolumeInputSpec(CommandLineInputSpec): "nn", "ws", "bs", - desc="Sampling algorithm (linear or nn (nearest neighborhoor), ws (WindowedSinc), bs (BSpline) )", + desc="Sampling algorithm (linear or nn (nearest neighbor), ws (WindowedSinc), bs (BSpline) )", argstr="--interpolation %s", ) transform_order = traits.Enum( @@ -145,23 +138,22 @@ class ResampleScalarVectorDWIVolumeOutputSpec(TraitedSpec): class ResampleScalarVectorDWIVolume(SEMLikeCommandLine): """title: Resample Scalar/Vector/DWI Volume -category: Filtering + category: Filtering -description: This module implements image and vector-image resampling through the use of itk Transforms.It can also handle diffusion weighted MRI image resampling. "Resampling" is performed in space coordinates, not pixel/grid coordinates. It is quite important to ensure that image spacing is properly set on the images involved. The interpolator is required since the mapping from one space to the other will often require evaluation of the intensity of the image at non-grid positions. + description: This module implements image and vector-image resampling through the use of itk Transforms.It can also handle diffusion weighted MRI image resampling. "Resampling" is performed in space coordinates, not pixel/grid coordinates. It is quite important to ensure that image spacing is properly set on the images involved. The interpolator is required since the mapping from one space to the other will often require evaluation of the intensity of the image at non-grid positions. -Warning: To resample DWMR Images, use nrrd input and output files. + Warning: To resample DWMR Images, use nrrd input and output files. -Warning: Do not use to resample Diffusion Tensor Images, tensors would not be reoriented + Warning: Do not use to resample Diffusion Tensor Images, tensors would not be reoriented -version: 0.1 + version: 0.1 -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ResampleScalarVectorDWIVolume + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ResampleScalarVectorDWIVolume -contributor: Francois Budin (UNC) + contributor: Francois Budin (UNC) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Information on the National Centers for Biomedical Computing can be obtained from http://nihroadmap.nih.gov/bioinformatics - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. Information on the National Centers for Biomedical Computing can be obtained from http://nihroadmap.nih.gov/bioinformatics + """ input_spec = ResampleScalarVectorDWIVolumeInputSpec output_spec = ResampleScalarVectorDWIVolumeOutputSpec diff --git a/nipype/interfaces/slicer/filtering/tests/__init__.py b/nipype/interfaces/slicer/filtering/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/slicer/filtering/tests/__init__.py +++ b/nipype/interfaces/slicer/filtering/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py b/nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py index 3ea978e771..2cd0ac229d 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_AddScalarVolumes.py @@ -4,12 +4,31 @@ def test_AddScalarVolumes_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume1=dict(argstr="%s", extensions=None, position=-3,), - inputVolume2=dict(argstr="%s", extensions=None, position=-2,), - order=dict(argstr="--order %s",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr="%s", + extensions=None, + position=-3, + ), + inputVolume2=dict( + argstr="%s", + extensions=None, + position=-2, + ), + order=dict( + argstr="--order %s", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = AddScalarVolumes.input_spec() @@ -19,7 +38,12 @@ def test_AddScalarVolumes_inputs(): def test_AddScalarVolumes_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = AddScalarVolumes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_CastScalarVolume.py b/nipype/interfaces/slicer/filtering/tests/test_auto_CastScalarVolume.py index e57c2a691b..8417ab1a90 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_CastScalarVolume.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_CastScalarVolume.py @@ -4,11 +4,26 @@ def test_CastScalarVolume_inputs(): input_map = dict( - InputVolume=dict(argstr="%s", extensions=None, position=-2,), - OutputVolume=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - type=dict(argstr="--type %s",), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + OutputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + type=dict( + argstr="--type %s", + ), ) inputs = CastScalarVolume.input_spec() @@ -18,7 +33,12 @@ def test_CastScalarVolume_inputs(): def test_CastScalarVolume_outputs(): - output_map = dict(OutputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + OutputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = CastScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_CheckerBoardFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_CheckerBoardFilter.py index 564e2e14f8..49b5133faa 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_CheckerBoardFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_CheckerBoardFilter.py @@ -4,12 +4,32 @@ def test_CheckerBoardFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - checkerPattern=dict(argstr="--checkerPattern %s", sep=",",), - environ=dict(nohash=True, usedefault=True,), - inputVolume1=dict(argstr="%s", extensions=None, position=-3,), - inputVolume2=dict(argstr="%s", extensions=None, position=-2,), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + checkerPattern=dict( + argstr="--checkerPattern %s", + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr="%s", + extensions=None, + position=-3, + ), + inputVolume2=dict( + argstr="%s", + extensions=None, + position=-2, + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = CheckerBoardFilter.input_spec() @@ -19,7 +39,12 @@ def test_CheckerBoardFilter_inputs(): def test_CheckerBoardFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = CheckerBoardFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_CurvatureAnisotropicDiffusion.py b/nipype/interfaces/slicer/filtering/tests/test_auto_CurvatureAnisotropicDiffusion.py index 189bd459a0..48421b7c21 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_CurvatureAnisotropicDiffusion.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_CurvatureAnisotropicDiffusion.py @@ -4,13 +4,32 @@ def test_CurvatureAnisotropicDiffusion_inputs(): input_map = dict( - args=dict(argstr="%s",), - conductance=dict(argstr="--conductance %f",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - iterations=dict(argstr="--iterations %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - timeStep=dict(argstr="--timeStep %f",), + args=dict( + argstr="%s", + ), + conductance=dict( + argstr="--conductance %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + iterations=dict( + argstr="--iterations %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + timeStep=dict( + argstr="--timeStep %f", + ), ) inputs = CurvatureAnisotropicDiffusion.input_spec() @@ -20,7 +39,12 @@ def test_CurvatureAnisotropicDiffusion_inputs(): def test_CurvatureAnisotropicDiffusion_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = CurvatureAnisotropicDiffusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py b/nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py index 93861cefa5..430e299787 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_ExtractSkeleton.py @@ -4,14 +4,35 @@ def test_ExtractSkeleton_inputs(): input_map = dict( - InputImageFileName=dict(argstr="%s", extensions=None, position=-2,), - OutputImageFileName=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - dontPrune=dict(argstr="--dontPrune ",), - environ=dict(nohash=True, usedefault=True,), - numPoints=dict(argstr="--numPoints %d",), - pointsFile=dict(argstr="--pointsFile %s",), - type=dict(argstr="--type %s",), + InputImageFileName=dict( + argstr="%s", + extensions=None, + position=-2, + ), + OutputImageFileName=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + dontPrune=dict( + argstr="--dontPrune ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + numPoints=dict( + argstr="--numPoints %d", + ), + pointsFile=dict( + argstr="--pointsFile %s", + ), + type=dict( + argstr="--type %s", + ), ) inputs = ExtractSkeleton.input_spec() @@ -21,7 +42,12 @@ def test_ExtractSkeleton_inputs(): def test_ExtractSkeleton_outputs(): - output_map = dict(OutputImageFileName=dict(extensions=None, position=-1,),) + output_map = dict( + OutputImageFileName=dict( + extensions=None, + position=-1, + ), + ) outputs = ExtractSkeleton.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py index a0655cfb6e..113490472d 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_GaussianBlurImageFilter.py @@ -4,11 +4,26 @@ def test_GaussianBlurImageFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - sigma=dict(argstr="--sigma %f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + sigma=dict( + argstr="--sigma %f", + ), ) inputs = GaussianBlurImageFilter.input_spec() @@ -18,7 +33,12 @@ def test_GaussianBlurImageFilter_inputs(): def test_GaussianBlurImageFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = GaussianBlurImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_GradientAnisotropicDiffusion.py b/nipype/interfaces/slicer/filtering/tests/test_auto_GradientAnisotropicDiffusion.py index 2b6e77d1d8..95810788c7 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_GradientAnisotropicDiffusion.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_GradientAnisotropicDiffusion.py @@ -4,13 +4,32 @@ def test_GradientAnisotropicDiffusion_inputs(): input_map = dict( - args=dict(argstr="%s",), - conductance=dict(argstr="--conductance %f",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - iterations=dict(argstr="--iterations %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - timeStep=dict(argstr="--timeStep %f",), + args=dict( + argstr="%s", + ), + conductance=dict( + argstr="--conductance %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + iterations=dict( + argstr="--iterations %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + timeStep=dict( + argstr="--timeStep %f", + ), ) inputs = GradientAnisotropicDiffusion.input_spec() @@ -20,7 +39,12 @@ def test_GradientAnisotropicDiffusion_inputs(): def test_GradientAnisotropicDiffusion_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = GradientAnisotropicDiffusion.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleFillHoleImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleFillHoleImageFilter.py index a12177d820..8891232347 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleFillHoleImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleFillHoleImageFilter.py @@ -4,10 +4,23 @@ def test_GrayscaleFillHoleImageFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = GrayscaleFillHoleImageFilter.input_spec() @@ -17,7 +30,12 @@ def test_GrayscaleFillHoleImageFilter_inputs(): def test_GrayscaleFillHoleImageFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = GrayscaleFillHoleImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleGrindPeakImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleGrindPeakImageFilter.py index ab1c23f716..d48d9ded63 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleGrindPeakImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_GrayscaleGrindPeakImageFilter.py @@ -4,10 +4,23 @@ def test_GrayscaleGrindPeakImageFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = GrayscaleGrindPeakImageFilter.input_spec() @@ -17,7 +30,12 @@ def test_GrayscaleGrindPeakImageFilter_inputs(): def test_GrayscaleGrindPeakImageFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = GrayscaleGrindPeakImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py b/nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py index 003ec4c8d8..cf2a959ff9 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_HistogramMatching.py @@ -4,14 +4,37 @@ def test_HistogramMatching_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-3,), - numberOfHistogramLevels=dict(argstr="--numberOfHistogramLevels %d",), - numberOfMatchPoints=dict(argstr="--numberOfMatchPoints %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - referenceVolume=dict(argstr="%s", extensions=None, position=-2,), - threshold=dict(argstr="--threshold ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-3, + ), + numberOfHistogramLevels=dict( + argstr="--numberOfHistogramLevels %d", + ), + numberOfMatchPoints=dict( + argstr="--numberOfMatchPoints %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + referenceVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + threshold=dict( + argstr="--threshold ", + ), ) inputs = HistogramMatching.input_spec() @@ -21,7 +44,12 @@ def test_HistogramMatching_inputs(): def test_HistogramMatching_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = HistogramMatching.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_ImageLabelCombine.py b/nipype/interfaces/slicer/filtering/tests/test_auto_ImageLabelCombine.py index 8fb1596420..802baf5f38 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_ImageLabelCombine.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_ImageLabelCombine.py @@ -4,12 +4,31 @@ def test_ImageLabelCombine_inputs(): input_map = dict( - InputLabelMap_A=dict(argstr="%s", extensions=None, position=-3,), - InputLabelMap_B=dict(argstr="%s", extensions=None, position=-2,), - OutputLabelMap=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - first_overwrites=dict(argstr="--first_overwrites ",), + InputLabelMap_A=dict( + argstr="%s", + extensions=None, + position=-3, + ), + InputLabelMap_B=dict( + argstr="%s", + extensions=None, + position=-2, + ), + OutputLabelMap=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + first_overwrites=dict( + argstr="--first_overwrites ", + ), ) inputs = ImageLabelCombine.input_spec() @@ -19,7 +38,12 @@ def test_ImageLabelCombine_inputs(): def test_ImageLabelCombine_outputs(): - output_map = dict(OutputLabelMap=dict(extensions=None, position=-1,),) + output_map = dict( + OutputLabelMap=dict( + extensions=None, + position=-1, + ), + ) outputs = ImageLabelCombine.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_MaskScalarVolume.py b/nipype/interfaces/slicer/filtering/tests/test_auto_MaskScalarVolume.py index fd8bf6aaf7..5070718d66 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_MaskScalarVolume.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_MaskScalarVolume.py @@ -4,13 +4,34 @@ def test_MaskScalarVolume_inputs(): input_map = dict( - InputVolume=dict(argstr="%s", extensions=None, position=-3,), - MaskVolume=dict(argstr="%s", extensions=None, position=-2,), - OutputVolume=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - label=dict(argstr="--label %d",), - replace=dict(argstr="--replace %d",), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-3, + ), + MaskVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + OutputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + label=dict( + argstr="--label %d", + ), + replace=dict( + argstr="--replace %d", + ), ) inputs = MaskScalarVolume.input_spec() @@ -20,7 +41,12 @@ def test_MaskScalarVolume_inputs(): def test_MaskScalarVolume_outputs(): - output_map = dict(OutputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + OutputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = MaskScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_MedianImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_MedianImageFilter.py index 969a0dead6..8b86a90c3b 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_MedianImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_MedianImageFilter.py @@ -4,11 +4,27 @@ def test_MedianImageFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - neighborhood=dict(argstr="--neighborhood %s", sep=",",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + neighborhood=dict( + argstr="--neighborhood %s", + sep=",", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = MedianImageFilter.input_spec() @@ -18,7 +34,12 @@ def test_MedianImageFilter_inputs(): def test_MedianImageFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = MedianImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_MultiplyScalarVolumes.py b/nipype/interfaces/slicer/filtering/tests/test_auto_MultiplyScalarVolumes.py index f6e521fe8e..817fdbbe95 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_MultiplyScalarVolumes.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_MultiplyScalarVolumes.py @@ -4,12 +4,31 @@ def test_MultiplyScalarVolumes_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume1=dict(argstr="%s", extensions=None, position=-3,), - inputVolume2=dict(argstr="%s", extensions=None, position=-2,), - order=dict(argstr="--order %s",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr="%s", + extensions=None, + position=-3, + ), + inputVolume2=dict( + argstr="%s", + extensions=None, + position=-2, + ), + order=dict( + argstr="--order %s", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = MultiplyScalarVolumes.input_spec() @@ -19,7 +38,12 @@ def test_MultiplyScalarVolumes_inputs(): def test_MultiplyScalarVolumes_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = MultiplyScalarVolumes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_N4ITKBiasFieldCorrection.py b/nipype/interfaces/slicer/filtering/tests/test_auto_N4ITKBiasFieldCorrection.py index 435b4d0f6a..43038036d5 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_N4ITKBiasFieldCorrection.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_N4ITKBiasFieldCorrection.py @@ -4,20 +4,57 @@ def test_N4ITKBiasFieldCorrection_inputs(): input_map = dict( - args=dict(argstr="%s",), - bsplineorder=dict(argstr="--bsplineorder %d",), - convergencethreshold=dict(argstr="--convergencethreshold %f",), - environ=dict(nohash=True, usedefault=True,), - histogramsharpening=dict(argstr="--histogramsharpening %s", sep=",",), - inputimage=dict(argstr="--inputimage %s", extensions=None,), - iterations=dict(argstr="--iterations %s", sep=",",), - maskimage=dict(argstr="--maskimage %s", extensions=None,), - meshresolution=dict(argstr="--meshresolution %s", sep=",",), - outputbiasfield=dict(argstr="--outputbiasfield %s", hash_files=False,), - outputimage=dict(argstr="--outputimage %s", hash_files=False,), - shrinkfactor=dict(argstr="--shrinkfactor %d",), - splinedistance=dict(argstr="--splinedistance %f",), - weightimage=dict(argstr="--weightimage %s", extensions=None,), + args=dict( + argstr="%s", + ), + bsplineorder=dict( + argstr="--bsplineorder %d", + ), + convergencethreshold=dict( + argstr="--convergencethreshold %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + histogramsharpening=dict( + argstr="--histogramsharpening %s", + sep=",", + ), + inputimage=dict( + argstr="--inputimage %s", + extensions=None, + ), + iterations=dict( + argstr="--iterations %s", + sep=",", + ), + maskimage=dict( + argstr="--maskimage %s", + extensions=None, + ), + meshresolution=dict( + argstr="--meshresolution %s", + sep=",", + ), + outputbiasfield=dict( + argstr="--outputbiasfield %s", + hash_files=False, + ), + outputimage=dict( + argstr="--outputimage %s", + hash_files=False, + ), + shrinkfactor=dict( + argstr="--shrinkfactor %d", + ), + splinedistance=dict( + argstr="--splinedistance %f", + ), + weightimage=dict( + argstr="--weightimage %s", + extensions=None, + ), ) inputs = N4ITKBiasFieldCorrection.input_spec() @@ -28,7 +65,12 @@ def test_N4ITKBiasFieldCorrection_inputs(): def test_N4ITKBiasFieldCorrection_outputs(): output_map = dict( - outputbiasfield=dict(extensions=None,), outputimage=dict(extensions=None,), + outputbiasfield=dict( + extensions=None, + ), + outputimage=dict( + extensions=None, + ), ) outputs = N4ITKBiasFieldCorrection.output_spec() diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_ResampleScalarVectorDWIVolume.py b/nipype/interfaces/slicer/filtering/tests/test_auto_ResampleScalarVectorDWIVolume.py index d1a28f3374..37dca6437c 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_ResampleScalarVectorDWIVolume.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_ResampleScalarVectorDWIVolume.py @@ -4,32 +4,96 @@ def test_ResampleScalarVectorDWIVolume_inputs(): input_map = dict( - Inverse_ITK_Transformation=dict(argstr="--Inverse_ITK_Transformation ",), - Reference=dict(argstr="--Reference %s", extensions=None,), - args=dict(argstr="%s",), - centered_transform=dict(argstr="--centered_transform ",), - defField=dict(argstr="--defField %s", extensions=None,), - default_pixel_value=dict(argstr="--default_pixel_value %f",), - direction_matrix=dict(argstr="--direction_matrix %s", sep=",",), - environ=dict(nohash=True, usedefault=True,), - hfieldtype=dict(argstr="--hfieldtype %s",), - image_center=dict(argstr="--image_center %s",), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - interpolation=dict(argstr="--interpolation %s",), - notbulk=dict(argstr="--notbulk ",), - number_of_thread=dict(argstr="--number_of_thread %d",), - origin=dict(argstr="--origin %s",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - rotation_point=dict(argstr="--rotation_point %s",), - size=dict(argstr="--size %s", sep=",",), - spaceChange=dict(argstr="--spaceChange ",), - spacing=dict(argstr="--spacing %s", sep=",",), - spline_order=dict(argstr="--spline_order %d",), - transform=dict(argstr="--transform %s",), - transform_matrix=dict(argstr="--transform_matrix %s", sep=",",), - transform_order=dict(argstr="--transform_order %s",), - transformationFile=dict(argstr="--transformationFile %s", extensions=None,), - window_function=dict(argstr="--window_function %s",), + Inverse_ITK_Transformation=dict( + argstr="--Inverse_ITK_Transformation ", + ), + Reference=dict( + argstr="--Reference %s", + extensions=None, + ), + args=dict( + argstr="%s", + ), + centered_transform=dict( + argstr="--centered_transform ", + ), + defField=dict( + argstr="--defField %s", + extensions=None, + ), + default_pixel_value=dict( + argstr="--default_pixel_value %f", + ), + direction_matrix=dict( + argstr="--direction_matrix %s", + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hfieldtype=dict( + argstr="--hfieldtype %s", + ), + image_center=dict( + argstr="--image_center %s", + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + interpolation=dict( + argstr="--interpolation %s", + ), + notbulk=dict( + argstr="--notbulk ", + ), + number_of_thread=dict( + argstr="--number_of_thread %d", + ), + origin=dict( + argstr="--origin %s", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + rotation_point=dict( + argstr="--rotation_point %s", + ), + size=dict( + argstr="--size %s", + sep=",", + ), + spaceChange=dict( + argstr="--spaceChange ", + ), + spacing=dict( + argstr="--spacing %s", + sep=",", + ), + spline_order=dict( + argstr="--spline_order %d", + ), + transform=dict( + argstr="--transform %s", + ), + transform_matrix=dict( + argstr="--transform_matrix %s", + sep=",", + ), + transform_order=dict( + argstr="--transform_order %s", + ), + transformationFile=dict( + argstr="--transformationFile %s", + extensions=None, + ), + window_function=dict( + argstr="--window_function %s", + ), ) inputs = ResampleScalarVectorDWIVolume.input_spec() @@ -39,7 +103,12 @@ def test_ResampleScalarVectorDWIVolume_inputs(): def test_ResampleScalarVectorDWIVolume_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = ResampleScalarVectorDWIVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_SubtractScalarVolumes.py b/nipype/interfaces/slicer/filtering/tests/test_auto_SubtractScalarVolumes.py index 6d8ae8ad73..abe3d9ad00 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_SubtractScalarVolumes.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_SubtractScalarVolumes.py @@ -4,12 +4,31 @@ def test_SubtractScalarVolumes_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume1=dict(argstr="%s", extensions=None, position=-3,), - inputVolume2=dict(argstr="%s", extensions=None, position=-2,), - order=dict(argstr="--order %s",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr="%s", + extensions=None, + position=-3, + ), + inputVolume2=dict( + argstr="%s", + extensions=None, + position=-2, + ), + order=dict( + argstr="--order %s", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = SubtractScalarVolumes.input_spec() @@ -19,7 +38,12 @@ def test_SubtractScalarVolumes_inputs(): def test_SubtractScalarVolumes_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = SubtractScalarVolumes.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_ThresholdScalarVolume.py b/nipype/interfaces/slicer/filtering/tests/test_auto_ThresholdScalarVolume.py index eec13b435e..0aaab0ff7a 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_ThresholdScalarVolume.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_ThresholdScalarVolume.py @@ -4,15 +4,38 @@ def test_ThresholdScalarVolume_inputs(): input_map = dict( - InputVolume=dict(argstr="%s", extensions=None, position=-2,), - OutputVolume=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - lower=dict(argstr="--lower %d",), - outsidevalue=dict(argstr="--outsidevalue %d",), - threshold=dict(argstr="--threshold %d",), - thresholdtype=dict(argstr="--thresholdtype %s",), - upper=dict(argstr="--upper %d",), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + OutputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + lower=dict( + argstr="--lower %d", + ), + outsidevalue=dict( + argstr="--outsidevalue %d", + ), + threshold=dict( + argstr="--threshold %d", + ), + thresholdtype=dict( + argstr="--thresholdtype %s", + ), + upper=dict( + argstr="--upper %d", + ), ) inputs = ThresholdScalarVolume.input_spec() @@ -22,7 +45,12 @@ def test_ThresholdScalarVolume_inputs(): def test_ThresholdScalarVolume_outputs(): - output_map = dict(OutputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + OutputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = ThresholdScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/tests/test_auto_VotingBinaryHoleFillingImageFilter.py b/nipype/interfaces/slicer/filtering/tests/test_auto_VotingBinaryHoleFillingImageFilter.py index d45159cc1b..bbaa19f848 100644 --- a/nipype/interfaces/slicer/filtering/tests/test_auto_VotingBinaryHoleFillingImageFilter.py +++ b/nipype/interfaces/slicer/filtering/tests/test_auto_VotingBinaryHoleFillingImageFilter.py @@ -4,14 +4,36 @@ def test_VotingBinaryHoleFillingImageFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - background=dict(argstr="--background %d",), - environ=dict(nohash=True, usedefault=True,), - foreground=dict(argstr="--foreground %d",), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - majorityThreshold=dict(argstr="--majorityThreshold %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - radius=dict(argstr="--radius %s", sep=",",), + args=dict( + argstr="%s", + ), + background=dict( + argstr="--background %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + foreground=dict( + argstr="--foreground %d", + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + majorityThreshold=dict( + argstr="--majorityThreshold %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + radius=dict( + argstr="--radius %s", + sep=",", + ), ) inputs = VotingBinaryHoleFillingImageFilter.input_spec() @@ -21,7 +43,12 @@ def test_VotingBinaryHoleFillingImageFilter_inputs(): def test_VotingBinaryHoleFillingImageFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = VotingBinaryHoleFillingImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/filtering/thresholdscalarvolume.py b/nipype/interfaces/slicer/filtering/thresholdscalarvolume.py index e72284456b..d5f0cef21f 100644 --- a/nipype/interfaces/slicer/filtering/thresholdscalarvolume.py +++ b/nipype/interfaces/slicer/filtering/thresholdscalarvolume.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class ThresholdScalarVolumeInputSpec(CommandLineInputSpec): @@ -51,19 +43,18 @@ class ThresholdScalarVolumeOutputSpec(TraitedSpec): class ThresholdScalarVolume(SEMLikeCommandLine): """title: Threshold Scalar Volume -category: Filtering + category: Filtering -description:

Threshold an image.

Set image values to a user-specified outside value if they are below, above, or between simple threshold values.

ThresholdAbove: The values greater than or equal to the threshold value are set to OutsideValue.

ThresholdBelow: The values less than or equal to the threshold value are set to OutsideValue.

ThresholdOutside: The values outside the range Lower-Upper are set to OutsideValue.

Although all image types are supported on input, only signed types are produced.

+ description:

Threshold an image.

Set image values to a user-specified outside value if they are below, above, or between simple threshold values.

ThresholdAbove: The values greater than or equal to the threshold value are set to OutsideValue.

ThresholdBelow: The values less than or equal to the threshold value are set to OutsideValue.

ThresholdOutside: The values outside the range Lower-Upper are set to OutsideValue.

Although all image types are supported on input, only signed types are produced.

-version: 0.1.0.$Revision: 2104 $(alpha) + version: 0.1.0.$Revision: 2104 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Threshold + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/Threshold -contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) + contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = ThresholdScalarVolumeInputSpec output_spec = ThresholdScalarVolumeOutputSpec diff --git a/nipype/interfaces/slicer/filtering/votingbinaryholefillingimagefilter.py b/nipype/interfaces/slicer/filtering/votingbinaryholefillingimagefilter.py index 2ed3736d1b..9903b07793 100644 --- a/nipype/interfaces/slicer/filtering/votingbinaryholefillingimagefilter.py +++ b/nipype/interfaces/slicer/filtering/votingbinaryholefillingimagefilter.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class VotingBinaryHoleFillingImageFilterInputSpec(CommandLineInputSpec): @@ -57,19 +50,18 @@ class VotingBinaryHoleFillingImageFilterOutputSpec(TraitedSpec): class VotingBinaryHoleFillingImageFilter(SEMLikeCommandLine): """title: Voting Binary Hole Filling Image Filter -category: Filtering + category: Filtering -description: Applies a voting operation in order to fill-in cavities. This can be used for smoothing contours and for filling holes in binary images. This technique is used frequently when segmenting complete organs that may have ducts or vasculature that may not have been included in the initial segmentation, e.g. lungs, kidneys, liver. + description: Applies a voting operation in order to fill-in cavities. This can be used for smoothing contours and for filling holes in binary images. This technique is used frequently when segmenting complete organs that may have ducts or vasculature that may not have been included in the initial segmentation, e.g. lungs, kidneys, liver. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/VotingBinaryHoleFillingImageFilter + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/VotingBinaryHoleFillingImageFilter -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This command module was derived from Insight/Examples/Filtering/VotingBinaryHoleFillingImageFilter (copyright) Insight Software Consortium - -""" + acknowledgements: This command module was derived from Insight/Examples/Filtering/VotingBinaryHoleFillingImageFilter (copyright) Insight Software Consortium + """ input_spec = VotingBinaryHoleFillingImageFilterInputSpec output_spec = VotingBinaryHoleFillingImageFilterOutputSpec diff --git a/nipype/interfaces/slicer/generate_classes.py b/nipype/interfaces/slicer/generate_classes.py index 54eeb0b089..a36dd6b55a 100644 --- a/nipype/interfaces/slicer/generate_classes.py +++ b/nipype/interfaces/slicer/generate_classes.py @@ -1,8 +1,8 @@ -# -*- coding: utf-8 -*- """This script generates Slicer Interfaces based on the CLI modules XML. CLI modules are selected from the hardcoded list below and generated code is placed in the cli_modules.py file (and imported in __init__.py). For this to work -correctly you must have your CLI executabes in $PATH""" +correctly you must have your CLI executables in $PATH""" + import xml.dom.minidom import subprocess import os @@ -16,7 +16,7 @@ def force_to_valid_python_variable_name(old_name): - """ Valid c++ names are not always valid in python, so + """Valid c++ names are not always valid in python, so provide alternate naming >>> force_to_valid_python_variable_name('lambda') @@ -33,28 +33,26 @@ def force_to_valid_python_variable_name(old_name): def add_class_to_package(class_codes, class_names, module_name, package_dir): module_python_filename = os.path.join(package_dir, "%s.py" % module_name) - f_m = open(module_python_filename, "w") - f_i = open(os.path.join(package_dir, "__init__.py"), "a+") - f_m.write( - """# -*- coding: utf-8 -*- + with open(module_python_filename, "w") as f_m: + f_m.write( + """# -*- coding: utf-8 -*- \"\"\"Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.\"\"\"\n\n""" - ) - imports = """\ + ) + imports = """\ from ..base import (CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath) import os\n\n\n""" - f_m.write(imports) - f_m.write("\n\n".join(class_codes)) - f_i.write("from %s import %s\n" % (module_name, ", ".join(class_names))) - f_m.close() - f_i.close() + f_m.write(imports) + f_m.write("\n\n".join(class_codes)) + with open(os.path.join(package_dir, "__init__.py"), "a+") as f_i: + f_i.write("from {} import {}\n".format(module_name, ", ".join(class_names))) def crawl_code_struct(code_struct, package_dir): subpackages = [] for k, v in code_struct.items(): - if isinstance(v, str) or isinstance(v, (str, bytes)): + if isinstance(v, (str, bytes)): module_name = k.lower() class_name = k class_code = v @@ -63,16 +61,15 @@ def crawl_code_struct(code_struct, package_dir): l1 = {} l2 = {} for key in list(v.keys()): - if isinstance(v[key], str) or isinstance(v[key], (str, bytes)): + if isinstance(v[key], (str, bytes)): l1[key] = v[key] else: l2[key] = v[key] if l2: v = l2 subpackages.append(k.lower()) - f_i = open(os.path.join(package_dir, "__init__.py"), "a+") - f_i.write("from %s import *\n" % k.lower()) - f_i.close() + with open(os.path.join(package_dir, "__init__.py"), "a+") as f_i: + f_i.write("from %s import *\n" % k.lower()) new_pkg_dir = os.path.join(package_dir, k.lower()) if os.path.exists(new_pkg_dir): rmtree(new_pkg_dir) @@ -88,9 +85,9 @@ def crawl_code_struct(code_struct, package_dir): list(v.values()), list(v.keys()), module_name, package_dir ) if subpackages: - f = open(os.path.join(package_dir, "setup.py"), "w") - f.write( - """# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- + with open(os.path.join(package_dir, "setup.py"), "w") as f: + f.write( + """# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration @@ -105,29 +102,28 @@ def configuration(parent_package='',top_path=None): from numpy.distutils.core import setup setup(**configuration(top_path='').todict()) """.format( - pkg_name=package_dir.split("/")[-1], - sub_pks="\n ".join( - [ - "config.add_data_dir('%s')" % sub_pkg - for sub_pkg in subpackages - ] - ), + pkg_name=package_dir.split("/")[-1], + sub_pks="\n ".join( + [ + "config.add_data_dir('%s')" % sub_pkg + for sub_pkg in subpackages + ] + ), + ) ) - ) - f.close() def generate_all_classes( modules_list=[], launcher=[], redirect_x=False, mipav_hacks=False ): - """ modules_list contains all the SEM compliant tools that should have wrappers created for them. - launcher containtains the command line prefix wrapper arugments needed to prepare - a proper environment for each of the modules. + """modules_list contains all the SEM compliant tools that should have wrappers created for them. + launcher containtains the command line prefix wrapper arguments needed to prepare + a proper environment for each of the modules. """ all_code = {} for module in modules_list: print("=" * 80) - print("Generating Definition for module {0}".format(module)) + print(f"Generating Definition for module {module}") print("^" * 80) package, code, module = generate_class( module, launcher, redirect_x=redirect_x, mipav_hacks=mipav_hacks @@ -196,7 +192,7 @@ def generate_class( if longFlagNode: # Prefer to use longFlag as name if it is given, rather than the parameter name longFlagName = longFlagNode[0].firstChild.nodeValue - # SEM automatically strips prefixed "--" or "-" from from xml before processing + # SEM automatically strips prefixed "--" or "-" from xml before processing # we need to replicate that behavior here The following # two nodes in xml have the same behavior in the program # --test @@ -331,7 +327,7 @@ def generate_class( ]: if not param.getElementsByTagName("channel"): raise RuntimeError( - "Insufficient XML specification: each element of type 'file', 'directory', 'image', 'geometry', 'transform', or 'table' requires 'channel' field.\n{0}".format( + "Insufficient XML specification: each element of type 'file', 'directory', 'image', 'geometry', 'transform', or 'table' requires 'channel' field.\n{}".format( traitsParams ) ) @@ -382,7 +378,7 @@ def generate_class( ) else: raise RuntimeError( - "Insufficient XML specification: each element of type 'file', 'directory', 'image', 'geometry', 'transform', or 'table' requires 'channel' field to be in ['input','output'].\n{0}".format( + "Insufficient XML specification: each element of type 'file', 'directory', 'image', 'geometry', 'transform', or 'table' requires 'channel' field to be in ['input','output'].\n{}".format( traitsParams ) ) @@ -417,7 +413,7 @@ def generate_class( output_filenames_code = "_outputs_filenames = {" output_filenames_code += ",".join( - ["'%s':'%s'" % (key, value) for key, value in outputs_filenames.items()] + [f"'{key}':'{value}'" for key, value in outputs_filenames.items()] ) output_filenames_code += "}" @@ -431,7 +427,7 @@ def generate_class( output_spec = %module_name%OutputSpec _cmd = "%launcher% %name% " %output_filenames_code%\n""" - template += " _redirect_x = {0}\n".format(str(redirect_x)) + template += f" _redirect_x = {redirect_x}\n" main_class = ( template.replace("%class_str%", class_string) @@ -494,9 +490,9 @@ def parse_params(params): list = [] for key, value in params.items(): if isinstance(value, (str, bytes)): - list.append('%s="%s"' % (key, value.replace('"', "'"))) + list.append('{}="{}"'.format(key, value.replace('"', "'"))) else: - list.append("%s=%s" % (key, value)) + list.append(f"{key}={value}") return ", ".join(list) diff --git a/nipype/interfaces/slicer/legacy/__init__.py b/nipype/interfaces/slicer/legacy/__init__.py index f65d44f058..4c0da2e0a0 100644 --- a/nipype/interfaces/slicer/legacy/__init__.py +++ b/nipype/interfaces/slicer/legacy/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .diffusion import * from .segmentation import OtsuThresholdSegmentation from .filtering import OtsuThresholdImageFilter, ResampleScalarVolume diff --git a/nipype/interfaces/slicer/legacy/converters.py b/nipype/interfaces/slicer/legacy/converters.py index aadd840d71..c5f0ecd21a 100644 --- a/nipype/interfaces/slicer/legacy/converters.py +++ b/nipype/interfaces/slicer/legacy/converters.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class BSplineToDeformationFieldInputSpec(CommandLineInputSpec): @@ -33,19 +25,18 @@ class BSplineToDeformationFieldOutputSpec(TraitedSpec): class BSplineToDeformationField(SEMLikeCommandLine): """title: BSpline to deformation field -category: Legacy.Converters + category: Legacy.Converters -description: Create a dense deformation field from a bspline+bulk transform. + description: Create a dense deformation field from a bspline+bulk transform. -version: 0.1.0.$Revision: 2104 $(alpha) + version: 0.1.0.$Revision: 2104 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BSplineToDeformationField + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BSplineToDeformationField -contributor: Andrey Fedorov (SPL, BWH) + contributor: Andrey Fedorov (SPL, BWH) -acknowledgements: This work is funded by NIH grants R01 CA111288 and U01 CA151261. - -""" + acknowledgements: This work is funded by NIH grants R01 CA111288 and U01 CA151261. + """ input_spec = BSplineToDeformationFieldInputSpec output_spec = BSplineToDeformationFieldOutputSpec diff --git a/nipype/interfaces/slicer/legacy/diffusion/__init__.py b/nipype/interfaces/slicer/legacy/diffusion/__init__.py index 9a9143d214..b40040d9e7 100644 --- a/nipype/interfaces/slicer/legacy/diffusion/__init__.py +++ b/nipype/interfaces/slicer/legacy/diffusion/__init__.py @@ -1,2 +1 @@ -# -*- coding: utf-8 -*- from .denoising import DWIUnbiasedNonLocalMeansFilter diff --git a/nipype/interfaces/slicer/legacy/diffusion/denoising.py b/nipype/interfaces/slicer/legacy/diffusion/denoising.py index 0cde8fe64e..8cccf949bb 100644 --- a/nipype/interfaces/slicer/legacy/diffusion/denoising.py +++ b/nipype/interfaces/slicer/legacy/diffusion/denoising.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class DWIUnbiasedNonLocalMeansFilterInputSpec(CommandLineInputSpec): @@ -32,7 +25,7 @@ class DWIUnbiasedNonLocalMeansFilterInputSpec(CommandLineInputSpec): argstr="--rc %s", ) hp = traits.Float( - desc="This parameter is related to noise; the larger the parameter, the more agressive the filtering. Should be near 1, and only values between 0.8 and 1.2 are allowed", + desc="This parameter is related to noise; the larger the parameter, the more aggressive the filtering. Should be near 1, and only values between 0.8 and 1.2 are allowed", argstr="--hp %f", ) ng = traits.Int( @@ -63,23 +56,22 @@ class DWIUnbiasedNonLocalMeansFilterOutputSpec(TraitedSpec): class DWIUnbiasedNonLocalMeansFilter(SEMLikeCommandLine): """title: DWI Unbiased Non Local Means Filter -category: Legacy.Diffusion.Denoising + category: Legacy.Diffusion.Denoising -description: This module reduces noise (or unwanted detail) on a set of diffusion weighted images. For this, it filters the images using a Unbiased Non Local Means for Rician noise algorithm. It exploits not only the spatial redundancy, but the redundancy in similar gradient directions as well; it takes into account the N closest gradient directions to the direction being processed (a maximum of 5 gradient directions is allowed to keep a reasonable computational load, since we do not use neither similarity maps nor block-wise implementation). -The noise parameter is automatically estimated in the same way as in the jointLMMSE module. -A complete description of the algorithm may be found in: -Antonio Tristan-Vega and Santiago Aja-Fernandez, DWI filtering using joint information for DTI and HARDI, Medical Image Analysis, Volume 14, Issue 2, Pages 205-218. 2010. -Please, note that the execution of this filter is extremely slow, son only very conservative parameters (block size and search size as small as possible) should be used. Even so, its execution may take several hours. The advantage of this filter over joint LMMSE is its better preservation of edges and fine structures. + description: This module reduces noise (or unwanted detail) on a set of diffusion weighted images. For this, it filters the images using a Unbiased Non Local Means for Rician noise algorithm. It exploits not only the spatial redundancy, but the redundancy in similar gradient directions as well; it takes into account the N closest gradient directions to the direction being processed (a maximum of 5 gradient directions is allowed to keep a reasonable computational load, since we do not use neither similarity maps nor block-wise implementation). + The noise parameter is automatically estimated in the same way as in the jointLMMSE module. + A complete description of the algorithm may be found in: + Antonio Tristan-Vega and Santiago Aja-Fernandez, DWI filtering using joint information for DTI and HARDI, Medical Image Analysis, Volume 14, Issue 2, Pages 205-218. 2010. + Please, note that the execution of this filter is extremely slow, son only very conservative parameters (block size and search size as small as possible) should be used. Even so, its execution may take several hours. The advantage of this filter over joint LMMSE is its better preservation of edges and fine structures. -version: 0.0.1.$Revision: 1 $(alpha) + version: 0.0.1.$Revision: 1 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/UnbiasedNonLocalMeansFilterForDWI + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/UnbiasedNonLocalMeansFilterForDWI -contributor: Antonio Tristan Vega (UVa), Santiago Aja Fernandez (UVa) + contributor: Antonio Tristan Vega (UVa), Santiago Aja Fernandez (UVa) -acknowledgements: Partially founded by grant number TEC2007-67073/TCM from the Comision Interministerial de Ciencia y Tecnologia (Spain). - -""" + acknowledgements: Partially founded by grant number TEC2007-67073/TCM from the Comision Interministerial de Ciencia y Tecnologia (Spain). + """ input_spec = DWIUnbiasedNonLocalMeansFilterInputSpec output_spec = DWIUnbiasedNonLocalMeansFilterOutputSpec diff --git a/nipype/interfaces/slicer/legacy/diffusion/tests/__init__.py b/nipype/interfaces/slicer/legacy/diffusion/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/slicer/legacy/diffusion/tests/__init__.py +++ b/nipype/interfaces/slicer/legacy/diffusion/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/slicer/legacy/diffusion/tests/test_auto_DWIUnbiasedNonLocalMeansFilter.py b/nipype/interfaces/slicer/legacy/diffusion/tests/test_auto_DWIUnbiasedNonLocalMeansFilter.py index 81f61c1bbc..8aa18dc6a3 100644 --- a/nipype/interfaces/slicer/legacy/diffusion/tests/test_auto_DWIUnbiasedNonLocalMeansFilter.py +++ b/nipype/interfaces/slicer/legacy/diffusion/tests/test_auto_DWIUnbiasedNonLocalMeansFilter.py @@ -4,15 +4,41 @@ def test_DWIUnbiasedNonLocalMeansFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - hp=dict(argstr="--hp %f",), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - ng=dict(argstr="--ng %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - rc=dict(argstr="--rc %s", sep=",",), - re=dict(argstr="--re %s", sep=",",), - rs=dict(argstr="--rs %s", sep=",",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + hp=dict( + argstr="--hp %f", + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + ng=dict( + argstr="--ng %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + rc=dict( + argstr="--rc %s", + sep=",", + ), + re=dict( + argstr="--re %s", + sep=",", + ), + rs=dict( + argstr="--rs %s", + sep=",", + ), ) inputs = DWIUnbiasedNonLocalMeansFilter.input_spec() @@ -22,7 +48,12 @@ def test_DWIUnbiasedNonLocalMeansFilter_inputs(): def test_DWIUnbiasedNonLocalMeansFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = DWIUnbiasedNonLocalMeansFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/filtering.py b/nipype/interfaces/slicer/legacy/filtering.py index ee041bbc50..978752f25b 100644 --- a/nipype/interfaces/slicer/legacy/filtering.py +++ b/nipype/interfaces/slicer/legacy/filtering.py @@ -1,20 +1,14 @@ -# -*- coding: utf-8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class OtsuThresholdImageFilterInputSpec(CommandLineInputSpec): @@ -50,23 +44,22 @@ class OtsuThresholdImageFilterOutputSpec(TraitedSpec): class OtsuThresholdImageFilter(SEMLikeCommandLine): """title: Otsu Threshold Image Filter -category: Legacy.Filtering + category: Legacy.Filtering -description: This filter creates a binary thresholded image that separates an image into foreground and background components. The filter calculates the optimum threshold separating those two classes so that their combined spread (intra-class variance) is minimal (see http://en.wikipedia.org/wiki/Otsu%27s_method). Then the filter applies that threshold to the input image using the itkBinaryThresholdImageFilter. The numberOfHistogram bins can be set for the Otsu Calculator. The insideValue and outsideValue can be set for the BinaryThresholdImageFilter. The filter produces a labeled volume. + description: This filter creates a binary thresholded image that separates an image into foreground and background components. The filter calculates the optimum threshold separating those two classes so that their combined spread (intra-class variance) is minimal (see http://en.wikipedia.org/wiki/Otsu%27s_method). Then the filter applies that threshold to the input image using the itkBinaryThresholdImageFilter. The numberOfHistogram bins can be set for the Otsu Calculator. The insideValue and outsideValue can be set for the BinaryThresholdImageFilter. The filter produces a labeled volume. -The original reference is: + The original reference is: -N.Otsu, A threshold selection method from gray level histograms, IEEE Trans.Syst.ManCybern.SMC-9,62–66 1979. + N.Otsu, A threshold selection method from gray level histograms, IEEE Trans.Syst.ManCybern.SMC-9,62–66 1979. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/OtsuThresholdImageFilter + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/OtsuThresholdImageFilter -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This command module was derived from Insight/Examples (copyright) Insight Software Consortium - -""" + acknowledgements: This command module was derived from Insight/Examples (copyright) Insight Software Consortium + """ input_spec = OtsuThresholdImageFilterInputSpec output_spec = OtsuThresholdImageFilterOutputSpec @@ -113,19 +106,18 @@ class ResampleScalarVolumeOutputSpec(TraitedSpec): class ResampleScalarVolume(SEMLikeCommandLine): """title: Resample Scalar Volume -category: Legacy.Filtering - -description: Resampling an image is an important task in image analysis. It is especially important in the frame of image registration. This module implements image resampling through the use of itk Transforms. This module uses an Identity Transform. The resampling is controlled by the Output Spacing. "Resampling" is performed in space coordinates, not pixel/grid coordinates. It is quite important to ensure that image spacing is properly set on the images involved. The interpolator is required since the mapping from one space to the other will often require evaluation of the intensity of the image at non-grid positions. Several interpolators are available: linear, nearest neighbor, bspline and five flavors of sinc. The sinc interpolators, although more precise, are much slower than the linear and nearest neighbor interpolator. To resample label volumnes, nearest neighbor interpolation should be used exclusively. + category: Legacy.Filtering -version: 0.1.0.$Revision: 20594 $(alpha) + description: Resampling an image is an important task in image analysis. It is especially important in the frame of image registration. This module implements image resampling through the use of itk Transforms. This module uses an Identity Transform. The resampling is controlled by the Output Spacing. "Resampling" is performed in space coordinates, not pixel/grid coordinates. It is quite important to ensure that image spacing is properly set on the images involved. The interpolator is required since the mapping from one space to the other will often require evaluation of the intensity of the image at non-grid positions. Several interpolators are available: linear, nearest neighbor, bspline and five flavors of sinc. The sinc interpolators, although more precise, are much slower than the linear and nearest neighbor interpolator. To resample label volumnes, nearest neighbor interpolation should be used exclusively. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ResampleVolume + version: 0.1.0.$Revision: 20594 $(alpha) -contributor: Bill Lorensen (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ResampleVolume -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Bill Lorensen (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = ResampleScalarVolumeInputSpec output_spec = ResampleScalarVolumeOutputSpec diff --git a/nipype/interfaces/slicer/legacy/registration.py b/nipype/interfaces/slicer/legacy/registration.py index 3bfd2377d4..01c9d17cb8 100644 --- a/nipype/interfaces/slicer/legacy/registration.py +++ b/nipype/interfaces/slicer/legacy/registration.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class BSplineDeformableRegistrationInputSpec(CommandLineInputSpec): @@ -96,19 +89,18 @@ class BSplineDeformableRegistrationOutputSpec(TraitedSpec): class BSplineDeformableRegistration(SEMLikeCommandLine): """title: BSpline Deformable Registration -category: Legacy.Registration + category: Legacy.Registration -description: Registers two images together using BSpline transform and mutual information. + description: Registers two images together using BSpline transform and mutual information. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BSplineDeformableRegistration + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/BSplineDeformableRegistration -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = BSplineDeformableRegistrationInputSpec output_spec = BSplineDeformableRegistrationOutputSpec @@ -183,25 +175,24 @@ class AffineRegistrationOutputSpec(TraitedSpec): class AffineRegistration(SEMLikeCommandLine): """title: Affine Registration -category: Legacy.Registration - -description: Registers two images together using an affine transform and mutual information. This module is often used to align images of different subjects or images of the same subject from different modalities. + category: Legacy.Registration -This module can smooth images prior to registration to mitigate noise and improve convergence. Many of the registration parameters require a working knowledge of the algorithm although the default parameters are sufficient for many registration tasks. + description: Registers two images together using an affine transform and mutual information. This module is often used to align images of different subjects or images of the same subject from different modalities. + This module can smooth images prior to registration to mitigate noise and improve convergence. Many of the registration parameters require a working knowledge of the algorithm although the default parameters are sufficient for many registration tasks. -version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/AffineRegistration + version: 0.1.0.$Revision: 19608 $(alpha) -contributor: Daniel Blezek (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/AffineRegistration -acknowledgements: This module was developed by Daniel Blezek while at GE Research with contributions from Jim Miller. + contributor: Daniel Blezek (GE) -This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + acknowledgements: This module was developed by Daniel Blezek while at GE Research with contributions from Jim Miller. -""" + This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = AffineRegistrationInputSpec output_spec = AffineRegistrationOutputSpec @@ -276,19 +267,18 @@ class MultiResolutionAffineRegistrationOutputSpec(TraitedSpec): class MultiResolutionAffineRegistration(SEMLikeCommandLine): """title: Robust Multiresolution Affine Registration -category: Legacy.Registration - -description: Provides affine registration using multiple resolution levels and decomposed affine transforms. + category: Legacy.Registration -version: 0.1.0.$Revision: 2104 $(alpha) + description: Provides affine registration using multiple resolution levels and decomposed affine transforms. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/MultiResolutionAffineRegistration + version: 0.1.0.$Revision: 2104 $(alpha) -contributor: Casey B Goodlett (Utah) + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/MultiResolutionAffineRegistration -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Casey B Goodlett (Utah) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = MultiResolutionAffineRegistrationInputSpec output_spec = MultiResolutionAffineRegistrationOutputSpec @@ -377,29 +367,28 @@ class RigidRegistrationOutputSpec(TraitedSpec): class RigidRegistration(SEMLikeCommandLine): """title: Rigid Registration -category: Legacy.Registration + category: Legacy.Registration -description: Registers two images together using a rigid transform and mutual information. + description: Registers two images together using a rigid transform and mutual information. -This module was originally distributed as "Linear registration" but has been renamed to eliminate confusion with the "Affine registration" module. + This module was originally distributed as "Linear registration" but has been renamed to eliminate confusion with the "Affine registration" module. -This module is often used to align images of different subjects or images of the same subject from different modalities. + This module is often used to align images of different subjects or images of the same subject from different modalities. -This module can smooth images prior to registration to mitigate noise and improve convergence. Many of the registration parameters require a working knowledge of the algorithm although the default parameters are sufficient for many registration tasks. + This module can smooth images prior to registration to mitigate noise and improve convergence. Many of the registration parameters require a working knowledge of the algorithm although the default parameters are sufficient for many registration tasks. -version: 0.1.0.$Revision: 19608 $(alpha) + version: 0.1.0.$Revision: 19608 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/RigidRegistration + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/RigidRegistration -contributor: Daniel Blezek (GE) + contributor: Daniel Blezek (GE) -acknowledgements: This module was developed by Daniel Blezek while at GE Research with contributions from Jim Miller. + acknowledgements: This module was developed by Daniel Blezek while at GE Research with contributions from Jim Miller. -This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = RigidRegistrationInputSpec output_spec = RigidRegistrationOutputSpec @@ -484,19 +473,18 @@ class LinearRegistrationOutputSpec(TraitedSpec): class LinearRegistration(SEMLikeCommandLine): """title: Linear Registration -category: Legacy.Registration - -description: Registers two images together using a rigid transform and mutual information. + category: Legacy.Registration -version: 0.1.0.$Revision: 19608 $(alpha) + description: Registers two images together using a rigid transform and mutual information. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/LinearRegistration + version: 0.1.0.$Revision: 19608 $(alpha) -contributor: Daniel Blezek (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/LinearRegistration -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Daniel Blezek (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = LinearRegistrationInputSpec output_spec = LinearRegistrationOutputSpec @@ -664,19 +652,18 @@ class ExpertAutomatedRegistrationOutputSpec(TraitedSpec): class ExpertAutomatedRegistration(SEMLikeCommandLine): """title: Expert Automated Registration -category: Legacy.Registration - -description: Provides rigid, affine, and BSpline registration methods via a simple GUI + category: Legacy.Registration -version: 0.1.0.$Revision: 2104 $(alpha) + description: Provides rigid, affine, and BSpline registration methods via a simple GUI -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ExpertAutomatedRegistration + version: 0.1.0.$Revision: 2104 $(alpha) -contributor: Stephen R Aylward (Kitware), Casey B Goodlett (Kitware) + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ExpertAutomatedRegistration -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Stephen R Aylward (Kitware), Casey B Goodlett (Kitware) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = ExpertAutomatedRegistrationInputSpec output_spec = ExpertAutomatedRegistrationOutputSpec diff --git a/nipype/interfaces/slicer/legacy/segmentation.py b/nipype/interfaces/slicer/legacy/segmentation.py index 118ffbcb77..664d9913ae 100644 --- a/nipype/interfaces/slicer/legacy/segmentation.py +++ b/nipype/interfaces/slicer/legacy/segmentation.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class OtsuThresholdSegmentationInputSpec(CommandLineInputSpec): @@ -55,19 +47,18 @@ class OtsuThresholdSegmentationOutputSpec(TraitedSpec): class OtsuThresholdSegmentation(SEMLikeCommandLine): """title: Otsu Threshold Segmentation -category: Legacy.Segmentation + category: Legacy.Segmentation -description: This filter creates a labeled image from a grayscale image. First, it calculates an optimal threshold that separates the image into foreground and background. This threshold separates those two classes so that their intra-class variance is minimal (see http://en.wikipedia.org/wiki/Otsu%27s_method). Then the filter runs a connected component algorithm to generate unique labels for each connected region of the foreground. Finally, the resulting image is relabeled to provide consecutive numbering. + description: This filter creates a labeled image from a grayscale image. First, it calculates an optimal threshold that separates the image into foreground and background. This threshold separates those two classes so that their intra-class variance is minimal (see http://en.wikipedia.org/wiki/Otsu%27s_method). Then the filter runs a connected component algorithm to generate unique labels for each connected region of the foreground. Finally, the resulting image is relabeled to provide consecutive numbering. -version: 1.0 + version: 1.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/OtsuThresholdSegmentation + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/OtsuThresholdSegmentation -contributor: Bill Lorensen (GE) + contributor: Bill Lorensen (GE) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = OtsuThresholdSegmentationInputSpec output_spec = OtsuThresholdSegmentationOutputSpec diff --git a/nipype/interfaces/slicer/legacy/tests/__init__.py b/nipype/interfaces/slicer/legacy/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/slicer/legacy/tests/__init__.py +++ b/nipype/interfaces/slicer/legacy/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_AffineRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_AffineRegistration.py index 44857bf3a8..bb2de08cfb 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_AffineRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_AffineRegistration.py @@ -4,21 +4,53 @@ def test_AffineRegistration_inputs(): input_map = dict( - FixedImageFileName=dict(argstr="%s", extensions=None, position=-2,), - MovingImageFileName=dict(argstr="%s", extensions=None, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixedsmoothingfactor=dict(argstr="--fixedsmoothingfactor %d",), - histogrambins=dict(argstr="--histogrambins %d",), - initialtransform=dict(argstr="--initialtransform %s", extensions=None,), - iterations=dict(argstr="--iterations %d",), - movingsmoothingfactor=dict(argstr="--movingsmoothingfactor %d",), - outputtransform=dict(argstr="--outputtransform %s", hash_files=False,), + FixedImageFileName=dict( + argstr="%s", + extensions=None, + position=-2, + ), + MovingImageFileName=dict( + argstr="%s", + extensions=None, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedsmoothingfactor=dict( + argstr="--fixedsmoothingfactor %d", + ), + histogrambins=dict( + argstr="--histogrambins %d", + ), + initialtransform=dict( + argstr="--initialtransform %s", + extensions=None, + ), + iterations=dict( + argstr="--iterations %d", + ), + movingsmoothingfactor=dict( + argstr="--movingsmoothingfactor %d", + ), + outputtransform=dict( + argstr="--outputtransform %s", + hash_files=False, + ), resampledmovingfilename=dict( - argstr="--resampledmovingfilename %s", hash_files=False, + argstr="--resampledmovingfilename %s", + hash_files=False, + ), + spatialsamples=dict( + argstr="--spatialsamples %d", + ), + translationscale=dict( + argstr="--translationscale %f", ), - spatialsamples=dict(argstr="--spatialsamples %d",), - translationscale=dict(argstr="--translationscale %f",), ) inputs = AffineRegistration.input_spec() @@ -29,8 +61,12 @@ def test_AffineRegistration_inputs(): def test_AffineRegistration_outputs(): output_map = dict( - outputtransform=dict(extensions=None,), - resampledmovingfilename=dict(extensions=None,), + outputtransform=dict( + extensions=None, + ), + resampledmovingfilename=dict( + extensions=None, + ), ) outputs = AffineRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineDeformableRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineDeformableRegistration.py index 7c777ebca3..41b316e7dc 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineDeformableRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineDeformableRegistration.py @@ -4,23 +4,60 @@ def test_BSplineDeformableRegistration_inputs(): input_map = dict( - FixedImageFileName=dict(argstr="%s", extensions=None, position=-2,), - MovingImageFileName=dict(argstr="%s", extensions=None, position=-1,), - args=dict(argstr="%s",), - constrain=dict(argstr="--constrain ",), - default=dict(argstr="--default %d",), - environ=dict(nohash=True, usedefault=True,), - gridSize=dict(argstr="--gridSize %d",), - histogrambins=dict(argstr="--histogrambins %d",), - initialtransform=dict(argstr="--initialtransform %s", extensions=None,), - iterations=dict(argstr="--iterations %d",), - maximumDeformation=dict(argstr="--maximumDeformation %f",), - outputtransform=dict(argstr="--outputtransform %s", hash_files=False,), - outputwarp=dict(argstr="--outputwarp %s", hash_files=False,), + FixedImageFileName=dict( + argstr="%s", + extensions=None, + position=-2, + ), + MovingImageFileName=dict( + argstr="%s", + extensions=None, + position=-1, + ), + args=dict( + argstr="%s", + ), + constrain=dict( + argstr="--constrain ", + ), + default=dict( + argstr="--default %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gridSize=dict( + argstr="--gridSize %d", + ), + histogrambins=dict( + argstr="--histogrambins %d", + ), + initialtransform=dict( + argstr="--initialtransform %s", + extensions=None, + ), + iterations=dict( + argstr="--iterations %d", + ), + maximumDeformation=dict( + argstr="--maximumDeformation %f", + ), + outputtransform=dict( + argstr="--outputtransform %s", + hash_files=False, + ), + outputwarp=dict( + argstr="--outputwarp %s", + hash_files=False, + ), resampledmovingfilename=dict( - argstr="--resampledmovingfilename %s", hash_files=False, + argstr="--resampledmovingfilename %s", + hash_files=False, + ), + spatialsamples=dict( + argstr="--spatialsamples %d", ), - spatialsamples=dict(argstr="--spatialsamples %d",), ) inputs = BSplineDeformableRegistration.input_spec() @@ -31,9 +68,15 @@ def test_BSplineDeformableRegistration_inputs(): def test_BSplineDeformableRegistration_outputs(): output_map = dict( - outputtransform=dict(extensions=None,), - outputwarp=dict(extensions=None,), - resampledmovingfilename=dict(extensions=None,), + outputtransform=dict( + extensions=None, + ), + outputwarp=dict( + extensions=None, + ), + resampledmovingfilename=dict( + extensions=None, + ), ) outputs = BSplineDeformableRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineToDeformationField.py b/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineToDeformationField.py index c4dc0f8969..fbd37eeb8e 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineToDeformationField.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_BSplineToDeformationField.py @@ -4,11 +4,25 @@ def test_BSplineToDeformationField_inputs(): input_map = dict( - args=dict(argstr="%s",), - defImage=dict(argstr="--defImage %s", hash_files=False,), - environ=dict(nohash=True, usedefault=True,), - refImage=dict(argstr="--refImage %s", extensions=None,), - tfm=dict(argstr="--tfm %s", extensions=None,), + args=dict( + argstr="%s", + ), + defImage=dict( + argstr="--defImage %s", + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + refImage=dict( + argstr="--refImage %s", + extensions=None, + ), + tfm=dict( + argstr="--tfm %s", + extensions=None, + ), ) inputs = BSplineToDeformationField.input_spec() @@ -18,7 +32,11 @@ def test_BSplineToDeformationField_inputs(): def test_BSplineToDeformationField_outputs(): - output_map = dict(defImage=dict(extensions=None,),) + output_map = dict( + defImage=dict( + extensions=None, + ), + ) outputs = BSplineToDeformationField.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_ExpertAutomatedRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_ExpertAutomatedRegistration.py index 6536d699b0..28f4e19d7b 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_ExpertAutomatedRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_ExpertAutomatedRegistration.py @@ -4,36 +4,105 @@ def test_ExpertAutomatedRegistration_inputs(): input_map = dict( - affineMaxIterations=dict(argstr="--affineMaxIterations %d",), - affineSamplingRatio=dict(argstr="--affineSamplingRatio %f",), - args=dict(argstr="%s",), - bsplineMaxIterations=dict(argstr="--bsplineMaxIterations %d",), - bsplineSamplingRatio=dict(argstr="--bsplineSamplingRatio %f",), - controlPointSpacing=dict(argstr="--controlPointSpacing %d",), - environ=dict(nohash=True, usedefault=True,), - expectedOffset=dict(argstr="--expectedOffset %f",), - expectedRotation=dict(argstr="--expectedRotation %f",), - expectedScale=dict(argstr="--expectedScale %f",), - expectedSkew=dict(argstr="--expectedSkew %f",), - fixedImage=dict(argstr="%s", extensions=None, position=-2,), - fixedImageMask=dict(argstr="--fixedImageMask %s", extensions=None,), - fixedLandmarks=dict(argstr="--fixedLandmarks %s...",), - initialization=dict(argstr="--initialization %s",), - interpolation=dict(argstr="--interpolation %s",), - loadTransform=dict(argstr="--loadTransform %s", extensions=None,), - metric=dict(argstr="--metric %s",), - minimizeMemory=dict(argstr="--minimizeMemory ",), - movingImage=dict(argstr="%s", extensions=None, position=-1,), - movingLandmarks=dict(argstr="--movingLandmarks %s...",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - randomNumberSeed=dict(argstr="--randomNumberSeed %d",), - registration=dict(argstr="--registration %s",), - resampledImage=dict(argstr="--resampledImage %s", hash_files=False,), - rigidMaxIterations=dict(argstr="--rigidMaxIterations %d",), - rigidSamplingRatio=dict(argstr="--rigidSamplingRatio %f",), - sampleFromOverlap=dict(argstr="--sampleFromOverlap ",), - saveTransform=dict(argstr="--saveTransform %s", hash_files=False,), - verbosityLevel=dict(argstr="--verbosityLevel %s",), + affineMaxIterations=dict( + argstr="--affineMaxIterations %d", + ), + affineSamplingRatio=dict( + argstr="--affineSamplingRatio %f", + ), + args=dict( + argstr="%s", + ), + bsplineMaxIterations=dict( + argstr="--bsplineMaxIterations %d", + ), + bsplineSamplingRatio=dict( + argstr="--bsplineSamplingRatio %f", + ), + controlPointSpacing=dict( + argstr="--controlPointSpacing %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expectedOffset=dict( + argstr="--expectedOffset %f", + ), + expectedRotation=dict( + argstr="--expectedRotation %f", + ), + expectedScale=dict( + argstr="--expectedScale %f", + ), + expectedSkew=dict( + argstr="--expectedSkew %f", + ), + fixedImage=dict( + argstr="%s", + extensions=None, + position=-2, + ), + fixedImageMask=dict( + argstr="--fixedImageMask %s", + extensions=None, + ), + fixedLandmarks=dict( + argstr="--fixedLandmarks %s...", + ), + initialization=dict( + argstr="--initialization %s", + ), + interpolation=dict( + argstr="--interpolation %s", + ), + loadTransform=dict( + argstr="--loadTransform %s", + extensions=None, + ), + metric=dict( + argstr="--metric %s", + ), + minimizeMemory=dict( + argstr="--minimizeMemory ", + ), + movingImage=dict( + argstr="%s", + extensions=None, + position=-1, + ), + movingLandmarks=dict( + argstr="--movingLandmarks %s...", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + randomNumberSeed=dict( + argstr="--randomNumberSeed %d", + ), + registration=dict( + argstr="--registration %s", + ), + resampledImage=dict( + argstr="--resampledImage %s", + hash_files=False, + ), + rigidMaxIterations=dict( + argstr="--rigidMaxIterations %d", + ), + rigidSamplingRatio=dict( + argstr="--rigidSamplingRatio %f", + ), + sampleFromOverlap=dict( + argstr="--sampleFromOverlap ", + ), + saveTransform=dict( + argstr="--saveTransform %s", + hash_files=False, + ), + verbosityLevel=dict( + argstr="--verbosityLevel %s", + ), ) inputs = ExpertAutomatedRegistration.input_spec() @@ -44,7 +113,12 @@ def test_ExpertAutomatedRegistration_inputs(): def test_ExpertAutomatedRegistration_outputs(): output_map = dict( - resampledImage=dict(extensions=None,), saveTransform=dict(extensions=None,), + resampledImage=dict( + extensions=None, + ), + saveTransform=dict( + extensions=None, + ), ) outputs = ExpertAutomatedRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_LinearRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_LinearRegistration.py index b19d3be344..77fb5d69f6 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_LinearRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_LinearRegistration.py @@ -4,22 +4,58 @@ def test_LinearRegistration_inputs(): input_map = dict( - FixedImageFileName=dict(argstr="%s", extensions=None, position=-2,), - MovingImageFileName=dict(argstr="%s", extensions=None, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixedsmoothingfactor=dict(argstr="--fixedsmoothingfactor %d",), - histogrambins=dict(argstr="--histogrambins %d",), - initialtransform=dict(argstr="--initialtransform %s", extensions=None,), - iterations=dict(argstr="--iterations %s", sep=",",), - learningrate=dict(argstr="--learningrate %s", sep=",",), - movingsmoothingfactor=dict(argstr="--movingsmoothingfactor %d",), - outputtransform=dict(argstr="--outputtransform %s", hash_files=False,), + FixedImageFileName=dict( + argstr="%s", + extensions=None, + position=-2, + ), + MovingImageFileName=dict( + argstr="%s", + extensions=None, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedsmoothingfactor=dict( + argstr="--fixedsmoothingfactor %d", + ), + histogrambins=dict( + argstr="--histogrambins %d", + ), + initialtransform=dict( + argstr="--initialtransform %s", + extensions=None, + ), + iterations=dict( + argstr="--iterations %s", + sep=",", + ), + learningrate=dict( + argstr="--learningrate %s", + sep=",", + ), + movingsmoothingfactor=dict( + argstr="--movingsmoothingfactor %d", + ), + outputtransform=dict( + argstr="--outputtransform %s", + hash_files=False, + ), resampledmovingfilename=dict( - argstr="--resampledmovingfilename %s", hash_files=False, + argstr="--resampledmovingfilename %s", + hash_files=False, + ), + spatialsamples=dict( + argstr="--spatialsamples %d", + ), + translationscale=dict( + argstr="--translationscale %f", ), - spatialsamples=dict(argstr="--spatialsamples %d",), - translationscale=dict(argstr="--translationscale %f",), ) inputs = LinearRegistration.input_spec() @@ -30,8 +66,12 @@ def test_LinearRegistration_inputs(): def test_LinearRegistration_outputs(): output_map = dict( - outputtransform=dict(extensions=None,), - resampledmovingfilename=dict(extensions=None,), + outputtransform=dict( + extensions=None, + ), + resampledmovingfilename=dict( + extensions=None, + ), ) outputs = LinearRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py index ad7f89e35d..0f1e19d4ba 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_MultiResolutionAffineRegistration.py @@ -4,19 +4,53 @@ def test_MultiResolutionAffineRegistration_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixedImage=dict(argstr="%s", extensions=None, position=-2,), - fixedImageMask=dict(argstr="--fixedImageMask %s", extensions=None,), - fixedImageROI=dict(argstr="--fixedImageROI %s",), - metricTolerance=dict(argstr="--metricTolerance %f",), - movingImage=dict(argstr="%s", extensions=None, position=-1,), - numIterations=dict(argstr="--numIterations %d",), - numLineIterations=dict(argstr="--numLineIterations %d",), - resampledImage=dict(argstr="--resampledImage %s", hash_files=False,), - saveTransform=dict(argstr="--saveTransform %s", hash_files=False,), - stepSize=dict(argstr="--stepSize %f",), - stepTolerance=dict(argstr="--stepTolerance %f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedImage=dict( + argstr="%s", + extensions=None, + position=-2, + ), + fixedImageMask=dict( + argstr="--fixedImageMask %s", + extensions=None, + ), + fixedImageROI=dict( + argstr="--fixedImageROI %s", + ), + metricTolerance=dict( + argstr="--metricTolerance %f", + ), + movingImage=dict( + argstr="%s", + extensions=None, + position=-1, + ), + numIterations=dict( + argstr="--numIterations %d", + ), + numLineIterations=dict( + argstr="--numLineIterations %d", + ), + resampledImage=dict( + argstr="--resampledImage %s", + hash_files=False, + ), + saveTransform=dict( + argstr="--saveTransform %s", + hash_files=False, + ), + stepSize=dict( + argstr="--stepSize %f", + ), + stepTolerance=dict( + argstr="--stepTolerance %f", + ), ) inputs = MultiResolutionAffineRegistration.input_spec() @@ -27,7 +61,12 @@ def test_MultiResolutionAffineRegistration_inputs(): def test_MultiResolutionAffineRegistration_outputs(): output_map = dict( - resampledImage=dict(extensions=None,), saveTransform=dict(extensions=None,), + resampledImage=dict( + extensions=None, + ), + saveTransform=dict( + extensions=None, + ), ) outputs = MultiResolutionAffineRegistration.output_spec() diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdImageFilter.py b/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdImageFilter.py index 853fbb5caa..672d971471 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdImageFilter.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdImageFilter.py @@ -4,13 +4,32 @@ def test_OtsuThresholdImageFilter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - insideValue=dict(argstr="--insideValue %d",), - numberOfBins=dict(argstr="--numberOfBins %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - outsideValue=dict(argstr="--outsideValue %d",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + insideValue=dict( + argstr="--insideValue %d", + ), + numberOfBins=dict( + argstr="--numberOfBins %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + outsideValue=dict( + argstr="--outsideValue %d", + ), ) inputs = OtsuThresholdImageFilter.input_spec() @@ -20,7 +39,12 @@ def test_OtsuThresholdImageFilter_inputs(): def test_OtsuThresholdImageFilter_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = OtsuThresholdImageFilter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdSegmentation.py b/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdSegmentation.py index 561bb246f2..a28c8231c8 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdSegmentation.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_OtsuThresholdSegmentation.py @@ -4,14 +4,35 @@ def test_OtsuThresholdSegmentation_inputs(): input_map = dict( - args=dict(argstr="%s",), - brightObjects=dict(argstr="--brightObjects ",), - environ=dict(nohash=True, usedefault=True,), - faceConnected=dict(argstr="--faceConnected ",), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - minimumObjectSize=dict(argstr="--minimumObjectSize %d",), - numberOfBins=dict(argstr="--numberOfBins %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + brightObjects=dict( + argstr="--brightObjects ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + faceConnected=dict( + argstr="--faceConnected ", + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + minimumObjectSize=dict( + argstr="--minimumObjectSize %d", + ), + numberOfBins=dict( + argstr="--numberOfBins %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = OtsuThresholdSegmentation.input_spec() @@ -21,7 +42,12 @@ def test_OtsuThresholdSegmentation_inputs(): def test_OtsuThresholdSegmentation_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = OtsuThresholdSegmentation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_ResampleScalarVolume.py b/nipype/interfaces/slicer/legacy/tests/test_auto_ResampleScalarVolume.py index a95967feca..2f47b3bd16 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_ResampleScalarVolume.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_ResampleScalarVolume.py @@ -4,12 +4,30 @@ def test_ResampleScalarVolume_inputs(): input_map = dict( - InputVolume=dict(argstr="%s", extensions=None, position=-2,), - OutputVolume=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - interpolation=dict(argstr="--interpolation %s",), - spacing=dict(argstr="--spacing %s", sep=",",), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + OutputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + interpolation=dict( + argstr="--interpolation %s", + ), + spacing=dict( + argstr="--spacing %s", + sep=",", + ), ) inputs = ResampleScalarVolume.input_spec() @@ -19,7 +37,12 @@ def test_ResampleScalarVolume_inputs(): def test_ResampleScalarVolume_outputs(): - output_map = dict(OutputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + OutputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = ResampleScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/legacy/tests/test_auto_RigidRegistration.py b/nipype/interfaces/slicer/legacy/tests/test_auto_RigidRegistration.py index ea4b5eda53..3e8aba0e4d 100644 --- a/nipype/interfaces/slicer/legacy/tests/test_auto_RigidRegistration.py +++ b/nipype/interfaces/slicer/legacy/tests/test_auto_RigidRegistration.py @@ -4,23 +4,61 @@ def test_RigidRegistration_inputs(): input_map = dict( - FixedImageFileName=dict(argstr="%s", extensions=None, position=-2,), - MovingImageFileName=dict(argstr="%s", extensions=None, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixedsmoothingfactor=dict(argstr="--fixedsmoothingfactor %d",), - histogrambins=dict(argstr="--histogrambins %d",), - initialtransform=dict(argstr="--initialtransform %s", extensions=None,), - iterations=dict(argstr="--iterations %s", sep=",",), - learningrate=dict(argstr="--learningrate %s", sep=",",), - movingsmoothingfactor=dict(argstr="--movingsmoothingfactor %d",), - outputtransform=dict(argstr="--outputtransform %s", hash_files=False,), + FixedImageFileName=dict( + argstr="%s", + extensions=None, + position=-2, + ), + MovingImageFileName=dict( + argstr="%s", + extensions=None, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedsmoothingfactor=dict( + argstr="--fixedsmoothingfactor %d", + ), + histogrambins=dict( + argstr="--histogrambins %d", + ), + initialtransform=dict( + argstr="--initialtransform %s", + extensions=None, + ), + iterations=dict( + argstr="--iterations %s", + sep=",", + ), + learningrate=dict( + argstr="--learningrate %s", + sep=",", + ), + movingsmoothingfactor=dict( + argstr="--movingsmoothingfactor %d", + ), + outputtransform=dict( + argstr="--outputtransform %s", + hash_files=False, + ), resampledmovingfilename=dict( - argstr="--resampledmovingfilename %s", hash_files=False, + argstr="--resampledmovingfilename %s", + hash_files=False, + ), + spatialsamples=dict( + argstr="--spatialsamples %d", + ), + testingmode=dict( + argstr="--testingmode ", + ), + translationscale=dict( + argstr="--translationscale %f", ), - spatialsamples=dict(argstr="--spatialsamples %d",), - testingmode=dict(argstr="--testingmode ",), - translationscale=dict(argstr="--translationscale %f",), ) inputs = RigidRegistration.input_spec() @@ -31,8 +69,12 @@ def test_RigidRegistration_inputs(): def test_RigidRegistration_outputs(): output_map = dict( - outputtransform=dict(extensions=None,), - resampledmovingfilename=dict(extensions=None,), + outputtransform=dict( + extensions=None, + ), + resampledmovingfilename=dict( + extensions=None, + ), ) outputs = RigidRegistration.output_spec() diff --git a/nipype/interfaces/slicer/quantification/__init__.py b/nipype/interfaces/slicer/quantification/__init__.py index c0e1e870e7..c34d46d1b5 100644 --- a/nipype/interfaces/slicer/quantification/__init__.py +++ b/nipype/interfaces/slicer/quantification/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- from .changequantification import IntensityDifferenceMetric from .petstandarduptakevaluecomputation import PETStandardUptakeValueComputation diff --git a/nipype/interfaces/slicer/quantification/changequantification.py b/nipype/interfaces/slicer/quantification/changequantification.py index c0e36b9bf9..952a8d6e1d 100644 --- a/nipype/interfaces/slicer/quantification/changequantification.py +++ b/nipype/interfaces/slicer/quantification/changequantification.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class IntensityDifferenceMetricInputSpec(CommandLineInputSpec): @@ -70,25 +62,24 @@ class IntensityDifferenceMetricOutputSpec(TraitedSpec): class IntensityDifferenceMetric(SEMLikeCommandLine): """title: - Intensity Difference Change Detection (FAST) + Intensity Difference Change Detection (FAST) -category: - Quantification.ChangeQuantification + category: + Quantification.ChangeQuantification -description: - Quantifies the changes between two spatially aligned images based on the pixel-wise difference of image intensities. + description: + Quantifies the changes between two spatially aligned images based on the pixel-wise difference of image intensities. -version: 0.1 + version: 0.1 -contributor: Andrey Fedorov + contributor: Andrey Fedorov -acknowledgements: + acknowledgements: - -""" + """ input_spec = IntensityDifferenceMetricInputSpec output_spec = IntensityDifferenceMetricOutputSpec diff --git a/nipype/interfaces/slicer/quantification/petstandarduptakevaluecomputation.py b/nipype/interfaces/slicer/quantification/petstandarduptakevaluecomputation.py index 9cf01c5359..4861eca651 100644 --- a/nipype/interfaces/slicer/quantification/petstandarduptakevaluecomputation.py +++ b/nipype/interfaces/slicer/quantification/petstandarduptakevaluecomputation.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class PETStandardUptakeValueComputationInputSpec(CommandLineInputSpec): @@ -69,19 +62,18 @@ class PETStandardUptakeValueComputationOutputSpec(TraitedSpec): class PETStandardUptakeValueComputation(SEMLikeCommandLine): """title: PET Standard Uptake Value Computation -category: Quantification + category: Quantification -description: Computes the standardized uptake value based on body weight. Takes an input PET image in DICOM and NRRD format (DICOM header must contain Radiopharmaceutical parameters). Produces a CSV file that contains patientID, studyDate, dose, labelID, suvmin, suvmax, suvmean, labelName for each volume of interest. It also displays some of the information as output strings in the GUI, the CSV file is optional in that case. The CSV file is appended to on each execution of the CLI. + description: Computes the standardized uptake value based on body weight. Takes an input PET image in DICOM and NRRD format (DICOM header must contain Radiopharmaceutical parameters). Produces a CSV file that contains patientID, studyDate, dose, labelID, suvmin, suvmax, suvmean, labelName for each volume of interest. It also displays some of the information as output strings in the GUI, the CSV file is optional in that case. The CSV file is appended to on each execution of the CLI. -version: 0.1.0.$Revision: 8595 $(alpha) + version: 0.1.0.$Revision: 8595 $(alpha) -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ComputeSUVBodyWeight + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ComputeSUVBodyWeight -contributor: Wendy Plesniak (SPL, BWH), Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) + contributor: Wendy Plesniak (SPL, BWH), Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) -acknowledgements: This work is funded by the Harvard Catalyst, and the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is funded by the Harvard Catalyst, and the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = PETStandardUptakeValueComputationInputSpec output_spec = PETStandardUptakeValueComputationOutputSpec diff --git a/nipype/interfaces/slicer/quantification/tests/__init__.py b/nipype/interfaces/slicer/quantification/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/slicer/quantification/tests/__init__.py +++ b/nipype/interfaces/slicer/quantification/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/slicer/quantification/tests/test_auto_IntensityDifferenceMetric.py b/nipype/interfaces/slicer/quantification/tests/test_auto_IntensityDifferenceMetric.py index 512991571e..6bc91e4d5e 100644 --- a/nipype/interfaces/slicer/quantification/tests/test_auto_IntensityDifferenceMetric.py +++ b/nipype/interfaces/slicer/quantification/tests/test_auto_IntensityDifferenceMetric.py @@ -4,15 +4,43 @@ def test_IntensityDifferenceMetric_inputs(): input_map = dict( - args=dict(argstr="%s",), - baselineSegmentationVolume=dict(argstr="%s", extensions=None, position=-3,), - baselineVolume=dict(argstr="%s", extensions=None, position=-4,), - changingBandSize=dict(argstr="--changingBandSize %d",), - environ=dict(nohash=True, usedefault=True,), - followupVolume=dict(argstr="%s", extensions=None, position=-2,), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - reportFileName=dict(argstr="--reportFileName %s", hash_files=False,), - sensitivityThreshold=dict(argstr="--sensitivityThreshold %f",), + args=dict( + argstr="%s", + ), + baselineSegmentationVolume=dict( + argstr="%s", + extensions=None, + position=-3, + ), + baselineVolume=dict( + argstr="%s", + extensions=None, + position=-4, + ), + changingBandSize=dict( + argstr="--changingBandSize %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + followupVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + reportFileName=dict( + argstr="--reportFileName %s", + hash_files=False, + ), + sensitivityThreshold=dict( + argstr="--sensitivityThreshold %f", + ), ) inputs = IntensityDifferenceMetric.input_spec() @@ -23,8 +51,13 @@ def test_IntensityDifferenceMetric_inputs(): def test_IntensityDifferenceMetric_outputs(): output_map = dict( - outputVolume=dict(extensions=None, position=-1,), - reportFileName=dict(extensions=None,), + outputVolume=dict( + extensions=None, + position=-1, + ), + reportFileName=dict( + extensions=None, + ), ) outputs = IntensityDifferenceMetric.output_spec() diff --git a/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py b/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py index 61ee94ec6e..aec22b541f 100644 --- a/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py +++ b/nipype/interfaces/slicer/quantification/tests/test_auto_PETStandardUptakeValueComputation.py @@ -4,18 +4,47 @@ def test_PETStandardUptakeValueComputation_inputs(): input_map = dict( - OutputLabel=dict(argstr="--OutputLabel %s",), - OutputLabelValue=dict(argstr="--OutputLabelValue %s",), - SUVMax=dict(argstr="--SUVMax %s",), - SUVMean=dict(argstr="--SUVMean %s",), - SUVMin=dict(argstr="--SUVMin %s",), - args=dict(argstr="%s",), - color=dict(argstr="--color %s", extensions=None,), - csvFile=dict(argstr="--csvFile %s", hash_files=False,), - environ=dict(nohash=True, usedefault=True,), - labelMap=dict(argstr="--labelMap %s", extensions=None,), - petDICOMPath=dict(argstr="--petDICOMPath %s",), - petVolume=dict(argstr="--petVolume %s", extensions=None,), + OutputLabel=dict( + argstr="--OutputLabel %s", + ), + OutputLabelValue=dict( + argstr="--OutputLabelValue %s", + ), + SUVMax=dict( + argstr="--SUVMax %s", + ), + SUVMean=dict( + argstr="--SUVMean %s", + ), + SUVMin=dict( + argstr="--SUVMin %s", + ), + args=dict( + argstr="%s", + ), + color=dict( + argstr="--color %s", + extensions=None, + ), + csvFile=dict( + argstr="--csvFile %s", + hash_files=False, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + labelMap=dict( + argstr="--labelMap %s", + extensions=None, + ), + petDICOMPath=dict( + argstr="--petDICOMPath %s", + ), + petVolume=dict( + argstr="--petVolume %s", + extensions=None, + ), ) inputs = PETStandardUptakeValueComputation.input_spec() @@ -25,7 +54,11 @@ def test_PETStandardUptakeValueComputation_inputs(): def test_PETStandardUptakeValueComputation_outputs(): - output_map = dict(csvFile=dict(extensions=None,),) + output_map = dict( + csvFile=dict( + extensions=None, + ), + ) outputs = PETStandardUptakeValueComputation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/registration/__init__.py b/nipype/interfaces/slicer/registration/__init__.py index faa3c92b2f..ddb3988eae 100644 --- a/nipype/interfaces/slicer/registration/__init__.py +++ b/nipype/interfaces/slicer/registration/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from .specialized import ( ACPCTransform, FiducialRegistration, diff --git a/nipype/interfaces/slicer/registration/brainsfit.py b/nipype/interfaces/slicer/registration/brainsfit.py index 2ca7f09d3c..079d538499 100644 --- a/nipype/interfaces/slicer/registration/brainsfit.py +++ b/nipype/interfaces/slicer/registration/brainsfit.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class BRAINSFitInputSpec(CommandLineInputSpec): @@ -65,23 +58,23 @@ class BRAINSFitInputSpec(CommandLineInputSpec): argstr="--initializeTransformMode %s", ) useRigid = traits.Bool( - desc="Perform a rigid registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + desc="Perform a rigid registration as part of the sequential registration steps. This family of options supersedes the use of transformType if any of them are set.", argstr="--useRigid ", ) useScaleVersor3D = traits.Bool( - desc="Perform a ScaleVersor3D registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + desc="Perform a ScaleVersor3D registration as part of the sequential registration steps. This family of options supersedes the use of transformType if any of them are set.", argstr="--useScaleVersor3D ", ) useScaleSkewVersor3D = traits.Bool( - desc="Perform a ScaleSkewVersor3D registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + desc="Perform a ScaleSkewVersor3D registration as part of the sequential registration steps. This family of options supersedes the use of transformType if any of them are set.", argstr="--useScaleSkewVersor3D ", ) useAffine = traits.Bool( - desc="Perform an Affine registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + desc="Perform an Affine registration as part of the sequential registration steps. This family of options supersedes the use of transformType if any of them are set.", argstr="--useAffine ", ) useBSpline = traits.Bool( - desc="Perform a BSpline registration as part of the sequential registration steps. This family of options superceeds the use of transformType if any of them are set.", + desc="Perform a BSpline registration as part of the sequential registration steps. This family of options supersedes the use of transformType if any of them are set.", argstr="--useBSpline ", ) numberOfSamples = traits.Int( @@ -104,7 +97,7 @@ class BRAINSFitInputSpec(CommandLineInputSpec): "NOMASK", "ROIAUTO", "ROI", - desc="What mode to use for using the masks. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. The Region Of Interest mode (choose ROI) uses the masks to define what parts of the image should be used for computing the transform.", + desc="What mode to use for using the masks. If ROIAUTO is chosen, then the mask is implicitly defined using a otsu foreground and hole filling algorithm. The Region Of Interest mode (choose ROI) uses the masks to define what parts of the image should be used for computing the transform.", argstr="--maskProcessingMode %s", ) fixedBinaryVolume = File( @@ -208,7 +201,7 @@ class BRAINSFitInputSpec(CommandLineInputSpec): ) transformType = InputMultiPath( traits.Str, - desc="Specifies a list of registration types to be used. The valid types are, Rigid, ScaleVersor3D, ScaleSkewVersor3D, Affine, and BSpline. Specifiying more than one in a comma separated list will initialize the next stage with the previous results. If registrationClass flag is used, it overrides this parameter setting.", + desc="Specifies a list of registration types to be used. The valid types are, Rigid, ScaleVersor3D, ScaleSkewVersor3D, Affine, and BSpline. Specifying more than one in a comma separated list will initialize the next stage with the previous results. If registrationClass flag is used, it overrides this parameter setting.", sep=",", argstr="--transformType %s", ) @@ -234,7 +227,7 @@ class BRAINSFitInputSpec(CommandLineInputSpec): argstr="--medianFilterSize %s", ) removeIntensityOutliers = traits.Float( - desc="The half percentage to decide outliers of image intensities. The default value is zero, which means no outlier removal. If the value of 0.005 is given, the moduel will throw away 0.005 % of both tails, so 0.01% of intensities in total would be ignored in its statistic calculation. ", + desc="The half percentage to decide outliers of image intensities. The default value is zero, which means no outlier removal. If the value of 0.005 is given, the module will throw away 0.005 % of both tails, so 0.01% of intensities in total would be ignored in its statistic calculation. ", argstr="--removeIntensityOutliers %f", ) useCachingOfBSplineWeightsMode = traits.Enum( @@ -251,11 +244,11 @@ class BRAINSFitInputSpec(CommandLineInputSpec): argstr="--useExplicitPDFDerivativesMode %s", ) ROIAutoDilateSize = traits.Float( - desc="This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", + desc="This flag is only relevant when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", argstr="--ROIAutoDilateSize %f", ) ROIAutoClosingSize = traits.Float( - desc="This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the hole closing size in mm. It is rounded up to the nearest whole pixel size in each direction. The default is to use a closing size of 9mm. For mouse data this value may need to be reset to 0.9 or smaller.", + desc="This flag is only relevant when using ROIAUTO mode for initializing masks. It defines the hole closing size in mm. It is rounded up to the nearest whole pixel size in each direction. The default is to use a closing size of 9mm. For mouse data this value may need to be reset to 0.9 or smaller.", argstr="--ROIAutoClosingSize %f", ) relaxationFactor = traits.Float( @@ -279,7 +272,7 @@ class BRAINSFitInputSpec(CommandLineInputSpec): argstr="--numberOfThreads %d", ) forceMINumberOfThreads = traits.Int( - desc="Force the the maximum number of threads to use for non thread safe MI metric. CAUTION: Inconsistent results my arise!", + desc="Force the maximum number of threads to use for non thread safe MI metric. CAUTION: Inconsistent results my arise!", argstr="--forceMINumberOfThreads %d", ) debugLevel = traits.Int( @@ -295,7 +288,7 @@ class BRAINSFitInputSpec(CommandLineInputSpec): argstr="--projectedGradientTolerance %f", ) gui = traits.Bool( - desc="Display intermediate image volumes for debugging. NOTE: This is not part of the standard build sytem, and probably does nothing on your installation.", + desc="Display intermediate image volumes for debugging. NOTE: This is not part of the standard build system, and probably does nothing on your installation.", argstr="--gui ", ) promptUser = traits.Bool( @@ -365,21 +358,20 @@ class BRAINSFitOutputSpec(TraitedSpec): class BRAINSFit(SEMLikeCommandLine): """title: General Registration (BRAINS) -category: Registration + category: Registration -description: Register a three-dimensional volume to a reference volume (Mattes Mutual Information by default). Described in BRAINSFit: Mutual Information Registrations of Whole-Brain 3D Images, Using the Insight Toolkit, Johnson H.J., Harris G., Williams K., The Insight Journal, 2007. http://hdl.handle.net/1926/1291 + description: Register a three-dimensional volume to a reference volume (Mattes Mutual Information by default). Described in BRAINSFit: Mutual Information Registrations of Whole-Brain 3D Images, Using the Insight Toolkit, Johnson H.J., Harris G., Williams K., The Insight Journal, 2007. http://hdl.handle.net/1926/1291 -version: 3.0.0 + version: 3.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:BRAINSFit + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:BRAINSFit -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://wwww.psychiatry.uiowa.edu + contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://wwww.psychiatry.uiowa.edu -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); Gregory Harris(1), Vincent Magnotta(1,2,3); Andriy Fedorov(5) 1=University of Iowa Department of Psychiatry, 2=University of Iowa Department of Radiology, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering, 5=Surgical Planning Lab, Harvard - -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); Gregory Harris(1), Vincent Magnotta(1,2,3); Andriy Fedorov(5) 1=University of Iowa Department of Psychiatry, 2=University of Iowa Department of Radiology, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering, 5=Surgical Planning Lab, Harvard + """ input_spec = BRAINSFitInputSpec output_spec = BRAINSFitOutputSpec diff --git a/nipype/interfaces/slicer/registration/brainsresample.py b/nipype/interfaces/slicer/registration/brainsresample.py index 9031b86d8c..82a69f6d0a 100644 --- a/nipype/interfaces/slicer/registration/brainsresample.py +++ b/nipype/interfaces/slicer/registration/brainsresample.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class BRAINSResampleInputSpec(CommandLineInputSpec): @@ -74,7 +67,7 @@ class BRAINSResampleInputSpec(CommandLineInputSpec): defaultValue = traits.Float(desc="Default voxel value", argstr="--defaultValue %f") gridSpacing = InputMultiPath( traits.Int, - desc="Add warped grid to output image to help show the deformation that occured with specified spacing. A spacing of 0 in a dimension indicates that grid lines should be rendered to fall exactly (i.e. do not allow displacements off that plane). This is useful for makeing a 2D image of grid lines from the 3D space ", + desc="Add warped grid to output image to help show the deformation that occurred with specified spacing. A spacing of 0 in a dimension indicates that grid lines should be rendered to fall exactly (i.e. do not allow displacements off that plane). This is useful for making a 2D image of grid lines from the 3D space ", sep=",", argstr="--gridSpacing %s", ) @@ -91,23 +84,22 @@ class BRAINSResampleOutputSpec(TraitedSpec): class BRAINSResample(SEMLikeCommandLine): """title: Resample Image (BRAINS) -category: Registration + category: Registration -description: - This program resamples an image image using a deformation field or a transform (BSpline, Affine, Rigid, etc.). + description: + This program resamples an image using a deformation field or a transform (BSpline, Affine, Rigid, etc.). -version: 3.0.0 + version: 3.0.0 -documentation-url: http://www.slicer.org/slicerWiki/index.php/Modules:BRAINSResample + documentation-url: http://www.slicer.org/slicerWiki/index.php/Modules:BRAINSResample -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Vincent Magnotta, Greg Harris, and Hans Johnson. + contributor: This tool was developed by Vincent Magnotta, Greg Harris, and Hans Johnson. -acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. - -""" + acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + """ input_spec = BRAINSResampleInputSpec output_spec = BRAINSResampleOutputSpec diff --git a/nipype/interfaces/slicer/registration/specialized.py b/nipype/interfaces/slicer/registration/specialized.py index 12835b0cef..30688928c2 100644 --- a/nipype/interfaces/slicer/registration/specialized.py +++ b/nipype/interfaces/slicer/registration/specialized.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class ACPCTransformInputSpec(CommandLineInputSpec): @@ -51,21 +44,20 @@ class ACPCTransformOutputSpec(TraitedSpec): class ACPCTransform(SEMLikeCommandLine): """title: ACPC Transform -category: Registration.Specialized + category: Registration.Specialized -description:

Calculate a transformation from two lists of fiducial points.

ACPC line is two fiducial points, one at the anterior commissure and one at the posterior commissure. The resulting transform will bring the line connecting them to horizontal to the AP axis.

The midline is a series of points defining the division between the hemispheres of the brain (the mid sagittal plane). The resulting transform will put the output volume with the mid sagittal plane lined up with the AS plane.

Use the Filtering moduleResample Scalar/Vector/DWI Volumeto apply the transformation to a volume.

+ description:

Calculate a transformation from two lists of fiducial points.

ACPC line is two fiducial points, one at the anterior commissure and one at the posterior commissure. The resulting transform will bring the line connecting them to horizontal to the AP axis.

The midline is a series of points defining the division between the hemispheres of the brain (the mid sagittal plane). The resulting transform will put the output volume with the mid sagittal plane lined up with the AS plane.

Use the Filtering moduleResample Scalar/Vector/DWI Volumeto apply the transformation to a volume.

-version: 1.0 + version: 1.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ACPCTransform + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ACPCTransform -license: slicer3 + license: slicer3 -contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) + contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = ACPCTransformInputSpec output_spec = ACPCTransformOutputSpec @@ -113,19 +105,18 @@ class FiducialRegistrationOutputSpec(TraitedSpec): class FiducialRegistration(SEMLikeCommandLine): """title: Fiducial Registration -category: Registration.Specialized - -description: Computes a rigid, similarity or affine transform from a matched list of fiducials + category: Registration.Specialized -version: 0.1.0.$Revision$ + description: Computes a rigid, similarity or affine transform from a matched list of fiducials -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/TransformFromFiducials + version: 0.1.0.$Revision$ -contributor: Casey B Goodlett (Kitware), Dominik Meier (SPL, BWH) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/TransformFromFiducials -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Casey B Goodlett (Kitware), Dominik Meier (SPL, BWH) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = FiducialRegistrationInputSpec output_spec = FiducialRegistrationOutputSpec @@ -200,7 +191,7 @@ class VBRAINSDemonWarpInputSpec(CommandLineInputSpec): argstr="--registrationFilterType %s", ) smoothDisplacementFieldSigma = traits.Float( - desc="A gaussian smoothing value to be applied to the deformation feild at each iteration.", + desc="A gaussian smoothing value to be applied to the deformation field at each iteration.", argstr="--smoothDisplacementFieldSigma %f", ) numberOfPyramidLevels = traits.Int( @@ -371,24 +362,23 @@ class VBRAINSDemonWarpOutputSpec(TraitedSpec): class VBRAINSDemonWarp(SEMLikeCommandLine): """title: Vector Demon Registration (BRAINS) -category: Registration.Specialized + category: Registration.Specialized -description: - This program finds a deformation field to warp a moving image onto a fixed image. The images must be of the same signal kind, and contain an image of the same kind of object. This program uses the Thirion Demons warp software in ITK, the Insight Toolkit. Additional information is available at: http://www.nitrc.org/projects/brainsdemonwarp. + description: + This program finds a deformation field to warp a moving image onto a fixed image. The images must be of the same signal kind, and contain an image of the same kind of object. This program uses the Thirion Demons warp software in ITK, the Insight Toolkit. Additional information is available at: http://www.nitrc.org/projects/brainsdemonwarp. -version: 3.0.0 + version: 3.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:BRAINSDemonWarp + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:BRAINSDemonWarp -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -contributor: This tool was developed by Hans J. Johnson and Greg Harris. + contributor: This tool was developed by Hans J. Johnson and Greg Harris. -acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. - -""" + acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + """ input_spec = VBRAINSDemonWarpInputSpec output_spec = VBRAINSDemonWarpOutputSpec @@ -463,7 +453,7 @@ class BRAINSDemonWarpInputSpec(CommandLineInputSpec): argstr="--registrationFilterType %s", ) smoothDisplacementFieldSigma = traits.Float( - desc="A gaussian smoothing value to be applied to the deformation feild at each iteration.", + desc="A gaussian smoothing value to be applied to the deformation field at each iteration.", argstr="--smoothDisplacementFieldSigma %f", ) numberOfPyramidLevels = traits.Int( @@ -520,7 +510,7 @@ class BRAINSDemonWarpInputSpec(CommandLineInputSpec): "ROIAUTO", "ROI", "BOBF", - desc="What mode to use for using the masks: NOMASK|ROIAUTO|ROI|BOBF. If ROIAUTO is choosen, then the mask is implicitly defined using a otsu forground and hole filling algorithm. Where the Region Of Interest mode uses the masks to define what parts of the image should be used for computing the deformation field. Brain Only Background Fill uses the masks to pre-process the input images by clipping and filling in the background with a predefined value.", + desc="What mode to use for using the masks: NOMASK|ROIAUTO|ROI|BOBF. If ROIAUTO is chosen, then the mask is implicitly defined using a otsu foreground and hole filling algorithm. Where the Region Of Interest mode uses the masks to define what parts of the image should be used for computing the deformation field. Brain Only Background Fill uses the masks to pre-process the input images by clipping and filling in the background with a predefined value.", argstr="--maskProcessingMode %s", ) fixedBinaryVolume = File( @@ -632,24 +622,23 @@ class BRAINSDemonWarpOutputSpec(TraitedSpec): class BRAINSDemonWarp(SEMLikeCommandLine): """title: Demon Registration (BRAINS) -category: Registration.Specialized - -description: - This program finds a deformation field to warp a moving image onto a fixed image. The images must be of the same signal kind, and contain an image of the same kind of object. This program uses the Thirion Demons warp software in ITK, the Insight Toolkit. Additional information is available at: http://www.nitrc.org/projects/brainsdemonwarp. + category: Registration.Specialized + description: + This program finds a deformation field to warp a moving image onto a fixed image. The images must be of the same signal kind, and contain an image of the same kind of object. This program uses the Thirion Demons warp software in ITK, the Insight Toolkit. Additional information is available at: http://www.nitrc.org/projects/brainsdemonwarp. -version: 3.0.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:BRAINSDemonWarp + version: 3.0.0 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Modules:BRAINSDemonWarp -contributor: This tool was developed by Hans J. Johnson and Greg Harris. + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + contributor: This tool was developed by Hans J. Johnson and Greg Harris. -""" + acknowledgements: The development of this tool was supported by funding from grants NS050568 and NS40068 from the National Institute of Neurological Disorders and Stroke and grants MH31593, MH40856, from the National Institute of Mental Health. + """ input_spec = BRAINSDemonWarpInputSpec output_spec = BRAINSDemonWarpOutputSpec diff --git a/nipype/interfaces/slicer/registration/tests/__init__.py b/nipype/interfaces/slicer/registration/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/slicer/registration/tests/__init__.py +++ b/nipype/interfaces/slicer/registration/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_ACPCTransform.py b/nipype/interfaces/slicer/registration/tests/test_auto_ACPCTransform.py index e36498110b..58c7c49f32 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_ACPCTransform.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_ACPCTransform.py @@ -4,12 +4,26 @@ def test_ACPCTransform_inputs(): input_map = dict( - acpc=dict(argstr="--acpc %s...",), - args=dict(argstr="%s",), - debugSwitch=dict(argstr="--debugSwitch ",), - environ=dict(nohash=True, usedefault=True,), - midline=dict(argstr="--midline %s...",), - outputTransform=dict(argstr="--outputTransform %s", hash_files=False,), + acpc=dict( + argstr="--acpc %s...", + ), + args=dict( + argstr="%s", + ), + debugSwitch=dict( + argstr="--debugSwitch ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + midline=dict( + argstr="--midline %s...", + ), + outputTransform=dict( + argstr="--outputTransform %s", + hash_files=False, + ), ) inputs = ACPCTransform.input_spec() @@ -19,7 +33,11 @@ def test_ACPCTransform_inputs(): def test_ACPCTransform_outputs(): - output_map = dict(outputTransform=dict(extensions=None,),) + output_map = dict( + outputTransform=dict( + extensions=None, + ), + ) outputs = ACPCTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py index 4136c8105d..d1c8055df3 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSDemonWarp.py @@ -4,64 +4,149 @@ def test_BRAINSDemonWarp_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), arrayOfPyramidLevelIterations=dict( - argstr="--arrayOfPyramidLevelIterations %s", sep=",", + argstr="--arrayOfPyramidLevelIterations %s", + sep=",", + ), + backgroundFillValue=dict( + argstr="--backgroundFillValue %d", ), - backgroundFillValue=dict(argstr="--backgroundFillValue %d",), checkerboardPatternSubdivisions=dict( - argstr="--checkerboardPatternSubdivisions %s", sep=",", - ), - environ=dict(nohash=True, usedefault=True,), - fixedBinaryVolume=dict(argstr="--fixedBinaryVolume %s", extensions=None,), - fixedVolume=dict(argstr="--fixedVolume %s", extensions=None,), - gradient_type=dict(argstr="--gradient_type %s",), - gui=dict(argstr="--gui ",), - histogramMatch=dict(argstr="--histogramMatch ",), + argstr="--checkerboardPatternSubdivisions %s", + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedBinaryVolume=dict( + argstr="--fixedBinaryVolume %s", + extensions=None, + ), + fixedVolume=dict( + argstr="--fixedVolume %s", + extensions=None, + ), + gradient_type=dict( + argstr="--gradient_type %s", + ), + gui=dict( + argstr="--gui ", + ), + histogramMatch=dict( + argstr="--histogramMatch ", + ), initializeWithDisplacementField=dict( - argstr="--initializeWithDisplacementField %s", extensions=None, + argstr="--initializeWithDisplacementField %s", + extensions=None, ), initializeWithTransform=dict( - argstr="--initializeWithTransform %s", extensions=None, - ), - inputPixelType=dict(argstr="--inputPixelType %s",), - interpolationMode=dict(argstr="--interpolationMode %s",), - lowerThresholdForBOBF=dict(argstr="--lowerThresholdForBOBF %d",), - maskProcessingMode=dict(argstr="--maskProcessingMode %s",), - max_step_length=dict(argstr="--max_step_length %f",), - medianFilterSize=dict(argstr="--medianFilterSize %s", sep=",",), - minimumFixedPyramid=dict(argstr="--minimumFixedPyramid %s", sep=",",), - minimumMovingPyramid=dict(argstr="--minimumMovingPyramid %s", sep=",",), - movingBinaryVolume=dict(argstr="--movingBinaryVolume %s", extensions=None,), - movingVolume=dict(argstr="--movingVolume %s", extensions=None,), - neighborhoodForBOBF=dict(argstr="--neighborhoodForBOBF %s", sep=",",), + argstr="--initializeWithTransform %s", + extensions=None, + ), + inputPixelType=dict( + argstr="--inputPixelType %s", + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + lowerThresholdForBOBF=dict( + argstr="--lowerThresholdForBOBF %d", + ), + maskProcessingMode=dict( + argstr="--maskProcessingMode %s", + ), + max_step_length=dict( + argstr="--max_step_length %f", + ), + medianFilterSize=dict( + argstr="--medianFilterSize %s", + sep=",", + ), + minimumFixedPyramid=dict( + argstr="--minimumFixedPyramid %s", + sep=",", + ), + minimumMovingPyramid=dict( + argstr="--minimumMovingPyramid %s", + sep=",", + ), + movingBinaryVolume=dict( + argstr="--movingBinaryVolume %s", + extensions=None, + ), + movingVolume=dict( + argstr="--movingVolume %s", + extensions=None, + ), + neighborhoodForBOBF=dict( + argstr="--neighborhoodForBOBF %s", + sep=",", + ), numberOfBCHApproximationTerms=dict( argstr="--numberOfBCHApproximationTerms %d", ), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - numberOfMatchPoints=dict(argstr="--numberOfMatchPoints %d",), - numberOfPyramidLevels=dict(argstr="--numberOfPyramidLevels %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + numberOfMatchPoints=dict( + argstr="--numberOfMatchPoints %d", + ), + numberOfPyramidLevels=dict( + argstr="--numberOfPyramidLevels %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), outputCheckerboardVolume=dict( - argstr="--outputCheckerboardVolume %s", hash_files=False, + argstr="--outputCheckerboardVolume %s", + hash_files=False, + ), + outputDebug=dict( + argstr="--outputDebug ", ), - outputDebug=dict(argstr="--outputDebug ",), outputDisplacementFieldPrefix=dict( argstr="--outputDisplacementFieldPrefix %s", ), outputDisplacementFieldVolume=dict( - argstr="--outputDisplacementFieldVolume %s", hash_files=False, - ), - outputNormalized=dict(argstr="--outputNormalized ",), - outputPixelType=dict(argstr="--outputPixelType %s",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - promptUser=dict(argstr="--promptUser ",), - registrationFilterType=dict(argstr="--registrationFilterType %s",), - seedForBOBF=dict(argstr="--seedForBOBF %s", sep=",",), - smoothDisplacementFieldSigma=dict(argstr="--smoothDisplacementFieldSigma %f",), - upFieldSmoothing=dict(argstr="--upFieldSmoothing %f",), - upperThresholdForBOBF=dict(argstr="--upperThresholdForBOBF %d",), - use_vanilla_dem=dict(argstr="--use_vanilla_dem ",), + argstr="--outputDisplacementFieldVolume %s", + hash_files=False, + ), + outputNormalized=dict( + argstr="--outputNormalized ", + ), + outputPixelType=dict( + argstr="--outputPixelType %s", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + promptUser=dict( + argstr="--promptUser ", + ), + registrationFilterType=dict( + argstr="--registrationFilterType %s", + ), + seedForBOBF=dict( + argstr="--seedForBOBF %s", + sep=",", + ), + smoothDisplacementFieldSigma=dict( + argstr="--smoothDisplacementFieldSigma %f", + ), + upFieldSmoothing=dict( + argstr="--upFieldSmoothing %f", + ), + upperThresholdForBOBF=dict( + argstr="--upperThresholdForBOBF %d", + ), + use_vanilla_dem=dict( + argstr="--use_vanilla_dem ", + ), ) inputs = BRAINSDemonWarp.input_spec() @@ -72,9 +157,15 @@ def test_BRAINSDemonWarp_inputs(): def test_BRAINSDemonWarp_outputs(): output_map = dict( - outputCheckerboardVolume=dict(extensions=None,), - outputDisplacementFieldVolume=dict(extensions=None,), - outputVolume=dict(extensions=None,), + outputCheckerboardVolume=dict( + extensions=None, + ), + outputDisplacementFieldVolume=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), ) outputs = BRAINSDemonWarp.output_spec() diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py index 9d558f1e68..0d7b124635 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSFit.py @@ -13,78 +13,205 @@ def test_BRAINSFit_inputs(): NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02=dict( argstr="--NEVER_USE_THIS_FLAG_IT_IS_OUTDATED_02 ", ), - ROIAutoClosingSize=dict(argstr="--ROIAutoClosingSize %f",), - ROIAutoDilateSize=dict(argstr="--ROIAutoDilateSize %f",), - args=dict(argstr="%s",), - backgroundFillValue=dict(argstr="--backgroundFillValue %f",), - bsplineTransform=dict(argstr="--bsplineTransform %s", hash_files=False,), + ROIAutoClosingSize=dict( + argstr="--ROIAutoClosingSize %f", + ), + ROIAutoDilateSize=dict( + argstr="--ROIAutoDilateSize %f", + ), + args=dict( + argstr="%s", + ), + backgroundFillValue=dict( + argstr="--backgroundFillValue %f", + ), + bsplineTransform=dict( + argstr="--bsplineTransform %s", + hash_files=False, + ), costFunctionConvergenceFactor=dict( argstr="--costFunctionConvergenceFactor %f", ), - costMetric=dict(argstr="--costMetric %s",), - debugLevel=dict(argstr="--debugLevel %d",), - environ=dict(nohash=True, usedefault=True,), - failureExitCode=dict(argstr="--failureExitCode %d",), - fixedBinaryVolume=dict(argstr="--fixedBinaryVolume %s", extensions=None,), - fixedVolume=dict(argstr="--fixedVolume %s", extensions=None,), - fixedVolumeTimeIndex=dict(argstr="--fixedVolumeTimeIndex %d",), - forceMINumberOfThreads=dict(argstr="--forceMINumberOfThreads %d",), - gui=dict(argstr="--gui ",), - histogramMatch=dict(argstr="--histogramMatch ",), - initialTransform=dict(argstr="--initialTransform %s", extensions=None,), - initializeTransformMode=dict(argstr="--initializeTransformMode %s",), - interpolationMode=dict(argstr="--interpolationMode %s",), - linearTransform=dict(argstr="--linearTransform %s", hash_files=False,), - maskInferiorCutOffFromCenter=dict(argstr="--maskInferiorCutOffFromCenter %f",), - maskProcessingMode=dict(argstr="--maskProcessingMode %s",), - maxBSplineDisplacement=dict(argstr="--maxBSplineDisplacement %f",), - maximumStepLength=dict(argstr="--maximumStepLength %f",), - medianFilterSize=dict(argstr="--medianFilterSize %s", sep=",",), - minimumStepLength=dict(argstr="--minimumStepLength %s", sep=",",), - movingBinaryVolume=dict(argstr="--movingBinaryVolume %s", extensions=None,), - movingVolume=dict(argstr="--movingVolume %s", extensions=None,), - movingVolumeTimeIndex=dict(argstr="--movingVolumeTimeIndex %d",), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - numberOfIterations=dict(argstr="--numberOfIterations %s", sep=",",), - numberOfMatchPoints=dict(argstr="--numberOfMatchPoints %d",), - numberOfSamples=dict(argstr="--numberOfSamples %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + costMetric=dict( + argstr="--costMetric %s", + ), + debugLevel=dict( + argstr="--debugLevel %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + failureExitCode=dict( + argstr="--failureExitCode %d", + ), + fixedBinaryVolume=dict( + argstr="--fixedBinaryVolume %s", + extensions=None, + ), + fixedVolume=dict( + argstr="--fixedVolume %s", + extensions=None, + ), + fixedVolumeTimeIndex=dict( + argstr="--fixedVolumeTimeIndex %d", + ), + forceMINumberOfThreads=dict( + argstr="--forceMINumberOfThreads %d", + ), + gui=dict( + argstr="--gui ", + ), + histogramMatch=dict( + argstr="--histogramMatch ", + ), + initialTransform=dict( + argstr="--initialTransform %s", + extensions=None, + ), + initializeTransformMode=dict( + argstr="--initializeTransformMode %s", + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + linearTransform=dict( + argstr="--linearTransform %s", + hash_files=False, + ), + maskInferiorCutOffFromCenter=dict( + argstr="--maskInferiorCutOffFromCenter %f", + ), + maskProcessingMode=dict( + argstr="--maskProcessingMode %s", + ), + maxBSplineDisplacement=dict( + argstr="--maxBSplineDisplacement %f", + ), + maximumStepLength=dict( + argstr="--maximumStepLength %f", + ), + medianFilterSize=dict( + argstr="--medianFilterSize %s", + sep=",", + ), + minimumStepLength=dict( + argstr="--minimumStepLength %s", + sep=",", + ), + movingBinaryVolume=dict( + argstr="--movingBinaryVolume %s", + extensions=None, + ), + movingVolume=dict( + argstr="--movingVolume %s", + extensions=None, + ), + movingVolumeTimeIndex=dict( + argstr="--movingVolumeTimeIndex %d", + ), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + numberOfIterations=dict( + argstr="--numberOfIterations %s", + sep=",", + ), + numberOfMatchPoints=dict( + argstr="--numberOfMatchPoints %d", + ), + numberOfSamples=dict( + argstr="--numberOfSamples %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), outputFixedVolumeROI=dict( - argstr="--outputFixedVolumeROI %s", hash_files=False, + argstr="--outputFixedVolumeROI %s", + hash_files=False, ), outputMovingVolumeROI=dict( - argstr="--outputMovingVolumeROI %s", hash_files=False, - ), - outputTransform=dict(argstr="--outputTransform %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - outputVolumePixelType=dict(argstr="--outputVolumePixelType %s",), - permitParameterVariation=dict(argstr="--permitParameterVariation %s", sep=",",), - projectedGradientTolerance=dict(argstr="--projectedGradientTolerance %f",), - promptUser=dict(argstr="--promptUser ",), - relaxationFactor=dict(argstr="--relaxationFactor %f",), - removeIntensityOutliers=dict(argstr="--removeIntensityOutliers %f",), - reproportionScale=dict(argstr="--reproportionScale %f",), - scaleOutputValues=dict(argstr="--scaleOutputValues ",), - skewScale=dict(argstr="--skewScale %f",), - splineGridSize=dict(argstr="--splineGridSize %s", sep=",",), + argstr="--outputMovingVolumeROI %s", + hash_files=False, + ), + outputTransform=dict( + argstr="--outputTransform %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + outputVolumePixelType=dict( + argstr="--outputVolumePixelType %s", + ), + permitParameterVariation=dict( + argstr="--permitParameterVariation %s", + sep=",", + ), + projectedGradientTolerance=dict( + argstr="--projectedGradientTolerance %f", + ), + promptUser=dict( + argstr="--promptUser ", + ), + relaxationFactor=dict( + argstr="--relaxationFactor %f", + ), + removeIntensityOutliers=dict( + argstr="--removeIntensityOutliers %f", + ), + reproportionScale=dict( + argstr="--reproportionScale %f", + ), + scaleOutputValues=dict( + argstr="--scaleOutputValues ", + ), + skewScale=dict( + argstr="--skewScale %f", + ), + splineGridSize=dict( + argstr="--splineGridSize %s", + sep=",", + ), strippedOutputTransform=dict( - argstr="--strippedOutputTransform %s", hash_files=False, + argstr="--strippedOutputTransform %s", + hash_files=False, + ), + transformType=dict( + argstr="--transformType %s", + sep=",", + ), + translationScale=dict( + argstr="--translationScale %f", + ), + useAffine=dict( + argstr="--useAffine ", + ), + useBSpline=dict( + argstr="--useBSpline ", ), - transformType=dict(argstr="--transformType %s", sep=",",), - translationScale=dict(argstr="--translationScale %f",), - useAffine=dict(argstr="--useAffine ",), - useBSpline=dict(argstr="--useBSpline ",), useCachingOfBSplineWeightsMode=dict( argstr="--useCachingOfBSplineWeightsMode %s", ), useExplicitPDFDerivativesMode=dict( argstr="--useExplicitPDFDerivativesMode %s", ), - useRigid=dict(argstr="--useRigid ",), - useScaleSkewVersor3D=dict(argstr="--useScaleSkewVersor3D ",), - useScaleVersor3D=dict(argstr="--useScaleVersor3D ",), - writeOutputTransformInFloat=dict(argstr="--writeOutputTransformInFloat ",), - writeTransformOnFailure=dict(argstr="--writeTransformOnFailure ",), + useRigid=dict( + argstr="--useRigid ", + ), + useScaleSkewVersor3D=dict( + argstr="--useScaleSkewVersor3D ", + ), + useScaleVersor3D=dict( + argstr="--useScaleVersor3D ", + ), + writeOutputTransformInFloat=dict( + argstr="--writeOutputTransformInFloat ", + ), + writeTransformOnFailure=dict( + argstr="--writeTransformOnFailure ", + ), ) inputs = BRAINSFit.input_spec() @@ -95,13 +222,27 @@ def test_BRAINSFit_inputs(): def test_BRAINSFit_outputs(): output_map = dict( - bsplineTransform=dict(extensions=None,), - linearTransform=dict(extensions=None,), - outputFixedVolumeROI=dict(extensions=None,), - outputMovingVolumeROI=dict(extensions=None,), - outputTransform=dict(extensions=None,), - outputVolume=dict(extensions=None,), - strippedOutputTransform=dict(extensions=None,), + bsplineTransform=dict( + extensions=None, + ), + linearTransform=dict( + extensions=None, + ), + outputFixedVolumeROI=dict( + extensions=None, + ), + outputMovingVolumeROI=dict( + extensions=None, + ), + outputTransform=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), + strippedOutputTransform=dict( + extensions=None, + ), ) outputs = BRAINSFit.output_spec() diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py index 2d94f19a5f..46d175da07 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_BRAINSResample.py @@ -4,19 +4,52 @@ def test_BRAINSResample_inputs(): input_map = dict( - args=dict(argstr="%s",), - defaultValue=dict(argstr="--defaultValue %f",), - deformationVolume=dict(argstr="--deformationVolume %s", extensions=None,), - environ=dict(nohash=True, usedefault=True,), - gridSpacing=dict(argstr="--gridSpacing %s", sep=",",), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - interpolationMode=dict(argstr="--interpolationMode %s",), - inverseTransform=dict(argstr="--inverseTransform ",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - pixelType=dict(argstr="--pixelType %s",), - referenceVolume=dict(argstr="--referenceVolume %s", extensions=None,), - warpTransform=dict(argstr="--warpTransform %s", extensions=None,), + args=dict( + argstr="%s", + ), + defaultValue=dict( + argstr="--defaultValue %f", + ), + deformationVolume=dict( + argstr="--deformationVolume %s", + extensions=None, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gridSpacing=dict( + argstr="--gridSpacing %s", + sep=",", + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + inverseTransform=dict( + argstr="--inverseTransform ", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + pixelType=dict( + argstr="--pixelType %s", + ), + referenceVolume=dict( + argstr="--referenceVolume %s", + extensions=None, + ), + warpTransform=dict( + argstr="--warpTransform %s", + extensions=None, + ), ) inputs = BRAINSResample.input_spec() @@ -26,7 +59,11 @@ def test_BRAINSResample_inputs(): def test_BRAINSResample_outputs(): - output_map = dict(outputVolume=dict(extensions=None,),) + output_map = dict( + outputVolume=dict( + extensions=None, + ), + ) outputs = BRAINSResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py b/nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py index 65c6016db6..6b511790c7 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_FiducialRegistration.py @@ -4,14 +4,32 @@ def test_FiducialRegistration_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fixedLandmarks=dict(argstr="--fixedLandmarks %s...",), - movingLandmarks=dict(argstr="--movingLandmarks %s...",), - outputMessage=dict(argstr="--outputMessage %s",), - rms=dict(argstr="--rms %f",), - saveTransform=dict(argstr="--saveTransform %s", hash_files=False,), - transformType=dict(argstr="--transformType %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedLandmarks=dict( + argstr="--fixedLandmarks %s...", + ), + movingLandmarks=dict( + argstr="--movingLandmarks %s...", + ), + outputMessage=dict( + argstr="--outputMessage %s", + ), + rms=dict( + argstr="--rms %f", + ), + saveTransform=dict( + argstr="--saveTransform %s", + hash_files=False, + ), + transformType=dict( + argstr="--transformType %s", + ), ) inputs = FiducialRegistration.input_spec() @@ -21,7 +39,11 @@ def test_FiducialRegistration_inputs(): def test_FiducialRegistration_outputs(): - output_map = dict(saveTransform=dict(extensions=None,),) + output_map = dict( + saveTransform=dict( + extensions=None, + ), + ) outputs = FiducialRegistration.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/registration/tests/test_auto_VBRAINSDemonWarp.py b/nipype/interfaces/slicer/registration/tests/test_auto_VBRAINSDemonWarp.py index 098360c1e3..af8bac8680 100644 --- a/nipype/interfaces/slicer/registration/tests/test_auto_VBRAINSDemonWarp.py +++ b/nipype/interfaces/slicer/registration/tests/test_auto_VBRAINSDemonWarp.py @@ -4,65 +4,151 @@ def test_VBRAINSDemonWarp_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), arrayOfPyramidLevelIterations=dict( - argstr="--arrayOfPyramidLevelIterations %s", sep=",", + argstr="--arrayOfPyramidLevelIterations %s", + sep=",", + ), + backgroundFillValue=dict( + argstr="--backgroundFillValue %d", ), - backgroundFillValue=dict(argstr="--backgroundFillValue %d",), checkerboardPatternSubdivisions=dict( - argstr="--checkerboardPatternSubdivisions %s", sep=",", - ), - environ=dict(nohash=True, usedefault=True,), - fixedBinaryVolume=dict(argstr="--fixedBinaryVolume %s", extensions=None,), - fixedVolume=dict(argstr="--fixedVolume %s...",), - gradient_type=dict(argstr="--gradient_type %s",), - gui=dict(argstr="--gui ",), - histogramMatch=dict(argstr="--histogramMatch ",), + argstr="--checkerboardPatternSubdivisions %s", + sep=",", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fixedBinaryVolume=dict( + argstr="--fixedBinaryVolume %s", + extensions=None, + ), + fixedVolume=dict( + argstr="--fixedVolume %s...", + ), + gradient_type=dict( + argstr="--gradient_type %s", + ), + gui=dict( + argstr="--gui ", + ), + histogramMatch=dict( + argstr="--histogramMatch ", + ), initializeWithDisplacementField=dict( - argstr="--initializeWithDisplacementField %s", extensions=None, + argstr="--initializeWithDisplacementField %s", + extensions=None, ), initializeWithTransform=dict( - argstr="--initializeWithTransform %s", extensions=None, - ), - inputPixelType=dict(argstr="--inputPixelType %s",), - interpolationMode=dict(argstr="--interpolationMode %s",), - lowerThresholdForBOBF=dict(argstr="--lowerThresholdForBOBF %d",), - makeBOBF=dict(argstr="--makeBOBF ",), - max_step_length=dict(argstr="--max_step_length %f",), - medianFilterSize=dict(argstr="--medianFilterSize %s", sep=",",), - minimumFixedPyramid=dict(argstr="--minimumFixedPyramid %s", sep=",",), - minimumMovingPyramid=dict(argstr="--minimumMovingPyramid %s", sep=",",), - movingBinaryVolume=dict(argstr="--movingBinaryVolume %s", extensions=None,), - movingVolume=dict(argstr="--movingVolume %s...",), - neighborhoodForBOBF=dict(argstr="--neighborhoodForBOBF %s", sep=",",), + argstr="--initializeWithTransform %s", + extensions=None, + ), + inputPixelType=dict( + argstr="--inputPixelType %s", + ), + interpolationMode=dict( + argstr="--interpolationMode %s", + ), + lowerThresholdForBOBF=dict( + argstr="--lowerThresholdForBOBF %d", + ), + makeBOBF=dict( + argstr="--makeBOBF ", + ), + max_step_length=dict( + argstr="--max_step_length %f", + ), + medianFilterSize=dict( + argstr="--medianFilterSize %s", + sep=",", + ), + minimumFixedPyramid=dict( + argstr="--minimumFixedPyramid %s", + sep=",", + ), + minimumMovingPyramid=dict( + argstr="--minimumMovingPyramid %s", + sep=",", + ), + movingBinaryVolume=dict( + argstr="--movingBinaryVolume %s", + extensions=None, + ), + movingVolume=dict( + argstr="--movingVolume %s...", + ), + neighborhoodForBOBF=dict( + argstr="--neighborhoodForBOBF %s", + sep=",", + ), numberOfBCHApproximationTerms=dict( argstr="--numberOfBCHApproximationTerms %d", ), - numberOfHistogramBins=dict(argstr="--numberOfHistogramBins %d",), - numberOfMatchPoints=dict(argstr="--numberOfMatchPoints %d",), - numberOfPyramidLevels=dict(argstr="--numberOfPyramidLevels %d",), - numberOfThreads=dict(argstr="--numberOfThreads %d",), + numberOfHistogramBins=dict( + argstr="--numberOfHistogramBins %d", + ), + numberOfMatchPoints=dict( + argstr="--numberOfMatchPoints %d", + ), + numberOfPyramidLevels=dict( + argstr="--numberOfPyramidLevels %d", + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), outputCheckerboardVolume=dict( - argstr="--outputCheckerboardVolume %s", hash_files=False, + argstr="--outputCheckerboardVolume %s", + hash_files=False, + ), + outputDebug=dict( + argstr="--outputDebug ", ), - outputDebug=dict(argstr="--outputDebug ",), outputDisplacementFieldPrefix=dict( argstr="--outputDisplacementFieldPrefix %s", ), outputDisplacementFieldVolume=dict( - argstr="--outputDisplacementFieldVolume %s", hash_files=False, - ), - outputNormalized=dict(argstr="--outputNormalized ",), - outputPixelType=dict(argstr="--outputPixelType %s",), - outputVolume=dict(argstr="--outputVolume %s", hash_files=False,), - promptUser=dict(argstr="--promptUser ",), - registrationFilterType=dict(argstr="--registrationFilterType %s",), - seedForBOBF=dict(argstr="--seedForBOBF %s", sep=",",), - smoothDisplacementFieldSigma=dict(argstr="--smoothDisplacementFieldSigma %f",), - upFieldSmoothing=dict(argstr="--upFieldSmoothing %f",), - upperThresholdForBOBF=dict(argstr="--upperThresholdForBOBF %d",), - use_vanilla_dem=dict(argstr="--use_vanilla_dem ",), - weightFactors=dict(argstr="--weightFactors %s", sep=",",), + argstr="--outputDisplacementFieldVolume %s", + hash_files=False, + ), + outputNormalized=dict( + argstr="--outputNormalized ", + ), + outputPixelType=dict( + argstr="--outputPixelType %s", + ), + outputVolume=dict( + argstr="--outputVolume %s", + hash_files=False, + ), + promptUser=dict( + argstr="--promptUser ", + ), + registrationFilterType=dict( + argstr="--registrationFilterType %s", + ), + seedForBOBF=dict( + argstr="--seedForBOBF %s", + sep=",", + ), + smoothDisplacementFieldSigma=dict( + argstr="--smoothDisplacementFieldSigma %f", + ), + upFieldSmoothing=dict( + argstr="--upFieldSmoothing %f", + ), + upperThresholdForBOBF=dict( + argstr="--upperThresholdForBOBF %d", + ), + use_vanilla_dem=dict( + argstr="--use_vanilla_dem ", + ), + weightFactors=dict( + argstr="--weightFactors %s", + sep=",", + ), ) inputs = VBRAINSDemonWarp.input_spec() @@ -73,9 +159,15 @@ def test_VBRAINSDemonWarp_inputs(): def test_VBRAINSDemonWarp_outputs(): output_map = dict( - outputCheckerboardVolume=dict(extensions=None,), - outputDisplacementFieldVolume=dict(extensions=None,), - outputVolume=dict(extensions=None,), + outputCheckerboardVolume=dict( + extensions=None, + ), + outputDisplacementFieldVolume=dict( + extensions=None, + ), + outputVolume=dict( + extensions=None, + ), ) outputs = VBRAINSDemonWarp.output_spec() diff --git a/nipype/interfaces/slicer/segmentation/__init__.py b/nipype/interfaces/slicer/segmentation/__init__.py index 48fdc62f8c..4c7e36f0c1 100644 --- a/nipype/interfaces/slicer/segmentation/__init__.py +++ b/nipype/interfaces/slicer/segmentation/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- from .specialized import RobustStatisticsSegmenter, EMSegmentCommandLine, BRAINSROIAuto from .simpleregiongrowingsegmentation import SimpleRegionGrowingSegmentation diff --git a/nipype/interfaces/slicer/segmentation/simpleregiongrowingsegmentation.py b/nipype/interfaces/slicer/segmentation/simpleregiongrowingsegmentation.py index a32a8dde5c..4d652ffb0e 100644 --- a/nipype/interfaces/slicer/segmentation/simpleregiongrowingsegmentation.py +++ b/nipype/interfaces/slicer/segmentation/simpleregiongrowingsegmentation.py @@ -1,21 +1,14 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class SimpleRegionGrowingSegmentationInputSpec(CommandLineInputSpec): @@ -63,19 +56,18 @@ class SimpleRegionGrowingSegmentationOutputSpec(TraitedSpec): class SimpleRegionGrowingSegmentation(SEMLikeCommandLine): """title: Simple Region Growing Segmentation -category: Segmentation + category: Segmentation -description: A simple region growing segmentation algorithm based on intensity statistics. To create a list of fiducials (Seeds) for this algorithm, click on the tool bar icon of an arrow pointing to a starburst fiducial to enter the 'place a new object mode' and then use the fiducials module. This module uses the Slicer Command Line Interface (CLI) and the ITK filters CurvatureFlowImageFilter and ConfidenceConnectedImageFilter. + description: A simple region growing segmentation algorithm based on intensity statistics. To create a list of fiducials (Seeds) for this algorithm, click on the tool bar icon of an arrow pointing to a starburst fiducial to enter the 'place a new object mode' and then use the fiducials module. This module uses the Slicer Command Line Interface (CLI) and the ITK filters CurvatureFlowImageFilter and ConfidenceConnectedImageFilter. -version: 0.1.0.$Revision: 19904 $(alpha) + version: 0.1.0.$Revision: 19904 $(alpha) -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/SimpleRegionGrowingSegmentation + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/SimpleRegionGrowingSegmentation -contributor: Jim Miller (GE) + contributor: Jim Miller (GE) -acknowledgements: This command module was derived from Insight/Examples (copyright) Insight Software Consortium - -""" + acknowledgements: This command module was derived from Insight/Examples (copyright) Insight Software Consortium + """ input_spec = SimpleRegionGrowingSegmentationInputSpec output_spec = SimpleRegionGrowingSegmentationOutputSpec diff --git a/nipype/interfaces/slicer/segmentation/specialized.py b/nipype/interfaces/slicer/segmentation/specialized.py index 0ae90d0334..fc278b1da5 100644 --- a/nipype/interfaces/slicer/segmentation/specialized.py +++ b/nipype/interfaces/slicer/segmentation/specialized.py @@ -1,21 +1,15 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, - isdefined, InputMultiPath, - OutputMultiPath, ) -import os class RobustStatisticsSegmenterInputSpec(CommandLineInputSpec): @@ -28,7 +22,7 @@ class RobustStatisticsSegmenterInputSpec(CommandLineInputSpec): argstr="--intensityHomogeneity %f", ) curvatureWeight = traits.Float( - desc="Given sphere 1.0 score and extreme rough bounday/surface 0 score, what is the expected smoothness of the object?", + desc="Given sphere 1.0 score and extreme rough boundary/surface 0 score, what is the expected smoothness of the object?", argstr="--curvatureWeight %f", ) labelValue = traits.Int( @@ -61,19 +55,18 @@ class RobustStatisticsSegmenterOutputSpec(TraitedSpec): class RobustStatisticsSegmenter(SEMLikeCommandLine): """title: Robust Statistics Segmenter -category: Segmentation.Specialized + category: Segmentation.Specialized -description: Active contour segmentation using robust statistic. + description: Active contour segmentation using robust statistic. -version: 1.0 + version: 1.0 -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/RobustStatisticsSegmenter + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/RobustStatisticsSegmenter -contributor: Yi Gao (gatech), Allen Tannenbaum (gatech), Ron Kikinis (SPL, BWH) + contributor: Yi Gao (gatech), Allen Tannenbaum (gatech), Ron Kikinis (SPL, BWH) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health + """ input_spec = RobustStatisticsSegmenterInputSpec output_spec = RobustStatisticsSegmenterOutputSpec @@ -194,25 +187,24 @@ class EMSegmentCommandLineOutputSpec(TraitedSpec): class EMSegmentCommandLine(SEMLikeCommandLine): """title: - EMSegment Command-line - + EMSegment Command-line -category: - Segmentation.Specialized + category: + Segmentation.Specialized -description: - This module is used to simplify the process of segmenting large collections of images by providing a command line interface to the EMSegment algorithm for script and batch processing. + description: + This module is used to simplify the process of segmenting large collections of images by providing a command line interface to the EMSegment algorithm for script and batch processing. -documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.0/EMSegment_Command-line -contributor: Sebastien Barre, Brad Davis, Kilian Pohl, Polina Golland, Yumin Yuan, Daniel Haehn + documentation-url: http://www.slicer.org/slicerWiki/index.php/Documentation/4.0/EMSegment_Command-line -acknowledgements: Many people and organizations have contributed to the funding, design, and development of the EMSegment algorithm and its various implementations. + contributor: Sebastien Barre, Brad Davis, Kilian Pohl, Polina Golland, Yumin Yuan, Daniel Haehn + acknowledgements: Many people and organizations have contributed to the funding, design, and development of the EMSegment algorithm and its various implementations. -""" + """ input_spec = EMSegmentCommandLineInputSpec output_spec = EMSegmentCommandLineOutputSpec @@ -257,7 +249,7 @@ class BRAINSROIAutoInputSpec(CommandLineInputSpec): argstr="--closingSize %f", ) ROIAutoDilateSize = traits.Float( - desc="This flag is only relavent when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", + desc="This flag is only relevant when using ROIAUTO mode for initializing masks. It defines the final dilation size to capture a bit of background outside the tissue region. At setting of 10mm has been shown to help regularize a BSpline registration type so that there is some background constraints to match the edges of the head better.", argstr="--ROIAutoDilateSize %f", ) outputVolumePixelType = traits.Enum( @@ -288,20 +280,19 @@ class BRAINSROIAutoOutputSpec(TraitedSpec): class BRAINSROIAuto(SEMLikeCommandLine): """title: Foreground masking (BRAINS) -category: Segmentation.Specialized - -description: This tool uses a combination of otsu thresholding and a closing operations to identify the most prominant foreground region in an image. + category: Segmentation.Specialized + description: This tool uses a combination of otsu thresholding and a closing operations to identify the most prominent foreground region in an image. -version: 2.4.1 -license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt + version: 2.4.1 -contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://wwww.psychiatry.uiowa.edu + license: https://www.nitrc.org/svn/brains/BuildScripts/trunk/License.txt -acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); Gregory Harris(1), Vincent Magnotta(1,2,3); Andriy Fedorov(5), fedorov -at- bwh.harvard.edu (Slicer integration); (1=University of Iowa Department of Psychiatry, 2=University of Iowa Department of Radiology, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering, 5=Surgical Planning Lab, Harvard) + contributor: Hans J. Johnson, hans-johnson -at- uiowa.edu, http://wwww.psychiatry.uiowa.edu -""" + acknowledgements: Hans Johnson(1,3,4); Kent Williams(1); Gregory Harris(1), Vincent Magnotta(1,2,3); Andriy Fedorov(5), fedorov -at- bwh.harvard.edu (Slicer integration); (1=University of Iowa Department of Psychiatry, 2=University of Iowa Department of Radiology, 3=University of Iowa Department of Biomedical Engineering, 4=University of Iowa Department of Electrical and Computer Engineering, 5=Surgical Planning Lab, Harvard) + """ input_spec = BRAINSROIAutoInputSpec output_spec = BRAINSROIAutoOutputSpec diff --git a/nipype/interfaces/slicer/segmentation/tests/__init__.py b/nipype/interfaces/slicer/segmentation/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/slicer/segmentation/tests/__init__.py +++ b/nipype/interfaces/slicer/segmentation/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/slicer/segmentation/tests/test_auto_BRAINSROIAuto.py b/nipype/interfaces/slicer/segmentation/tests/test_auto_BRAINSROIAuto.py index c88798ec2d..8990caaf1a 100644 --- a/nipype/interfaces/slicer/segmentation/tests/test_auto_BRAINSROIAuto.py +++ b/nipype/interfaces/slicer/segmentation/tests/test_auto_BRAINSROIAuto.py @@ -4,19 +4,43 @@ def test_BRAINSROIAuto_inputs(): input_map = dict( - ROIAutoDilateSize=dict(argstr="--ROIAutoDilateSize %f",), - args=dict(argstr="%s",), - closingSize=dict(argstr="--closingSize %f",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="--inputVolume %s", extensions=None,), - numberOfThreads=dict(argstr="--numberOfThreads %d",), - otsuPercentileThreshold=dict(argstr="--otsuPercentileThreshold %f",), + ROIAutoDilateSize=dict( + argstr="--ROIAutoDilateSize %f", + ), + args=dict( + argstr="%s", + ), + closingSize=dict( + argstr="--closingSize %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="--inputVolume %s", + extensions=None, + ), + numberOfThreads=dict( + argstr="--numberOfThreads %d", + ), + otsuPercentileThreshold=dict( + argstr="--otsuPercentileThreshold %f", + ), outputClippedVolumeROI=dict( - argstr="--outputClippedVolumeROI %s", hash_files=False, + argstr="--outputClippedVolumeROI %s", + hash_files=False, + ), + outputROIMaskVolume=dict( + argstr="--outputROIMaskVolume %s", + hash_files=False, + ), + outputVolumePixelType=dict( + argstr="--outputVolumePixelType %s", + ), + thresholdCorrectionFactor=dict( + argstr="--thresholdCorrectionFactor %f", ), - outputROIMaskVolume=dict(argstr="--outputROIMaskVolume %s", hash_files=False,), - outputVolumePixelType=dict(argstr="--outputVolumePixelType %s",), - thresholdCorrectionFactor=dict(argstr="--thresholdCorrectionFactor %f",), ) inputs = BRAINSROIAuto.input_spec() @@ -27,8 +51,12 @@ def test_BRAINSROIAuto_inputs(): def test_BRAINSROIAuto_outputs(): output_map = dict( - outputClippedVolumeROI=dict(extensions=None,), - outputROIMaskVolume=dict(extensions=None,), + outputClippedVolumeROI=dict( + extensions=None, + ), + outputROIMaskVolume=dict( + extensions=None, + ), ) outputs = BRAINSROIAuto.output_spec() diff --git a/nipype/interfaces/slicer/segmentation/tests/test_auto_EMSegmentCommandLine.py b/nipype/interfaces/slicer/segmentation/tests/test_auto_EMSegmentCommandLine.py index 241f58c6c0..2ed2595d4e 100644 --- a/nipype/interfaces/slicer/segmentation/tests/test_auto_EMSegmentCommandLine.py +++ b/nipype/interfaces/slicer/segmentation/tests/test_auto_EMSegmentCommandLine.py @@ -4,37 +4,81 @@ def test_EMSegmentCommandLine_inputs(): input_map = dict( - args=dict(argstr="%s",), - atlasVolumeFileNames=dict(argstr="--atlasVolumeFileNames %s...",), - disableCompression=dict(argstr="--disableCompression ",), - disableMultithreading=dict(argstr="--disableMultithreading %d",), - dontUpdateIntermediateData=dict(argstr="--dontUpdateIntermediateData %d",), - dontWriteResults=dict(argstr="--dontWriteResults ",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + atlasVolumeFileNames=dict( + argstr="--atlasVolumeFileNames %s...", + ), + disableCompression=dict( + argstr="--disableCompression ", + ), + disableMultithreading=dict( + argstr="--disableMultithreading %d", + ), + dontUpdateIntermediateData=dict( + argstr="--dontUpdateIntermediateData %d", + ), + dontWriteResults=dict( + argstr="--dontWriteResults ", + ), + environ=dict( + nohash=True, + usedefault=True, + ), generateEmptyMRMLSceneAndQuit=dict( - argstr="--generateEmptyMRMLSceneAndQuit %s", hash_files=False, - ), - intermediateResultsDirectory=dict(argstr="--intermediateResultsDirectory %s",), - keepTempFiles=dict(argstr="--keepTempFiles ",), - loadAtlasNonCentered=dict(argstr="--loadAtlasNonCentered ",), - loadTargetCentered=dict(argstr="--loadTargetCentered ",), - mrmlSceneFileName=dict(argstr="--mrmlSceneFileName %s", extensions=None,), - parametersMRMLNodeName=dict(argstr="--parametersMRMLNodeName %s",), - registrationAffineType=dict(argstr="--registrationAffineType %d",), - registrationDeformableType=dict(argstr="--registrationDeformableType %d",), - registrationPackage=dict(argstr="--registrationPackage %s",), + argstr="--generateEmptyMRMLSceneAndQuit %s", + hash_files=False, + ), + intermediateResultsDirectory=dict( + argstr="--intermediateResultsDirectory %s", + ), + keepTempFiles=dict( + argstr="--keepTempFiles ", + ), + loadAtlasNonCentered=dict( + argstr="--loadAtlasNonCentered ", + ), + loadTargetCentered=dict( + argstr="--loadTargetCentered ", + ), + mrmlSceneFileName=dict( + argstr="--mrmlSceneFileName %s", + extensions=None, + ), + parametersMRMLNodeName=dict( + argstr="--parametersMRMLNodeName %s", + ), + registrationAffineType=dict( + argstr="--registrationAffineType %d", + ), + registrationDeformableType=dict( + argstr="--registrationDeformableType %d", + ), + registrationPackage=dict( + argstr="--registrationPackage %s", + ), resultMRMLSceneFileName=dict( - argstr="--resultMRMLSceneFileName %s", hash_files=False, + argstr="--resultMRMLSceneFileName %s", + hash_files=False, ), resultStandardVolumeFileName=dict( - argstr="--resultStandardVolumeFileName %s", extensions=None, + argstr="--resultStandardVolumeFileName %s", + extensions=None, ), resultVolumeFileName=dict( - argstr="--resultVolumeFileName %s", hash_files=False, + argstr="--resultVolumeFileName %s", + hash_files=False, + ), + targetVolumeFileNames=dict( + argstr="--targetVolumeFileNames %s...", + ), + taskPreProcessingSetting=dict( + argstr="--taskPreProcessingSetting %s", + ), + verbose=dict( + argstr="--verbose ", ), - targetVolumeFileNames=dict(argstr="--targetVolumeFileNames %s...",), - taskPreProcessingSetting=dict(argstr="--taskPreProcessingSetting %s",), - verbose=dict(argstr="--verbose ",), ) inputs = EMSegmentCommandLine.input_spec() @@ -45,9 +89,15 @@ def test_EMSegmentCommandLine_inputs(): def test_EMSegmentCommandLine_outputs(): output_map = dict( - generateEmptyMRMLSceneAndQuit=dict(extensions=None,), - resultMRMLSceneFileName=dict(extensions=None,), - resultVolumeFileName=dict(extensions=None,), + generateEmptyMRMLSceneAndQuit=dict( + extensions=None, + ), + resultMRMLSceneFileName=dict( + extensions=None, + ), + resultVolumeFileName=dict( + extensions=None, + ), ) outputs = EMSegmentCommandLine.output_spec() diff --git a/nipype/interfaces/slicer/segmentation/tests/test_auto_RobustStatisticsSegmenter.py b/nipype/interfaces/slicer/segmentation/tests/test_auto_RobustStatisticsSegmenter.py index deed609acb..4bd05c6fc2 100644 --- a/nipype/interfaces/slicer/segmentation/tests/test_auto_RobustStatisticsSegmenter.py +++ b/nipype/interfaces/slicer/segmentation/tests/test_auto_RobustStatisticsSegmenter.py @@ -4,16 +4,43 @@ def test_RobustStatisticsSegmenter_inputs(): input_map = dict( - args=dict(argstr="%s",), - curvatureWeight=dict(argstr="--curvatureWeight %f",), - environ=dict(nohash=True, usedefault=True,), - expectedVolume=dict(argstr="--expectedVolume %f",), - intensityHomogeneity=dict(argstr="--intensityHomogeneity %f",), - labelImageFileName=dict(argstr="%s", extensions=None, position=-2,), - labelValue=dict(argstr="--labelValue %d",), - maxRunningTime=dict(argstr="--maxRunningTime %f",), - originalImageFileName=dict(argstr="%s", extensions=None, position=-3,), - segmentedImageFileName=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + curvatureWeight=dict( + argstr="--curvatureWeight %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + expectedVolume=dict( + argstr="--expectedVolume %f", + ), + intensityHomogeneity=dict( + argstr="--intensityHomogeneity %f", + ), + labelImageFileName=dict( + argstr="%s", + extensions=None, + position=-2, + ), + labelValue=dict( + argstr="--labelValue %d", + ), + maxRunningTime=dict( + argstr="--maxRunningTime %f", + ), + originalImageFileName=dict( + argstr="%s", + extensions=None, + position=-3, + ), + segmentedImageFileName=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = RobustStatisticsSegmenter.input_spec() @@ -23,7 +50,12 @@ def test_RobustStatisticsSegmenter_inputs(): def test_RobustStatisticsSegmenter_outputs(): - output_map = dict(segmentedImageFileName=dict(extensions=None, position=-1,),) + output_map = dict( + segmentedImageFileName=dict( + extensions=None, + position=-1, + ), + ) outputs = RobustStatisticsSegmenter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/segmentation/tests/test_auto_SimpleRegionGrowingSegmentation.py b/nipype/interfaces/slicer/segmentation/tests/test_auto_SimpleRegionGrowingSegmentation.py index 9da82507cc..9a308ec959 100644 --- a/nipype/interfaces/slicer/segmentation/tests/test_auto_SimpleRegionGrowingSegmentation.py +++ b/nipype/interfaces/slicer/segmentation/tests/test_auto_SimpleRegionGrowingSegmentation.py @@ -4,17 +4,44 @@ def test_SimpleRegionGrowingSegmentation_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - iterations=dict(argstr="--iterations %d",), - labelvalue=dict(argstr="--labelvalue %d",), - multiplier=dict(argstr="--multiplier %f",), - neighborhood=dict(argstr="--neighborhood %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), - seed=dict(argstr="--seed %s...",), - smoothingIterations=dict(argstr="--smoothingIterations %d",), - timestep=dict(argstr="--timestep %f",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + iterations=dict( + argstr="--iterations %d", + ), + labelvalue=dict( + argstr="--labelvalue %d", + ), + multiplier=dict( + argstr="--multiplier %f", + ), + neighborhood=dict( + argstr="--neighborhood %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + seed=dict( + argstr="--seed %s...", + ), + smoothingIterations=dict( + argstr="--smoothingIterations %d", + ), + timestep=dict( + argstr="--timestep %f", + ), ) inputs = SimpleRegionGrowingSegmentation.input_spec() @@ -24,7 +51,12 @@ def test_SimpleRegionGrowingSegmentation_inputs(): def test_SimpleRegionGrowingSegmentation_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = SimpleRegionGrowingSegmentation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/surface.py b/nipype/interfaces/slicer/surface.py index 970d067157..3993e5028d 100644 --- a/nipype/interfaces/slicer/surface.py +++ b/nipype/interfaces/slicer/surface.py @@ -1,21 +1,15 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, InputMultiPath, OutputMultiPath, ) -import os class MergeModelsInputSpec(CommandLineInputSpec): @@ -33,19 +27,18 @@ class MergeModelsOutputSpec(TraitedSpec): class MergeModels(SEMLikeCommandLine): """title: Merge Models -category: Surface Models + category: Surface Models -description: Merge the polydata from two input models and output a new model with the added polydata. Uses the vtkAppendPolyData filter. Works on .vtp and .vtk surface files. + description: Merge the polydata from two input models and output a new model with the added polydata. Uses the vtkAppendPolyData filter. Works on .vtp and .vtk surface files. -version: $Revision$ + version: $Revision$ -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/MergeModels + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/MergeModels -contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH), Daniel Haehn (SPL, BWH) + contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH), Daniel Haehn (SPL, BWH) -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. - -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = MergeModelsInputSpec output_spec = MergeModelsOutputSpec @@ -74,19 +67,18 @@ class ModelToLabelMapOutputSpec(TraitedSpec): class ModelToLabelMap(SEMLikeCommandLine): """title: Model To Label Map -category: Surface Models - -description: Intersects an input model with an reference volume and produces an output label map. + category: Surface Models -version: 0.1.0.$Revision: 8643 $(alpha) + description: Intersects an input model with an reference volume and produces an output label map. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/PolyDataToLabelMap + version: 0.1.0.$Revision: 8643 $(alpha) -contributor: Nicole Aucoin (SPL, BWH), Xiaodong Tao (GE) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/PolyDataToLabelMap -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Nicole Aucoin (SPL, BWH), Xiaodong Tao (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = ModelToLabelMapInputSpec output_spec = ModelToLabelMapOutputSpec @@ -141,21 +133,20 @@ class GrayscaleModelMakerOutputSpec(TraitedSpec): class GrayscaleModelMaker(SEMLikeCommandLine): """title: Grayscale Model Maker -category: Surface Models - -description: Create 3D surface models from grayscale data. This module uses Marching Cubes to create an isosurface at a given threshold. The resulting surface consists of triangles that separate a volume into regions below and above the threshold. The resulting surface can be smoothed and decimated. This model works on continuous data while the module Model Maker works on labeled (or discrete) data. + category: Surface Models -version: 3.0 + description: Create 3D surface models from grayscale data. This module uses Marching Cubes to create an isosurface at a given threshold. The resulting surface consists of triangles that separate a volume into regions below and above the threshold. The resulting surface can be smoothed and decimated. This model works on continuous data while the module Model Maker works on labeled (or discrete) data. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GrayscaleModelMaker + version: 3.0 -license: slicer3 + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/GrayscaleModelMaker -contributor: Nicole Aucoin (SPL, BWH), Bill Lorensen (GE) + license: slicer3 -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Nicole Aucoin (SPL, BWH), Bill Lorensen (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = GrayscaleModelMakerInputSpec output_spec = GrayscaleModelMakerOutputSpec @@ -185,19 +176,18 @@ class ProbeVolumeWithModelOutputSpec(TraitedSpec): class ProbeVolumeWithModel(SEMLikeCommandLine): """title: Probe Volume With Model -category: Surface Models + category: Surface Models -description: Paint a model by a volume (using vtkProbeFilter). + description: Paint a model by a volume (using vtkProbeFilter). -version: 0.1.0.$Revision: 1892 $(alpha) + version: 0.1.0.$Revision: 1892 $(alpha) -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ProbeVolumeWithModel + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ProbeVolumeWithModel -contributor: Lauren O'Donnell (SPL, BWH) + contributor: Lauren O'Donnell (SPL, BWH) -acknowledgements: BWH, NCIGT/LMI - -""" + acknowledgements: BWH, NCIGT/LMI + """ input_spec = ProbeVolumeWithModelInputSpec output_spec = ProbeVolumeWithModelOutputSpec @@ -239,19 +229,18 @@ class LabelMapSmoothingOutputSpec(TraitedSpec): class LabelMapSmoothing(SEMLikeCommandLine): """title: Label Map Smoothing -category: Surface Models - -description: This filter smoothes a binary label map. With a label map as input, this filter runs an anti-alising algorithm followed by a Gaussian smoothing algorithm. The output is a smoothed label map. + category: Surface Models -version: 1.0 + description: This filter smoothes a binary label map. With a label map as input, this filter runs an anti-alising algorithm followed by a Gaussian smoothing algorithm. The output is a smoothed label map. -documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/LabelMapSmoothing + version: 1.0 -contributor: Dirk Padfield (GE), Josh Cates (Utah), Ross Whitaker (Utah) + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/LabelMapSmoothing -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. This filter is based on work developed at the University of Utah, and implemented at GE Research. + contributor: Dirk Padfield (GE), Josh Cates (Utah), Ross Whitaker (Utah) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. This filter is based on work developed at the University of Utah, and implemented at GE Research. + """ input_spec = LabelMapSmoothingInputSpec output_spec = LabelMapSmoothingOutputSpec @@ -273,7 +262,7 @@ class ModelMakerInputSpec(CommandLineInputSpec): ) modelSceneFile = traits.Either( traits.Bool, - InputMultiPath(File(),), + InputMultiPath(File()), hash_files=False, desc="Generated models, under a model hierarchy node. Models are imported into Slicer under a model hierarchy node, and their colors are set by the color table associated with the input label map volume. The model hierarchy node must be created before running the model maker, by selecting Create New ModelHierarchy from the Models drop down menu. If you're running from the command line, a model hierarchy node in a new mrml scene will be created for you.", argstr="--modelSceneFile %s...", @@ -354,21 +343,20 @@ class ModelMakerOutputSpec(TraitedSpec): class ModelMaker(SEMLikeCommandLine): """title: Model Maker -category: Surface Models - -description: Create 3D surface models from segmented data.

Models are imported into Slicer under a model hierarchy node in a MRML scene. The model colors are set by the color table associated with the input volume (these colours will only be visible if you load the model scene file).

Create Multiple:

If you specify a list of Labels, it will over ride any start/end label settings.

If you clickGenerate Allit will over ride the list of lables and any start/end label settings.

Model Maker Settings:

You can set the number of smoothing iterations, target reduction in number of polygons (decimal percentage). Use 0 and 1 if you wish no smoothing nor decimation.
You can set the flags to split normals or generate point normals in this pane as well.
You can save a copy of the models after intermediate steps (marching cubes, smoothing, and decimation if not joint smoothing, otherwise just after decimation); these models are not saved in the mrml file, turn off deleting temporary files first in the python window:
slicer.modules.modelmaker.cliModuleLogic().DeleteTemporaryFilesOff()

+ category: Surface Models -version: 4.1 + description: Create 3D surface models from segmented data.

Models are imported into Slicer under a model hierarchy node in a MRML scene. The model colors are set by the color table associated with the input volume (these colours will only be visible if you load the model scene file).

Create Multiple:

If you specify a list of Labels, it will over ride any start/end label settings.

If you clickGenerate Allit will over ride the list of labels and any start/end label settings.

Model Maker Settings:

You can set the number of smoothing iterations, target reduction in number of polygons (decimal percentage). Use 0 and 1 if you wish no smoothing nor decimation.
You can set the flags to split normals or generate point normals in this pane as well.
You can save a copy of the models after intermediate steps (marching cubes, smoothing, and decimation if not joint smoothing, otherwise just after decimation); these models are not saved in the mrml file, turn off deleting temporary files first in the python window:
slicer.modules.modelmaker.cliModuleLogic().DeleteTemporaryFilesOff()

-documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ModelMaker + version: 4.1 -license: slicer4 + documentation-url: http://wiki.slicer.org/slicerWiki/index.php/Documentation/4.1/Modules/ModelMaker -contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH), Bill Lorensen (GE) + license: slicer4 -acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + contributor: Nicole Aucoin (SPL, BWH), Ron Kikinis (SPL, BWH), Bill Lorensen (GE) -""" + acknowledgements: This work is part of the National Alliance for Medical Image Computing (NAMIC), funded by the National Institutes of Health through the NIH Roadmap for Medical Research, Grant U54 EB005149. + """ input_spec = ModelMakerInputSpec output_spec = ModelMakerOutputSpec diff --git a/nipype/interfaces/slicer/tests/__init__.py b/nipype/interfaces/slicer/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/slicer/tests/__init__.py +++ b/nipype/interfaces/slicer/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/slicer/tests/test_auto_DicomToNrrdConverter.py b/nipype/interfaces/slicer/tests/test_auto_DicomToNrrdConverter.py index 6411e0ee54..b02dfd595d 100644 --- a/nipype/interfaces/slicer/tests/test_auto_DicomToNrrdConverter.py +++ b/nipype/interfaces/slicer/tests/test_auto_DicomToNrrdConverter.py @@ -4,15 +4,35 @@ def test_DicomToNrrdConverter_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputDicomDirectory=dict(argstr="--inputDicomDirectory %s",), - outputDirectory=dict(argstr="--outputDirectory %s", hash_files=False,), - outputVolume=dict(argstr="--outputVolume %s",), - smallGradientThreshold=dict(argstr="--smallGradientThreshold %f",), - useBMatrixGradientDirections=dict(argstr="--useBMatrixGradientDirections ",), - useIdentityMeaseurementFrame=dict(argstr="--useIdentityMeaseurementFrame ",), - writeProtocolGradientsFile=dict(argstr="--writeProtocolGradientsFile ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputDicomDirectory=dict( + argstr="--inputDicomDirectory %s", + ), + outputDirectory=dict( + argstr="--outputDirectory %s", + hash_files=False, + ), + outputVolume=dict( + argstr="--outputVolume %s", + ), + smallGradientThreshold=dict( + argstr="--smallGradientThreshold %f", + ), + useBMatrixGradientDirections=dict( + argstr="--useBMatrixGradientDirections ", + ), + useIdentityMeaseurementFrame=dict( + argstr="--useIdentityMeaseurementFrame ", + ), + writeProtocolGradientsFile=dict( + argstr="--writeProtocolGradientsFile ", + ), ) inputs = DicomToNrrdConverter.input_spec() @@ -22,7 +42,9 @@ def test_DicomToNrrdConverter_inputs(): def test_DicomToNrrdConverter_outputs(): - output_map = dict(outputDirectory=dict(),) + output_map = dict( + outputDirectory=dict(), + ) outputs = DicomToNrrdConverter.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_EMSegmentTransformToNewFormat.py b/nipype/interfaces/slicer/tests/test_auto_EMSegmentTransformToNewFormat.py index d65723f4af..338fa49cae 100644 --- a/nipype/interfaces/slicer/tests/test_auto_EMSegmentTransformToNewFormat.py +++ b/nipype/interfaces/slicer/tests/test_auto_EMSegmentTransformToNewFormat.py @@ -4,11 +4,24 @@ def test_EMSegmentTransformToNewFormat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputMRMLFileName=dict(argstr="--inputMRMLFileName %s", extensions=None,), - outputMRMLFileName=dict(argstr="--outputMRMLFileName %s", hash_files=False,), - templateFlag=dict(argstr="--templateFlag ",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputMRMLFileName=dict( + argstr="--inputMRMLFileName %s", + extensions=None, + ), + outputMRMLFileName=dict( + argstr="--outputMRMLFileName %s", + hash_files=False, + ), + templateFlag=dict( + argstr="--templateFlag ", + ), ) inputs = EMSegmentTransformToNewFormat.input_spec() @@ -18,7 +31,11 @@ def test_EMSegmentTransformToNewFormat_inputs(): def test_EMSegmentTransformToNewFormat_outputs(): - output_map = dict(outputMRMLFileName=dict(extensions=None,),) + output_map = dict( + outputMRMLFileName=dict( + extensions=None, + ), + ) outputs = EMSegmentTransformToNewFormat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_GrayscaleModelMaker.py b/nipype/interfaces/slicer/tests/test_auto_GrayscaleModelMaker.py index eaaa00d788..8bab4bd963 100644 --- a/nipype/interfaces/slicer/tests/test_auto_GrayscaleModelMaker.py +++ b/nipype/interfaces/slicer/tests/test_auto_GrayscaleModelMaker.py @@ -4,16 +4,41 @@ def test_GrayscaleModelMaker_inputs(): input_map = dict( - InputVolume=dict(argstr="%s", extensions=None, position=-2,), - OutputGeometry=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - decimate=dict(argstr="--decimate %f",), - environ=dict(nohash=True, usedefault=True,), - name=dict(argstr="--name %s",), - pointnormals=dict(argstr="--pointnormals ",), - smooth=dict(argstr="--smooth %d",), - splitnormals=dict(argstr="--splitnormals ",), - threshold=dict(argstr="--threshold %f",), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + OutputGeometry=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + decimate=dict( + argstr="--decimate %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + name=dict( + argstr="--name %s", + ), + pointnormals=dict( + argstr="--pointnormals ", + ), + smooth=dict( + argstr="--smooth %d", + ), + splitnormals=dict( + argstr="--splitnormals ", + ), + threshold=dict( + argstr="--threshold %f", + ), ) inputs = GrayscaleModelMaker.input_spec() @@ -23,7 +48,12 @@ def test_GrayscaleModelMaker_inputs(): def test_GrayscaleModelMaker_outputs(): - output_map = dict(OutputGeometry=dict(extensions=None, position=-1,),) + output_map = dict( + OutputGeometry=dict( + extensions=None, + position=-1, + ), + ) outputs = GrayscaleModelMaker.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_LabelMapSmoothing.py b/nipype/interfaces/slicer/tests/test_auto_LabelMapSmoothing.py index 5077a0f23c..3dab7b1498 100644 --- a/nipype/interfaces/slicer/tests/test_auto_LabelMapSmoothing.py +++ b/nipype/interfaces/slicer/tests/test_auto_LabelMapSmoothing.py @@ -4,14 +4,35 @@ def test_LabelMapSmoothing_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - gaussianSigma=dict(argstr="--gaussianSigma %f",), - inputVolume=dict(argstr="%s", extensions=None, position=-2,), - labelToSmooth=dict(argstr="--labelToSmooth %d",), - maxRMSError=dict(argstr="--maxRMSError %f",), - numberOfIterations=dict(argstr="--numberOfIterations %d",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + gaussianSigma=dict( + argstr="--gaussianSigma %f", + ), + inputVolume=dict( + argstr="%s", + extensions=None, + position=-2, + ), + labelToSmooth=dict( + argstr="--labelToSmooth %d", + ), + maxRMSError=dict( + argstr="--maxRMSError %f", + ), + numberOfIterations=dict( + argstr="--numberOfIterations %d", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = LabelMapSmoothing.input_spec() @@ -21,7 +42,12 @@ def test_LabelMapSmoothing_inputs(): def test_LabelMapSmoothing_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = LabelMapSmoothing.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_MergeModels.py b/nipype/interfaces/slicer/tests/test_auto_MergeModels.py index 43398aa45f..dc93147248 100644 --- a/nipype/interfaces/slicer/tests/test_auto_MergeModels.py +++ b/nipype/interfaces/slicer/tests/test_auto_MergeModels.py @@ -4,11 +4,28 @@ def test_MergeModels_inputs(): input_map = dict( - Model1=dict(argstr="%s", extensions=None, position=-3,), - Model2=dict(argstr="%s", extensions=None, position=-2,), - ModelOutput=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + Model1=dict( + argstr="%s", + extensions=None, + position=-3, + ), + Model2=dict( + argstr="%s", + extensions=None, + position=-2, + ), + ModelOutput=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = MergeModels.input_spec() @@ -18,7 +35,12 @@ def test_MergeModels_inputs(): def test_MergeModels_outputs(): - output_map = dict(ModelOutput=dict(extensions=None, position=-1,),) + output_map = dict( + ModelOutput=dict( + extensions=None, + position=-1, + ), + ) outputs = MergeModels.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_ModelMaker.py b/nipype/interfaces/slicer/tests/test_auto_ModelMaker.py index 888b7e0477..905b1417e9 100644 --- a/nipype/interfaces/slicer/tests/test_auto_ModelMaker.py +++ b/nipype/interfaces/slicer/tests/test_auto_ModelMaker.py @@ -4,26 +4,72 @@ def test_ModelMaker_inputs(): input_map = dict( - InputVolume=dict(argstr="%s", extensions=None, position=-1,), - args=dict(argstr="%s",), - color=dict(argstr="--color %s", extensions=None,), - debug=dict(argstr="--debug ",), - decimate=dict(argstr="--decimate %f",), - end=dict(argstr="--end %d",), - environ=dict(nohash=True, usedefault=True,), - filtertype=dict(argstr="--filtertype %s",), - generateAll=dict(argstr="--generateAll ",), - jointsmooth=dict(argstr="--jointsmooth ",), - labels=dict(argstr="--labels %s", sep=",",), - modelSceneFile=dict(argstr="--modelSceneFile %s...", hash_files=False,), - name=dict(argstr="--name %s",), - pad=dict(argstr="--pad ",), - pointnormals=dict(argstr="--pointnormals ",), - saveIntermediateModels=dict(argstr="--saveIntermediateModels ",), - skipUnNamed=dict(argstr="--skipUnNamed ",), - smooth=dict(argstr="--smooth %d",), - splitnormals=dict(argstr="--splitnormals ",), - start=dict(argstr="--start %d",), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-1, + ), + args=dict( + argstr="%s", + ), + color=dict( + argstr="--color %s", + extensions=None, + ), + debug=dict( + argstr="--debug ", + ), + decimate=dict( + argstr="--decimate %f", + ), + end=dict( + argstr="--end %d", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + filtertype=dict( + argstr="--filtertype %s", + ), + generateAll=dict( + argstr="--generateAll ", + ), + jointsmooth=dict( + argstr="--jointsmooth ", + ), + labels=dict( + argstr="--labels %s", + sep=",", + ), + modelSceneFile=dict( + argstr="--modelSceneFile %s...", + hash_files=False, + ), + name=dict( + argstr="--name %s", + ), + pad=dict( + argstr="--pad ", + ), + pointnormals=dict( + argstr="--pointnormals ", + ), + saveIntermediateModels=dict( + argstr="--saveIntermediateModels ", + ), + skipUnNamed=dict( + argstr="--skipUnNamed ", + ), + smooth=dict( + argstr="--smooth %d", + ), + splitnormals=dict( + argstr="--splitnormals ", + ), + start=dict( + argstr="--start %d", + ), ) inputs = ModelMaker.input_spec() @@ -33,7 +79,9 @@ def test_ModelMaker_inputs(): def test_ModelMaker_outputs(): - output_map = dict(modelSceneFile=dict(),) + output_map = dict( + modelSceneFile=dict(), + ) outputs = ModelMaker.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_ModelToLabelMap.py b/nipype/interfaces/slicer/tests/test_auto_ModelToLabelMap.py index ad7c305824..8449c15fce 100644 --- a/nipype/interfaces/slicer/tests/test_auto_ModelToLabelMap.py +++ b/nipype/interfaces/slicer/tests/test_auto_ModelToLabelMap.py @@ -4,12 +4,31 @@ def test_ModelToLabelMap_inputs(): input_map = dict( - InputVolume=dict(argstr="%s", extensions=None, position=-3,), - OutputVolume=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - distance=dict(argstr="--distance %f",), - environ=dict(nohash=True, usedefault=True,), - surface=dict(argstr="%s", extensions=None, position=-2,), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-3, + ), + OutputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + distance=dict( + argstr="--distance %f", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + surface=dict( + argstr="%s", + extensions=None, + position=-2, + ), ) inputs = ModelToLabelMap.input_spec() @@ -19,7 +38,12 @@ def test_ModelToLabelMap_inputs(): def test_ModelToLabelMap_outputs(): - output_map = dict(OutputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + OutputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = ModelToLabelMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py b/nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py index 97e7d4ae38..e2b4a1a2f7 100644 --- a/nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py +++ b/nipype/interfaces/slicer/tests/test_auto_OrientScalarVolume.py @@ -4,11 +4,26 @@ def test_OrientScalarVolume_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - inputVolume1=dict(argstr="%s", extensions=None, position=-2,), - orientation=dict(argstr="--orientation %s",), - outputVolume=dict(argstr="%s", hash_files=False, position=-1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + inputVolume1=dict( + argstr="%s", + extensions=None, + position=-2, + ), + orientation=dict( + argstr="--orientation %s", + ), + outputVolume=dict( + argstr="%s", + hash_files=False, + position=-1, + ), ) inputs = OrientScalarVolume.input_spec() @@ -18,7 +33,12 @@ def test_OrientScalarVolume_inputs(): def test_OrientScalarVolume_outputs(): - output_map = dict(outputVolume=dict(extensions=None, position=-1,),) + output_map = dict( + outputVolume=dict( + extensions=None, + position=-1, + ), + ) outputs = OrientScalarVolume.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_ProbeVolumeWithModel.py b/nipype/interfaces/slicer/tests/test_auto_ProbeVolumeWithModel.py index c4b12dc7a0..77498c0b08 100644 --- a/nipype/interfaces/slicer/tests/test_auto_ProbeVolumeWithModel.py +++ b/nipype/interfaces/slicer/tests/test_auto_ProbeVolumeWithModel.py @@ -4,11 +4,28 @@ def test_ProbeVolumeWithModel_inputs(): input_map = dict( - InputModel=dict(argstr="%s", extensions=None, position=-2,), - InputVolume=dict(argstr="%s", extensions=None, position=-3,), - OutputModel=dict(argstr="%s", hash_files=False, position=-1,), - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + InputModel=dict( + argstr="%s", + extensions=None, + position=-2, + ), + InputVolume=dict( + argstr="%s", + extensions=None, + position=-3, + ), + OutputModel=dict( + argstr="%s", + hash_files=False, + position=-1, + ), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = ProbeVolumeWithModel.input_spec() @@ -18,7 +35,12 @@ def test_ProbeVolumeWithModel_inputs(): def test_ProbeVolumeWithModel_outputs(): - output_map = dict(OutputModel=dict(extensions=None, position=-1,),) + output_map = dict( + OutputModel=dict( + extensions=None, + position=-1, + ), + ) outputs = ProbeVolumeWithModel.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/slicer/tests/test_auto_SlicerCommandLine.py b/nipype/interfaces/slicer/tests/test_auto_SlicerCommandLine.py index dda2e3d8f8..7a16ed38bb 100644 --- a/nipype/interfaces/slicer/tests/test_auto_SlicerCommandLine.py +++ b/nipype/interfaces/slicer/tests/test_auto_SlicerCommandLine.py @@ -4,7 +4,13 @@ def test_SlicerCommandLine_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = SlicerCommandLine.input_spec() diff --git a/nipype/interfaces/slicer/utilities.py b/nipype/interfaces/slicer/utilities.py index ad998e58fe..eb079766c9 100644 --- a/nipype/interfaces/slicer/utilities.py +++ b/nipype/interfaces/slicer/utilities.py @@ -1,21 +1,13 @@ -# -*- coding: utf-8 -*- -# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import ( - CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, - Directory, traits, - isdefined, - InputMultiPath, - OutputMultiPath, ) -import os class EMSegmentTransformToNewFormatInputSpec(CommandLineInputSpec): @@ -46,18 +38,17 @@ class EMSegmentTransformToNewFormatOutputSpec(TraitedSpec): class EMSegmentTransformToNewFormat(SEMLikeCommandLine): """title: - Transform MRML Files to New EMSegmenter Standard + Transform MRML Files to New EMSegmenter Standard -category: - Utilities + category: + Utilities -description: - Transform MRML Files to New EMSegmenter Standard + description: + Transform MRML Files to New EMSegmenter Standard - -""" + """ input_spec = EMSegmentTransformToNewFormatInputSpec output_spec = EMSegmentTransformToNewFormatOutputSpec diff --git a/nipype/interfaces/spm/__init__.py b/nipype/interfaces/spm/__init__.py index fcb6926eb6..160bbae150 100644 --- a/nipype/interfaces/spm/__init__.py +++ b/nipype/interfaces/spm/__init__.py @@ -1,9 +1,9 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """SPM is a software package for the analysis of brain imaging data sequences.""" from .base import Info, SPMCommand, logger, no_spm, scans_for_fname, scans_for_fnames from .preprocess import ( + ApplyVDM, FieldMap, SliceTiming, Realign, @@ -14,6 +14,7 @@ Segment, Smooth, NewSegment, + MultiChannelNewSegment, DARTEL, DARTELNorm2MNI, CreateWarped, diff --git a/nipype/interfaces/spm/base.py b/nipype/interfaces/spm/base.py index a70e0ab166..4998f0af34 100644 --- a/nipype/interfaces/spm/base.py +++ b/nipype/interfaces/spm/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The spm module provides basic functions for interfacing with SPM tools. @@ -24,10 +23,11 @@ # Local imports from ... import logging -from ...utils import spm_docs as sd, NUMPY_MMAP +from ...utils import spm_docs as sd from ..base import ( BaseInterface, traits, + Tuple, isdefined, InputMultiPath, BaseInterfaceInputSpec, @@ -38,7 +38,7 @@ ) from ..base.traits_extension import NoDefaultSpecified from ..matlab import MatlabCommand -from ...external.due import due, Doi, BibTeX +from ...external.due import BibTeX __docformat__ = "restructuredtext" logger = logging.getLogger("nipype.interface") @@ -50,12 +50,9 @@ def func_is_3d(in_file): if isinstance(in_file, list): return func_is_3d(in_file[0]) else: - img = load(in_file, mmap=NUMPY_MMAP) + img = load(in_file) shape = img.shape - if len(shape) == 3 or (len(shape) == 4 and shape[3] == 1): - return True - else: - return False + return len(shape) == 3 or (len(shape) == 4 and shape[3] == 1) def get_first_3dfile(in_files): @@ -78,7 +75,7 @@ def scans_for_fname(fname): for sno, f in enumerate(fname): scans[sno] = "%s,1" % f return scans - img = load(fname, mmap=NUMPY_MMAP) + img = load(fname) if len(img.shape) == 3: return np.array(("%s,1" % fname,), dtype=object) else: @@ -201,7 +198,6 @@ def getinfo(klass, matlab_cmd=None, paths=None, use_mcr=None): and klass._command == matlab_cmd and klass._paths == paths ): - return {"name": klass._name, "path": klass._path, "release": klass._version} logger.debug("matlab command or path has changed. recomputing version.") mlab = MatlabCommand(matlab_cmd=matlab_cmd, resource_monitor=False) @@ -225,7 +221,7 @@ def getinfo(klass, matlab_cmd=None, paths=None, use_mcr=None): """ try: out = mlab.run() - except (IOError, RuntimeError) as e: + except (OSError, RuntimeError) as e: # if no Matlab at all -- exception could be raised # No Matlab -- no spm logger.debug("%s", e) @@ -251,14 +247,11 @@ def getinfo(klass, matlab_cmd=None, paths=None, use_mcr=None): def no_spm(): - """ Checks if SPM is NOT installed + """Checks if SPM is NOT installed used with pytest.mark.skipif decorator to skip tests that will fail if spm is not installed""" - if "NIPYPE_NO_MATLAB" in os.environ or Info.version() is None: - return True - else: - return False + return "NIPYPE_NO_MATLAB" in os.environ or Info.version() is None class SPMCommandInputSpec(BaseInterfaceInputSpec): @@ -270,7 +263,7 @@ class SPMCommandInputSpec(BaseInterfaceInputSpec): True, min_ver="8", usedefault=True, - desc=("Generate SPM8 and higher " "compatible jobs"), + desc=("Generate SPM8 and higher compatible jobs"), ) @@ -290,7 +283,7 @@ class SPMCommand(BaseInterface): _paths = None _use_mcr = None - references_ = [ + _references = [ { "entry": BibTeX( "@book{FrackowiakFristonFrithDolanMazziotta1997," @@ -307,7 +300,7 @@ class SPMCommand(BaseInterface): ] def __init__(self, **inputs): - super(SPMCommand, self).__init__(**inputs) + super().__init__(**inputs) self.inputs.on_trait_change( self._matlab_cmd_update, ["matlab_cmd", "mfile", "paths", "use_mcr"] ) @@ -361,7 +354,9 @@ def version(self): use_mcr=self.inputs.use_mcr, ) if info_dict: - return "%s.%s" % (info_dict["name"].split("SPM")[-1], info_dict["release"]) + return "{}.{}".format( + info_dict["name"].split("SPM")[-1], info_dict["release"] + ) @property def jobtype(self): @@ -403,7 +398,7 @@ def _format_arg(self, opt, spec, val): """Convert input to appropriate format for SPM.""" if spec.is_trait_type(traits.Bool): return int(val) - elif spec.is_trait_type(traits.Tuple): + elif spec.is_trait_type(traits.BaseTuple): return list(val) else: return val @@ -485,7 +480,7 @@ def _generate_job(self, prefix="", contents=None): return jobstring if isinstance(contents, dict): for key, value in list(contents.items()): - newprefix = "%s.%s" % (prefix, key) + newprefix = f"{prefix}.{key}" jobstring += self._generate_job(newprefix, value) return jobstring if isinstance(contents, np.ndarray): @@ -504,9 +499,9 @@ def _generate_job(self, prefix="", contents=None): "{}" if not isinstance(el, (str, bytes)) else "'{}'" ] val_format = ", ".join(items_format).format - jobstring += "[{}];...\n".format(val_format(*val)) + jobstring += f"[{val_format(*val)}];...\n" elif isinstance(val, (str, bytes)): - jobstring += "'{}';...\n".format(val) + jobstring += f"'{val}';...\n" else: jobstring += "%s;...\n" % str(val) jobstring += "};\n" @@ -520,9 +515,9 @@ def _generate_job(self, prefix="", contents=None): jobstring += self._generate_job(newprefix, val[field]) return jobstring if isinstance(contents, (str, bytes)): - jobstring += "%s = '%s';\n" % (prefix, contents) + jobstring += f"{prefix} = '{contents}';\n" return jobstring - jobstring += "%s = %s;\n" % (prefix, str(contents)) + jobstring += f"{prefix} = {contents};\n" return jobstring def _make_matlab_command(self, contents, postscript=None): @@ -562,7 +557,7 @@ def _make_matlab_command(self, contents, postscript=None): if self.mlab.inputs.mfile: if isdefined(self.inputs.use_v8struct) and self.inputs.use_v8struct: mscript += self._generate_job( - "jobs{1}.spm.%s.%s" % (self.jobtype, self.jobname), contents[0] + f"jobs{{1}}.spm.{self.jobtype}.{self.jobname}", contents[0] ) else: if self.jobname in [ @@ -577,13 +572,13 @@ def _make_matlab_command(self, contents, postscript=None): ]: # parentheses mscript += self._generate_job( - "jobs{1}.%s{1}.%s(1)" % (self.jobtype, self.jobname), + f"jobs{{1}}.{self.jobtype}{{1}}.{self.jobname}(1)", contents[0], ) else: # curly brackets mscript += self._generate_job( - "jobs{1}.%s{1}.%s{1}" % (self.jobtype, self.jobname), + f"jobs{{1}}.{self.jobtype}{{1}}.{self.jobname}{{1}}", contents[0], ) else: @@ -621,11 +616,11 @@ def __init__( self, value=NoDefaultSpecified, exists=False, resolve=False, **metadata ): """Create an ImageFileSPM trait.""" - super(ImageFileSPM, self).__init__( + super().__init__( value=value, exists=exists, types=["nifti1", "nifti2"], allow_compressed=False, resolve=resolve, - **metadata + **metadata, ) diff --git a/nipype/interfaces/spm/model.py b/nipype/interfaces/spm/model.py index 2d09f23e90..de5447b4b7 100644 --- a/nipype/interfaces/spm/model.py +++ b/nipype/interfaces/spm/model.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The spm module provides basic functions for interfacing with matlab @@ -13,10 +12,11 @@ # Local imports from ... import logging -from ...utils.filemanip import ensure_list, simplify_list, split_filename +from ...utils.filemanip import ensure_list, simplify_list, split_filename, load_spm_mat from ..base import ( Bunch, traits, + Tuple, TraitedSpec, File, Directory, @@ -81,7 +81,7 @@ class Level1DesignInputSpec(SPMCommandInputSpec): mandatory=True, ) volterra_expansion_order = traits.Enum( - 1, 2, field="volt", desc=("Model interactions - yes:1, no:2") + 1, 2, field="volt", desc=("Model interactions - no:1, yes:2") ) global_intensity_normalization = traits.Enum( "none", @@ -145,8 +145,7 @@ class Level1Design(SPMCommand): _jobname = "fmri_spec" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["spm_mat_dir", "mask_image"]: return np.array([str(val)], dtype=object) if opt in ["session_info"]: # , 'factor_info']: @@ -154,16 +153,13 @@ def _format_arg(self, opt, spec, val): return [val] else: return val - return super(Level1Design, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self): - """validate spm realign options if set to None ignore - """ - einputs = super(Level1Design, self)._parse_inputs( - skip=("mask_threshold", "flags") - ) + """validate spm realign options if set to None ignore""" + einputs = super()._parse_inputs(skip=("mask_threshold", "flags")) if isdefined(self.inputs.flags): - einputs[0].update({flag: val for (flag, val) in self.inputs.flags.items()}) + einputs[0].update(self.inputs.flags) for sessinfo in einputs[0]["sess"]: sessinfo["scans"] = scans_for_fnames( ensure_list(sessinfo["scans"]), keep4d=False @@ -193,9 +189,7 @@ def _make_matlab_command(self, content): postscript += "save SPM SPM;\n" else: postscript = None - return super(Level1Design, self)._make_matlab_command( - content, postscript=postscript - ) + return super()._make_matlab_command(content, postscript=postscript) def _list_outputs(self): outputs = self._outputs().get() @@ -252,6 +246,34 @@ class EstimateModelOutputSpec(TraitedSpec): ImageFileSPM(exists=True), desc="Images of the standard deviation of parameter posteriors", ) + con_images = OutputMultiPath( + File(exists=True), + desc=( + "contrast images from a t-contrast " + "(created if factor_info used in Level1Design)" + ), + ) + spmT_images = OutputMultiPath( + File(exists=True), + desc=( + "stat images from a t-contrast" + "(created if factor_info used in Level1Design)" + ), + ) + ess_images = OutputMultiPath( + File(exists=True), + desc=( + "contrast images from an F-contrast" + "(created if factor_info used in Level1Design)" + ), + ) + spmF_images = OutputMultiPath( + File(exists=True), + desc=( + "stat images from an F-contrast" + "(created if factor_info used in Level1Design)" + ), + ) class EstimateModel(SPMCommand): @@ -273,58 +295,73 @@ class EstimateModel(SPMCommand): _jobname = "fmri_est" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "spm_mat_file": return np.array([str(val)], dtype=object) if opt == "estimation_method": if isinstance(val, (str, bytes)): - return {"{}".format(val): 1} + return {f"{val}": 1} else: return val - return super(EstimateModel, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self): - """validate spm realign options if set to None ignore - """ - einputs = super(EstimateModel, self)._parse_inputs(skip=("flags")) + """validate spm realign options if set to None ignore""" + einputs = super()._parse_inputs(skip=("flags")) if isdefined(self.inputs.flags): - einputs[0].update({flag: val for (flag, val) in self.inputs.flags.items()}) + einputs[0].update(self.inputs.flags) return einputs def _list_outputs(self): - import scipy.io as sio - outputs = self._outputs().get() pth = os.path.dirname(self.inputs.spm_mat_file) outtype = "nii" if "12" in self.version.split(".")[0] else "img" - spm = sio.loadmat(self.inputs.spm_mat_file, struct_as_record=False) + spm = load_spm_mat(self.inputs.spm_mat_file, struct_as_record=False) betas = [vbeta.fname[0] for vbeta in spm["SPM"][0, 0].Vbeta[0]] if ( - "Bayesian" in self.inputs.estimation_method.keys() - or "Bayesian2" in self.inputs.estimation_method.keys() + "Bayesian" in self.inputs.estimation_method + or "Bayesian2" in self.inputs.estimation_method ): - outputs["labels"] = os.path.join(pth, "labels.{}".format(outtype)) + outputs["labels"] = os.path.join(pth, f"labels.{outtype}") outputs["SDerror"] = glob(os.path.join(pth, "Sess*_SDerror*")) outputs["ARcoef"] = glob(os.path.join(pth, "Sess*_AR_*")) if betas: - outputs["Cbetas"] = [ - os.path.join(pth, "C{}".format(beta)) for beta in betas - ] - outputs["SDbetas"] = [ - os.path.join(pth, "SD{}".format(beta)) for beta in betas - ] + outputs["Cbetas"] = [os.path.join(pth, f"C{beta}") for beta in betas] + outputs["SDbetas"] = [os.path.join(pth, f"SD{beta}") for beta in betas] - if "Classical" in self.inputs.estimation_method.keys(): - outputs["residual_image"] = os.path.join(pth, "ResMS.{}".format(outtype)) - outputs["RPVimage"] = os.path.join(pth, "RPV.{}".format(outtype)) + if "Classical" in self.inputs.estimation_method: + outputs["residual_image"] = os.path.join(pth, f"ResMS.{outtype}") + outputs["RPVimage"] = os.path.join(pth, f"RPV.{outtype}") if self.inputs.write_residuals: outputs["residual_images"] = glob(os.path.join(pth, "Res_*")) if betas: outputs["beta_images"] = [os.path.join(pth, beta) for beta in betas] + # When 'factor_info' is used in Level1Design + # spm automatically creates contrast + try: + contrast = [c.Vcon[0][0].fname[0] for c in spm["SPM"][0, 0].xCon[0]] + contrast_spm = [c.Vspm[0][0].fname[0] for c in spm["SPM"][0, 0].xCon[0]] + except Exception: + contrast = [] + contrast_spm = [] + + if contrast: + outputs["con_images"] = [ + os.path.join(pth, cont) for cont in contrast if 'con' in cont + ] + outputs["ess_images"] = [ + os.path.join(pth, cont) for cont in contrast if 'ess' in cont + ] + if contrast_spm: + outputs["spmT_images"] = [ + os.path.join(pth, cont) for cont in contrast_spm if 'spmT' in cont + ] + outputs["spmF_images"] = [ + os.path.join(pth, cont) for cont in contrast_spm if 'spmF' in cont + ] - outputs["mask_image"] = os.path.join(pth, "mask.{}".format(outtype)) + outputs["mask_image"] = os.path.join(pth, f"mask.{outtype}") outputs["spm_mat_file"] = os.path.join(pth, "SPM.mat") return outputs @@ -339,31 +376,31 @@ class EstimateContrastInputSpec(SPMCommandInputSpec): ) contrasts = traits.List( traits.Either( - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("F"), traits.List( traits.Either( - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), traits.List(traits.Float), ), - traits.Tuple( + Tuple( traits.Str, traits.Enum("T"), traits.List(traits.Str), @@ -464,6 +501,10 @@ def _make_matlab_command(self, _): load(jobs{1}.stats{1}.con.spmmat{:}); SPM.swd = '%s'; save(jobs{1}.stats{1}.con.spmmat{:},'SPM'); +[msg,id] = lastwarn(''); +if strcmp(id,'MATLAB:save:sizeTooBigForMATFile') + save(jobs{1}.stats{1}.con.spmmat{:},'SPM','-v7.3'); +end names = SPM.xX.name;""" % (self.inputs.spm_mat_file, os.getcwd()) ] @@ -514,12 +555,12 @@ def _make_matlab_command(self, _): script += ["sidx = find(condsess(idx)==%d);" % (sno + 1)] script += [ "consess{%d}.tcon.convec(idx(sidx)) = %f;" - % (i + 1, sw * contrast.weights[c0],) + % (i + 1, sw * contrast.weights[c0]) ] else: script += [ "consess{%d}.tcon.convec(idx) = %f;" - % (i + 1, contrast.weights[c0],) + % (i + 1, contrast.weights[c0]) ] for i, contrast in enumerate(contrasts): if contrast.stat == "F": @@ -542,11 +583,9 @@ def _make_matlab_command(self, _): return "\n".join(script) def _list_outputs(self): - import scipy.io as sio - outputs = self._outputs().get() pth, _ = os.path.split(self.inputs.spm_mat_file) - spm = sio.loadmat(self.inputs.spm_mat_file, struct_as_record=False) + spm = load_spm_mat(self.inputs.spm_mat_file, struct_as_record=False) con_images = [] spmT_images = [] for con in spm["SPM"][0, 0].xCon[0]: @@ -590,6 +629,16 @@ class ThresholdInputSpec(SPMCommandInputSpec): "set to p-value)" ), ) + use_vox_fdr_correction = traits.Bool( + False, + usedefault=True, + desc=( + "whether to use voxel-based FDR " + "correction for initial threshold " + "(height_threshold_type has to be " + "set to q-value)" + ), + ) use_topo_fdr = traits.Bool( True, usedefault=True, @@ -620,7 +669,7 @@ class ThresholdInputSpec(SPMCommandInputSpec): desc=( "In case no clusters survive the " "topological inference step this " - "will pick a culster with the highes " + "will pick a culster with the highest " "sum of t-values. Use with care." ), ) @@ -665,8 +714,16 @@ def _gen_pre_topo_map_filename(self): def _make_matlab_command(self, _): script = "con_index = %d;\n" % self.inputs.contrast_index script += "cluster_forming_thr = %f;\n" % self.inputs.height_threshold - if self.inputs.use_fwe_correction: + + if self.inputs.use_fwe_correction and self.inputs.use_vox_fdr_correction: + raise ValueError( + "'use_fwe_correction' and 'use_vox_fdr_correction' can't both be True" + ) + + if self.inputs.use_fwe_correction and not self.inputs.use_vox_fdr_correction: script += "thresDesc = 'FWE';\n" + elif self.inputs.use_vox_fdr_correction and not self.inputs.use_fwe_correction: + script += "thresDesc = 'FDR';\n" else: script += "thresDesc = 'none';\n" @@ -691,6 +748,8 @@ def _make_matlab_command(self, _): FWHM = SPM.xVol.FWHM; df = [SPM.xCon(con_index).eidf SPM.xX.erdf]; STAT = SPM.xCon(con_index).STAT; +VspmSv = cat(1,SPM.xCon(con_index).Vspm); + R = SPM.xVol.R; S = SPM.xVol.S; n = 1; @@ -699,6 +758,9 @@ def _make_matlab_command(self, _): case 'FWE' cluster_forming_thr = spm_uc(cluster_forming_thr,df,STAT,R,n,S); + case 'FDR' + cluster_forming_thr = spm_uc_FDR(cluster_forming_thr,df,STAT,n,VspmSv,0); + case 'none' if strcmp(height_threshold_type, 'p-value') cluster_forming_thr = spm_u(cluster_forming_thr^(1/n),df,STAT); @@ -787,30 +849,22 @@ def _make_matlab_command(self, _): def aggregate_outputs(self, runtime=None): outputs = self._outputs() - setattr(outputs, "thresholded_map", self._gen_thresholded_map_filename()) - setattr(outputs, "pre_topo_fdr_map", self._gen_pre_topo_map_filename()) + outputs.thresholded_map = self._gen_thresholded_map_filename() + outputs.pre_topo_fdr_map = self._gen_pre_topo_map_filename() for line in runtime.stdout.split("\n"): if line.startswith("activation_forced = "): - setattr( - outputs, - "activation_forced", - line[len("activation_forced = ") :].strip() == "1", + outputs.activation_forced = ( + line[len("activation_forced = ") :].strip() == "1" ) elif line.startswith("n_clusters = "): - setattr( - outputs, "n_clusters", int(line[len("n_clusters = ") :].strip()) - ) + outputs.n_clusters = int(line[len("n_clusters = ") :].strip()) elif line.startswith("pre_topo_n_clusters = "): - setattr( - outputs, - "pre_topo_n_clusters", - int(line[len("pre_topo_n_clusters = ") :].strip()), + outputs.pre_topo_n_clusters = int( + line[len("pre_topo_n_clusters = ") :].strip() ) elif line.startswith("cluster_forming_thr = "): - setattr( - outputs, - "cluster_forming_thr", - float(line[len("cluster_forming_thr = ") :].strip()), + outputs.cluster_forming_thr = float( + line[len("cluster_forming_thr = ") :].strip() ) return outputs @@ -830,8 +884,7 @@ class ThresholdStatisticsInputSpec(SPMCommandInputSpec): mandatory=True, desc="which contrast in the SPM.mat to use" ) height_threshold = traits.Float( - desc=("stat value for initial thresholding (defining clusters)"), - mandatory=True, + desc=("stat value for initial thresholding (defining clusters)"), mandatory=True ) extent_threshold = traits.Int( 0, usedefault=True, desc="Minimum cluster size in voxels" @@ -1020,8 +1073,7 @@ class FactorialDesign(SPMCommand): _jobname = "factorial_design" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["spm_mat_dir", "explicit_mask_file"]: return np.array([str(val)], dtype=object) if opt in ["covariates"]: @@ -1038,12 +1090,11 @@ def _format_arg(self, opt, spec, val): outdict[mapping[key]] = keyval outlist.append(outdict) return outlist - return super(FactorialDesign, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self): - """validate spm realign options if set to None ignore - """ - einputs = super(FactorialDesign, self)._parse_inputs() + """validate spm realign options if set to None ignore""" + einputs = super()._parse_inputs() if not isdefined(self.inputs.spm_mat_dir): einputs[0]["dir"] = np.array([str(os.getcwd())], dtype=object) return einputs @@ -1079,11 +1130,10 @@ class OneSampleTTestDesign(FactorialDesign): input_spec = OneSampleTTestDesignInputSpec def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["in_files"]: return np.array(val, dtype=object) - return super(OneSampleTTestDesign, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) class TwoSampleTTestDesignInputSpec(FactorialDesignInputSpec): @@ -1127,11 +1177,10 @@ class TwoSampleTTestDesign(FactorialDesign): input_spec = TwoSampleTTestDesignInputSpec def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["group1_files", "group2_files"]: return np.array(val, dtype=object) - return super(TwoSampleTTestDesign, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) class PairedTTestDesignInputSpec(FactorialDesignInputSpec): @@ -1164,11 +1213,10 @@ class PairedTTestDesign(FactorialDesign): input_spec = PairedTTestDesignInputSpec def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["paired_files"]: return [dict(scans=np.array(files, dtype=object)) for files in val] - return super(PairedTTestDesign, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) class MultipleRegressionDesignInputSpec(FactorialDesignInputSpec): @@ -1206,8 +1254,7 @@ class MultipleRegressionDesign(FactorialDesign): input_spec = MultipleRegressionDesignInputSpec def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["in_files"]: return np.array(val, dtype=object) if opt in ["user_covariates"]: @@ -1219,4 +1266,4 @@ def _format_arg(self, opt, spec, val): outdict[mapping[key]] = keyval outlist.append(outdict) return outlist - return super(MultipleRegressionDesign, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) diff --git a/nipype/interfaces/spm/preprocess.py b/nipype/interfaces/spm/preprocess.py index c9bba24c1a..8d931a72ba 100644 --- a/nipype/interfaces/spm/preprocess.py +++ b/nipype/interfaces/spm/preprocess.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""SPM wrappers for preprocessing data -""" +"""SPM wrappers for preprocessing data""" import os from copy import deepcopy @@ -21,6 +19,7 @@ TraitedSpec, isdefined, traits, + Tuple, InputMultiPath, InputMultiObject, File, @@ -41,10 +40,11 @@ class FieldMapInputSpec(SPMCommandInputSpec): jobtype = traits.Enum( "calculatevdm", - "applyvdm", usedefault=True, - desc="one of: calculatevdm, applyvdm", + deprecated="1.9.0", # Two minor releases in the future + desc="Must be 'calculatevdm'; to apply VDM, use the ApplyVDM interface.", ) + phase_file = File( mandatory=True, exists=True, @@ -59,7 +59,7 @@ class FieldMapInputSpec(SPMCommandInputSpec): field="subj.data.presubphasemag.magnitude", desc="presubstracted magnitude file", ) - echo_times = traits.Tuple( + echo_times = Tuple( traits.Float, traits.Float, mandatory=True, @@ -230,25 +230,151 @@ class FieldMap(SPMCommand): _jobname = "fieldmap" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" + if opt in ["phase_file", "magnitude_file", "anat_file", "epi_file"]: return scans_for_fname(ensure_list(val)) - return super(FieldMap, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self): - """validate spm fieldmap options if set to None ignore - """ - einputs = super(FieldMap, self)._parse_inputs() - return [{self.inputs.jobtype: einputs[0]}] + """validate spm fieldmap options if set to None ignore""" + + einputs = super()._parse_inputs() + return [{"calculatevdm": einputs[0]}] def _list_outputs(self): outputs = self._outputs().get() jobtype = self.inputs.jobtype - if jobtype == "calculatevdm": - outputs["vdm"] = fname_presuffix(self.inputs.phase_file, prefix="vdm5_sc") + outputs["vdm"] = fname_presuffix(self.inputs.phase_file, prefix="vdm5_sc") + + return outputs + + +class ApplyVDMInputSpec(SPMCommandInputSpec): + in_files = InputMultiObject( + ImageFileSPM(exists=True), + field="data.scans", + mandatory=True, + copyfile=True, + desc="list of filenames to apply the vdm to", + ) + vdmfile = File( + field="data.vdmfile", + desc="Voxel displacement map to use", + mandatory=True, + copyfile=True, + ) + distortion_direction = traits.Int( + 2, + field="roptions.pedir", + desc="phase encode direction input data have been acquired with", + usedefault=True, + ) + write_which = traits.List( + traits.Int, + [2, 1], + field="roptions.which", + minlen=2, + maxlen=2, + usedefault=True, + desc="If the first value is non-zero, reslice all images. If the second value is non-zero, reslice a mean image.", + ) + interpolation = traits.Range( + value=4, + low=0, + high=7, + field="roptions.rinterp", + desc="degree of b-spline used for interpolation", + ) + write_wrap = traits.List( + traits.Int(), + minlen=3, + maxlen=3, + field="roptions.wrap", + desc=("Check if interpolation should wrap in [x,y,z]"), + ) + write_mask = traits.Bool( + field="roptions.mask", desc="True/False mask time series images" + ) + out_prefix = traits.String( + "u", + field="roptions.prefix", + usedefault=True, + desc="fieldmap corrected output prefix", + ) + + +class ApplyVDMOutputSpec(TraitedSpec): + out_files = OutputMultiPath( + traits.Either(traits.List(File(exists=True)), File(exists=True)), + desc=("These will be the fieldmap corrected files."), + ) + mean_image = File(exists=True, desc="Mean image") + + +class ApplyVDM(SPMCommand): + """Use the fieldmap toolbox from spm to apply the voxel displacement map (VDM) to some epi files. + + http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=173 + + .. important:: + + This interface does not deal with real/imag magnitude images nor + with the two phase files case. + + """ + + input_spec = ApplyVDMInputSpec + output_spec = ApplyVDMOutputSpec + _jobtype = "tools" + _jobname = "fieldmap" + + def _format_arg(self, opt, spec, val): + """Convert input to appropriate format for spm""" + + if opt == 'in_files': + return scans_for_fnames( + ensure_list(val), keep4d=False, separate_sessions=False + ) + if opt == 'vdmfile': + return scans_for_fname(ensure_list(val)) + return super()._format_arg(opt, spec, val) + + def _parse_inputs(self): + """validate spm fieldmap options if set to None ignore""" + + einputs = super()._parse_inputs() + + return [{"applyvdm": einputs[0]}] + + def _list_outputs(self): + outputs = self._outputs().get() + resliced_all = self.inputs.write_which[0] > 0 + resliced_mean = self.inputs.write_which[1] > 0 + if resliced_mean: + if isinstance(self.inputs.in_files[0], list): + first_image = self.inputs.in_files[0][0] + else: + first_image = self.inputs.in_files[0] + outputs["mean_image"] = fname_presuffix(first_image, prefix="meanu") + + if resliced_all: + outputs["out_files"] = [] + for idx, imgf in enumerate(ensure_list(self.inputs.in_files)): + appliedvdm_run = [] + if isinstance(imgf, list): + for i, inner_imgf in enumerate(ensure_list(imgf)): + newfile = fname_presuffix( + inner_imgf, prefix=self.inputs.out_prefix + ) + appliedvdm_run.append(newfile) + else: + appliedvdm_run = fname_presuffix( + imgf, prefix=self.inputs.out_prefix + ) + outputs["out_files"].append(appliedvdm_run) return outputs @@ -276,12 +402,14 @@ class SliceTimingInputSpec(SPMCommandInputSpec): mandatory=True, ) slice_order = traits.List( - traits.Float(), + traits.Either(traits.Int(), traits.Float()), field="so", desc=("1-based order or onset (in ms) in which slices are acquired"), mandatory=True, ) - ref_slice = traits.Int( + ref_slice = traits.Either( + traits.Int(), + traits.Float(), field="refslice", desc="1-based Number of the reference slice or " "reference time point if slice_order is in " @@ -327,13 +455,12 @@ class SliceTiming(SPMCommand): _jobname = "st" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "in_files": return scans_for_fnames( ensure_list(val), keep4d=False, separate_sessions=True ) - return super(SliceTiming, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -397,7 +524,8 @@ class RealignInputSpec(SPMCommandInputSpec): field="eoptions.wrap", desc="Check if interpolation should wrap in [x,y,z]", ) - write_which = traits.ListInt( + write_which = traits.List( + traits.Int, [2, 1], field="roptions.which", minlen=2, @@ -476,8 +604,7 @@ class Realign(SPMCommand): _jobname = "realign" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "in_files": if self.inputs.jobtype == "write": separate_sessions = False @@ -486,12 +613,11 @@ def _format_arg(self, opt, spec, val): return scans_for_fnames( val, keep4d=False, separate_sessions=separate_sessions ) - return super(Realign, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self): - """validate spm realign options if set to None ignore - """ - einputs = super(Realign, self)._parse_inputs() + """validate spm realign options if set to None ignore""" + einputs = super()._parse_inputs() return [{"%s" % (self.inputs.jobtype): einputs[0]}] def _list_outputs(self): @@ -546,7 +672,6 @@ def _list_outputs(self): class RealignUnwarpInputSpec(SPMCommandInputSpec): - in_files = InputMultiObject( traits.Either( ImageFileSPM(exists=True), traits.List(ImageFileSPM(exists=True)) @@ -607,7 +732,8 @@ class RealignUnwarpInputSpec(SPMCommandInputSpec): "maximization and smoothness maximization of the estimated field." ), ) - est_reg_factor = traits.ListInt( + est_reg_factor = traits.List( + traits.Int, [100000], field="uweoptions.lambda", minlen=1, @@ -645,7 +771,8 @@ class RealignUnwarpInputSpec(SPMCommandInputSpec): field="uweoptions.rem", desc="Re-estimate movement parameters at each unwarping iteration.", ) - est_num_of_iterations = traits.ListInt( + est_num_of_iterations = traits.List( + traits.Int, [5], field="uweoptions.noi", minlen=1, @@ -659,7 +786,8 @@ class RealignUnwarpInputSpec(SPMCommandInputSpec): usedefault=True, desc="Point in position space to perform Taylor-expansion around.", ) - reslice_which = traits.ListInt( + reslice_which = traits.List( + traits.Int, [2, 1], field="uwroptions.uwwhich", minlen=2, @@ -743,17 +871,15 @@ class RealignUnwarp(SPMCommand): _jobname = "realignunwarp" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "in_files": return scans_for_fnames( ensure_list(val), keep4d=False, separate_sessions=True ) - return super(RealignUnwarp, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self, skip=()): - - spmdict = super(RealignUnwarp, self)._parse_inputs(skip=())[0] + spmdict = super()._parse_inputs(skip=())[0] if isdefined(self.inputs.phase_map): pmscan = spmdict["data"]["pmscan"] @@ -919,8 +1045,7 @@ class Coregister(SPMCommand): _jobname = "coreg" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "target" or (opt == "source" and self.inputs.jobtype != "write"): return scans_for_fnames(ensure_list(val), keep4d=True) if opt == "apply_to_files": @@ -930,17 +1055,14 @@ def _format_arg(self, opt, spec, val): return scans_for_fnames(val + self.inputs.apply_to_files) else: return scans_for_fnames(val) - return super(Coregister, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self): - """validate spm coregister options if set to None ignore - """ + """validate spm coregister options if set to None ignore""" if self.inputs.jobtype == "write": - einputs = super(Coregister, self)._parse_inputs( - skip=("jobtype", "apply_to_files") - ) + einputs = super()._parse_inputs(skip=("jobtype", "apply_to_files")) else: - einputs = super(Coregister, self)._parse_inputs(skip=("jobtype")) + einputs = super()._parse_inputs(skip=("jobtype")) jobtype = self.inputs.jobtype return [{"%s" % (jobtype): einputs[0]}] @@ -1068,7 +1190,7 @@ class NormalizeInputSpec(SPMCommandInputSpec): class NormalizeOutputSpec(TraitedSpec): normalization_parameters = OutputMultiPath( - File(exists=True), desc=("MAT files containing the normalization parameters"), + File(exists=True), desc=("MAT files containing the normalization parameters") ) normalized_source = OutputMultiPath( File(exists=True), desc="Normalized source files" @@ -1096,8 +1218,7 @@ class Normalize(SPMCommand): _jobname = "normalise" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "template": return scans_for_fname(ensure_list(val)) if opt == "source": @@ -1109,14 +1230,11 @@ def _format_arg(self, opt, spec, val): if opt in ["write_wrap"]: if len(val) != 3: raise ValueError("%s must have 3 elements" % opt) - return super(Normalize, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self): - """Validate spm normalize options if set to None ignore - """ - einputs = super(Normalize, self)._parse_inputs( - skip=("jobtype", "apply_to_files") - ) + """Validate spm normalize options if set to None ignore""" + einputs = super()._parse_inputs(skip=("jobtype", "apply_to_files")) if isdefined(self.inputs.apply_to_files): inputfiles = deepcopy(self.inputs.apply_to_files) if isdefined(self.inputs.source): @@ -1149,7 +1267,7 @@ def _list_outputs(self): outputs["normalized_source"] = self.inputs.source elif "write" in self.inputs.jobtype: if isdefined(self.inputs.write_preserve) and self.inputs.write_preserve: - prefixNorm = "".join(["m", self.inputs.out_prefix]) + prefixNorm = f"m{self.inputs.out_prefix}" else: prefixNorm = self.inputs.out_prefix outputs["normalized_files"] = [] @@ -1331,8 +1449,7 @@ class Normalize12(SPMCommand): _jobname = "normalise" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "tpm": return scans_for_fname(ensure_list(val)) if opt == "image_to_align": @@ -1344,14 +1461,11 @@ def _format_arg(self, opt, spec, val): if opt in ["nonlinear_regularization"]: if len(val) != 5: raise ValueError("%s must have 5 elements" % opt) - return super(Normalize12, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self, skip=()): - """validate spm normalize options if set to None ignore - """ - einputs = super(Normalize12, self)._parse_inputs( - skip=("jobtype", "apply_to_files") - ) + """validate spm normalize options if set to None ignore""" + einputs = super()._parse_inputs(skip=("jobtype", "apply_to_files")) if isdefined(self.inputs.apply_to_files): inputfiles = deepcopy(self.inputs.apply_to_files) if isdefined(self.inputs.image_to_align): @@ -1376,25 +1490,22 @@ def _list_outputs(self): outputs["deformation_field"].append(fname_presuffix(imgf, prefix="y_")) outputs["deformation_field"] = simplify_list(outputs["deformation_field"]) - if self.inputs.jobtype == "estimate": - if isdefined(self.inputs.apply_to_files): - outputs["normalized_files"] = self.inputs.apply_to_files - outputs["normalized_image"] = fname_presuffix( - self.inputs.image_to_align, prefix="w" - ) - elif "write" in self.inputs.jobtype: + if "write" in self.inputs.jobtype: outputs["normalized_files"] = [] if isdefined(self.inputs.apply_to_files): filelist = ensure_list(self.inputs.apply_to_files) for f in filelist: if isinstance(f, list): - run = [fname_presuffix(in_f, prefix="w") for in_f in f] + run = [ + fname_presuffix(in_f, prefix=self.inputs.out_prefix) + for in_f in f + ] else: - run = [fname_presuffix(f, prefix="w")] + run = [fname_presuffix(f, prefix=self.inputs.out_prefix)] outputs["normalized_files"].extend(run) if isdefined(self.inputs.image_to_align): outputs["normalized_image"] = fname_presuffix( - self.inputs.image_to_align, prefix="w" + self.inputs.image_to_align, prefix=self.inputs.out_prefix ) return outputs @@ -1524,7 +1635,7 @@ class SegmentInputSpec(SPMCommandInputSpec): desc="FWHM of Gaussian smoothness of bias", ) sampling_distance = traits.Float( - field="opts.samp", desc=("Sampling distance on data for parameter estimation"), + field="opts.samp", desc=("Sampling distance on data for parameter estimation") ) mask_image = File( exists=True, @@ -1535,7 +1646,7 @@ class SegmentInputSpec(SPMCommandInputSpec): class SegmentOutputSpec(TraitedSpec): native_gm_image = File(desc="native space grey probability map") - normalized_gm_image = File(desc="normalized grey probability map",) + normalized_gm_image = File(desc="normalized grey probability map") modulated_gm_image = File(desc=("modulated, normalized grey probability map")) native_wm_image = File(desc="native space white probability map") normalized_wm_image = File(desc="normalized white probability map") @@ -1583,8 +1694,7 @@ def __init__(self, **inputs): SPMCommand.__init__(self, **inputs) def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" clean_masks_dict = {"no": 0, "light": 1, "thorough": 2} if opt in ["data", "tissue_prob_maps"]: @@ -1598,7 +1708,7 @@ def _format_arg(self, opt, spec, val): return scans_for_fname(val) if opt == "clean_masks": return clean_masks_dict[val] - return super(Segment, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -1611,7 +1721,7 @@ def _list_outputs(self): [("modulated", "mw"), ("normalized", "w"), ("native", "")] ): if getattr(self.inputs, outtype)[idx]: - outfield = "%s_%s_image" % (image, tissue) + outfield = f"{image}_{tissue}_image" outputs[outfield] = fname_presuffix( f, prefix="%sc%d" % (prefix, tidx + 1) ) @@ -1635,10 +1745,10 @@ class NewSegmentInputSpec(SPMCommandInputSpec): field="channel", copyfile=False, ) - channel_info = traits.Tuple( + channel_info = Tuple( traits.Float(), traits.Float(), - traits.Tuple(traits.Bool, traits.Bool), + Tuple(traits.Bool, traits.Bool), desc="""A tuple with the following fields: - bias reguralisation (0-10) - FWHM of Gaussian smoothness of bias @@ -1646,11 +1756,11 @@ class NewSegmentInputSpec(SPMCommandInputSpec): field="channel", ) tissues = traits.List( - traits.Tuple( - traits.Tuple(ImageFileSPM(exists=True), traits.Int()), + Tuple( + Tuple(ImageFileSPM(exists=True), traits.Int()), traits.Int(), - traits.Tuple(traits.Bool, traits.Bool), - traits.Tuple(traits.Bool, traits.Bool), + Tuple(traits.Bool, traits.Bool), + Tuple(traits.Bool, traits.Bool), ), desc="""A list of tuples (one per tissue) with the following fields: - tissue probability map (4D), 1-based index to frame @@ -1680,7 +1790,7 @@ class NewSegmentInputSpec(SPMCommandInputSpec): ), ) sampling_distance = traits.Float( - field="warp.samp", desc=("Sampling distance on data for parameter estimation"), + field="warp.samp", desc=("Sampling distance on data for parameter estimation") ) write_deformation_fields = traits.List( traits.Bool(), @@ -1761,8 +1871,7 @@ def __init__(self, **inputs): SPMCommand.__init__(self, **inputs) def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["channel_files", "channel_info"]: # structure have to be recreated because of some weird traits error @@ -1787,11 +1896,9 @@ def _format_arg(self, opt, spec, val): new_tissues.append(new_tissue) return new_tissues elif opt == "write_deformation_fields": - return super(NewSegment, self)._format_arg( - opt, spec, [int(val[0]), int(val[1])] - ) + return super()._format_arg(opt, spec, [int(val[0]), int(val[1])]) else: - return super(NewSegment, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -1865,6 +1972,259 @@ def _list_outputs(self): return outputs +class MultiChannelNewSegmentInputSpec(SPMCommandInputSpec): + channels = traits.List( + Tuple( + InputMultiPath( + ImageFileSPM(exists=True), + mandatory=True, + desc="A list of files to be segmented", + field="channel", + copyfile=False, + ), + Tuple( + traits.Float(), + traits.Float(), + Tuple(traits.Bool, traits.Bool), + desc="""A tuple with the following fields: + - bias reguralisation (0-10) + - FWHM of Gaussian smoothness of bias + - which maps to save (Field, Corrected) - a tuple of two boolean values""", + field="channel", + ), + ), + desc="""A list of tuples (one per each channel) with the following fields: + - a list of channel files (only 1rst channel files will be segmented) + - a tuple with the following channel-specific info fields: + - bias reguralisation (0-10) + - FWHM of Gaussian smoothness of bias + - which maps to save (Field, Corrected) - a tuple of two boolean values""", + field="channel", + ) + tissues = traits.List( + Tuple( + Tuple(ImageFileSPM(exists=True), traits.Int()), + traits.Int(), + Tuple(traits.Bool, traits.Bool), + Tuple(traits.Bool, traits.Bool), + ), + desc="""A list of tuples (one per tissue) with the following fields: + - tissue probability map (4D), 1-based index to frame + - number of gaussians + - which maps to save [Native, DARTEL] - a tuple of two boolean values + - which maps to save [Unmodulated, Modulated] - a tuple of two boolean values""", + field="tissue", + ) + affine_regularization = traits.Enum( + "mni", + "eastern", + "subj", + "none", + field="warp.affreg", + desc="mni, eastern, subj, none ", + ) + warping_regularization = traits.Either( + traits.List(traits.Float(), minlen=5, maxlen=5), + traits.Float(), + field="warp.reg", + desc=( + "Warping regularization " + "parameter(s). Accepts float " + "or list of floats (the " + "latter is required by " + "SPM12)" + ), + ) + sampling_distance = traits.Float( + field="warp.samp", desc=("Sampling distance on data for parameter estimation") + ) + write_deformation_fields = traits.List( + traits.Bool(), + minlen=2, + maxlen=2, + field="warp.write", + desc=("Which deformation fields to write:[Inverse, Forward]"), + ) + + +class MultiChannelNewSegmentOutputSpec(TraitedSpec): + native_class_images = traits.List( + traits.List(File(exists=True)), desc="native space probability maps" + ) + dartel_input_images = traits.List( + traits.List(File(exists=True)), desc="dartel imported class images" + ) + normalized_class_images = traits.List( + traits.List(File(exists=True)), desc="normalized class images" + ) + modulated_class_images = traits.List( + traits.List(File(exists=True)), desc=("modulated+normalized class images") + ) + transformation_mat = OutputMultiPath( + File(exists=True), desc="Normalization transformation" + ) + bias_corrected_images = OutputMultiPath( + File(exists=True), desc="bias corrected images" + ) + bias_field_images = OutputMultiPath(File(exists=True), desc="bias field images") + forward_deformation_field = OutputMultiPath(File(exists=True)) + inverse_deformation_field = OutputMultiPath(File(exists=True)) + + +class MultiChannelNewSegment(SPMCommand): + """Use spm_preproc8 (New Segment) to separate structural images into + different tissue classes. Supports multiple modalities and multichannel inputs. + + http://www.fil.ion.ucl.ac.uk/spm/doc/manual.pdf#page=45 + + Examples + -------- + >>> import nipype.interfaces.spm as spm + >>> seg = spm.MultiChannelNewSegment() + >>> seg.inputs.channels = [('structural.nii',(0.0001, 60, (True, True)))] + >>> seg.run() # doctest: +SKIP + + For VBM pre-processing [http://www.fil.ion.ucl.ac.uk/~john/misc/VBMclass10.pdf], + TPM.nii should be replaced by /path/to/spm8/toolbox/Seg/TPM.nii + + >>> seg = MultiChannelNewSegment() + >>> channel1= ('T1.nii',(0.0001, 60, (True, True))) + >>> channel2= ('T2.nii',(0.0001, 60, (True, True))) + >>> seg.inputs.channels = [channel1, channel2] + >>> tissue1 = (('TPM.nii', 1), 2, (True,True), (False, False)) + >>> tissue2 = (('TPM.nii', 2), 2, (True,True), (False, False)) + >>> tissue3 = (('TPM.nii', 3), 2, (True,False), (False, False)) + >>> tissue4 = (('TPM.nii', 4), 2, (False,False), (False, False)) + >>> tissue5 = (('TPM.nii', 5), 2, (False,False), (False, False)) + >>> seg.inputs.tissues = [tissue1, tissue2, tissue3, tissue4, tissue5] + >>> seg.run() # doctest: +SKIP + + """ + + input_spec = MultiChannelNewSegmentInputSpec + output_spec = MultiChannelNewSegmentOutputSpec + + def __init__(self, **inputs): + _local_version = SPMCommand().version + if _local_version and "12." in _local_version: + self._jobtype = "spatial" + self._jobname = "preproc" + else: + self._jobtype = "tools" + self._jobname = "preproc8" + + SPMCommand.__init__(self, **inputs) + + def _format_arg(self, opt, spec, val): + """Convert input to appropriate format for spm""" + + if opt == "channels": + # structure have to be recreated because of some weird traits error + new_channels = [] + for channel in val: + new_channel = {} + new_channel["vols"] = scans_for_fnames(channel[0]) + if isdefined(channel[1]): + info = channel[1] + new_channel["biasreg"] = info[0] + new_channel["biasfwhm"] = info[1] + new_channel["write"] = [int(info[2][0]), int(info[2][1])] + new_channels.append(new_channel) + return new_channels + elif opt == "tissues": + new_tissues = [] + for tissue in val: + new_tissue = {} + new_tissue["tpm"] = np.array( + [",".join([tissue[0][0], str(tissue[0][1])])], dtype=object + ) + new_tissue["ngaus"] = tissue[1] + new_tissue["native"] = [int(tissue[2][0]), int(tissue[2][1])] + new_tissue["warped"] = [int(tissue[3][0]), int(tissue[3][1])] + new_tissues.append(new_tissue) + return new_tissues + elif opt == "write_deformation_fields": + return super()._format_arg(opt, spec, [int(val[0]), int(val[1])]) + else: + return super()._format_arg(opt, spec, val) + + def _list_outputs(self): + outputs = self._outputs().get() + outputs["native_class_images"] = [] + outputs["dartel_input_images"] = [] + outputs["normalized_class_images"] = [] + outputs["modulated_class_images"] = [] + outputs["transformation_mat"] = [] + outputs["bias_corrected_images"] = [] + outputs["bias_field_images"] = [] + outputs["inverse_deformation_field"] = [] + outputs["forward_deformation_field"] = [] + + n_classes = 5 + if isdefined(self.inputs.tissues): + n_classes = len(self.inputs.tissues) + for i in range(n_classes): + outputs["native_class_images"].append([]) + outputs["dartel_input_images"].append([]) + outputs["normalized_class_images"].append([]) + outputs["modulated_class_images"].append([]) + + # main outputs are generated for the first channel images only + for filename in self.inputs.channels[0][0]: + pth, base, ext = split_filename(filename) + if isdefined(self.inputs.tissues): + for i, tissue in enumerate(self.inputs.tissues): + if tissue[2][0]: + outputs["native_class_images"][i].append( + os.path.join(pth, "c%d%s.nii" % (i + 1, base)) + ) + if tissue[2][1]: + outputs["dartel_input_images"][i].append( + os.path.join(pth, "rc%d%s.nii" % (i + 1, base)) + ) + if tissue[3][0]: + outputs["normalized_class_images"][i].append( + os.path.join(pth, "wc%d%s.nii" % (i + 1, base)) + ) + if tissue[3][1]: + outputs["modulated_class_images"][i].append( + os.path.join(pth, "mwc%d%s.nii" % (i + 1, base)) + ) + else: + for i in range(n_classes): + outputs["native_class_images"][i].append( + os.path.join(pth, "c%d%s.nii" % (i + 1, base)) + ) + outputs["transformation_mat"].append( + os.path.join(pth, "%s_seg8.mat" % base) + ) + + if isdefined(self.inputs.write_deformation_fields): + if self.inputs.write_deformation_fields[0]: + outputs["inverse_deformation_field"].append( + os.path.join(pth, "iy_%s.nii" % base) + ) + if self.inputs.write_deformation_fields[1]: + outputs["forward_deformation_field"].append( + os.path.join(pth, "y_%s.nii" % base) + ) + + # bias field related images are generated for images in all channels + for channel in self.inputs.channels: + for filename in channel[0]: + pth, base, ext = split_filename(filename) + if isdefined(channel[1]): + if channel[1][2][0]: + outputs["bias_field_images"].append( + os.path.join(pth, "BiasField_%s.nii" % (base)) + ) + if channel[1][2][1]: + outputs["bias_corrected_images"].append( + os.path.join(pth, "m%s.nii" % (base)) + ) + return outputs + + class SmoothInputSpec(SPMCommandInputSpec): in_files = InputMultiPath( ImageFileSPM(exists=True), @@ -1923,7 +2283,7 @@ def _format_arg(self, opt, spec, val): else: return val - return super(Smooth, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -1958,9 +2318,9 @@ class DARTELInputSpec(SPMCommandInputSpec): desc=("Form of regularization energy term"), ) iteration_parameters = traits.List( - traits.Tuple( + Tuple( traits.Range(1, 10), - traits.Tuple(traits.Float, traits.Float, traits.Float), + Tuple(traits.Float, traits.Float, traits.Float), traits.Enum(1, 2, 4, 8, 16, 32, 64, 128, 256, 512), traits.Enum(0, 0.5, 1, 2, 4, 8, 16, 32), ), @@ -1977,7 +2337,7 @@ class DARTELInputSpec(SPMCommandInputSpec): """, ) - optimization_parameters = traits.Tuple( + optimization_parameters = Tuple( traits.Float, traits.Range(1, 8), traits.Range(1, 8), @@ -2021,8 +2381,7 @@ class DARTEL(SPMCommand): _jobname = "dartel" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["image_files"]: return scans_for_fnames(val, keep4d=True, separate_sessions=True) @@ -2046,7 +2405,7 @@ def _format_arg(self, opt, spec, val): new_param["its"] = val[2] return [new_param] else: - return super(DARTEL, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -2062,7 +2421,7 @@ def _list_outputs(self): for filename in self.inputs.image_files[0]: pth, base, ext = split_filename(filename) outputs["dartel_flow_fields"].append( - os.path.realpath("u_%s_%s%s" % (base, self.inputs.template_prefix, ext)) + os.path.realpath(f"u_{base}_{self.inputs.template_prefix}{ext}") ) return outputs @@ -2088,14 +2447,14 @@ class DARTELNorm2MNIInputSpec(SPMCommandInputSpec): mandatory=True, copyfile=False, ) - voxel_size = traits.Tuple( + voxel_size = Tuple( traits.Float, traits.Float, traits.Float, desc="Voxel sizes for output file", field="mni_norm.vox", ) - bounding_box = traits.Tuple( + bounding_box = Tuple( traits.Float, traits.Float, traits.Float, @@ -2149,8 +2508,7 @@ class DARTELNorm2MNI(SPMCommand): _jobname = "dartel" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["template_file"]: return np.array([val], dtype=object) elif opt in ["flowfield_files"]: @@ -2167,7 +2525,7 @@ def _format_arg(self, opt, spec, val): else: return [val, val, val] else: - return super(DARTELNorm2MNI, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -2181,9 +2539,7 @@ def _list_outputs(self): prefix = "s" + prefix for filename in self.inputs.apply_to_files: pth, base, ext = split_filename(filename) - outputs["normalized_files"].append( - os.path.realpath("%s%s%s" % (prefix, base, ext)) - ) + outputs["normalized_files"].append(os.path.realpath(f"{prefix}{base}{ext}")) return outputs @@ -2243,15 +2599,14 @@ class CreateWarped(SPMCommand): _jobname = "dartel" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["image_files"]: return scans_for_fnames(val, keep4d=True, separate_sessions=True) if opt in ["flowfield_files"]: return scans_for_fnames(val, keep4d=True) else: - return super(CreateWarped, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -2259,9 +2614,9 @@ def _list_outputs(self): for filename in self.inputs.image_files: pth, base, ext = split_filename(filename) if isdefined(self.inputs.modulate) and self.inputs.modulate: - outputs["warped_files"].append(os.path.realpath("mw%s%s" % (base, ext))) + outputs["warped_files"].append(os.path.realpath(f"mw{base}{ext}")) else: - outputs["warped_files"].append(os.path.realpath("w%s%s" % (base, ext))) + outputs["warped_files"].append(os.path.realpath(f"w{base}{ext}")) return outputs @@ -2288,8 +2643,7 @@ class ApplyDeformations(SPMCommand): _jobname = "defs" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["deformation_field", "reference_volume"]: val = [val] @@ -2299,7 +2653,7 @@ def _format_arg(self, opt, spec, val): return scans_for_fnames(val, keep4d=False, separate_sessions=False) else: - return super(ApplyDeformations, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): outputs = self._outputs().get() @@ -2311,7 +2665,6 @@ def _list_outputs(self): class VBMSegmentInputSpec(SPMCommandInputSpec): - in_files = InputMultiPath( ImageFileSPM(exists=True), desc="A list of files to be segmented", @@ -2323,11 +2676,11 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): tissues = ImageFileSPM( exists=True, field="estwrite.tpm", desc="tissue probability map" ) - gaussians_per_class = traits.Tuple( + gaussians_per_class = Tuple( (2, 2, 2, 3, 4, 2), *([traits.Int()] * 6), usedefault=True, - desc="number of gaussians for each tissue class" + desc="number of gaussians for each tissue class", ) bias_regularization = traits.Enum( 0.0001, @@ -2357,7 +2710,7 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): desc="Controls balance between parameters and data", ) - spatial_normalization = traits.Enum("high", "low", usedefault=True,) + spatial_normalization = traits.Enum("high", "low", usedefault=True) dartel_template = ImageFileSPM( exists=True, field="estwrite.extopts.dartelwarp.normhigh.darteltpm" ) @@ -2378,9 +2731,9 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): ) display_results = traits.Bool(True, usedefault=True, field="estwrite.extopts.print") - gm_native = traits.Bool(False, usedefault=True, field="estwrite.output.GM.native",) + gm_native = traits.Bool(False, usedefault=True, field="estwrite.output.GM.native") gm_normalized = traits.Bool( - False, usedefault=True, field="estwrite.output.GM.warped", + False, usedefault=True, field="estwrite.output.GM.warped" ) gm_modulated_normalized = traits.Range( 0, @@ -2399,9 +2752,9 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): desc="0=None,1=rigid(SPM8 default),2=affine", ) - wm_native = traits.Bool(False, usedefault=True, field="estwrite.output.WM.native",) + wm_native = traits.Bool(False, usedefault=True, field="estwrite.output.WM.native") wm_normalized = traits.Bool( - False, usedefault=True, field="estwrite.output.WM.warped", + False, usedefault=True, field="estwrite.output.WM.warped" ) wm_modulated_normalized = traits.Range( 0, @@ -2420,11 +2773,9 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): desc="0=None,1=rigid(SPM8 default),2=affine", ) - csf_native = traits.Bool( - False, usedefault=True, field="estwrite.output.CSF.native", - ) + csf_native = traits.Bool(False, usedefault=True, field="estwrite.output.CSF.native") csf_normalized = traits.Bool( - False, usedefault=True, field="estwrite.output.CSF.warped", + False, usedefault=True, field="estwrite.output.CSF.warped" ) csf_modulated_normalized = traits.Range( 0, @@ -2444,13 +2795,13 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): ) bias_corrected_native = traits.Bool( - False, usedefault=True, field="estwrite.output.bias.native", + False, usedefault=True, field="estwrite.output.bias.native" ) bias_corrected_normalized = traits.Bool( - True, usedefault=True, field="estwrite.output.bias.warped", + True, usedefault=True, field="estwrite.output.bias.warped" ) bias_corrected_affine = traits.Bool( - False, usedefault=True, field="estwrite.output.bias.affine", + False, usedefault=True, field="estwrite.output.bias.affine" ) pve_label_native = traits.Bool( @@ -2472,7 +2823,7 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): False, usedefault=True, field="estwrite.jacobian.warped" ) - deformation_field = traits.Tuple( + deformation_field = Tuple( (0, 0), traits.Bool, traits.Bool, @@ -2483,7 +2834,6 @@ class VBMSegmentInputSpec(SPMCommandInputSpec): class VBMSegmentOuputSpec(TraitedSpec): - native_class_images = traits.List( traits.List(File(exists=True)), desc="native space probability maps" ) @@ -2612,7 +2962,7 @@ def _list_outputs(self): ) if self.inputs.pve_label_normalized: outputs["pve_label_normalized_images"].append( - os.path.join(pth, "w%sp0%s.nii" % (dartel_px, base)) + os.path.join(pth, f"w{dartel_px}p0{base}.nii") ) if self.inputs.pve_label_dartel == 1: outputs["pve_label_registered_images"].append( @@ -2629,16 +2979,16 @@ def _list_outputs(self): ) if self.inputs.bias_corrected_normalized: outputs["normalized_bias_corrected_images"].append( - os.path.join(pth, "wm%s%s.nii" % (dartel_px, base)) + os.path.join(pth, f"wm{dartel_px}{base}.nii") ) if self.inputs.deformation_field[0]: outputs["forward_deformation_field"].append( - os.path.join(pth, "y_%s%s.nii" % (dartel_px, base)) + os.path.join(pth, f"y_{dartel_px}{base}.nii") ) if self.inputs.deformation_field[1]: outputs["inverse_deformation_field"].append( - os.path.join(pth, "iy_%s%s.nii" % (dartel_px, base)) + os.path.join(pth, f"iy_{dartel_px}{base}.nii") ) if self.inputs.jacobian_determinant and do_dartel: @@ -2648,8 +2998,7 @@ def _list_outputs(self): return outputs def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt in ["in_files"]: return scans_for_fnames(val, keep4d=True) elif opt in ["spatial_normalization"]: @@ -2658,18 +3007,16 @@ def _format_arg(self, opt, spec, val): elif opt in ["dartel_template"]: return np.array([val], dtype=object) elif opt in ["deformation_field"]: - return super(VBMSegment, self)._format_arg( - opt, spec, [int(val[0]), int(val[1])] - ) + return super()._format_arg(opt, spec, [int(val[0]), int(val[1])]) else: - return super(VBMSegment, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _parse_inputs(self): if self.inputs.spatial_normalization == "low": - einputs = super(VBMSegment, self)._parse_inputs( + einputs = super()._parse_inputs( skip=("spatial_normalization", "dartel_template") ) einputs[0]["estwrite"]["extopts"]["dartelwarp"] = {"normlow": 1} return einputs else: - return super(VBMSegment, self)._parse_inputs(skip=("spatial_normalization")) + return super()._parse_inputs(skip=("spatial_normalization")) diff --git a/nipype/interfaces/spm/tests/__init__.py b/nipype/interfaces/spm/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/spm/tests/__init__.py +++ b/nipype/interfaces/spm/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/spm/tests/test_auto_Analyze2nii.py b/nipype/interfaces/spm/tests/test_auto_Analyze2nii.py index 771cb640b1..15fe9399ed 100644 --- a/nipype/interfaces/spm/tests/test_auto_Analyze2nii.py +++ b/nipype/interfaces/spm/tests/test_auto_Analyze2nii.py @@ -4,12 +4,20 @@ def test_Analyze2nii_inputs(): input_map = dict( - analyze_file=dict(extensions=None, mandatory=True,), + analyze_file=dict( + extensions=None, + mandatory=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = Analyze2nii.input_spec() @@ -21,11 +29,18 @@ def test_Analyze2nii_inputs(): def test_Analyze2nii_outputs(): output_map = dict( matlab_cmd=dict(), - mfile=dict(usedefault=True,), - nifti_file=dict(extensions=None,), + mfile=dict( + usedefault=True, + ), + nifti_file=dict( + extensions=None, + ), paths=dict(), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) outputs = Analyze2nii.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py b/nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py index 6e741ae607..d41a0fb4b6 100644 --- a/nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py +++ b/nipype/interfaces/spm/tests/test_auto_ApplyDeformations.py @@ -4,11 +4,22 @@ def test_ApplyDeformations_inputs(): input_map = dict( - deformation_field=dict(extensions=None, field="comp{1}.def", mandatory=True,), - in_files=dict(field="fnames", mandatory=True,), - interp=dict(field="interp",), + deformation_field=dict( + extensions=None, + field="comp{1}.def", + mandatory=True, + ), + in_files=dict( + field="fnames", + mandatory=True, + ), + interp=dict( + field="interp", + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), reference_volume=dict( extensions=[".hdr", ".img", ".img.gz", ".nii"], @@ -16,7 +27,10 @@ def test_ApplyDeformations_inputs(): mandatory=True, ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = ApplyDeformations.input_spec() @@ -26,7 +40,9 @@ def test_ApplyDeformations_inputs(): def test_ApplyDeformations_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = ApplyDeformations.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_ApplyInverseDeformation.py b/nipype/interfaces/spm/tests/test_auto_ApplyInverseDeformation.py index b9389091b3..c652bd7e12 100644 --- a/nipype/interfaces/spm/tests/test_auto_ApplyInverseDeformation.py +++ b/nipype/interfaces/spm/tests/test_auto_ApplyInverseDeformation.py @@ -4,24 +4,43 @@ def test_ApplyInverseDeformation_inputs(): input_map = dict( - bounding_box=dict(field="comp{1}.inv.comp{1}.sn2def.bb",), + bounding_box=dict( + field="comp{1}.inv.comp{1}.sn2def.bb", + ), deformation=dict( extensions=None, field="comp{1}.inv.comp{1}.sn2def.matname", xor=["deformation_field"], ), deformation_field=dict( - extensions=None, field="comp{1}.inv.comp{1}.def", xor=["deformation"], + extensions=None, + field="comp{1}.inv.comp{1}.def", + xor=["deformation"], + ), + in_files=dict( + field="fnames", + mandatory=True, + ), + interpolation=dict( + field="interp", ), - in_files=dict(field="fnames", mandatory=True,), - interpolation=dict(field="interp",), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), - target=dict(extensions=None, field="comp{1}.inv.space",), + target=dict( + extensions=None, + field="comp{1}.inv.space", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - voxel_sizes=dict(field="comp{1}.inv.comp{1}.sn2def.vox",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + voxel_sizes=dict( + field="comp{1}.inv.comp{1}.sn2def.vox", + ), ) inputs = ApplyInverseDeformation.input_spec() @@ -31,7 +50,9 @@ def test_ApplyInverseDeformation_inputs(): def test_ApplyInverseDeformation_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = ApplyInverseDeformation.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_ApplyTransform.py b/nipype/interfaces/spm/tests/test_auto_ApplyTransform.py index 99f140ecac..ae0516370d 100644 --- a/nipype/interfaces/spm/tests/test_auto_ApplyTransform.py +++ b/nipype/interfaces/spm/tests/test_auto_ApplyTransform.py @@ -4,14 +4,29 @@ def test_ApplyTransform_inputs(): input_map = dict( - in_file=dict(copyfile=True, extensions=None, mandatory=True,), - mat=dict(extensions=None, mandatory=True,), + in_file=dict( + copyfile=True, + extensions=None, + mandatory=True, + ), + mat=dict( + extensions=None, + mandatory=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - out_file=dict(extensions=None, genfile=True,), + mfile=dict( + usedefault=True, + ), + out_file=dict( + extensions=None, + genfile=True, + ), paths=dict(), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = ApplyTransform.input_spec() @@ -21,7 +36,11 @@ def test_ApplyTransform_inputs(): def test_ApplyTransform_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ApplyTransform.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_ApplyVDM.py b/nipype/interfaces/spm/tests/test_auto_ApplyVDM.py new file mode 100644 index 0000000000..6d3b3c360d --- /dev/null +++ b/nipype/interfaces/spm/tests/test_auto_ApplyVDM.py @@ -0,0 +1,68 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..preprocess import ApplyVDM + + +def test_ApplyVDM_inputs(): + input_map = dict( + distortion_direction=dict( + field="roptions.pedir", + usedefault=True, + ), + in_files=dict( + copyfile=True, + field="data.scans", + mandatory=True, + ), + interpolation=dict( + field="roptions.rinterp", + ), + matlab_cmd=dict(), + mfile=dict( + usedefault=True, + ), + out_prefix=dict( + field="roptions.prefix", + usedefault=True, + ), + paths=dict(), + use_mcr=dict(), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + vdmfile=dict( + copyfile=True, + extensions=None, + field="data.vdmfile", + mandatory=True, + ), + write_mask=dict( + field="roptions.mask", + ), + write_which=dict( + field="roptions.which", + usedefault=True, + ), + write_wrap=dict( + field="roptions.wrap", + ), + ) + inputs = ApplyVDM.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_ApplyVDM_outputs(): + output_map = dict( + mean_image=dict( + extensions=None, + ), + out_files=dict(), + ) + outputs = ApplyVDM.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/spm/tests/test_auto_CalcCoregAffine.py b/nipype/interfaces/spm/tests/test_auto_CalcCoregAffine.py index 3c67fe75c6..156591cbb9 100644 --- a/nipype/interfaces/spm/tests/test_auto_CalcCoregAffine.py +++ b/nipype/interfaces/spm/tests/test_auto_CalcCoregAffine.py @@ -4,15 +4,31 @@ def test_CalcCoregAffine_inputs(): input_map = dict( - invmat=dict(extensions=None,), - mat=dict(extensions=None,), + invmat=dict( + extensions=None, + ), + mat=dict( + extensions=None, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - moving=dict(copyfile=False, extensions=None, mandatory=True,), + mfile=dict( + usedefault=True, + ), + moving=dict( + copyfile=False, + extensions=None, + mandatory=True, + ), paths=dict(), - target=dict(extensions=None, mandatory=True,), + target=dict( + extensions=None, + mandatory=True, + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = CalcCoregAffine.input_spec() @@ -22,7 +38,14 @@ def test_CalcCoregAffine_inputs(): def test_CalcCoregAffine_outputs(): - output_map = dict(invmat=dict(extensions=None,), mat=dict(extensions=None,),) + output_map = dict( + invmat=dict( + extensions=None, + ), + mat=dict( + extensions=None, + ), + ) outputs = CalcCoregAffine.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Coregister.py b/nipype/interfaces/spm/tests/test_auto_Coregister.py index 04e39ce23b..940f69ebbf 100644 --- a/nipype/interfaces/spm/tests/test_auto_Coregister.py +++ b/nipype/interfaces/spm/tests/test_auto_Coregister.py @@ -4,28 +4,59 @@ def test_Coregister_inputs(): input_map = dict( - apply_to_files=dict(copyfile=True, field="other",), - cost_function=dict(field="eoptions.cost_fun",), - fwhm=dict(field="eoptions.fwhm",), - jobtype=dict(usedefault=True,), + apply_to_files=dict( + copyfile=True, + field="other", + ), + cost_function=dict( + field="eoptions.cost_fun", + ), + fwhm=dict( + field="eoptions.fwhm", + ), + jobtype=dict( + usedefault=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - out_prefix=dict(field="roptions.prefix", usedefault=True,), + mfile=dict( + usedefault=True, + ), + out_prefix=dict( + field="roptions.prefix", + usedefault=True, + ), paths=dict(), - separation=dict(field="eoptions.sep",), - source=dict(copyfile=True, field="source", mandatory=True,), + separation=dict( + field="eoptions.sep", + ), + source=dict( + copyfile=True, + field="source", + mandatory=True, + ), target=dict( copyfile=False, extensions=[".hdr", ".img", ".img.gz", ".nii"], field="ref", mandatory=True, ), - tolerance=dict(field="eoptions.tol",), + tolerance=dict( + field="eoptions.tol", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - write_interp=dict(field="roptions.interp",), - write_mask=dict(field="roptions.mask",), - write_wrap=dict(field="roptions.wrap",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + write_interp=dict( + field="roptions.interp", + ), + write_mask=dict( + field="roptions.mask", + ), + write_wrap=dict( + field="roptions.wrap", + ), ) inputs = Coregister.input_spec() @@ -35,7 +66,10 @@ def test_Coregister_inputs(): def test_Coregister_outputs(): - output_map = dict(coregistered_files=dict(), coregistered_source=dict(),) + output_map = dict( + coregistered_files=dict(), + coregistered_source=dict(), + ) outputs = Coregister.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_CreateWarped.py b/nipype/interfaces/spm/tests/test_auto_CreateWarped.py index b172972fe7..f62694641c 100644 --- a/nipype/interfaces/spm/tests/test_auto_CreateWarped.py +++ b/nipype/interfaces/spm/tests/test_auto_CreateWarped.py @@ -5,17 +5,34 @@ def test_CreateWarped_inputs(): input_map = dict( flowfield_files=dict( - copyfile=False, field="crt_warped.flowfields", mandatory=True, + copyfile=False, + field="crt_warped.flowfields", + mandatory=True, + ), + image_files=dict( + copyfile=False, + field="crt_warped.images", + mandatory=True, + ), + interp=dict( + field="crt_warped.interp", + ), + iterations=dict( + field="crt_warped.K", ), - image_files=dict(copyfile=False, field="crt_warped.images", mandatory=True,), - interp=dict(field="crt_warped.interp",), - iterations=dict(field="crt_warped.K",), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - modulate=dict(field="crt_warped.jactransf",), + mfile=dict( + usedefault=True, + ), + modulate=dict( + field="crt_warped.jactransf", + ), paths=dict(), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = CreateWarped.input_spec() @@ -25,7 +42,9 @@ def test_CreateWarped_inputs(): def test_CreateWarped_outputs(): - output_map = dict(warped_files=dict(),) + output_map = dict( + warped_files=dict(), + ) outputs = CreateWarped.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_DARTEL.py b/nipype/interfaces/spm/tests/test_auto_DARTEL.py index ca031dfd1e..5fbba0c287 100644 --- a/nipype/interfaces/spm/tests/test_auto_DARTEL.py +++ b/nipype/interfaces/spm/tests/test_auto_DARTEL.py @@ -4,16 +4,34 @@ def test_DARTEL_inputs(): input_map = dict( - image_files=dict(copyfile=False, field="warp.images", mandatory=True,), - iteration_parameters=dict(field="warp.settings.param",), + image_files=dict( + copyfile=False, + field="warp.images", + mandatory=True, + ), + iteration_parameters=dict( + field="warp.settings.param", + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - optimization_parameters=dict(field="warp.settings.optim",), + mfile=dict( + usedefault=True, + ), + optimization_parameters=dict( + field="warp.settings.optim", + ), paths=dict(), - regularization_form=dict(field="warp.settings.rform",), - template_prefix=dict(field="warp.settings.template", usedefault=True,), + regularization_form=dict( + field="warp.settings.rform", + ), + template_prefix=dict( + field="warp.settings.template", + usedefault=True, + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = DARTEL.input_spec() @@ -25,7 +43,9 @@ def test_DARTEL_inputs(): def test_DARTEL_outputs(): output_map = dict( dartel_flow_fields=dict(), - final_template_file=dict(extensions=None,), + final_template_file=dict( + extensions=None, + ), template_files=dict(), ) outputs = DARTEL.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_DARTELNorm2MNI.py b/nipype/interfaces/spm/tests/test_auto_DARTELNorm2MNI.py index 3b406b3c27..d4b8ad8a78 100644 --- a/nipype/interfaces/spm/tests/test_auto_DARTELNorm2MNI.py +++ b/nipype/interfaces/spm/tests/test_auto_DARTELNorm2MNI.py @@ -5,14 +5,27 @@ def test_DARTELNorm2MNI_inputs(): input_map = dict( apply_to_files=dict( - copyfile=False, field="mni_norm.data.subjs.images", mandatory=True, + copyfile=False, + field="mni_norm.data.subjs.images", + mandatory=True, + ), + bounding_box=dict( + field="mni_norm.bb", + ), + flowfield_files=dict( + field="mni_norm.data.subjs.flowfields", + mandatory=True, + ), + fwhm=dict( + field="mni_norm.fwhm", ), - bounding_box=dict(field="mni_norm.bb",), - flowfield_files=dict(field="mni_norm.data.subjs.flowfields", mandatory=True,), - fwhm=dict(field="mni_norm.fwhm",), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - modulate=dict(field="mni_norm.preserve",), + mfile=dict( + usedefault=True, + ), + modulate=dict( + field="mni_norm.preserve", + ), paths=dict(), template_file=dict( copyfile=False, @@ -21,8 +34,13 @@ def test_DARTELNorm2MNI_inputs(): mandatory=True, ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - voxel_size=dict(field="mni_norm.vox",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + voxel_size=dict( + field="mni_norm.vox", + ), ) inputs = DARTELNorm2MNI.input_spec() @@ -33,7 +51,10 @@ def test_DARTELNorm2MNI_inputs(): def test_DARTELNorm2MNI_outputs(): output_map = dict( - normalization_parameter_file=dict(extensions=None,), normalized_files=dict(), + normalization_parameter_file=dict( + extensions=None, + ), + normalized_files=dict(), ) outputs = DARTELNorm2MNI.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_DicomImport.py b/nipype/interfaces/spm/tests/test_auto_DicomImport.py index ddb3f81c78..e0459d467f 100644 --- a/nipype/interfaces/spm/tests/test_auto_DicomImport.py +++ b/nipype/interfaces/spm/tests/test_auto_DicomImport.py @@ -4,16 +4,36 @@ def test_DicomImport_inputs(): input_map = dict( - format=dict(field="convopts.format", usedefault=True,), - icedims=dict(field="convopts.icedims", usedefault=True,), - in_files=dict(field="data", mandatory=True,), + format=dict( + field="convopts.format", + usedefault=True, + ), + icedims=dict( + field="convopts.icedims", + usedefault=True, + ), + in_files=dict( + field="data", + mandatory=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - output_dir=dict(field="outdir", usedefault=True,), - output_dir_struct=dict(field="root", usedefault=True,), + mfile=dict( + usedefault=True, + ), + output_dir=dict( + field="outdir", + usedefault=True, + ), + output_dir_struct=dict( + field="root", + usedefault=True, + ), paths=dict(), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = DicomImport.input_spec() @@ -23,7 +43,9 @@ def test_DicomImport_inputs(): def test_DicomImport_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = DicomImport.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_EstimateContrast.py b/nipype/interfaces/spm/tests/test_auto_EstimateContrast.py index 323cb3707c..84fb496e9c 100644 --- a/nipype/interfaces/spm/tests/test_auto_EstimateContrast.py +++ b/nipype/interfaces/spm/tests/test_auto_EstimateContrast.py @@ -4,19 +4,40 @@ def test_EstimateContrast_inputs(): input_map = dict( - beta_images=dict(copyfile=False, mandatory=True,), - contrasts=dict(mandatory=True,), - group_contrast=dict(xor=["use_derivs"],), + beta_images=dict( + copyfile=False, + mandatory=True, + ), + contrasts=dict( + mandatory=True, + ), + group_contrast=dict( + xor=["use_derivs"], + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), - residual_image=dict(copyfile=False, extensions=None, mandatory=True,), + residual_image=dict( + copyfile=False, + extensions=None, + mandatory=True, + ), spm_mat_file=dict( - copyfile=True, extensions=None, field="spmmat", mandatory=True, + copyfile=True, + extensions=None, + field="spmmat", + mandatory=True, + ), + use_derivs=dict( + xor=["group_contrast"], ), - use_derivs=dict(xor=["group_contrast"],), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = EstimateContrast.input_spec() @@ -31,7 +52,9 @@ def test_EstimateContrast_outputs(): ess_images=dict(), spmF_images=dict(), spmT_images=dict(), - spm_mat_file=dict(extensions=None,), + spm_mat_file=dict( + extensions=None, + ), ) outputs = EstimateContrast.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_EstimateModel.py b/nipype/interfaces/spm/tests/test_auto_EstimateModel.py index 5e2b25e0c7..04c4679767 100644 --- a/nipype/interfaces/spm/tests/test_auto_EstimateModel.py +++ b/nipype/interfaces/spm/tests/test_auto_EstimateModel.py @@ -4,17 +4,30 @@ def test_EstimateModel_inputs(): input_map = dict( - estimation_method=dict(field="method", mandatory=True,), + estimation_method=dict( + field="method", + mandatory=True, + ), flags=dict(), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), spm_mat_file=dict( - copyfile=True, extensions=None, field="spmmat", mandatory=True, + copyfile=True, + extensions=None, + field="spmmat", + mandatory=True, ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - write_residuals=dict(field="write_residuals",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + write_residuals=dict( + field="write_residuals", + ), ) inputs = EstimateModel.input_spec() @@ -27,15 +40,29 @@ def test_EstimateModel_outputs(): output_map = dict( ARcoef=dict(), Cbetas=dict(), - RPVimage=dict(extensions=[".hdr", ".img", ".img.gz", ".nii"],), + RPVimage=dict( + extensions=[".hdr", ".img", ".img.gz", ".nii"], + ), SDbetas=dict(), SDerror=dict(), beta_images=dict(), - labels=dict(extensions=[".hdr", ".img", ".img.gz", ".nii"],), - mask_image=dict(extensions=[".hdr", ".img", ".img.gz", ".nii"],), - residual_image=dict(extensions=[".hdr", ".img", ".img.gz", ".nii"],), + con_images=dict(), + ess_images=dict(), + labels=dict( + extensions=[".hdr", ".img", ".img.gz", ".nii"], + ), + mask_image=dict( + extensions=[".hdr", ".img", ".img.gz", ".nii"], + ), + residual_image=dict( + extensions=[".hdr", ".img", ".img.gz", ".nii"], + ), residual_images=dict(), - spm_mat_file=dict(extensions=None,), + spmF_images=dict(), + spmT_images=dict(), + spm_mat_file=dict( + extensions=None, + ), ) outputs = EstimateModel.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_FactorialDesign.py b/nipype/interfaces/spm/tests/test_auto_FactorialDesign.py index 0fb35c010f..de435ea771 100644 --- a/nipype/interfaces/spm/tests/test_auto_FactorialDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_FactorialDesign.py @@ -4,24 +4,39 @@ def test_FactorialDesign_inputs(): input_map = dict( - covariates=dict(field="cov",), - explicit_mask_file=dict(extensions=None, field="masking.em",), + covariates=dict( + field="cov", + ), + explicit_mask_file=dict( + extensions=None, + field="masking.em", + ), global_calc_mean=dict( - field="globalc.g_mean", xor=["global_calc_omit", "global_calc_values"], + field="globalc.g_mean", + xor=["global_calc_omit", "global_calc_values"], ), global_calc_omit=dict( - field="globalc.g_omit", xor=["global_calc_mean", "global_calc_values"], + field="globalc.g_omit", + xor=["global_calc_mean", "global_calc_values"], ), global_calc_values=dict( field="globalc.g_user.global_uval", xor=["global_calc_mean", "global_calc_omit"], ), - global_normalization=dict(field="globalm.glonorm",), + global_normalization=dict( + field="globalm.glonorm", + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - no_grand_mean_scaling=dict(field="globalm.gmsca.gmsca_no",), + mfile=dict( + usedefault=True, + ), + no_grand_mean_scaling=dict( + field="globalm.gmsca.gmsca_no", + ), paths=dict(), - spm_mat_dir=dict(field="dir",), + spm_mat_dir=dict( + field="dir", + ), threshold_mask_absolute=dict( field="masking.tm.tma.athresh", xor=["threshold_mask_none", "threshold_mask_relative"], @@ -34,9 +49,14 @@ def test_FactorialDesign_inputs(): field="masking.tm.tmr.rthresh", xor=["threshold_mask_absolute", "threshold_mask_none"], ), - use_implicit_threshold=dict(field="masking.im",), + use_implicit_threshold=dict( + field="masking.im", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = FactorialDesign.input_spec() @@ -46,7 +66,11 @@ def test_FactorialDesign_inputs(): def test_FactorialDesign_outputs(): - output_map = dict(spm_mat_file=dict(extensions=None,),) + output_map = dict( + spm_mat_file=dict( + extensions=None, + ), + ) outputs = FactorialDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_FieldMap.py b/nipype/interfaces/spm/tests/test_auto_FieldMap.py index 19d0bc3e19..ccd9e70c6e 100644 --- a/nipype/interfaces/spm/tests/test_auto_FieldMap.py +++ b/nipype/interfaces/spm/tests/test_auto_FieldMap.py @@ -4,35 +4,79 @@ def test_FieldMap_inputs(): input_map = dict( - anat_file=dict(copyfile=False, extensions=None, field="subj.anat",), - blip_direction=dict(field="subj.defaults.defaultsval.blipdir", mandatory=True,), - echo_times=dict(field="subj.defaults.defaultsval.et", mandatory=True,), + anat_file=dict( + copyfile=False, + extensions=None, + field="subj.anat", + ), + blip_direction=dict( + field="subj.defaults.defaultsval.blipdir", + mandatory=True, + ), + echo_times=dict( + field="subj.defaults.defaultsval.et", + mandatory=True, + ), epi_file=dict( - copyfile=False, extensions=None, field="subj.session.epi", mandatory=True, + copyfile=False, + extensions=None, + field="subj.session.epi", + mandatory=True, + ), + epifm=dict( + field="subj.defaults.defaultsval.epifm", + usedefault=True, ), - epifm=dict(field="subj.defaults.defaultsval.epifm", usedefault=True,), jacobian_modulation=dict( - field="subj.defaults.defaultsval.ajm", usedefault=True, + field="subj.defaults.defaultsval.ajm", + usedefault=True, + ), + jobtype=dict( + deprecated="1.9.0", + usedefault=True, ), - jobtype=dict(usedefault=True,), magnitude_file=dict( copyfile=False, extensions=None, field="subj.data.presubphasemag.magnitude", mandatory=True, ), - mask_fwhm=dict(field="subj.defaults.defaultsval.mflags.fwhm", usedefault=True,), - maskbrain=dict(field="subj.defaults.defaultsval.maskbrain", usedefault=True,), - matchanat=dict(field="subj.matchanat", usedefault=True,), - matchvdm=dict(field="subj.matchvdm", usedefault=True,), + mask_fwhm=dict( + field="subj.defaults.defaultsval.mflags.fwhm", + usedefault=True, + ), + maskbrain=dict( + field="subj.defaults.defaultsval.maskbrain", + usedefault=True, + ), + matchanat=dict( + field="subj.matchanat", + usedefault=True, + ), + matchvdm=dict( + field="subj.matchvdm", + usedefault=True, + ), matlab_cmd=dict(), - method=dict(field="subj.defaults.defaultsval.uflags.method", usedefault=True,), - mfile=dict(usedefault=True,), + method=dict( + field="subj.defaults.defaultsval.uflags.method", + usedefault=True, + ), + mfile=dict( + usedefault=True, + ), ndilate=dict( - field="subj.defaults.defaultsval.mflags.ndilate", usedefault=True, + field="subj.defaults.defaultsval.mflags.ndilate", + usedefault=True, + ), + nerode=dict( + field="subj.defaults.defaultsval.mflags.nerode", + usedefault=True, + ), + pad=dict( + field="subj.defaults.defaultsval.uflags.pad", + usedefault=True, ), - nerode=dict(field="subj.defaults.defaultsval.mflags.nerode", usedefault=True,), - pad=dict(field="subj.defaults.defaultsval.uflags.pad", usedefault=True,), paths=dict(), phase_file=dict( copyfile=False, @@ -40,24 +84,44 @@ def test_FieldMap_inputs(): field="subj.data.presubphasemag.phase", mandatory=True, ), - reg=dict(field="subj.defaults.defaultsval.mflags.reg", usedefault=True,), - sessname=dict(field="subj.sessname", usedefault=True,), + reg=dict( + field="subj.defaults.defaultsval.mflags.reg", + usedefault=True, + ), + sessname=dict( + field="subj.sessname", + usedefault=True, + ), template=dict( copyfile=False, extensions=None, field="subj.defaults.defaultsval.mflags.template", ), - thresh=dict(field="subj.defaults.defaultsval.mflags.thresh", usedefault=True,), + thresh=dict( + field="subj.defaults.defaultsval.mflags.thresh", + usedefault=True, + ), total_readout_time=dict( - field="subj.defaults.defaultsval.tert", mandatory=True, + field="subj.defaults.defaultsval.tert", + mandatory=True, ), unwarp_fwhm=dict( - field="subj.defaults.defaultsval.uflags.fwhm", usedefault=True, + field="subj.defaults.defaultsval.uflags.fwhm", + usedefault=True, ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - writeunwarped=dict(field="subj.writeunwarped", usedefault=True,), - ws=dict(field="subj.defaults.defaultsval.uflags.ws", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + writeunwarped=dict( + field="subj.writeunwarped", + usedefault=True, + ), + ws=dict( + field="subj.defaults.defaultsval.uflags.ws", + usedefault=True, + ), ) inputs = FieldMap.input_spec() @@ -67,7 +131,11 @@ def test_FieldMap_inputs(): def test_FieldMap_outputs(): - output_map = dict(vdm=dict(extensions=None,),) + output_map = dict( + vdm=dict( + extensions=None, + ), + ) outputs = FieldMap.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Level1Design.py b/nipype/interfaces/spm/tests/test_auto_Level1Design.py index 8a57a7b86e..04c9f315ef 100644 --- a/nipype/interfaces/spm/tests/test_auto_Level1Design.py +++ b/nipype/interfaces/spm/tests/test_auto_Level1Design.py @@ -4,25 +4,61 @@ def test_Level1Design_inputs(): input_map = dict( - bases=dict(field="bases", mandatory=True,), - factor_info=dict(field="fact",), + bases=dict( + field="bases", + mandatory=True, + ), + factor_info=dict( + field="fact", + ), flags=dict(), - global_intensity_normalization=dict(field="global",), - interscan_interval=dict(field="timing.RT", mandatory=True,), - mask_image=dict(extensions=None, field="mask",), - mask_threshold=dict(usedefault=True,), + global_intensity_normalization=dict( + field="global", + ), + interscan_interval=dict( + field="timing.RT", + mandatory=True, + ), + mask_image=dict( + extensions=None, + field="mask", + ), + mask_threshold=dict( + usedefault=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - microtime_onset=dict(field="timing.fmri_t0",), - microtime_resolution=dict(field="timing.fmri_t",), - model_serial_correlations=dict(field="cvi",), + mfile=dict( + usedefault=True, + ), + microtime_onset=dict( + field="timing.fmri_t0", + ), + microtime_resolution=dict( + field="timing.fmri_t", + ), + model_serial_correlations=dict( + field="cvi", + ), paths=dict(), - session_info=dict(field="sess", mandatory=True,), - spm_mat_dir=dict(field="dir",), - timing_units=dict(field="timing.units", mandatory=True,), + session_info=dict( + field="sess", + mandatory=True, + ), + spm_mat_dir=dict( + field="dir", + ), + timing_units=dict( + field="timing.units", + mandatory=True, + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - volterra_expansion_order=dict(field="volt",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + volterra_expansion_order=dict( + field="volt", + ), ) inputs = Level1Design.input_spec() @@ -32,7 +68,11 @@ def test_Level1Design_inputs(): def test_Level1Design_outputs(): - output_map = dict(spm_mat_file=dict(extensions=None,),) + output_map = dict( + spm_mat_file=dict( + extensions=None, + ), + ) outputs = Level1Design.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_MultiChannelNewSegment.py b/nipype/interfaces/spm/tests/test_auto_MultiChannelNewSegment.py new file mode 100644 index 0000000000..9c8f743d45 --- /dev/null +++ b/nipype/interfaces/spm/tests/test_auto_MultiChannelNewSegment.py @@ -0,0 +1,59 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..preprocess import MultiChannelNewSegment + + +def test_MultiChannelNewSegment_inputs(): + input_map = dict( + affine_regularization=dict( + field="warp.affreg", + ), + channels=dict( + field="channel", + ), + matlab_cmd=dict(), + mfile=dict( + usedefault=True, + ), + paths=dict(), + sampling_distance=dict( + field="warp.samp", + ), + tissues=dict( + field="tissue", + ), + use_mcr=dict(), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + warping_regularization=dict( + field="warp.reg", + ), + write_deformation_fields=dict( + field="warp.write", + ), + ) + inputs = MultiChannelNewSegment.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value + + +def test_MultiChannelNewSegment_outputs(): + output_map = dict( + bias_corrected_images=dict(), + bias_field_images=dict(), + dartel_input_images=dict(), + forward_deformation_field=dict(), + inverse_deformation_field=dict(), + modulated_class_images=dict(), + native_class_images=dict(), + normalized_class_images=dict(), + transformation_mat=dict(), + ) + outputs = MultiChannelNewSegment.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(outputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/spm/tests/test_auto_MultipleRegressionDesign.py b/nipype/interfaces/spm/tests/test_auto_MultipleRegressionDesign.py index 478c869474..61d3b38a74 100644 --- a/nipype/interfaces/spm/tests/test_auto_MultipleRegressionDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_MultipleRegressionDesign.py @@ -4,26 +4,47 @@ def test_MultipleRegressionDesign_inputs(): input_map = dict( - covariates=dict(field="cov",), - explicit_mask_file=dict(extensions=None, field="masking.em",), + covariates=dict( + field="cov", + ), + explicit_mask_file=dict( + extensions=None, + field="masking.em", + ), global_calc_mean=dict( - field="globalc.g_mean", xor=["global_calc_omit", "global_calc_values"], + field="globalc.g_mean", + xor=["global_calc_omit", "global_calc_values"], ), global_calc_omit=dict( - field="globalc.g_omit", xor=["global_calc_mean", "global_calc_values"], + field="globalc.g_omit", + xor=["global_calc_mean", "global_calc_values"], ), global_calc_values=dict( field="globalc.g_user.global_uval", xor=["global_calc_mean", "global_calc_omit"], ), - global_normalization=dict(field="globalm.glonorm",), - in_files=dict(field="des.mreg.scans", mandatory=True,), - include_intercept=dict(field="des.mreg.incint", usedefault=True,), + global_normalization=dict( + field="globalm.glonorm", + ), + in_files=dict( + field="des.mreg.scans", + mandatory=True, + ), + include_intercept=dict( + field="des.mreg.incint", + usedefault=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - no_grand_mean_scaling=dict(field="globalm.gmsca.gmsca_no",), + mfile=dict( + usedefault=True, + ), + no_grand_mean_scaling=dict( + field="globalm.gmsca.gmsca_no", + ), paths=dict(), - spm_mat_dir=dict(field="dir",), + spm_mat_dir=dict( + field="dir", + ), threshold_mask_absolute=dict( field="masking.tm.tma.athresh", xor=["threshold_mask_none", "threshold_mask_relative"], @@ -36,10 +57,17 @@ def test_MultipleRegressionDesign_inputs(): field="masking.tm.tmr.rthresh", xor=["threshold_mask_absolute", "threshold_mask_none"], ), - use_implicit_threshold=dict(field="masking.im",), + use_implicit_threshold=dict( + field="masking.im", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - user_covariates=dict(field="des.mreg.mcov",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + user_covariates=dict( + field="des.mreg.mcov", + ), ) inputs = MultipleRegressionDesign.input_spec() @@ -49,7 +77,11 @@ def test_MultipleRegressionDesign_inputs(): def test_MultipleRegressionDesign_outputs(): - output_map = dict(spm_mat_file=dict(extensions=None,),) + output_map = dict( + spm_mat_file=dict( + extensions=None, + ), + ) outputs = MultipleRegressionDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_NewSegment.py b/nipype/interfaces/spm/tests/test_auto_NewSegment.py index e05643b92e..dae310f6e2 100644 --- a/nipype/interfaces/spm/tests/test_auto_NewSegment.py +++ b/nipype/interfaces/spm/tests/test_auto_NewSegment.py @@ -4,18 +4,39 @@ def test_NewSegment_inputs(): input_map = dict( - affine_regularization=dict(field="warp.affreg",), - channel_files=dict(copyfile=False, field="channel", mandatory=True,), - channel_info=dict(field="channel",), + affine_regularization=dict( + field="warp.affreg", + ), + channel_files=dict( + copyfile=False, + field="channel", + mandatory=True, + ), + channel_info=dict( + field="channel", + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), - sampling_distance=dict(field="warp.samp",), - tissues=dict(field="tissue",), + sampling_distance=dict( + field="warp.samp", + ), + tissues=dict( + field="tissue", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - warping_regularization=dict(field="warp.reg",), - write_deformation_fields=dict(field="warp.write",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + warping_regularization=dict( + field="warp.reg", + ), + write_deformation_fields=dict( + field="warp.write", + ), ) inputs = NewSegment.input_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_Normalize.py b/nipype/interfaces/spm/tests/test_auto_Normalize.py index e028c609c9..caa063d923 100644 --- a/nipype/interfaces/spm/tests/test_auto_Normalize.py +++ b/nipype/interfaces/spm/tests/test_auto_Normalize.py @@ -4,15 +4,33 @@ def test_Normalize_inputs(): input_map = dict( - DCT_period_cutoff=dict(field="eoptions.cutoff",), - affine_regularization_type=dict(field="eoptions.regtype",), - apply_to_files=dict(copyfile=True, field="subj.resample",), - jobtype=dict(usedefault=True,), + DCT_period_cutoff=dict( + field="eoptions.cutoff", + ), + affine_regularization_type=dict( + field="eoptions.regtype", + ), + apply_to_files=dict( + copyfile=True, + field="subj.resample", + ), + jobtype=dict( + usedefault=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - nonlinear_iterations=dict(field="eoptions.nits",), - nonlinear_regularization=dict(field="eoptions.reg",), - out_prefix=dict(field="roptions.prefix", usedefault=True,), + mfile=dict( + usedefault=True, + ), + nonlinear_iterations=dict( + field="eoptions.nits", + ), + nonlinear_regularization=dict( + field="eoptions.reg", + ), + out_prefix=dict( + field="roptions.prefix", + usedefault=True, + ), parameter_file=dict( copyfile=False, extensions=None, @@ -22,10 +40,19 @@ def test_Normalize_inputs(): ), paths=dict(), source=dict( - copyfile=True, field="subj.source", mandatory=True, xor=["parameter_file"], + copyfile=True, + field="subj.source", + mandatory=True, + xor=["parameter_file"], + ), + source_image_smoothing=dict( + field="eoptions.smosrc", + ), + source_weight=dict( + copyfile=False, + extensions=None, + field="subj.wtsrc", ), - source_image_smoothing=dict(field="eoptions.smosrc",), - source_weight=dict(copyfile=False, extensions=None, field="subj.wtsrc",), template=dict( copyfile=False, extensions=None, @@ -33,15 +60,34 @@ def test_Normalize_inputs(): mandatory=True, xor=["parameter_file"], ), - template_image_smoothing=dict(field="eoptions.smoref",), - template_weight=dict(copyfile=False, extensions=None, field="eoptions.weight",), + template_image_smoothing=dict( + field="eoptions.smoref", + ), + template_weight=dict( + copyfile=False, + extensions=None, + field="eoptions.weight", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - write_bounding_box=dict(field="roptions.bb",), - write_interp=dict(field="roptions.interp",), - write_preserve=dict(field="roptions.preserve",), - write_voxel_sizes=dict(field="roptions.vox",), - write_wrap=dict(field="roptions.wrap",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + write_bounding_box=dict( + field="roptions.bb", + ), + write_interp=dict( + field="roptions.interp", + ), + write_preserve=dict( + field="roptions.preserve", + ), + write_voxel_sizes=dict( + field="roptions.vox", + ), + write_wrap=dict( + field="roptions.wrap", + ), ) inputs = Normalize.input_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_Normalize12.py b/nipype/interfaces/spm/tests/test_auto_Normalize12.py index b64475eab3..965ffafec9 100644 --- a/nipype/interfaces/spm/tests/test_auto_Normalize12.py +++ b/nipype/interfaces/spm/tests/test_auto_Normalize12.py @@ -4,10 +4,19 @@ def test_Normalize12_inputs(): input_map = dict( - affine_regularization_type=dict(field="eoptions.affreg",), - apply_to_files=dict(copyfile=True, field="subj.resample",), - bias_fwhm=dict(field="eoptions.biasfwhm",), - bias_regularization=dict(field="eoptions.biasreg",), + affine_regularization_type=dict( + field="eoptions.affreg", + ), + apply_to_files=dict( + copyfile=True, + field="subj.resample", + ), + bias_fwhm=dict( + field="eoptions.biasfwhm", + ), + bias_regularization=dict( + field="eoptions.biasreg", + ), deformation_file=dict( copyfile=False, extensions=[".hdr", ".img", ".img.gz", ".nii"], @@ -22,13 +31,24 @@ def test_Normalize12_inputs(): mandatory=True, xor=["deformation_file"], ), - jobtype=dict(usedefault=True,), + jobtype=dict( + usedefault=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - out_prefix=dict(field="woptions.prefix", usedefault=True,), + mfile=dict( + usedefault=True, + ), + out_prefix=dict( + field="woptions.prefix", + usedefault=True, + ), paths=dict(), - sampling_distance=dict(field="eoptions.samp",), - smoothness=dict(field="eoptions.fwhm",), + sampling_distance=dict( + field="eoptions.samp", + ), + smoothness=dict( + field="eoptions.fwhm", + ), tpm=dict( copyfile=False, extensions=None, @@ -36,11 +56,22 @@ def test_Normalize12_inputs(): xor=["deformation_file"], ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - warping_regularization=dict(field="eoptions.reg",), - write_bounding_box=dict(field="woptions.bb",), - write_interp=dict(field="woptions.interp",), - write_voxel_sizes=dict(field="woptions.vox",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + warping_regularization=dict( + field="eoptions.reg", + ), + write_bounding_box=dict( + field="woptions.bb", + ), + write_interp=dict( + field="woptions.interp", + ), + write_voxel_sizes=dict( + field="woptions.vox", + ), ) inputs = Normalize12.input_spec() @@ -51,7 +82,9 @@ def test_Normalize12_inputs(): def test_Normalize12_outputs(): output_map = dict( - deformation_field=dict(), normalized_files=dict(), normalized_image=dict(), + deformation_field=dict(), + normalized_files=dict(), + normalized_image=dict(), ) outputs = Normalize12.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_OneSampleTTestDesign.py b/nipype/interfaces/spm/tests/test_auto_OneSampleTTestDesign.py index cd5197602c..9b77ab0af7 100644 --- a/nipype/interfaces/spm/tests/test_auto_OneSampleTTestDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_OneSampleTTestDesign.py @@ -4,25 +4,43 @@ def test_OneSampleTTestDesign_inputs(): input_map = dict( - covariates=dict(field="cov",), - explicit_mask_file=dict(extensions=None, field="masking.em",), + covariates=dict( + field="cov", + ), + explicit_mask_file=dict( + extensions=None, + field="masking.em", + ), global_calc_mean=dict( - field="globalc.g_mean", xor=["global_calc_omit", "global_calc_values"], + field="globalc.g_mean", + xor=["global_calc_omit", "global_calc_values"], ), global_calc_omit=dict( - field="globalc.g_omit", xor=["global_calc_mean", "global_calc_values"], + field="globalc.g_omit", + xor=["global_calc_mean", "global_calc_values"], ), global_calc_values=dict( field="globalc.g_user.global_uval", xor=["global_calc_mean", "global_calc_omit"], ), - global_normalization=dict(field="globalm.glonorm",), - in_files=dict(field="des.t1.scans", mandatory=True,), + global_normalization=dict( + field="globalm.glonorm", + ), + in_files=dict( + field="des.t1.scans", + mandatory=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - no_grand_mean_scaling=dict(field="globalm.gmsca.gmsca_no",), + mfile=dict( + usedefault=True, + ), + no_grand_mean_scaling=dict( + field="globalm.gmsca.gmsca_no", + ), paths=dict(), - spm_mat_dir=dict(field="dir",), + spm_mat_dir=dict( + field="dir", + ), threshold_mask_absolute=dict( field="masking.tm.tma.athresh", xor=["threshold_mask_none", "threshold_mask_relative"], @@ -35,9 +53,14 @@ def test_OneSampleTTestDesign_inputs(): field="masking.tm.tmr.rthresh", xor=["threshold_mask_absolute", "threshold_mask_none"], ), - use_implicit_threshold=dict(field="masking.im",), + use_implicit_threshold=dict( + field="masking.im", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = OneSampleTTestDesign.input_spec() @@ -47,7 +70,11 @@ def test_OneSampleTTestDesign_inputs(): def test_OneSampleTTestDesign_outputs(): - output_map = dict(spm_mat_file=dict(extensions=None,),) + output_map = dict( + spm_mat_file=dict( + extensions=None, + ), + ) outputs = OneSampleTTestDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_PairedTTestDesign.py b/nipype/interfaces/spm/tests/test_auto_PairedTTestDesign.py index bb516488ee..6be1f6ec01 100644 --- a/nipype/interfaces/spm/tests/test_auto_PairedTTestDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_PairedTTestDesign.py @@ -4,27 +4,49 @@ def test_PairedTTestDesign_inputs(): input_map = dict( - ancova=dict(field="des.pt.ancova",), - covariates=dict(field="cov",), - explicit_mask_file=dict(extensions=None, field="masking.em",), + ancova=dict( + field="des.pt.ancova", + ), + covariates=dict( + field="cov", + ), + explicit_mask_file=dict( + extensions=None, + field="masking.em", + ), global_calc_mean=dict( - field="globalc.g_mean", xor=["global_calc_omit", "global_calc_values"], + field="globalc.g_mean", + xor=["global_calc_omit", "global_calc_values"], ), global_calc_omit=dict( - field="globalc.g_omit", xor=["global_calc_mean", "global_calc_values"], + field="globalc.g_omit", + xor=["global_calc_mean", "global_calc_values"], ), global_calc_values=dict( field="globalc.g_user.global_uval", xor=["global_calc_mean", "global_calc_omit"], ), - global_normalization=dict(field="globalm.glonorm",), - grand_mean_scaling=dict(field="des.pt.gmsca",), + global_normalization=dict( + field="globalm.glonorm", + ), + grand_mean_scaling=dict( + field="des.pt.gmsca", + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - no_grand_mean_scaling=dict(field="globalm.gmsca.gmsca_no",), - paired_files=dict(field="des.pt.pair", mandatory=True,), + mfile=dict( + usedefault=True, + ), + no_grand_mean_scaling=dict( + field="globalm.gmsca.gmsca_no", + ), + paired_files=dict( + field="des.pt.pair", + mandatory=True, + ), paths=dict(), - spm_mat_dir=dict(field="dir",), + spm_mat_dir=dict( + field="dir", + ), threshold_mask_absolute=dict( field="masking.tm.tma.athresh", xor=["threshold_mask_none", "threshold_mask_relative"], @@ -37,9 +59,14 @@ def test_PairedTTestDesign_inputs(): field="masking.tm.tmr.rthresh", xor=["threshold_mask_absolute", "threshold_mask_none"], ), - use_implicit_threshold=dict(field="masking.im",), + use_implicit_threshold=dict( + field="masking.im", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = PairedTTestDesign.input_spec() @@ -49,7 +76,11 @@ def test_PairedTTestDesign_inputs(): def test_PairedTTestDesign_outputs(): - output_map = dict(spm_mat_file=dict(extensions=None,),) + output_map = dict( + spm_mat_file=dict( + extensions=None, + ), + ) outputs = PairedTTestDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Realign.py b/nipype/interfaces/spm/tests/test_auto_Realign.py index ab76f6a82d..8262243a61 100644 --- a/nipype/interfaces/spm/tests/test_auto_Realign.py +++ b/nipype/interfaces/spm/tests/test_auto_Realign.py @@ -4,25 +4,63 @@ def test_Realign_inputs(): input_map = dict( - fwhm=dict(field="eoptions.fwhm",), - in_files=dict(copyfile=True, field="data", mandatory=True,), - interp=dict(field="eoptions.interp",), - jobtype=dict(usedefault=True,), + fwhm=dict( + field="eoptions.fwhm", + ), + in_files=dict( + copyfile=True, + field="data", + mandatory=True, + ), + interp=dict( + field="eoptions.interp", + ), + jobtype=dict( + usedefault=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - out_prefix=dict(field="roptions.prefix", usedefault=True,), + mfile=dict( + usedefault=True, + ), + out_prefix=dict( + field="roptions.prefix", + usedefault=True, + ), paths=dict(), - quality=dict(field="eoptions.quality",), - register_to_mean=dict(field="eoptions.rtm",), - separation=dict(field="eoptions.sep",), + quality=dict( + field="eoptions.quality", + ), + register_to_mean=dict( + field="eoptions.rtm", + ), + separation=dict( + field="eoptions.sep", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - weight_img=dict(extensions=None, field="eoptions.weight",), - wrap=dict(field="eoptions.wrap",), - write_interp=dict(field="roptions.interp",), - write_mask=dict(field="roptions.mask",), - write_which=dict(field="roptions.which", maxlen=2, minlen=2, usedefault=True,), - write_wrap=dict(field="roptions.wrap",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + weight_img=dict( + extensions=None, + field="eoptions.weight", + ), + wrap=dict( + field="eoptions.wrap", + ), + write_interp=dict( + field="roptions.interp", + ), + write_mask=dict( + field="roptions.mask", + ), + write_which=dict( + field="roptions.which", + usedefault=True, + ), + write_wrap=dict( + field="roptions.wrap", + ), ) inputs = Realign.input_spec() @@ -33,7 +71,9 @@ def test_Realign_inputs(): def test_Realign_outputs(): output_map = dict( - mean_image=dict(extensions=None,), + mean_image=dict( + extensions=None, + ), modified_in_files=dict(), realigned_files=dict(), realignment_parameters=dict(), diff --git a/nipype/interfaces/spm/tests/test_auto_RealignUnwarp.py b/nipype/interfaces/spm/tests/test_auto_RealignUnwarp.py index fd4e420423..dc996c130e 100644 --- a/nipype/interfaces/spm/tests/test_auto_RealignUnwarp.py +++ b/nipype/interfaces/spm/tests/test_auto_RealignUnwarp.py @@ -4,41 +4,98 @@ def test_RealignUnwarp_inputs(): input_map = dict( - est_basis_func=dict(field="uweoptions.basfcn",), - est_first_order_effects=dict(field="uweoptions.fot",), - est_jacobian_deformations=dict(field="uweoptions.jm",), + est_basis_func=dict( + field="uweoptions.basfcn", + ), + est_first_order_effects=dict( + field="uweoptions.fot", + ), + est_jacobian_deformations=dict( + field="uweoptions.jm", + ), est_num_of_iterations=dict( - field="uweoptions.noi", maxlen=1, minlen=1, usedefault=True, + field="uweoptions.noi", + usedefault=True, + ), + est_re_est_mov_par=dict( + field="uweoptions.rem", ), - est_re_est_mov_par=dict(field="uweoptions.rem",), est_reg_factor=dict( - field="uweoptions.lambda", maxlen=1, minlen=1, usedefault=True, - ), - est_reg_order=dict(field="uweoptions.regorder",), - est_second_order_effects=dict(field="uweoptions.sot",), - est_taylor_expansion_point=dict(field="uweoptions.expround", usedefault=True,), - est_unwarp_fwhm=dict(field="uweoptions.uwfwhm",), - fwhm=dict(field="eoptions.fwhm",), - in_files=dict(copyfile=True, field="data.scans", mandatory=True,), - interp=dict(field="eoptions.einterp",), + field="uweoptions.lambda", + usedefault=True, + ), + est_reg_order=dict( + field="uweoptions.regorder", + ), + est_second_order_effects=dict( + field="uweoptions.sot", + ), + est_taylor_expansion_point=dict( + field="uweoptions.expround", + usedefault=True, + ), + est_unwarp_fwhm=dict( + field="uweoptions.uwfwhm", + ), + fwhm=dict( + field="eoptions.fwhm", + ), + in_files=dict( + copyfile=True, + field="data.scans", + mandatory=True, + ), + interp=dict( + field="eoptions.einterp", + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - out_prefix=dict(field="uwroptions.prefix", usedefault=True,), + mfile=dict( + usedefault=True, + ), + out_prefix=dict( + field="uwroptions.prefix", + usedefault=True, + ), paths=dict(), - phase_map=dict(copyfile=False, extensions=None, field="data.pmscan",), - quality=dict(field="eoptions.quality",), - register_to_mean=dict(field="eoptions.rtm",), - reslice_interp=dict(field="uwroptions.rinterp",), - reslice_mask=dict(field="uwroptions.mask",), + phase_map=dict( + copyfile=False, + extensions=None, + field="data.pmscan", + ), + quality=dict( + field="eoptions.quality", + ), + register_to_mean=dict( + field="eoptions.rtm", + ), + reslice_interp=dict( + field="uwroptions.rinterp", + ), + reslice_mask=dict( + field="uwroptions.mask", + ), reslice_which=dict( - field="uwroptions.uwwhich", maxlen=2, minlen=2, usedefault=True, + field="uwroptions.uwwhich", + usedefault=True, + ), + reslice_wrap=dict( + field="uwroptions.wrap", + ), + separation=dict( + field="eoptions.sep", ), - reslice_wrap=dict(field="uwroptions.wrap",), - separation=dict(field="eoptions.sep",), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - weight_img=dict(extensions=None, field="eoptions.weight",), - wrap=dict(field="eoptions.ewrap",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + weight_img=dict( + extensions=None, + field="eoptions.weight", + ), + wrap=dict( + field="eoptions.ewrap", + ), ) inputs = RealignUnwarp.input_spec() @@ -49,7 +106,9 @@ def test_RealignUnwarp_inputs(): def test_RealignUnwarp_outputs(): output_map = dict( - mean_image=dict(extensions=None,), + mean_image=dict( + extensions=None, + ), modified_in_files=dict(), realigned_unwarped_files=dict(), realignment_parameters=dict(), diff --git a/nipype/interfaces/spm/tests/test_auto_Reslice.py b/nipype/interfaces/spm/tests/test_auto_Reslice.py index 46083f8192..c48d1a4b88 100644 --- a/nipype/interfaces/spm/tests/test_auto_Reslice.py +++ b/nipype/interfaces/spm/tests/test_auto_Reslice.py @@ -4,15 +4,30 @@ def test_Reslice_inputs(): input_map = dict( - in_file=dict(extensions=None, mandatory=True,), - interp=dict(usedefault=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), + interp=dict( + usedefault=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - out_file=dict(extensions=None,), + mfile=dict( + usedefault=True, + ), + out_file=dict( + extensions=None, + ), paths=dict(), - space_defining=dict(extensions=None, mandatory=True,), + space_defining=dict( + extensions=None, + mandatory=True, + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = Reslice.input_spec() @@ -22,7 +37,11 @@ def test_Reslice_inputs(): def test_Reslice_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Reslice.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_ResliceToReference.py b/nipype/interfaces/spm/tests/test_auto_ResliceToReference.py index ebea9a0bf4..8bbb1d1307 100644 --- a/nipype/interfaces/spm/tests/test_auto_ResliceToReference.py +++ b/nipype/interfaces/spm/tests/test_auto_ResliceToReference.py @@ -4,16 +4,33 @@ def test_ResliceToReference_inputs(): input_map = dict( - bounding_box=dict(field="comp{2}.idbbvox.bb",), - in_files=dict(field="fnames", mandatory=True,), - interpolation=dict(field="interp",), + bounding_box=dict( + field="comp{2}.idbbvox.bb", + ), + in_files=dict( + field="fnames", + mandatory=True, + ), + interpolation=dict( + field="interp", + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), - target=dict(extensions=None, field="comp{1}.id.space",), + target=dict( + extensions=None, + field="comp{1}.id.space", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - voxel_sizes=dict(field="comp{2}.idbbvox.vox",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + voxel_sizes=dict( + field="comp{2}.idbbvox.vox", + ), ) inputs = ResliceToReference.input_spec() @@ -23,7 +40,9 @@ def test_ResliceToReference_inputs(): def test_ResliceToReference_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = ResliceToReference.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_SPMCommand.py b/nipype/interfaces/spm/tests/test_auto_SPMCommand.py index bde05ad1be..0c0a8d7506 100644 --- a/nipype/interfaces/spm/tests/test_auto_SPMCommand.py +++ b/nipype/interfaces/spm/tests/test_auto_SPMCommand.py @@ -5,10 +5,15 @@ def test_SPMCommand_inputs(): input_map = dict( matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = SPMCommand.input_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_Segment.py b/nipype/interfaces/spm/tests/test_auto_Segment.py index ea07881981..4859c76a00 100644 --- a/nipype/interfaces/spm/tests/test_auto_Segment.py +++ b/nipype/interfaces/spm/tests/test_auto_Segment.py @@ -4,26 +4,64 @@ def test_Segment_inputs(): input_map = dict( - affine_regularization=dict(field="opts.regtype",), - bias_fwhm=dict(field="opts.biasfwhm",), - bias_regularization=dict(field="opts.biasreg",), - clean_masks=dict(field="output.cleanup",), - csf_output_type=dict(field="output.CSF",), - data=dict(copyfile=False, field="data", mandatory=True,), - gaussians_per_class=dict(field="opts.ngaus",), - gm_output_type=dict(field="output.GM",), - mask_image=dict(extensions=None, field="opts.msk",), + affine_regularization=dict( + field="opts.regtype", + ), + bias_fwhm=dict( + field="opts.biasfwhm", + ), + bias_regularization=dict( + field="opts.biasreg", + ), + clean_masks=dict( + field="output.cleanup", + ), + csf_output_type=dict( + field="output.CSF", + ), + data=dict( + copyfile=False, + field="data", + mandatory=True, + ), + gaussians_per_class=dict( + field="opts.ngaus", + ), + gm_output_type=dict( + field="output.GM", + ), + mask_image=dict( + extensions=None, + field="opts.msk", + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), - sampling_distance=dict(field="opts.samp",), - save_bias_corrected=dict(field="output.biascor",), - tissue_prob_maps=dict(field="opts.tpm",), + sampling_distance=dict( + field="opts.samp", + ), + save_bias_corrected=dict( + field="output.biascor", + ), + tissue_prob_maps=dict( + field="opts.tpm", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), - warp_frequency_cutoff=dict(field="opts.warpco",), - warping_regularization=dict(field="opts.warpreg",), - wm_output_type=dict(field="output.WM",), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + warp_frequency_cutoff=dict( + field="opts.warpco", + ), + warping_regularization=dict( + field="opts.warpreg", + ), + wm_output_type=dict( + field="output.WM", + ), ) inputs = Segment.input_spec() @@ -34,21 +72,47 @@ def test_Segment_inputs(): def test_Segment_outputs(): output_map = dict( - bias_corrected_image=dict(extensions=None,), - inverse_transformation_mat=dict(extensions=None,), - modulated_csf_image=dict(extensions=None,), - modulated_gm_image=dict(extensions=None,), + bias_corrected_image=dict( + extensions=None, + ), + inverse_transformation_mat=dict( + extensions=None, + ), + modulated_csf_image=dict( + extensions=None, + ), + modulated_gm_image=dict( + extensions=None, + ), modulated_input_image=dict( - deprecated="0.10", extensions=None, new_name="bias_corrected_image", - ), - modulated_wm_image=dict(extensions=None,), - native_csf_image=dict(extensions=None,), - native_gm_image=dict(extensions=None,), - native_wm_image=dict(extensions=None,), - normalized_csf_image=dict(extensions=None,), - normalized_gm_image=dict(extensions=None,), - normalized_wm_image=dict(extensions=None,), - transformation_mat=dict(extensions=None,), + deprecated="0.10", + extensions=None, + new_name="bias_corrected_image", + ), + modulated_wm_image=dict( + extensions=None, + ), + native_csf_image=dict( + extensions=None, + ), + native_gm_image=dict( + extensions=None, + ), + native_wm_image=dict( + extensions=None, + ), + normalized_csf_image=dict( + extensions=None, + ), + normalized_gm_image=dict( + extensions=None, + ), + normalized_wm_image=dict( + extensions=None, + ), + transformation_mat=dict( + extensions=None, + ), ) outputs = Segment.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_SliceTiming.py b/nipype/interfaces/spm/tests/test_auto_SliceTiming.py index 8c99e4c4e3..85ddf03c52 100644 --- a/nipype/interfaces/spm/tests/test_auto_SliceTiming.py +++ b/nipype/interfaces/spm/tests/test_auto_SliceTiming.py @@ -4,18 +4,45 @@ def test_SliceTiming_inputs(): input_map = dict( - in_files=dict(copyfile=False, field="scans", mandatory=True,), + in_files=dict( + copyfile=False, + field="scans", + mandatory=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - num_slices=dict(field="nslices", mandatory=True,), - out_prefix=dict(field="prefix", usedefault=True,), + mfile=dict( + usedefault=True, + ), + num_slices=dict( + field="nslices", + mandatory=True, + ), + out_prefix=dict( + field="prefix", + usedefault=True, + ), paths=dict(), - ref_slice=dict(field="refslice", mandatory=True,), - slice_order=dict(field="so", mandatory=True,), - time_acquisition=dict(field="ta", mandatory=True,), - time_repetition=dict(field="tr", mandatory=True,), + ref_slice=dict( + field="refslice", + mandatory=True, + ), + slice_order=dict( + field="so", + mandatory=True, + ), + time_acquisition=dict( + field="ta", + mandatory=True, + ), + time_repetition=dict( + field="tr", + mandatory=True, + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = SliceTiming.input_spec() @@ -25,7 +52,9 @@ def test_SliceTiming_inputs(): def test_SliceTiming_outputs(): - output_map = dict(timecorrected_files=dict(),) + output_map = dict( + timecorrected_files=dict(), + ) outputs = SliceTiming.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Smooth.py b/nipype/interfaces/spm/tests/test_auto_Smooth.py index 4e0025a292..5ed7aa57c0 100644 --- a/nipype/interfaces/spm/tests/test_auto_Smooth.py +++ b/nipype/interfaces/spm/tests/test_auto_Smooth.py @@ -4,16 +4,34 @@ def test_Smooth_inputs(): input_map = dict( - data_type=dict(field="dtype",), - fwhm=dict(field="fwhm",), - implicit_masking=dict(field="im",), - in_files=dict(copyfile=False, field="data", mandatory=True,), + data_type=dict( + field="dtype", + ), + fwhm=dict( + field="fwhm", + ), + implicit_masking=dict( + field="im", + ), + in_files=dict( + copyfile=False, + field="data", + mandatory=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - out_prefix=dict(field="prefix", usedefault=True,), + mfile=dict( + usedefault=True, + ), + out_prefix=dict( + field="prefix", + usedefault=True, + ), paths=dict(), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = Smooth.input_spec() @@ -23,7 +41,9 @@ def test_Smooth_inputs(): def test_Smooth_outputs(): - output_map = dict(smoothed_files=dict(),) + output_map = dict( + smoothed_files=dict(), + ) outputs = Smooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_Threshold.py b/nipype/interfaces/spm/tests/test_auto_Threshold.py index 75fcbf06e2..128ab0586c 100644 --- a/nipype/interfaces/spm/tests/test_auto_Threshold.py +++ b/nipype/interfaces/spm/tests/test_auto_Threshold.py @@ -4,21 +4,53 @@ def test_Threshold_inputs(): input_map = dict( - contrast_index=dict(mandatory=True,), - extent_fdr_p_threshold=dict(usedefault=True,), - extent_threshold=dict(usedefault=True,), - force_activation=dict(usedefault=True,), - height_threshold=dict(usedefault=True,), - height_threshold_type=dict(usedefault=True,), + contrast_index=dict( + mandatory=True, + ), + extent_fdr_p_threshold=dict( + usedefault=True, + ), + extent_threshold=dict( + usedefault=True, + ), + force_activation=dict( + usedefault=True, + ), + height_threshold=dict( + usedefault=True, + ), + height_threshold_type=dict( + usedefault=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), - spm_mat_file=dict(copyfile=True, extensions=None, mandatory=True,), - stat_image=dict(copyfile=False, extensions=None, mandatory=True,), - use_fwe_correction=dict(usedefault=True,), + spm_mat_file=dict( + copyfile=True, + extensions=None, + mandatory=True, + ), + stat_image=dict( + copyfile=False, + extensions=None, + mandatory=True, + ), + use_fwe_correction=dict( + usedefault=True, + ), use_mcr=dict(), - use_topo_fdr=dict(usedefault=True,), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_topo_fdr=dict( + usedefault=True, + ), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + use_vox_fdr_correction=dict( + usedefault=True, + ), ) inputs = Threshold.input_spec() @@ -32,9 +64,13 @@ def test_Threshold_outputs(): activation_forced=dict(), cluster_forming_thr=dict(), n_clusters=dict(), - pre_topo_fdr_map=dict(extensions=None,), + pre_topo_fdr_map=dict( + extensions=None, + ), pre_topo_n_clusters=dict(), - thresholded_map=dict(extensions=None,), + thresholded_map=dict( + extensions=None, + ), ) outputs = Threshold.output_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_ThresholdStatistics.py b/nipype/interfaces/spm/tests/test_auto_ThresholdStatistics.py index c654be7b3d..89c5a42e57 100644 --- a/nipype/interfaces/spm/tests/test_auto_ThresholdStatistics.py +++ b/nipype/interfaces/spm/tests/test_auto_ThresholdStatistics.py @@ -4,16 +4,35 @@ def test_ThresholdStatistics_inputs(): input_map = dict( - contrast_index=dict(mandatory=True,), - extent_threshold=dict(usedefault=True,), - height_threshold=dict(mandatory=True,), + contrast_index=dict( + mandatory=True, + ), + extent_threshold=dict( + usedefault=True, + ), + height_threshold=dict( + mandatory=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), + mfile=dict( + usedefault=True, + ), paths=dict(), - spm_mat_file=dict(copyfile=True, extensions=None, mandatory=True,), - stat_image=dict(copyfile=False, extensions=None, mandatory=True,), + spm_mat_file=dict( + copyfile=True, + extensions=None, + mandatory=True, + ), + stat_image=dict( + copyfile=False, + extensions=None, + mandatory=True, + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = ThresholdStatistics.input_spec() diff --git a/nipype/interfaces/spm/tests/test_auto_TwoSampleTTestDesign.py b/nipype/interfaces/spm/tests/test_auto_TwoSampleTTestDesign.py index fa0cc9e331..fd03e6c867 100644 --- a/nipype/interfaces/spm/tests/test_auto_TwoSampleTTestDesign.py +++ b/nipype/interfaces/spm/tests/test_auto_TwoSampleTTestDesign.py @@ -4,27 +4,50 @@ def test_TwoSampleTTestDesign_inputs(): input_map = dict( - covariates=dict(field="cov",), - dependent=dict(field="des.t2.dept",), - explicit_mask_file=dict(extensions=None, field="masking.em",), + covariates=dict( + field="cov", + ), + dependent=dict( + field="des.t2.dept", + ), + explicit_mask_file=dict( + extensions=None, + field="masking.em", + ), global_calc_mean=dict( - field="globalc.g_mean", xor=["global_calc_omit", "global_calc_values"], + field="globalc.g_mean", + xor=["global_calc_omit", "global_calc_values"], ), global_calc_omit=dict( - field="globalc.g_omit", xor=["global_calc_mean", "global_calc_values"], + field="globalc.g_omit", + xor=["global_calc_mean", "global_calc_values"], ), global_calc_values=dict( field="globalc.g_user.global_uval", xor=["global_calc_mean", "global_calc_omit"], ), - global_normalization=dict(field="globalm.glonorm",), - group1_files=dict(field="des.t2.scans1", mandatory=True,), - group2_files=dict(field="des.t2.scans2", mandatory=True,), + global_normalization=dict( + field="globalm.glonorm", + ), + group1_files=dict( + field="des.t2.scans1", + mandatory=True, + ), + group2_files=dict( + field="des.t2.scans2", + mandatory=True, + ), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - no_grand_mean_scaling=dict(field="globalm.gmsca.gmsca_no",), + mfile=dict( + usedefault=True, + ), + no_grand_mean_scaling=dict( + field="globalm.gmsca.gmsca_no", + ), paths=dict(), - spm_mat_dir=dict(field="dir",), + spm_mat_dir=dict( + field="dir", + ), threshold_mask_absolute=dict( field="masking.tm.tma.athresh", xor=["threshold_mask_none", "threshold_mask_relative"], @@ -37,10 +60,17 @@ def test_TwoSampleTTestDesign_inputs(): field="masking.tm.tmr.rthresh", xor=["threshold_mask_absolute", "threshold_mask_none"], ), - unequal_variance=dict(field="des.t2.variance",), - use_implicit_threshold=dict(field="masking.im",), + unequal_variance=dict( + field="des.t2.variance", + ), + use_implicit_threshold=dict( + field="masking.im", + ), use_mcr=dict(), - use_v8struct=dict(min_ver="8", usedefault=True,), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), ) inputs = TwoSampleTTestDesign.input_spec() @@ -50,7 +80,11 @@ def test_TwoSampleTTestDesign_inputs(): def test_TwoSampleTTestDesign_outputs(): - output_map = dict(spm_mat_file=dict(extensions=None,),) + output_map = dict( + spm_mat_file=dict( + extensions=None, + ), + ) outputs = TwoSampleTTestDesign.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/spm/tests/test_auto_VBMSegment.py b/nipype/interfaces/spm/tests/test_auto_VBMSegment.py index 626ce9893f..4bc4664c27 100644 --- a/nipype/interfaces/spm/tests/test_auto_VBMSegment.py +++ b/nipype/interfaces/spm/tests/test_auto_VBMSegment.py @@ -5,64 +5,146 @@ def test_VBMSegment_inputs(): input_map = dict( bias_corrected_affine=dict( - field="estwrite.output.bias.affine", usedefault=True, + field="estwrite.output.bias.affine", + usedefault=True, ), bias_corrected_native=dict( - field="estwrite.output.bias.native", usedefault=True, + field="estwrite.output.bias.native", + usedefault=True, ), bias_corrected_normalized=dict( - field="estwrite.output.bias.warped", usedefault=True, + field="estwrite.output.bias.warped", + usedefault=True, + ), + bias_fwhm=dict( + field="estwrite.opts.biasfwhm", + usedefault=True, + ), + bias_regularization=dict( + field="estwrite.opts.biasreg", + usedefault=True, + ), + cleanup_partitions=dict( + field="estwrite.extopts.cleanup", + usedefault=True, + ), + csf_dartel=dict( + field="estwrite.output.CSF.dartel", + usedefault=True, ), - bias_fwhm=dict(field="estwrite.opts.biasfwhm", usedefault=True,), - bias_regularization=dict(field="estwrite.opts.biasreg", usedefault=True,), - cleanup_partitions=dict(field="estwrite.extopts.cleanup", usedefault=True,), - csf_dartel=dict(field="estwrite.output.CSF.dartel", usedefault=True,), csf_modulated_normalized=dict( - field="estwrite.output.CSF.modulated", usedefault=True, + field="estwrite.output.CSF.modulated", + usedefault=True, + ), + csf_native=dict( + field="estwrite.output.CSF.native", + usedefault=True, + ), + csf_normalized=dict( + field="estwrite.output.CSF.warped", + usedefault=True, ), - csf_native=dict(field="estwrite.output.CSF.native", usedefault=True,), - csf_normalized=dict(field="estwrite.output.CSF.warped", usedefault=True,), dartel_template=dict( extensions=[".hdr", ".img", ".img.gz", ".nii"], field="estwrite.extopts.dartelwarp.normhigh.darteltpm", ), - deformation_field=dict(field="estwrite.output.warps", usedefault=True,), - display_results=dict(field="estwrite.extopts.print", usedefault=True,), - gaussians_per_class=dict(usedefault=True,), - gm_dartel=dict(field="estwrite.output.GM.dartel", usedefault=True,), + deformation_field=dict( + field="estwrite.output.warps", + usedefault=True, + ), + display_results=dict( + field="estwrite.extopts.print", + usedefault=True, + ), + gaussians_per_class=dict( + usedefault=True, + ), + gm_dartel=dict( + field="estwrite.output.GM.dartel", + usedefault=True, + ), gm_modulated_normalized=dict( - field="estwrite.output.GM.modulated", usedefault=True, + field="estwrite.output.GM.modulated", + usedefault=True, + ), + gm_native=dict( + field="estwrite.output.GM.native", + usedefault=True, + ), + gm_normalized=dict( + field="estwrite.output.GM.warped", + usedefault=True, + ), + in_files=dict( + copyfile=False, + field="estwrite.data", + mandatory=True, + ), + jacobian_determinant=dict( + field="estwrite.jacobian.warped", + usedefault=True, ), - gm_native=dict(field="estwrite.output.GM.native", usedefault=True,), - gm_normalized=dict(field="estwrite.output.GM.warped", usedefault=True,), - in_files=dict(copyfile=False, field="estwrite.data", mandatory=True,), - jacobian_determinant=dict(field="estwrite.jacobian.warped", usedefault=True,), matlab_cmd=dict(), - mfile=dict(usedefault=True,), - mrf_weighting=dict(field="estwrite.extopts.mrf", usedefault=True,), + mfile=dict( + usedefault=True, + ), + mrf_weighting=dict( + field="estwrite.extopts.mrf", + usedefault=True, + ), paths=dict(), - pve_label_dartel=dict(field="estwrite.output.label.dartel", usedefault=True,), - pve_label_native=dict(field="estwrite.output.label.native", usedefault=True,), + pve_label_dartel=dict( + field="estwrite.output.label.dartel", + usedefault=True, + ), + pve_label_native=dict( + field="estwrite.output.label.native", + usedefault=True, + ), pve_label_normalized=dict( - field="estwrite.output.label.warped", usedefault=True, + field="estwrite.output.label.warped", + usedefault=True, + ), + sampling_distance=dict( + field="estwrite.opts.samp", + usedefault=True, + ), + spatial_normalization=dict( + usedefault=True, ), - sampling_distance=dict(field="estwrite.opts.samp", usedefault=True,), - spatial_normalization=dict(usedefault=True,), tissues=dict( - extensions=[".hdr", ".img", ".img.gz", ".nii"], field="estwrite.tpm", + extensions=[".hdr", ".img", ".img.gz", ".nii"], + field="estwrite.tpm", ), use_mcr=dict(), use_sanlm_denoising_filter=dict( - field="estwrite.extopts.sanlm", usedefault=True, + field="estwrite.extopts.sanlm", + usedefault=True, + ), + use_v8struct=dict( + min_ver="8", + usedefault=True, + ), + warping_regularization=dict( + field="estwrite.opts.warpreg", + usedefault=True, + ), + wm_dartel=dict( + field="estwrite.output.WM.dartel", + usedefault=True, ), - use_v8struct=dict(min_ver="8", usedefault=True,), - warping_regularization=dict(field="estwrite.opts.warpreg", usedefault=True,), - wm_dartel=dict(field="estwrite.output.WM.dartel", usedefault=True,), wm_modulated_normalized=dict( - field="estwrite.output.WM.modulated", usedefault=True, + field="estwrite.output.WM.modulated", + usedefault=True, + ), + wm_native=dict( + field="estwrite.output.WM.native", + usedefault=True, + ), + wm_normalized=dict( + field="estwrite.output.WM.warped", + usedefault=True, ), - wm_native=dict(field="estwrite.output.WM.native", usedefault=True,), - wm_normalized=dict(field="estwrite.output.WM.warped", usedefault=True,), ) inputs = VBMSegment.input_spec() diff --git a/nipype/interfaces/spm/tests/test_base.py b/nipype/interfaces/spm/tests/test_base.py index c2c991d742..1f653c0a86 100644 --- a/nipype/interfaces/spm/tests/test_base.py +++ b/nipype/interfaces/spm/tests/test_base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os diff --git a/nipype/interfaces/spm/tests/test_model.py b/nipype/interfaces/spm/tests/test_model.py index a960d06fb8..fd9a0236d7 100644 --- a/nipype/interfaces/spm/tests/test_model.py +++ b/nipype/interfaces/spm/tests/test_model.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os diff --git a/nipype/interfaces/spm/tests/test_preprocess.py b/nipype/interfaces/spm/tests/test_preprocess.py index de5c79caba..74608749ec 100644 --- a/nipype/interfaces/spm/tests/test_preprocess.py +++ b/nipype/interfaces/spm/tests/test_preprocess.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os diff --git a/nipype/interfaces/spm/tests/test_utils.py b/nipype/interfaces/spm/tests/test_utils.py index 1afc887b06..83a9b1e43e 100644 --- a/nipype/interfaces/spm/tests/test_utils.py +++ b/nipype/interfaces/spm/tests/test_utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -21,9 +20,9 @@ def test_coreg(): assert not isdefined(coreg.inputs.mat) pth, mov, _ = split_filename(moving) _, tgt, _ = split_filename(target) - mat = os.path.join(pth, "%s_to_%s.mat" % (mov, tgt)) + mat = os.path.join(pth, f"{mov}_to_{tgt}.mat") invmat = fname_presuffix(mat, prefix="inverse_") - scrpt = coreg._make_matlab_command(None) + script = coreg._make_matlab_command(None) assert coreg.inputs.mat == mat assert coreg.inputs.invmat == invmat @@ -35,11 +34,11 @@ def test_apply_transform(): assert applymat.inputs.matlab_cmd == "mymatlab" applymat.inputs.in_file = moving applymat.inputs.mat = mat - scrpt = applymat._make_matlab_command(None) + script = applymat._make_matlab_command(None) expected = "[p n e v] = spm_fileparts(V.fname);" - assert expected in scrpt + assert expected in script expected = "V.mat = transform.M * V.mat;" - assert expected in scrpt + assert expected in script def test_reslice(): diff --git a/nipype/interfaces/spm/utils.py b/nipype/interfaces/spm/utils.py index 99e3d57d3b..76944893e1 100644 --- a/nipype/interfaces/spm/utils.py +++ b/nipype/interfaces/spm/utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -24,7 +23,6 @@ class Analyze2niiOutputSpec(SPMCommandInputSpec): class Analyze2nii(SPMCommand): - input_spec = Analyze2niiInputSpec output_spec = Analyze2niiOutputSpec @@ -52,7 +50,7 @@ class CalcCoregAffineInputSpec(SPMCommandInputSpec): exists=True, mandatory=True, copyfile=False, - desc=("volume transform can be applied to register with " "target"), + desc=("volume transform can be applied to register with target"), ) mat = File(desc="Filename used to store affine matrix") invmat = File(desc="Filename used to store inverse affine matrix") @@ -64,7 +62,7 @@ class CalcCoregAffineOutputSpec(TraitedSpec): class CalcCoregAffine(SPMCommand): - """ Uses SPM (spm_coreg) to calculate the transform mapping + """Uses SPM (spm_coreg) to calculate the transform mapping moving to target. Saves Transform in mat (matlab binary file) Also saves inverse transform @@ -90,15 +88,15 @@ class CalcCoregAffine(SPMCommand): output_spec = CalcCoregAffineOutputSpec def _make_inv_file(self): - """ makes filename to hold inverse transform if not specified""" + """makes filename to hold inverse transform if not specified""" invmat = fname_presuffix(self.inputs.mat, prefix="inverse_") return invmat def _make_mat_file(self): - """ makes name for matfile if doesn exist""" + """makes name for matfile if doesn exist""" pth, mv, _ = split_filename(self.inputs.moving) _, tgt, _ = split_filename(self.inputs.target) - mat = os.path.join(pth, "%s_to_%s.mat" % (mv, tgt)) + mat = os.path.join(pth, f"{mv}_to_{tgt}.mat") return mat def _make_matlab_command(self, _): @@ -108,16 +106,16 @@ def _make_matlab_command(self, _): if not isdefined(self.inputs.invmat): self.inputs.invmat = self._make_inv_file() script = """ - target = '%s'; - moving = '%s'; + target = '{}'; + moving = '{}'; targetv = spm_vol(target); movingv = spm_vol(moving); x = spm_coreg(targetv, movingv); M = spm_matrix(x); - save('%s' , 'M' ); + save('{}' , 'M' ); M = inv(M); - save('%s','M') - """ % ( + save('{}','M') + """.format( self.inputs.target, self.inputs.moving, self.inputs.mat, @@ -148,7 +146,7 @@ class ApplyTransformOutputSpec(TraitedSpec): class ApplyTransform(SPMCommand): - """ Uses SPM to apply transform stored in a .mat file to given file + """Uses SPM to apply transform stored in a .mat file to given file Examples -------- @@ -169,9 +167,9 @@ def _make_matlab_command(self, _): outputs = self._list_outputs() self.inputs.out_file = outputs["out_file"] script = """ - infile = '%s'; - outfile = '%s' - transform = load('%s'); + infile = '{}'; + outfile = '{}' + transform = load('{}'); V = spm_vol(infile); X = spm_read_vols(V); @@ -180,7 +178,7 @@ def _make_matlab_command(self, _): V.fname = fullfile(outfile); spm_write_vol(V,X); - """ % ( + """.format( self.inputs.in_file, self.inputs.out_file, self.inputs.mat, @@ -228,13 +226,13 @@ class ResliceOutputSpec(TraitedSpec): class Reslice(SPMCommand): - """ uses spm_reslice to resample in_file into space of space_defining""" + """uses spm_reslice to resample in_file into space of space_defining""" input_spec = ResliceInputSpec output_spec = ResliceOutputSpec def _make_matlab_command(self, _): - """ generates script""" + """generates script""" if not isdefined(self.inputs.out_file): self.inputs.out_file = fname_presuffix(self.inputs.in_file, prefix="r") script = """ @@ -305,7 +303,7 @@ class ApplyInverseDeformationOutput(TraitedSpec): class ApplyInverseDeformation(SPMCommand): - """ Uses spm to apply inverse deformation stored in a .mat file or a + """Uses spm to apply inverse deformation stored in a .mat file or a deformation field to a given file Examples @@ -326,8 +324,7 @@ class ApplyInverseDeformation(SPMCommand): _jobname = "defs" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "in_files": return scans_for_fnames(ensure_list(val)) if opt == "target": @@ -402,8 +399,7 @@ class ResliceToReference(SPMCommand): _jobname = "defs" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "in_files": return scans_for_fnames(ensure_list(val)) if opt == "target": @@ -466,7 +462,7 @@ class DicomImportOutputSpec(TraitedSpec): class DicomImport(SPMCommand): - """ Uses spm to convert DICOM files to nii or img+hdr. + """Uses spm to convert DICOM files to nii or img+hdr. Examples -------- @@ -484,8 +480,7 @@ class DicomImport(SPMCommand): _jobname = "dicom" def _format_arg(self, opt, spec, val): - """Convert input to appropriate format for spm - """ + """Convert input to appropriate format for spm""" if opt == "in_files": return np.array(val, dtype=object) if opt == "output_dir": @@ -496,13 +491,13 @@ def _format_arg(self, opt, spec, val): if val: return 1 return 0 - return super(DicomImport, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _run_interface(self, runtime): od = os.path.abspath(self.inputs.output_dir) if not os.path.isdir(od): os.mkdir(od) - return super(DicomImport, self)._run_interface(runtime) + return super()._run_interface(runtime) def _list_outputs(self): from glob import glob diff --git a/nipype/interfaces/tests/__init__.py b/nipype/interfaces/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/tests/__init__.py +++ b/nipype/interfaces/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/tests/test_auto_BIDSDataGrabber.py b/nipype/interfaces/tests/test_auto_BIDSDataGrabber.py index 0263177c5e..c2a899958c 100644 --- a/nipype/interfaces/tests/test_auto_BIDSDataGrabber.py +++ b/nipype/interfaces/tests/test_auto_BIDSDataGrabber.py @@ -4,11 +4,21 @@ def test_BIDSDataGrabber_inputs(): input_map = dict( - base_dir=dict(mandatory=True,), + base_dir=dict( + mandatory=True, + ), extra_derivatives=dict(), - index_derivatives=dict(mandatory=True, usedefault=True,), + index_derivatives=dict( + mandatory=True, + usedefault=True, + ), + load_layout=dict( + mandatory=False, + ), output_query=dict(), - raise_on_empty=dict(usedefault=True,), + raise_on_empty=dict( + usedefault=True, + ), ) inputs = BIDSDataGrabber.input_spec() diff --git a/nipype/interfaces/tests/test_auto_Bru2.py b/nipype/interfaces/tests/test_auto_Bru2.py index 5256b2732f..7935d2fc97 100644 --- a/nipype/interfaces/tests/test_auto_Bru2.py +++ b/nipype/interfaces/tests/test_auto_Bru2.py @@ -4,14 +4,34 @@ def test_Bru2_inputs(): input_map = dict( - actual_size=dict(argstr="-a",), - append_protocol_name=dict(argstr="-p",), - args=dict(argstr="%s",), - compress=dict(argstr="-z",), - environ=dict(nohash=True, usedefault=True,), - force_conversion=dict(argstr="-f",), - input_dir=dict(argstr="%s", mandatory=True, position=-1,), - output_filename=dict(argstr="-o %s", genfile=True,), + actual_size=dict( + argstr="-a", + ), + append_protocol_name=dict( + argstr="-p", + ), + args=dict( + argstr="%s", + ), + compress=dict( + argstr="-z", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + force_conversion=dict( + argstr="-f", + ), + input_dir=dict( + argstr="%s", + mandatory=True, + position=-1, + ), + output_filename=dict( + argstr="-o %s", + genfile=True, + ), ) inputs = Bru2.input_spec() @@ -21,7 +41,11 @@ def test_Bru2_inputs(): def test_Bru2_outputs(): - output_map = dict(nii_file=dict(extensions=None,),) + output_map = dict( + nii_file=dict( + extensions=None, + ), + ) outputs = Bru2.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_C3d.py b/nipype/interfaces/tests/test_auto_C3d.py index d55216b454..d4d26e8264 100644 --- a/nipype/interfaces/tests/test_auto_C3d.py +++ b/nipype/interfaces/tests/test_auto_C3d.py @@ -4,19 +4,55 @@ def test_C3d_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", mandatory=True, position=1,), - interp=dict(argstr="-interpolation %s",), - is_4d=dict(usedefault=True,), - multicomp_split=dict(argstr="-mcr", position=0, usedefault=True,), - out_file=dict(argstr="-o %s", extensions=None, position=-1, xor=["out_files"],), - out_files=dict(argstr="-oo %s", position=-1, xor=["out_file"],), - pix_type=dict(argstr="-type %s",), - resample=dict(argstr="-resample %s",), - scale=dict(argstr="-scale %s",), - shift=dict(argstr="-shift %s",), - smooth=dict(argstr="-smooth %s",), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + mandatory=True, + position=1, + ), + interp=dict( + argstr="-interpolation %s", + ), + is_4d=dict( + usedefault=True, + ), + multicomp_split=dict( + argstr="-mcr", + position=0, + usedefault=True, + ), + out_file=dict( + argstr="-o %s", + extensions=None, + position=-1, + xor=["out_files"], + ), + out_files=dict( + argstr="-oo %s", + position=-1, + xor=["out_file"], + ), + pix_type=dict( + argstr="-type %s", + ), + resample=dict( + argstr="-resample %s", + ), + scale=dict( + argstr="-scale %s", + ), + shift=dict( + argstr="-shift %s", + ), + smooth=dict( + argstr="-smooth %s", + ), ) inputs = C3d.input_spec() @@ -26,7 +62,9 @@ def test_C3d_inputs(): def test_C3d_outputs(): - output_map = dict(out_files=dict(),) + output_map = dict( + out_files=dict(), + ) outputs = C3d.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_C3dAffineTool.py b/nipype/interfaces/tests/test_auto_C3dAffineTool.py index 963d2f7931..153f6090a7 100644 --- a/nipype/interfaces/tests/test_auto_C3dAffineTool.py +++ b/nipype/interfaces/tests/test_auto_C3dAffineTool.py @@ -4,13 +4,37 @@ def test_C3dAffineTool_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - fsl2ras=dict(argstr="-fsl2ras", position=4,), - itk_transform=dict(argstr="-oitk %s", hash_files=False, position=5,), - reference_file=dict(argstr="-ref %s", extensions=None, position=1,), - source_file=dict(argstr="-src %s", extensions=None, position=2,), - transform_file=dict(argstr="%s", extensions=None, position=3,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fsl2ras=dict( + argstr="-fsl2ras", + position=4, + ), + itk_transform=dict( + argstr="-oitk %s", + hash_files=False, + position=5, + ), + reference_file=dict( + argstr="-ref %s", + extensions=None, + position=1, + ), + source_file=dict( + argstr="-src %s", + extensions=None, + position=2, + ), + transform_file=dict( + argstr="%s", + extensions=None, + position=3, + ), ) inputs = C3dAffineTool.input_spec() @@ -20,7 +44,11 @@ def test_C3dAffineTool_inputs(): def test_C3dAffineTool_outputs(): - output_map = dict(itk_transform=dict(extensions=None,),) + output_map = dict( + itk_transform=dict( + extensions=None, + ), + ) outputs = C3dAffineTool.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_CopyMeta.py b/nipype/interfaces/tests/test_auto_CopyMeta.py index 6415514c3d..f7a554226e 100644 --- a/nipype/interfaces/tests/test_auto_CopyMeta.py +++ b/nipype/interfaces/tests/test_auto_CopyMeta.py @@ -4,10 +4,16 @@ def test_CopyMeta_inputs(): input_map = dict( - dest_file=dict(extensions=None, mandatory=True,), + dest_file=dict( + extensions=None, + mandatory=True, + ), exclude_classes=dict(), include_classes=dict(), - src_file=dict(extensions=None, mandatory=True,), + src_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = CopyMeta.input_spec() @@ -17,7 +23,11 @@ def test_CopyMeta_inputs(): def test_CopyMeta_outputs(): - output_map = dict(dest_file=dict(extensions=None,),) + output_map = dict( + dest_file=dict( + extensions=None, + ), + ) outputs = CopyMeta.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_DataFinder.py b/nipype/interfaces/tests/test_auto_DataFinder.py index 81cdc92ac8..e1f24b3517 100644 --- a/nipype/interfaces/tests/test_auto_DataFinder.py +++ b/nipype/interfaces/tests/test_auto_DataFinder.py @@ -5,11 +5,17 @@ def test_DataFinder_inputs(): input_map = dict( ignore_regexes=dict(), - match_regex=dict(usedefault=True,), + match_regex=dict( + usedefault=True, + ), max_depth=dict(), min_depth=dict(), - root_paths=dict(mandatory=True,), - unpack_single=dict(usedefault=True,), + root_paths=dict( + mandatory=True, + ), + unpack_single=dict( + usedefault=True, + ), ) inputs = DataFinder.input_spec() diff --git a/nipype/interfaces/tests/test_auto_DataGrabber.py b/nipype/interfaces/tests/test_auto_DataGrabber.py index c3817e43e7..a58e4dd434 100644 --- a/nipype/interfaces/tests/test_auto_DataGrabber.py +++ b/nipype/interfaces/tests/test_auto_DataGrabber.py @@ -5,10 +5,18 @@ def test_DataGrabber_inputs(): input_map = dict( base_directory=dict(), - drop_blank_outputs=dict(usedefault=True,), - raise_on_empty=dict(usedefault=True,), - sort_filelist=dict(mandatory=True,), - template=dict(mandatory=True,), + drop_blank_outputs=dict( + usedefault=True, + ), + raise_on_empty=dict( + usedefault=True, + ), + sort_filelist=dict( + mandatory=True, + ), + template=dict( + mandatory=True, + ), template_args=dict(), ) inputs = DataGrabber.input_spec() diff --git a/nipype/interfaces/tests/test_auto_DataSink.py b/nipype/interfaces/tests/test_auto_DataSink.py index 870dbc3c85..1ce4183b70 100644 --- a/nipype/interfaces/tests/test_auto_DataSink.py +++ b/nipype/interfaces/tests/test_auto_DataSink.py @@ -4,16 +4,22 @@ def test_DataSink_inputs(): input_map = dict( - _outputs=dict(usedefault=True,), + _outputs=dict( + usedefault=True, + ), base_directory=dict(), bucket=dict(), container=dict(), creds_path=dict(), encrypt_bucket_keys=dict(), local_copy=dict(), - parameterization=dict(usedefault=True,), + parameterization=dict( + usedefault=True, + ), regexp_substitutions=dict(), - remove_dest_dir=dict(usedefault=True,), + remove_dest_dir=dict( + usedefault=True, + ), strip_dir=dict(), substitutions=dict(), ) @@ -25,7 +31,9 @@ def test_DataSink_inputs(): def test_DataSink_outputs(): - output_map = dict(out_file=dict(),) + output_map = dict( + out_file=dict(), + ) outputs = DataSink.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_Dcm2nii.py b/nipype/interfaces/tests/test_auto_Dcm2nii.py index 9aca885a64..948aafa083 100644 --- a/nipype/interfaces/tests/test_auto_Dcm2nii.py +++ b/nipype/interfaces/tests/test_auto_Dcm2nii.py @@ -4,25 +4,75 @@ def test_Dcm2nii_inputs(): input_map = dict( - anonymize=dict(argstr="-a", usedefault=True,), - args=dict(argstr="%s",), - collapse_folders=dict(argstr="-c", usedefault=True,), - config_file=dict(argstr="-b %s", extensions=None, genfile=True,), - convert_all_pars=dict(argstr="-v", usedefault=True,), - date_in_filename=dict(argstr="-d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - events_in_filename=dict(argstr="-e", usedefault=True,), - gzip_output=dict(argstr="-g", usedefault=True,), - id_in_filename=dict(argstr="-i", usedefault=True,), - nii_output=dict(argstr="-n", usedefault=True,), - output_dir=dict(argstr="-o %s", genfile=True,), - protocol_in_filename=dict(argstr="-p", usedefault=True,), - reorient=dict(argstr="-r",), - reorient_and_crop=dict(argstr="-x", usedefault=True,), + anonymize=dict( + argstr="-a", + usedefault=True, + ), + args=dict( + argstr="%s", + ), + collapse_folders=dict( + argstr="-c", + usedefault=True, + ), + config_file=dict( + argstr="-b %s", + extensions=None, + genfile=True, + ), + convert_all_pars=dict( + argstr="-v", + usedefault=True, + ), + date_in_filename=dict( + argstr="-d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + events_in_filename=dict( + argstr="-e", + usedefault=True, + ), + gzip_output=dict( + argstr="-g", + usedefault=True, + ), + id_in_filename=dict( + argstr="-i", + usedefault=True, + ), + nii_output=dict( + argstr="-n", + usedefault=True, + ), + output_dir=dict( + argstr="-o %s", + genfile=True, + ), + protocol_in_filename=dict( + argstr="-p", + usedefault=True, + ), + reorient=dict( + argstr="-r", + ), + reorient_and_crop=dict( + argstr="-x", + usedefault=True, + ), source_dir=dict( - argstr="%s", mandatory=True, position=-1, xor=["source_names"], + argstr="%s", + mandatory=True, + position=-1, + xor=["source_names"], + ), + source_in_filename=dict( + argstr="-f", + usedefault=True, ), - source_in_filename=dict(argstr="-f", usedefault=True,), source_names=dict( argstr="%s", copyfile=False, @@ -30,7 +80,10 @@ def test_Dcm2nii_inputs(): position=-1, xor=["source_dir"], ), - spm_analyze=dict(argstr="-s", xor=["nii_output"],), + spm_analyze=dict( + argstr="-s", + xor=["nii_output"], + ), ) inputs = Dcm2nii.input_spec() diff --git a/nipype/interfaces/tests/test_auto_Dcm2niix.py b/nipype/interfaces/tests/test_auto_Dcm2niix.py index dfaa46d36a..3dc69d325f 100644 --- a/nipype/interfaces/tests/test_auto_Dcm2niix.py +++ b/nipype/interfaces/tests/test_auto_Dcm2niix.py @@ -4,24 +4,68 @@ def test_Dcm2niix_inputs(): input_map = dict( - anon_bids=dict(argstr="-ba", requires=["bids_format"],), - args=dict(argstr="%s",), - bids_format=dict(argstr="-b", usedefault=True,), - comment=dict(argstr="-c %s",), - compress=dict(argstr="-z %s", usedefault=True,), - compression=dict(argstr="-%d",), - crop=dict(argstr="-x", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - has_private=dict(argstr="-t", usedefault=True,), - ignore_deriv=dict(argstr="-i",), - merge_imgs=dict(argstr="-m", usedefault=True,), - out_filename=dict(argstr="-f %s",), - output_dir=dict(argstr="-o %s", usedefault=True,), - philips_float=dict(argstr="-p",), - series_numbers=dict(argstr="-n %s...",), - single_file=dict(argstr="-s", usedefault=True,), + anon_bids=dict( + argstr="-ba", + requires=["bids_format"], + ), + args=dict( + argstr="%s", + ), + bids_format=dict( + argstr="-b", + usedefault=True, + ), + comment=dict( + argstr="-c %s", + ), + compress=dict( + argstr="-z %s", + usedefault=True, + ), + compression=dict( + argstr="-%d", + ), + crop=dict( + argstr="-x", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + has_private=dict( + argstr="-t", + usedefault=True, + ), + ignore_deriv=dict( + argstr="-i", + ), + merge_imgs=dict( + argstr="-m %d", + usedefault=True, + ), + out_filename=dict( + argstr="-f %s", + ), + output_dir=dict( + argstr="-o %s", + usedefault=True, + ), + philips_float=dict( + argstr="-p", + ), + series_numbers=dict( + argstr="-n %s...", + ), + single_file=dict( + argstr="-s", + usedefault=True, + ), source_dir=dict( - argstr="%s", mandatory=True, position=-1, xor=["source_names"], + argstr="%s", + mandatory=True, + position=-1, + xor=["source_names"], ), source_names=dict( argstr="%s", @@ -30,8 +74,13 @@ def test_Dcm2niix_inputs(): position=-1, xor=["source_dir"], ), - to_nrrd=dict(argstr="-e",), - verbose=dict(argstr="-v", usedefault=True,), + to_nrrd=dict( + argstr="-e", + ), + verbose=dict( + argstr="-v", + usedefault=True, + ), ) inputs = Dcm2niix.input_spec() @@ -41,7 +90,13 @@ def test_Dcm2niix_inputs(): def test_Dcm2niix_outputs(): - output_map = dict(bids=dict(), bvals=dict(), bvecs=dict(), converted_files=dict(),) + output_map = dict( + bids=dict(), + bvals=dict(), + bvecs=dict(), + converted_files=dict(), + mvecs=dict(), + ) outputs = Dcm2niix.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_DcmStack.py b/nipype/interfaces/tests/test_auto_DcmStack.py index af0ff91495..02bf268904 100644 --- a/nipype/interfaces/tests/test_auto_DcmStack.py +++ b/nipype/interfaces/tests/test_auto_DcmStack.py @@ -4,12 +4,18 @@ def test_DcmStack_inputs(): input_map = dict( - dicom_files=dict(mandatory=True,), + dicom_files=dict( + mandatory=True, + ), embed_meta=dict(), exclude_regexes=dict(), - force_read=dict(usedefault=True,), + force_read=dict( + usedefault=True, + ), include_regexes=dict(), - out_ext=dict(usedefault=True,), + out_ext=dict( + usedefault=True, + ), out_format=dict(), out_path=dict(), ) @@ -21,7 +27,11 @@ def test_DcmStack_inputs(): def test_DcmStack_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = DcmStack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_ExportFile.py b/nipype/interfaces/tests/test_auto_ExportFile.py index 8dd84b29b9..adac52e161 100644 --- a/nipype/interfaces/tests/test_auto_ExportFile.py +++ b/nipype/interfaces/tests/test_auto_ExportFile.py @@ -4,10 +4,18 @@ def test_ExportFile_inputs(): input_map = dict( - check_extension=dict(), + check_extension=dict( + usedefault=True, + ), clobber=dict(), - in_file=dict(extensions=None, mandatory=True,), - out_file=dict(extensions=None, mandatory=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), + out_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = ExportFile.input_spec() @@ -17,7 +25,11 @@ def test_ExportFile_inputs(): def test_ExportFile_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = ExportFile.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_FreeSurferSource.py b/nipype/interfaces/tests/test_auto_FreeSurferSource.py index c7102512ae..875380f75f 100644 --- a/nipype/interfaces/tests/test_auto_FreeSurferSource.py +++ b/nipype/interfaces/tests/test_auto_FreeSurferSource.py @@ -4,9 +4,15 @@ def test_FreeSurferSource_inputs(): input_map = dict( - hemi=dict(usedefault=True,), - subject_id=dict(mandatory=True,), - subjects_dir=dict(mandatory=True,), + hemi=dict( + usedefault=True, + ), + subject_id=dict( + mandatory=True, + ), + subjects_dir=dict( + mandatory=True, + ), ) inputs = FreeSurferSource.input_spec() @@ -17,43 +23,143 @@ def test_FreeSurferSource_inputs(): def test_FreeSurferSource_outputs(): output_map = dict( - BA_stats=dict(altkey="BA", loc="stats",), - T1=dict(extensions=None, loc="mri",), - annot=dict(altkey="*annot", loc="label",), - aparc_a2009s_stats=dict(altkey="aparc.a2009s", loc="stats",), - aparc_aseg=dict(altkey="aparc*aseg", loc="mri",), - aparc_stats=dict(altkey="aparc", loc="stats",), - area_pial=dict(altkey="area.pial", loc="surf",), - aseg=dict(extensions=None, loc="mri",), - aseg_stats=dict(altkey="aseg", loc="stats",), - avg_curv=dict(loc="surf",), - brain=dict(extensions=None, loc="mri",), - brainmask=dict(extensions=None, loc="mri",), - curv=dict(loc="surf",), - curv_pial=dict(altkey="curv.pial", loc="surf",), - curv_stats=dict(altkey="curv", loc="stats",), - entorhinal_exvivo_stats=dict(altkey="entorhinal_exvivo", loc="stats",), - filled=dict(extensions=None, loc="mri",), - graymid=dict(altkey=["graymid", "midthickness"], loc="surf",), - inflated=dict(loc="surf",), - jacobian_white=dict(loc="surf",), - label=dict(altkey="*label", loc="label",), - norm=dict(extensions=None, loc="mri",), - nu=dict(extensions=None, loc="mri",), - orig=dict(extensions=None, loc="mri",), - pial=dict(loc="surf",), - rawavg=dict(extensions=None, loc="mri",), - ribbon=dict(altkey="*ribbon", loc="mri",), - smoothwm=dict(loc="surf",), - sphere=dict(loc="surf",), - sphere_reg=dict(altkey="sphere.reg", loc="surf",), - sulc=dict(loc="surf",), - thickness=dict(loc="surf",), - volume=dict(loc="surf",), - white=dict(loc="surf",), - wm=dict(extensions=None, loc="mri",), - wmparc=dict(extensions=None, loc="mri",), - wmparc_stats=dict(altkey="wmparc", loc="stats",), + BA_stats=dict( + altkey="BA", + loc="stats", + ), + T1=dict( + extensions=None, + loc="mri", + ), + annot=dict( + altkey="*annot", + loc="label", + ), + aparc_a2009s_stats=dict( + altkey="aparc.a2009s", + loc="stats", + ), + aparc_aseg=dict( + altkey="aparc*aseg", + loc="mri", + ), + aparc_stats=dict( + altkey="aparc", + loc="stats", + ), + area_pial=dict( + altkey="area.pial", + loc="surf", + ), + aseg=dict( + extensions=None, + loc="mri", + ), + aseg_stats=dict( + altkey="aseg", + loc="stats", + ), + avg_curv=dict( + loc="surf", + ), + brain=dict( + extensions=None, + loc="mri", + ), + brainmask=dict( + extensions=None, + loc="mri", + ), + curv=dict( + loc="surf", + ), + curv_pial=dict( + altkey="curv.pial", + loc="surf", + ), + curv_stats=dict( + altkey="curv", + loc="stats", + ), + entorhinal_exvivo_stats=dict( + altkey="entorhinal_exvivo", + loc="stats", + ), + filled=dict( + extensions=None, + loc="mri", + ), + graymid=dict( + altkey=["graymid", "midthickness"], + loc="surf", + ), + inflated=dict( + loc="surf", + ), + jacobian_white=dict( + loc="surf", + ), + label=dict( + altkey="*label", + loc="label", + ), + norm=dict( + extensions=None, + loc="mri", + ), + nu=dict( + extensions=None, + loc="mri", + ), + orig=dict( + extensions=None, + loc="mri", + ), + pial=dict( + loc="surf", + ), + rawavg=dict( + extensions=None, + loc="mri", + ), + ribbon=dict( + altkey="*ribbon", + loc="mri", + ), + smoothwm=dict( + loc="surf", + ), + sphere=dict( + loc="surf", + ), + sphere_reg=dict( + altkey="sphere.reg", + loc="surf", + ), + sulc=dict( + loc="surf", + ), + thickness=dict( + loc="surf", + ), + volume=dict( + loc="surf", + ), + white=dict( + loc="surf", + ), + wm=dict( + extensions=None, + loc="mri", + ), + wmparc=dict( + extensions=None, + loc="mri", + ), + wmparc_stats=dict( + altkey="wmparc", + loc="stats", + ), ) outputs = FreeSurferSource.output_spec() diff --git a/nipype/interfaces/tests/test_auto_GroupAndStack.py b/nipype/interfaces/tests/test_auto_GroupAndStack.py index f330efde20..7282e23a8b 100644 --- a/nipype/interfaces/tests/test_auto_GroupAndStack.py +++ b/nipype/interfaces/tests/test_auto_GroupAndStack.py @@ -4,12 +4,18 @@ def test_GroupAndStack_inputs(): input_map = dict( - dicom_files=dict(mandatory=True,), + dicom_files=dict( + mandatory=True, + ), embed_meta=dict(), exclude_regexes=dict(), - force_read=dict(usedefault=True,), + force_read=dict( + usedefault=True, + ), include_regexes=dict(), - out_ext=dict(usedefault=True,), + out_ext=dict( + usedefault=True, + ), out_format=dict(), out_path=dict(), ) @@ -21,7 +27,9 @@ def test_GroupAndStack_inputs(): def test_GroupAndStack_outputs(): - output_map = dict(out_list=dict(),) + output_map = dict( + out_list=dict(), + ) outputs = GroupAndStack.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_JSONFileGrabber.py b/nipype/interfaces/tests/test_auto_JSONFileGrabber.py index c01a584949..6e548f17c1 100644 --- a/nipype/interfaces/tests/test_auto_JSONFileGrabber.py +++ b/nipype/interfaces/tests/test_auto_JSONFileGrabber.py @@ -3,7 +3,12 @@ def test_JSONFileGrabber_inputs(): - input_map = dict(defaults=dict(), in_file=dict(extensions=None,),) + input_map = dict( + defaults=dict(), + in_file=dict( + extensions=None, + ), + ) inputs = JSONFileGrabber.input_spec() for key, metadata in list(input_map.items()): diff --git a/nipype/interfaces/tests/test_auto_JSONFileSink.py b/nipype/interfaces/tests/test_auto_JSONFileSink.py index c88faba852..cdfa32195b 100644 --- a/nipype/interfaces/tests/test_auto_JSONFileSink.py +++ b/nipype/interfaces/tests/test_auto_JSONFileSink.py @@ -4,9 +4,15 @@ def test_JSONFileSink_inputs(): input_map = dict( - _outputs=dict(usedefault=True,), - in_dict=dict(usedefault=True,), - out_file=dict(extensions=None,), + _outputs=dict( + usedefault=True, + ), + in_dict=dict( + usedefault=True, + ), + out_file=dict( + extensions=None, + ), ) inputs = JSONFileSink.input_spec() @@ -16,7 +22,11 @@ def test_JSONFileSink_inputs(): def test_JSONFileSink_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = JSONFileSink.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_LookupMeta.py b/nipype/interfaces/tests/test_auto_LookupMeta.py index fa0129798e..22f6678734 100644 --- a/nipype/interfaces/tests/test_auto_LookupMeta.py +++ b/nipype/interfaces/tests/test_auto_LookupMeta.py @@ -4,7 +4,13 @@ def test_LookupMeta_inputs(): input_map = dict( - in_file=dict(extensions=None, mandatory=True,), meta_keys=dict(mandatory=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), + meta_keys=dict( + mandatory=True, + ), ) inputs = LookupMeta.input_spec() diff --git a/nipype/interfaces/tests/test_auto_MatlabCommand.py b/nipype/interfaces/tests/test_auto_MatlabCommand.py index 0dea244ec8..1dfd9c1dde 100644 --- a/nipype/interfaces/tests/test_auto_MatlabCommand.py +++ b/nipype/interfaces/tests/test_auto_MatlabCommand.py @@ -4,20 +4,53 @@ def test_MatlabCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - logfile=dict(argstr="-logfile %s", extensions=None,), - mfile=dict(usedefault=True,), - nodesktop=dict(argstr="-nodesktop", nohash=True, usedefault=True,), - nosplash=dict(argstr="-nosplash", nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + logfile=dict( + argstr="-logfile %s", + extensions=None, + ), + mfile=dict( + usedefault=True, + ), + nodesktop=dict( + argstr="-nodesktop", + nohash=True, + usedefault=True, + ), + nosplash=dict( + argstr="-nosplash", + nohash=True, + usedefault=True, + ), paths=dict(), - postscript=dict(usedefault=True,), - prescript=dict(usedefault=True,), - script=dict(argstr='-r "%s;exit"', mandatory=True, position=-1,), - script_file=dict(extensions=None, usedefault=True,), - single_comp_thread=dict(argstr="-singleCompThread", nohash=True,), + postscript=dict( + usedefault=True, + ), + prescript=dict( + usedefault=True, + ), + script=dict( + argstr='-r "%s;exit"', + mandatory=True, + position=-1, + ), + script_file=dict( + extensions=None, + usedefault=True, + ), + single_comp_thread=dict( + argstr="-singleCompThread", + nohash=True, + ), uses_mcr=dict( - nohash=True, xor=["nodesktop", "nosplash", "single_comp_thread"], + nohash=True, + xor=["nodesktop", "nosplash", "single_comp_thread"], ), ) inputs = MatlabCommand.input_spec() diff --git a/nipype/interfaces/tests/test_auto_MergeNifti.py b/nipype/interfaces/tests/test_auto_MergeNifti.py index 38c0f39f72..f199fc5da6 100644 --- a/nipype/interfaces/tests/test_auto_MergeNifti.py +++ b/nipype/interfaces/tests/test_auto_MergeNifti.py @@ -4,9 +4,13 @@ def test_MergeNifti_inputs(): input_map = dict( - in_files=dict(mandatory=True,), + in_files=dict( + mandatory=True, + ), merge_dim=dict(), - out_ext=dict(usedefault=True,), + out_ext=dict( + usedefault=True, + ), out_format=dict(), out_path=dict(), sort_order=dict(), @@ -19,7 +23,11 @@ def test_MergeNifti_inputs(): def test_MergeNifti_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = MergeNifti.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_MeshFix.py b/nipype/interfaces/tests/test_auto_MeshFix.py index 9a69fc0859..1ae3b2b67c 100644 --- a/nipype/interfaces/tests/test_auto_MeshFix.py +++ b/nipype/interfaces/tests/test_auto_MeshFix.py @@ -4,18 +4,41 @@ def test_MeshFix_inputs(): input_map = dict( - args=dict(argstr="%s",), - cut_inner=dict(argstr="--cut-inner %d",), - cut_outer=dict(argstr="--cut-outer %d",), - decouple_inin=dict(argstr="--decouple-inin %d",), - decouple_outin=dict(argstr="--decouple-outin %d",), - decouple_outout=dict(argstr="--decouple-outout %d",), - dilation=dict(argstr="--dilate %d",), - dont_clean=dict(argstr="--no-clean",), - environ=dict(nohash=True, usedefault=True,), - epsilon_angle=dict(argstr="-a %f",), + args=dict( + argstr="%s", + ), + cut_inner=dict( + argstr="--cut-inner %d", + ), + cut_outer=dict( + argstr="--cut-outer %d", + ), + decouple_inin=dict( + argstr="--decouple-inin %d", + ), + decouple_outin=dict( + argstr="--decouple-outin %d", + ), + decouple_outout=dict( + argstr="--decouple-outout %d", + ), + dilation=dict( + argstr="--dilate %d", + ), + dont_clean=dict( + argstr="--no-clean", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + epsilon_angle=dict( + argstr="-a %f", + ), finetuning_distance=dict( - argstr="%f", position=-2, requires=["finetuning_substeps"], + argstr="%f", + position=-2, + requires=["finetuning_substeps"], ), finetuning_inwards=dict( argstr="--fineTuneIn ", @@ -29,37 +52,75 @@ def test_MeshFix_inputs(): xor=["finetuning_inwards"], ), finetuning_substeps=dict( - argstr="%d", position=-1, requires=["finetuning_distance"], + argstr="%d", + position=-1, + requires=["finetuning_distance"], + ), + in_file1=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + in_file2=dict( + argstr="%s", + extensions=None, + position=2, + ), + join_closest_components=dict( + argstr="-jc", + xor=["join_closest_components"], ), - in_file1=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - in_file2=dict(argstr="%s", extensions=None, position=2,), - join_closest_components=dict(argstr="-jc", xor=["join_closest_components"],), join_overlapping_largest_components=dict( - argstr="-j", xor=["join_closest_components"], - ), - laplacian_smoothing_steps=dict(argstr="--smooth %d",), - number_of_biggest_shells=dict(argstr="--shells %d",), - out_filename=dict(argstr="-o %s", extensions=None, genfile=True,), - output_type=dict(usedefault=True,), - quiet_mode=dict(argstr="-q",), - remove_handles=dict(argstr="--remove-handles",), + argstr="-j", + xor=["join_closest_components"], + ), + laplacian_smoothing_steps=dict( + argstr="--smooth %d", + ), + number_of_biggest_shells=dict( + argstr="--shells %d", + ), + out_filename=dict( + argstr="-o %s", + extensions=None, + genfile=True, + ), + output_type=dict( + usedefault=True, + ), + quiet_mode=dict( + argstr="-q", + ), + remove_handles=dict( + argstr="--remove-handles", + ), save_as_freesurfer_mesh=dict( - argstr="--fsmesh", xor=["save_as_vrml", "save_as_stl"], + argstr="--fsmesh", + xor=["save_as_vrml", "save_as_stl"], ), save_as_stl=dict( - argstr="--stl", xor=["save_as_vrml", "save_as_freesurfer_mesh"], + argstr="--stl", + xor=["save_as_vrml", "save_as_freesurfer_mesh"], ), save_as_vrml=dict( - argstr="--wrl", xor=["save_as_stl", "save_as_freesurfer_mesh"], + argstr="--wrl", + xor=["save_as_stl", "save_as_freesurfer_mesh"], + ), + set_intersections_to_one=dict( + argstr="--intersect", ), - set_intersections_to_one=dict(argstr="--intersect",), uniform_remeshing_steps=dict( - argstr="-u %d", requires=["uniform_remeshing_vertices"], + argstr="-u %d", + requires=["uniform_remeshing_vertices"], ), uniform_remeshing_vertices=dict( - argstr="--vertices %d", requires=["uniform_remeshing_steps"], + argstr="--vertices %d", + requires=["uniform_remeshing_steps"], + ), + x_shift=dict( + argstr="--smooth %d", ), - x_shift=dict(argstr="--smooth %d",), ) inputs = MeshFix.input_spec() @@ -69,7 +130,11 @@ def test_MeshFix_inputs(): def test_MeshFix_outputs(): - output_map = dict(mesh_file=dict(extensions=None,),) + output_map = dict( + mesh_file=dict( + extensions=None, + ), + ) outputs = MeshFix.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_MySQLSink.py b/nipype/interfaces/tests/test_auto_MySQLSink.py index 30bf18ef26..702a21e9ce 100644 --- a/nipype/interfaces/tests/test_auto_MySQLSink.py +++ b/nipype/interfaces/tests/test_auto_MySQLSink.py @@ -4,8 +4,14 @@ def test_MySQLSink_inputs(): input_map = dict( - config=dict(extensions=None, mandatory=True, xor=["host"],), - database_name=dict(mandatory=True,), + config=dict( + extensions=None, + mandatory=True, + xor=["host"], + ), + database_name=dict( + mandatory=True, + ), host=dict( mandatory=True, requires=["username", "password"], @@ -13,7 +19,9 @@ def test_MySQLSink_inputs(): xor=["config"], ), password=dict(), - table_name=dict(mandatory=True,), + table_name=dict( + mandatory=True, + ), username=dict(), ) inputs = MySQLSink.input_spec() diff --git a/nipype/interfaces/tests/test_auto_PETPVC.py b/nipype/interfaces/tests/test_auto_PETPVC.py index 49ba858e4a..f7da7f45dd 100644 --- a/nipype/interfaces/tests/test_auto_PETPVC.py +++ b/nipype/interfaces/tests/test_auto_PETPVC.py @@ -4,20 +4,65 @@ def test_PETPVC_inputs(): input_map = dict( - alpha=dict(argstr="-a %.4f", usedefault=True,), - args=dict(argstr="%s",), - debug=dict(argstr="-d", usedefault=True,), - environ=dict(nohash=True, usedefault=True,), - fwhm_x=dict(argstr="-x %.4f", mandatory=True,), - fwhm_y=dict(argstr="-y %.4f", mandatory=True,), - fwhm_z=dict(argstr="-z %.4f", mandatory=True,), - in_file=dict(argstr="-i %s", extensions=None, mandatory=True,), - mask_file=dict(argstr="-m %s", extensions=None, mandatory=True,), - n_deconv=dict(argstr="-k %d", usedefault=True,), - n_iter=dict(argstr="-n %d", usedefault=True,), - out_file=dict(argstr="-o %s", extensions=None, genfile=True, hash_files=False,), - pvc=dict(argstr="-p %s", mandatory=True,), - stop_crit=dict(argstr="-s %.4f", usedefault=True,), + alpha=dict( + argstr="-a %.4f", + usedefault=True, + ), + args=dict( + argstr="%s", + ), + debug=dict( + argstr="-d", + usedefault=True, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fwhm_x=dict( + argstr="-x %.4f", + mandatory=True, + ), + fwhm_y=dict( + argstr="-y %.4f", + mandatory=True, + ), + fwhm_z=dict( + argstr="-z %.4f", + mandatory=True, + ), + in_file=dict( + argstr="-i %s", + extensions=None, + mandatory=True, + ), + mask_file=dict( + argstr="-m %s", + extensions=None, + mandatory=True, + ), + n_deconv=dict( + argstr="-k %d", + usedefault=True, + ), + n_iter=dict( + argstr="-n %d", + usedefault=True, + ), + out_file=dict( + argstr="-o %s", + extensions=None, + genfile=True, + hash_files=False, + ), + pvc=dict( + argstr="-p %s", + mandatory=True, + ), + stop_crit=dict( + argstr="-s %.4f", + usedefault=True, + ), ) inputs = PETPVC.input_spec() @@ -27,7 +72,11 @@ def test_PETPVC_inputs(): def test_PETPVC_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = PETPVC.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_Quickshear.py b/nipype/interfaces/tests/test_auto_Quickshear.py index 06b829af9a..92212335dc 100644 --- a/nipype/interfaces/tests/test_auto_Quickshear.py +++ b/nipype/interfaces/tests/test_auto_Quickshear.py @@ -4,11 +4,29 @@ def test_Quickshear_inputs(): input_map = dict( - args=dict(argstr="%s",), - buff=dict(argstr="%d", position=4,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - mask_file=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + args=dict( + argstr="%s", + ), + buff=dict( + argstr="%d", + position=4, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + mask_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), out_file=dict( argstr="%s", extensions=None, @@ -26,7 +44,11 @@ def test_Quickshear_inputs(): def test_Quickshear_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Quickshear.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_RCommand.py b/nipype/interfaces/tests/test_auto_RCommand.py new file mode 100644 index 0000000000..adfcf36cf0 --- /dev/null +++ b/nipype/interfaces/tests/test_auto_RCommand.py @@ -0,0 +1,31 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ..r import RCommand + + +def test_RCommand_inputs(): + input_map = dict( + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + rfile=dict( + usedefault=True, + ), + script=dict( + argstr='-e "%s"', + mandatory=True, + position=-1, + ), + script_file=dict( + extensions=None, + usedefault=True, + ), + ) + inputs = RCommand.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + assert getattr(inputs.traits()[key], metakey) == value diff --git a/nipype/interfaces/tests/test_auto_Reorient.py b/nipype/interfaces/tests/test_auto_Reorient.py index bb4660a05c..eb7a0ce5ff 100644 --- a/nipype/interfaces/tests/test_auto_Reorient.py +++ b/nipype/interfaces/tests/test_auto_Reorient.py @@ -4,8 +4,13 @@ def test_Reorient_inputs(): input_map = dict( - in_file=dict(extensions=None, mandatory=True,), - orientation=dict(usedefault=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), + orientation=dict( + usedefault=True, + ), ) inputs = Reorient.input_spec() @@ -16,7 +21,12 @@ def test_Reorient_inputs(): def test_Reorient_outputs(): output_map = dict( - out_file=dict(extensions=None,), transform=dict(extensions=None,), + out_file=dict( + extensions=None, + ), + transform=dict( + extensions=None, + ), ) outputs = Reorient.output_spec() diff --git a/nipype/interfaces/tests/test_auto_Rescale.py b/nipype/interfaces/tests/test_auto_Rescale.py index d8c83c24ca..5b14cfc8c0 100644 --- a/nipype/interfaces/tests/test_auto_Rescale.py +++ b/nipype/interfaces/tests/test_auto_Rescale.py @@ -4,10 +4,18 @@ def test_Rescale_inputs(): input_map = dict( - in_file=dict(extensions=None, mandatory=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), invert=dict(), - percentile=dict(usedefault=True,), - ref_file=dict(extensions=None, mandatory=True,), + percentile=dict( + usedefault=True, + ), + ref_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = Rescale.input_spec() @@ -17,7 +25,11 @@ def test_Rescale_inputs(): def test_Rescale_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Rescale.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_S3DataGrabber.py b/nipype/interfaces/tests/test_auto_S3DataGrabber.py index 96b32701e2..4b71fe49c3 100644 --- a/nipype/interfaces/tests/test_auto_S3DataGrabber.py +++ b/nipype/interfaces/tests/test_auto_S3DataGrabber.py @@ -4,14 +4,28 @@ def test_S3DataGrabber_inputs(): input_map = dict( - anon=dict(usedefault=True,), - bucket=dict(mandatory=True,), - bucket_path=dict(usedefault=True,), + anon=dict( + usedefault=True, + ), + bucket=dict( + mandatory=True, + ), + bucket_path=dict( + usedefault=True, + ), local_directory=dict(), - raise_on_empty=dict(usedefault=True,), - region=dict(usedefault=True,), - sort_filelist=dict(mandatory=True,), - template=dict(mandatory=True,), + raise_on_empty=dict( + usedefault=True, + ), + region=dict( + usedefault=True, + ), + sort_filelist=dict( + mandatory=True, + ), + template=dict( + mandatory=True, + ), template_args=dict(), ) inputs = S3DataGrabber.input_spec() diff --git a/nipype/interfaces/tests/test_auto_SQLiteSink.py b/nipype/interfaces/tests/test_auto_SQLiteSink.py index f1a62ead15..fe33b65675 100644 --- a/nipype/interfaces/tests/test_auto_SQLiteSink.py +++ b/nipype/interfaces/tests/test_auto_SQLiteSink.py @@ -4,8 +4,13 @@ def test_SQLiteSink_inputs(): input_map = dict( - database_file=dict(extensions=None, mandatory=True,), - table_name=dict(mandatory=True,), + database_file=dict( + extensions=None, + mandatory=True, + ), + table_name=dict( + mandatory=True, + ), ) inputs = SQLiteSink.input_spec() diff --git a/nipype/interfaces/tests/test_auto_SSHDataGrabber.py b/nipype/interfaces/tests/test_auto_SSHDataGrabber.py index 7a759cb07f..5a58cad276 100644 --- a/nipype/interfaces/tests/test_auto_SSHDataGrabber.py +++ b/nipype/interfaces/tests/test_auto_SSHDataGrabber.py @@ -4,17 +4,35 @@ def test_SSHDataGrabber_inputs(): input_map = dict( - base_directory=dict(mandatory=True,), - download_files=dict(usedefault=True,), - drop_blank_outputs=dict(usedefault=True,), - hostname=dict(mandatory=True,), + base_directory=dict( + mandatory=True, + ), + download_files=dict( + usedefault=True, + ), + drop_blank_outputs=dict( + usedefault=True, + ), + hostname=dict( + mandatory=True, + ), password=dict(), - raise_on_empty=dict(usedefault=True,), - sort_filelist=dict(mandatory=True,), - ssh_log_to_file=dict(usedefault=True,), - template=dict(mandatory=True,), + raise_on_empty=dict( + usedefault=True, + ), + sort_filelist=dict( + mandatory=True, + ), + ssh_log_to_file=dict( + usedefault=True, + ), + template=dict( + mandatory=True, + ), template_args=dict(), - template_expression=dict(usedefault=True,), + template_expression=dict( + usedefault=True, + ), username=dict(), ) inputs = SSHDataGrabber.input_spec() diff --git a/nipype/interfaces/tests/test_auto_SelectFiles.py b/nipype/interfaces/tests/test_auto_SelectFiles.py index 722c431b8f..06f86c36f0 100644 --- a/nipype/interfaces/tests/test_auto_SelectFiles.py +++ b/nipype/interfaces/tests/test_auto_SelectFiles.py @@ -5,9 +5,15 @@ def test_SelectFiles_inputs(): input_map = dict( base_directory=dict(), - force_lists=dict(usedefault=True,), - raise_on_empty=dict(usedefault=True,), - sort_filelist=dict(usedefault=True,), + force_lists=dict( + usedefault=True, + ), + raise_on_empty=dict( + usedefault=True, + ), + sort_filelist=dict( + usedefault=True, + ), ) inputs = SelectFiles.input_spec() diff --git a/nipype/interfaces/tests/test_auto_SignalExtraction.py b/nipype/interfaces/tests/test_auto_SignalExtraction.py index 2af759b50a..272d94f54d 100644 --- a/nipype/interfaces/tests/test_auto_SignalExtraction.py +++ b/nipype/interfaces/tests/test_auto_SignalExtraction.py @@ -4,13 +4,29 @@ def test_SignalExtraction_inputs(): input_map = dict( - class_labels=dict(mandatory=True,), - detrend=dict(usedefault=True,), - in_file=dict(extensions=None, mandatory=True,), - incl_shared_variance=dict(usedefault=True,), - include_global=dict(usedefault=True,), - label_files=dict(mandatory=True,), - out_file=dict(extensions=None, usedefault=True,), + class_labels=dict( + mandatory=True, + ), + detrend=dict( + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), + incl_shared_variance=dict( + usedefault=True, + ), + include_global=dict( + usedefault=True, + ), + label_files=dict( + mandatory=True, + ), + out_file=dict( + extensions=None, + usedefault=True, + ), ) inputs = SignalExtraction.input_spec() @@ -20,7 +36,11 @@ def test_SignalExtraction_inputs(): def test_SignalExtraction_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = SignalExtraction.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_SlicerCommandLine.py b/nipype/interfaces/tests/test_auto_SlicerCommandLine.py index 99bd82a8f3..c13466483b 100644 --- a/nipype/interfaces/tests/test_auto_SlicerCommandLine.py +++ b/nipype/interfaces/tests/test_auto_SlicerCommandLine.py @@ -4,8 +4,13 @@ def test_SlicerCommandLine_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), module=dict(), ) inputs = SlicerCommandLine.input_spec() diff --git a/nipype/interfaces/tests/test_auto_SplitNifti.py b/nipype/interfaces/tests/test_auto_SplitNifti.py index 219f378a82..14ccc6bdb0 100644 --- a/nipype/interfaces/tests/test_auto_SplitNifti.py +++ b/nipype/interfaces/tests/test_auto_SplitNifti.py @@ -4,8 +4,13 @@ def test_SplitNifti_inputs(): input_map = dict( - in_file=dict(extensions=None, mandatory=True,), - out_ext=dict(usedefault=True,), + in_file=dict( + extensions=None, + mandatory=True, + ), + out_ext=dict( + usedefault=True, + ), out_format=dict(), out_path=dict(), split_dim=dict(), @@ -18,7 +23,9 @@ def test_SplitNifti_inputs(): def test_SplitNifti_outputs(): - output_map = dict(out_list=dict(),) + output_map = dict( + out_list=dict(), + ) outputs = SplitNifti.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/tests/test_auto_XNATSink.py b/nipype/interfaces/tests/test_auto_XNATSink.py index d22e2a1a63..ec6f920f57 100644 --- a/nipype/interfaces/tests/test_auto_XNATSink.py +++ b/nipype/interfaces/tests/test_auto_XNATSink.py @@ -4,17 +4,39 @@ def test_XNATSink_inputs(): input_map = dict( - _outputs=dict(usedefault=True,), - assessor_id=dict(xor=["reconstruction_id"],), + _outputs=dict( + usedefault=True, + ), + assessor_id=dict( + xor=["reconstruction_id"], + ), cache_dir=dict(), - config=dict(extensions=None, mandatory=True, xor=["server"],), - experiment_id=dict(mandatory=True,), - project_id=dict(mandatory=True,), + config=dict( + extensions=None, + mandatory=True, + xor=["server"], + ), + experiment_id=dict( + mandatory=True, + ), + project_id=dict( + mandatory=True, + ), pwd=dict(), - reconstruction_id=dict(xor=["assessor_id"],), - server=dict(mandatory=True, requires=["user", "pwd"], xor=["config"],), - share=dict(usedefault=True,), - subject_id=dict(mandatory=True,), + reconstruction_id=dict( + xor=["assessor_id"], + ), + server=dict( + mandatory=True, + requires=["user", "pwd"], + xor=["config"], + ), + share=dict( + usedefault=True, + ), + subject_id=dict( + mandatory=True, + ), user=dict(), ) inputs = XNATSink.input_spec() diff --git a/nipype/interfaces/tests/test_auto_XNATSource.py b/nipype/interfaces/tests/test_auto_XNATSource.py index a60af06b6a..f115657c9f 100644 --- a/nipype/interfaces/tests/test_auto_XNATSource.py +++ b/nipype/interfaces/tests/test_auto_XNATSource.py @@ -5,11 +5,23 @@ def test_XNATSource_inputs(): input_map = dict( cache_dir=dict(), - config=dict(extensions=None, mandatory=True, xor=["server"],), + config=dict( + extensions=None, + mandatory=True, + xor=["server"], + ), pwd=dict(), - query_template=dict(mandatory=True,), - query_template_args=dict(usedefault=True,), - server=dict(mandatory=True, requires=["user", "pwd"], xor=["config"],), + query_template=dict( + mandatory=True, + ), + query_template_args=dict( + usedefault=True, + ), + server=dict( + mandatory=True, + requires=["user", "pwd"], + xor=["config"], + ), user=dict(), ) inputs = XNATSource.input_spec() diff --git a/nipype/interfaces/tests/test_dcm2nii.py b/nipype/interfaces/tests/test_dcm2nii.py new file mode 100644 index 0000000000..5154534c5a --- /dev/null +++ b/nipype/interfaces/tests/test_dcm2nii.py @@ -0,0 +1,32 @@ +import pytest + + +from nipype.interfaces import dcm2nii + + +@pytest.mark.parametrize( + "fname, extension, search_crop", + [ + ("output_1", ".txt", False), + ("output_w_[]_meta_1", ".json", False), + ("output_w_**^$?_meta_2", ".txt", False), + ("output_cropped", ".txt", True), + ], +) +def test_search_files(tmp_path, fname, extension, search_crop): + tmp_fname = fname + extension + test_file = tmp_path / tmp_fname + test_file.touch() + if search_crop: + tmp_cropped_fname = fname + "_Crop_1" + extension + test_cropped_file = tmp_path / tmp_cropped_fname + test_cropped_file.touch() + + actual_files_list = dcm2nii.search_files( + str(tmp_path / fname), [extension], search_crop + ) + for f in actual_files_list: + if search_crop: + assert f in (str(test_cropped_file), str(test_file)) + else: + assert str(test_file) == f diff --git a/nipype/interfaces/tests/test_extra_dcm2nii.py b/nipype/interfaces/tests/test_extra_dcm2nii.py index e76f300ec6..b093d26e6d 100644 --- a/nipype/interfaces/tests/test_extra_dcm2nii.py +++ b/nipype/interfaces/tests/test_extra_dcm2nii.py @@ -1,6 +1,5 @@ import os import pytest -import shutil from nipype.interfaces.dcm2nii import Dcm2niix @@ -22,7 +21,7 @@ def _fetch_data(datadir, dicoms): """Fetches some test DICOMs using datalad""" api.install(path=datadir, source=DICOM_DIR) data = os.path.join(datadir, dicoms) - api.get(path=data) + api.get(path=data, dataset=datadir) except IncompleteResultsError as exc: pytest.skip("Failed to fetch test data: %s" % str(exc)) return data @@ -32,7 +31,6 @@ def _fetch_data(datadir, dicoms): @pytest.mark.skipif(no_datalad, reason="Datalad required") @pytest.mark.skipif(no_dcm2niix, reason="Dcm2niix required") -@pytest.mark.xfail(reason="Intermittent failures. Let's come back to this later.") def test_dcm2niix_dti(fetch_data, tmpdir): tmpdir.chdir() datadir = tmpdir.mkdir("data").strpath diff --git a/nipype/interfaces/tests/test_image.py b/nipype/interfaces/tests/test_image.py index d1ed2578a6..43e0cd0648 100644 --- a/nipype/interfaces/tests/test_image.py +++ b/nipype/interfaces/tests/test_image.py @@ -4,10 +4,10 @@ import nibabel as nb import pytest +from looseversion import LooseVersion from nibabel.orientations import axcodes2ornt, ornt_transform from ..image import _as_reoriented_backport, _orientations -from ... import LooseVersion nibabel24 = LooseVersion(nb.__version__) >= LooseVersion("2.4.0") diff --git a/nipype/interfaces/tests/test_io.py b/nipype/interfaces/tests/test_io.py index ef210de030..fc7f03db9f 100644 --- a/nipype/interfaces/tests/test_io.py +++ b/nipype/interfaces/tests/test_io.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -465,7 +464,7 @@ def test_datasink_substitutions(tmpdir): files.append(f) open(f, "w") ds = nio.DataSink( - parametrization=False, + parameterization=False, base_directory=str(outdir), substitutions=[("ababab", "ABABAB")], # end archoring ($) is used to assure operation on the filename @@ -518,7 +517,7 @@ def test_datasink_copydir_2(_temp_analyze_files, tmpdir): base_directory=tmpdir.mkdir("basedir").strpath, parameterization=False ) ds.inputs.remove_dest_dir = True - setattr(ds.inputs, "outdir", pth) + ds.inputs.outdir = pth ds.run() sep = os.path.sep assert not tmpdir.join("basedir", pth.split(sep)[-1], fname).check() @@ -536,7 +535,7 @@ def test_datafinder_depth(tmpdir): df.inputs.min_depth = min_depth df.inputs.max_depth = max_depth result = df.run() - expected = ["{}".format(x) for x in range(min_depth, max_depth + 1)] + expected = [f"{x}" for x in range(min_depth, max_depth + 1)] for path, exp_fname in zip(result.outputs.out_paths, expected): _, fname = os.path.split(path) assert fname == exp_fname @@ -566,12 +565,11 @@ def test_freesurfersource(): def test_freesurfersource_incorrectdir(): fss = nio.FreeSurferSource() - with pytest.raises(TraitError) as err: + with pytest.raises(TraitError): fss.inputs.subjects_dir = "path/to/no/existing/directory" def test_jsonsink_input(): - ds = nio.JSONFileSink() assert ds.inputs._outputs == {} @@ -596,7 +594,7 @@ def test_jsonsink(tmpdir, inputs_attributes): expected_data[key] = val res = js.run() - with open(res.outputs.out_file, "r") as f: + with open(res.outputs.out_file) as f: data = simplejson.load(f) assert data == expected_data @@ -661,8 +659,7 @@ def test_bids_infields_outfields(tmpdir): @pytest.mark.skipif(no_paramiko, reason="paramiko library is not available") @pytest.mark.skipif(no_local_ssh, reason="SSH Server is not running") def test_SSHDataGrabber(tmpdir): - """Test SSHDataGrabber by connecting to localhost and collecting some data. - """ + """Test SSHDataGrabber by connecting to localhost and collecting some data.""" old_cwd = tmpdir.chdir() source_dir = tmpdir.mkdir("source") @@ -709,10 +706,10 @@ def _mock_get_ssh_client(self): def test_ExportFile(tmp_path): - testin = tmp_path / "in.txt" - testin.write_text("test string") + test_in = tmp_path / "in.txt" + test_in.write_text("test string", encoding='utf-8') i = nio.ExportFile() - i.inputs.in_file = str(testin) + i.inputs.in_file = str(test_in) i.inputs.out_file = str(tmp_path / "out.tsv") i.inputs.check_extension = True with pytest.raises(RuntimeError): diff --git a/nipype/interfaces/tests/test_matlab.py b/nipype/interfaces/tests/test_matlab.py index 64f1de846f..d028dd3059 100644 --- a/nipype/interfaces/tests/test_matlab.py +++ b/nipype/interfaces/tests/test_matlab.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os diff --git a/nipype/interfaces/tests/test_nilearn.py b/nipype/interfaces/tests/test_nilearn.py index 6c3a52a670..1fed076b47 100644 --- a/nipype/interfaces/tests/test_nilearn.py +++ b/nipype/interfaces/tests/test_nilearn.py @@ -22,7 +22,6 @@ @pytest.mark.skipif(no_nilearn, reason="the nilearn library is not available") class TestSignalExtraction: - filenames = { "in_file": "fmri.nii", "label_files": "labels.nii", @@ -118,7 +117,7 @@ def test_signal_extr_shared(self): self._test_4d_label(wanted, self.fake_4d_label_data) def test_signal_extr_traits_valid(self): - """ Test a node using the SignalExtraction interface. + """Test a node using the SignalExtraction interface. Unlike interface.run(), node.run() checks the traits """ # run @@ -157,7 +156,7 @@ def _test_4d_label( self.assert_expected_output(wanted_labels, wanted) def assert_expected_output(self, labels, wanted): - with open(self.filenames["out_file"], "r") as output: + with open(self.filenames["out_file"]) as output: got = [line.split() for line in output] labels_got = got.pop(0) # remove header assert labels_got == labels @@ -169,7 +168,7 @@ def assert_expected_output(self, labels, wanted): for j, segment in enumerate(time): npt.assert_almost_equal(segment, wanted[i][j], decimal=1) - # dj: self doesnt have orig_dir at this point, not sure how to change it. + # dj: self doesn't have orig_dir at this point, not sure how to change it. # should work without it # def teardown_class(self): # self.orig_dir.chdir() @@ -184,10 +183,11 @@ def assert_expected_output(self, labels, wanted): [[2, -2, -1, -2, -5], [3, 0, 3, -5, -2]], [[-4, -2, -2, 1, -2], [3, 1, 4, -3, -2]], ], - ] + ], + np.int16, ) - fake_label_data = np.array([[[1, 0], [3, 1]], [[2, 0], [1, 3]]]) + fake_label_data = np.array([[[1, 0], [3, 1]], [[2, 0], [1, 3]]], np.uint8) fake_equiv_4d_label_data = np.array( [ diff --git a/nipype/interfaces/tests/test_r.py b/nipype/interfaces/tests/test_r.py new file mode 100644 index 0000000000..6e980e61cd --- /dev/null +++ b/nipype/interfaces/tests/test_r.py @@ -0,0 +1,61 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +import os + +import pytest +from nipype.interfaces import r + +no_r = r.no_r + + +@pytest.mark.skipif(no_r, reason="R is not available") +def test_cmdline(tmp_path): + default_script_file = str(tmp_path / "testscript") + ri = r.RCommand(script="1 + 1", script_file=default_script_file, rfile=False) + r_cmd = r.get_r_command() + + assert ri.cmdline == r_cmd + (' -e "1 + 1"') + + assert ri.inputs.script == "1 + 1" + assert ri.inputs.script_file == default_script_file + assert not os.path.exists(ri.inputs.script_file), "scriptfile should not exist" + assert not os.path.exists( + default_script_file + ), "default scriptfile should not exist." + + +@pytest.mark.skipif(no_r, reason="R is not available") +def test_run_interface(tmpdir): + cwd = tmpdir.chdir() + default_script_file = r.RInputSpec().script_file + + rc = r.RCommand(r_cmd="foo_m") + assert not os.path.exists(default_script_file), "scriptfile should not exist 1." + with pytest.raises(ValueError): + rc.run() # script is mandatory + assert not os.path.exists(default_script_file), "scriptfile should not exist 2." + if os.path.exists(default_script_file): # cleanup + os.remove(default_script_file) + + rc.inputs.script = "a=1;" + assert not os.path.exists(default_script_file), "scriptfile should not exist 3." + with pytest.raises(IOError): + rc.run() # foo_m is not an executable + assert os.path.exists(default_script_file), "scriptfile should exist 3." + if os.path.exists(default_script_file): # cleanup + os.remove(default_script_file) + cwd.chdir() + + +@pytest.mark.skipif(no_r, reason="R is not available") +def test_set_rcmd(tmpdir): + cwd = tmpdir.chdir() + default_script_file = r.RInputSpec().script_file + + ri = r.RCommand() + _default_r_cmd = ri._cmd + ri.set_default_r_cmd("foo") + assert not os.path.exists(default_script_file), "scriptfile should not exist." + assert ri._cmd == "foo" + ri.set_default_r_cmd(_default_r_cmd) + cwd.chdir() diff --git a/nipype/interfaces/utility/__init__.py b/nipype/interfaces/utility/__init__.py index f5556e7263..b4df1c2afb 100644 --- a/nipype/interfaces/utility/__init__.py +++ b/nipype/interfaces/utility/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/interfaces/utility/base.py b/nipype/interfaces/utility/base.py index 5a59d95bad..ecc1bf7935 100644 --- a/nipype/interfaces/utility/base.py +++ b/nipype/interfaces/utility/base.py @@ -1,10 +1,9 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ - # changing to temporary directories - >>> tmp = getfixture('tmpdir') - >>> old = tmp.chdir() +# changing to temporary directories +>>> tmp = getfixture('tmpdir') +>>> old = tmp.chdir() """ import os import re @@ -58,7 +57,7 @@ class IdentityInterface(IOBase): output_spec = DynamicTraitedSpec def __init__(self, fields=None, mandatory_inputs=True, **inputs): - super(IdentityInterface, self).__init__(**inputs) + super().__init__(**inputs) if fields is None or not fields: raise ValueError("Identity Interface fields must be a non-empty list") # Each input must be in the fields. @@ -175,7 +174,7 @@ class Merge(IOBase): output_spec = MergeOutputSpec def __init__(self, numinputs=0, **inputs): - super(Merge, self).__init__(**inputs) + super().__init__(**inputs) self._numinputs = numinputs if numinputs >= 1: input_names = ["in%d" % (i + 1) for i in range(numinputs)] @@ -211,14 +210,12 @@ def _list_outputs(self): class RenameInputSpec(DynamicTraitedSpec): in_file = File(exists=True, mandatory=True, desc="file to rename") keep_ext = traits.Bool( - desc=("Keep in_file extension, replace " "non-extension component of name") + desc="Keep in_file extension, replace non-extension component of name" ) format_string = Str( mandatory=True, desc="Python formatting string for output template" ) - parse_string = Str( - desc="Python regexp parse string to define " "replacement inputs" - ) + parse_string = Str(desc="Python regexp parse string to define replacement inputs") use_fullpath = traits.Bool( False, usedefault=True, desc="Use full path as input to regex parser" ) @@ -229,7 +226,7 @@ class RenameOutputSpec(TraitedSpec): class Rename(SimpleInterface, IOBase): - """Change the name of a file based on a mapped format string. + r"""Change the name of a file based on a mapped format string. To use additional inputs that will be defined at run-time, the class constructor must be called with the format template, and the fields @@ -275,7 +272,7 @@ class Rename(SimpleInterface, IOBase): output_spec = RenameOutputSpec def __init__(self, format_string=None, **inputs): - super(Rename, self).__init__(**inputs) + super().__init__(**inputs) if format_string is not None: self.inputs.format_string = format_string self.fmt_fields = re.findall(r"%\((.+?)\)", format_string) @@ -362,7 +359,9 @@ def _list_outputs(self): splits.extend(self.inputs.splits) splits = np.cumsum(splits) for i in range(len(splits) - 1): - val = np.array(self.inputs.inlist)[splits[i] : splits[i + 1]].tolist() + val = np.array(self.inputs.inlist, dtype=object)[ + splits[i] : splits[i + 1] + ].tolist() if self.inputs.squeeze and len(val) == 1: val = val[0] outputs["out%d" % (i + 1)] = val @@ -407,7 +406,9 @@ class Select(IOBase): def _list_outputs(self): outputs = self._outputs().get() - out = np.array(self.inputs.inlist)[np.array(self.inputs.index)].tolist() + out = np.array(self.inputs.inlist, dtype=object)[ + np.array(self.inputs.index) + ].tolist() outputs["out"] = out return outputs diff --git a/nipype/interfaces/utility/csv.py b/nipype/interfaces/utility/csv.py index 04cb28438e..7470eecbfe 100644 --- a/nipype/interfaces/utility/csv.py +++ b/nipype/interfaces/utility/csv.py @@ -1,8 +1,7 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""CSV Handling utilities -""" +"""CSV Handling utilities""" +import csv from ..base import traits, TraitedSpec, DynamicTraitedSpec, File, BaseInterface from ..io import add_traits @@ -14,6 +13,7 @@ class CSVReaderInputSpec(DynamicTraitedSpec, TraitedSpec): header = traits.Bool( False, usedefault=True, desc="True if the first line is a column header" ) + delimiter = traits.String(",", usedefault=True, desc="Delimiter to use.") class CSVReader(BaseInterface): @@ -53,18 +53,15 @@ def _append_entry(self, outputs, entry): outputs[key].append(value) return outputs - def _parse_line(self, line): - line = line.replace("\n", "") - entry = [x.strip() for x in line.split(",")] - return entry - def _get_outfields(self): - with open(self.inputs.in_file, "r") as fid: - entry = self._parse_line(fid.readline()) + with open(self.inputs.in_file) as fid: + reader = csv.reader(fid, delimiter=self.inputs.delimiter) + + entry = next(reader) if self.inputs.header: self._outfields = tuple(entry) else: - self._outfields = tuple(["column_" + str(x) for x in range(len(entry))]) + self._outfields = tuple("column_" + str(x) for x in range(len(entry))) return self._outfields def _run_interface(self, runtime): @@ -72,7 +69,7 @@ def _run_interface(self, runtime): return runtime def _outputs(self): - return self._add_output_traits(super(CSVReader, self)._outputs()) + return self._add_output_traits(super()._outputs()) def _add_output_traits(self, base): return add_traits(base, self._get_outfields()) @@ -82,11 +79,11 @@ def _list_outputs(self): isHeader = True for key in self._outfields: outputs[key] = [] # initialize outfields - with open(self.inputs.in_file, "r") as fid: - for line in fid.readlines(): + with open(self.inputs.in_file) as fid: + reader = csv.reader(fid, delimiter=self.inputs.delimiter) + for entry in reader: if self.inputs.header and isHeader: # skip header line isHeader = False continue - entry = self._parse_line(line) outputs = self._append_entry(outputs, entry) return outputs diff --git a/nipype/interfaces/utility/tests/__init__.py b/nipype/interfaces/utility/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/utility/tests/__init__.py +++ b/nipype/interfaces/utility/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/utility/tests/test_auto_AssertEqual.py b/nipype/interfaces/utility/tests/test_auto_AssertEqual.py index 2045d9149a..c550a5efba 100644 --- a/nipype/interfaces/utility/tests/test_auto_AssertEqual.py +++ b/nipype/interfaces/utility/tests/test_auto_AssertEqual.py @@ -4,8 +4,14 @@ def test_AssertEqual_inputs(): input_map = dict( - volume1=dict(extensions=None, mandatory=True,), - volume2=dict(extensions=None, mandatory=True,), + volume1=dict( + extensions=None, + mandatory=True, + ), + volume2=dict( + extensions=None, + mandatory=True, + ), ) inputs = AssertEqual.input_spec() diff --git a/nipype/interfaces/utility/tests/test_auto_CSVReader.py b/nipype/interfaces/utility/tests/test_auto_CSVReader.py index 98adf59f6d..a96a4d11bf 100644 --- a/nipype/interfaces/utility/tests/test_auto_CSVReader.py +++ b/nipype/interfaces/utility/tests/test_auto_CSVReader.py @@ -4,7 +4,16 @@ def test_CSVReader_inputs(): input_map = dict( - header=dict(usedefault=True,), in_file=dict(extensions=None, mandatory=True,), + delimiter=dict( + usedefault=True, + ), + header=dict( + usedefault=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), ) inputs = CSVReader.input_spec() diff --git a/nipype/interfaces/utility/tests/test_auto_Function.py b/nipype/interfaces/utility/tests/test_auto_Function.py index f2713a4407..fdbccc3098 100644 --- a/nipype/interfaces/utility/tests/test_auto_Function.py +++ b/nipype/interfaces/utility/tests/test_auto_Function.py @@ -3,7 +3,11 @@ def test_Function_inputs(): - input_map = dict(function_str=dict(mandatory=True,),) + input_map = dict( + function_str=dict( + mandatory=True, + ), + ) inputs = Function.input_spec() for key, metadata in list(input_map.items()): diff --git a/nipype/interfaces/utility/tests/test_auto_Merge.py b/nipype/interfaces/utility/tests/test_auto_Merge.py index 7658529a9d..f9304a9897 100644 --- a/nipype/interfaces/utility/tests/test_auto_Merge.py +++ b/nipype/interfaces/utility/tests/test_auto_Merge.py @@ -4,9 +4,15 @@ def test_Merge_inputs(): input_map = dict( - axis=dict(usedefault=True,), - no_flatten=dict(usedefault=True,), - ravel_inputs=dict(usedefault=True,), + axis=dict( + usedefault=True, + ), + no_flatten=dict( + usedefault=True, + ), + ravel_inputs=dict( + usedefault=True, + ), ) inputs = Merge.input_spec() @@ -16,7 +22,9 @@ def test_Merge_inputs(): def test_Merge_outputs(): - output_map = dict(out=dict(),) + output_map = dict( + out=dict(), + ) outputs = Merge.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/utility/tests/test_auto_Rename.py b/nipype/interfaces/utility/tests/test_auto_Rename.py index a722afac0e..5b9a183796 100644 --- a/nipype/interfaces/utility/tests/test_auto_Rename.py +++ b/nipype/interfaces/utility/tests/test_auto_Rename.py @@ -4,11 +4,18 @@ def test_Rename_inputs(): input_map = dict( - format_string=dict(mandatory=True,), - in_file=dict(extensions=None, mandatory=True,), + format_string=dict( + mandatory=True, + ), + in_file=dict( + extensions=None, + mandatory=True, + ), keep_ext=dict(), parse_string=dict(), - use_fullpath=dict(usedefault=True,), + use_fullpath=dict( + usedefault=True, + ), ) inputs = Rename.input_spec() @@ -18,7 +25,11 @@ def test_Rename_inputs(): def test_Rename_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Rename.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/utility/tests/test_auto_Select.py b/nipype/interfaces/utility/tests/test_auto_Select.py index 76f9061446..21dcb91670 100644 --- a/nipype/interfaces/utility/tests/test_auto_Select.py +++ b/nipype/interfaces/utility/tests/test_auto_Select.py @@ -3,7 +3,14 @@ def test_Select_inputs(): - input_map = dict(index=dict(mandatory=True,), inlist=dict(mandatory=True,),) + input_map = dict( + index=dict( + mandatory=True, + ), + inlist=dict( + mandatory=True, + ), + ) inputs = Select.input_spec() for key, metadata in list(input_map.items()): @@ -12,7 +19,9 @@ def test_Select_inputs(): def test_Select_outputs(): - output_map = dict(out=dict(),) + output_map = dict( + out=dict(), + ) outputs = Select.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/utility/tests/test_auto_Split.py b/nipype/interfaces/utility/tests/test_auto_Split.py index 901162ecab..60f46fb73c 100644 --- a/nipype/interfaces/utility/tests/test_auto_Split.py +++ b/nipype/interfaces/utility/tests/test_auto_Split.py @@ -4,9 +4,15 @@ def test_Split_inputs(): input_map = dict( - inlist=dict(mandatory=True,), - splits=dict(mandatory=True,), - squeeze=dict(usedefault=True,), + inlist=dict( + mandatory=True, + ), + splits=dict( + mandatory=True, + ), + squeeze=dict( + usedefault=True, + ), ) inputs = Split.input_spec() diff --git a/nipype/interfaces/utility/tests/test_base.py b/nipype/interfaces/utility/tests/test_base.py index a19cff16b4..4a4e6d8899 100644 --- a/nipype/interfaces/utility/tests/test_base.py +++ b/nipype/interfaces/utility/tests/test_base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -72,7 +71,7 @@ def test_merge(tmpdir, args, kwargs, in_lists, expected): numinputs = args[0] if args else 0 if numinputs >= 1: for i in range(1, numinputs + 1): - setattr(node.inputs, "in{:d}".format(i), in_lists[i - 1]) + setattr(node.inputs, f"in{i:d}", in_lists[i - 1]) res = node.run() if numinputs < 1: diff --git a/nipype/interfaces/utility/tests/test_csv.py b/nipype/interfaces/utility/tests/test_csv.py index ffd69f000f..2ce78876cc 100644 --- a/nipype/interfaces/utility/tests/test_csv.py +++ b/nipype/interfaces/utility/tests/test_csv.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -27,3 +26,43 @@ def test_csvReader(tmpdir): assert out.outputs.column_0 == ["foo", "bar", "baz"] assert out.outputs.column_1 == ["hello", "world", "goodbye"] assert out.outputs.column_2 == ["300.1", "5", "0.3"] + + +def test_csvReader_quoted(tmpdir): + lines = ['foo,"hello, world",300.1\n'] + + name = tmpdir.join("testfile.csv").strpath + with open(name, "w") as fid: + reader = utility.CSVReader() + fid.writelines(lines) + fid.flush() + reader.inputs.in_file = name + out = reader.run() + + assert out.outputs.column_0 == ["foo"] + assert out.outputs.column_1 == ["hello, world"] + assert out.outputs.column_2 == ["300.1"] + + +def test_csvReader_tabs(tmpdir): + header = "files\tlabels\terosion\n" + lines = ["foo\thello\t300.1\n", "bar\tworld\t5\n", "baz\tgoodbye\t0.3\n"] + for x in range(2): + name = tmpdir.join("testfile.csv").strpath + with open(name, "w") as fid: + reader = utility.CSVReader(delimiter="\t") + if x % 2 == 0: + fid.write(header) + reader.inputs.header = True + fid.writelines(lines) + fid.flush() + reader.inputs.in_file = name + out = reader.run() + if x % 2 == 0: + assert out.outputs.files == ["foo", "bar", "baz"] + assert out.outputs.labels == ["hello", "world", "goodbye"] + assert out.outputs.erosion == ["300.1", "5", "0.3"] + else: + assert out.outputs.column_0 == ["foo", "bar", "baz"] + assert out.outputs.column_1 == ["hello", "world", "goodbye"] + assert out.outputs.column_2 == ["300.1", "5", "0.3"] diff --git a/nipype/interfaces/utility/tests/test_wrappers.py b/nipype/interfaces/utility/tests/test_wrappers.py index 98ee7c7959..345d6483ad 100644 --- a/nipype/interfaces/utility/tests/test_wrappers.py +++ b/nipype/interfaces/utility/tests/test_wrappers.py @@ -1,7 +1,5 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -import os import pytest from nipype.interfaces import utility @@ -73,7 +71,7 @@ def should_fail(tmp): def test_should_fail(tmpdir): - with pytest.raises(NameError): + with pytest.raises(pe.nodes.NodeExecutionError): should_fail(tmpdir) @@ -95,7 +93,7 @@ def test_function_with_imports(tmpdir): def test_aux_connect_function(tmpdir): - """ This tests excution nodes with multiple inputs and auxiliary + """This tests execution nodes with multiple inputs and auxiliary function inside the Workflow connect function. """ tmpdir.chdir() @@ -103,7 +101,7 @@ def test_aux_connect_function(tmpdir): wf = pe.Workflow(name="test_workflow") def _gen_tuple(size): - return [1,] * size + return [1] * size def _sum_and_sub_mul(a, b, c): return (a + b) * c, (a - b) * c @@ -138,7 +136,7 @@ def _inc(x): (params, gen_tuple, [(("size", _inc), "size")]), (params, ssm, [(("num", _inc), "c")]), (gen_tuple, split, [("tuple", "inlist")]), - (split, ssm, [(("out1", _inc), "a"), ("out2", "b"),]), + (split, ssm, [(("out1", _inc), "a"), ("out2", "b")]), ] ) diff --git a/nipype/interfaces/utility/wrappers.py b/nipype/interfaces/utility/wrappers.py index f638816166..db38de660c 100644 --- a/nipype/interfaces/utility/wrappers.py +++ b/nipype/interfaces/utility/wrappers.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -71,12 +70,12 @@ def __init__( in an otherwise empty namespace """ - super(Function, self).__init__(**inputs) + super().__init__(**inputs) if function: - if hasattr(function, "__call__"): + if callable(function): try: self.inputs.function_str = getsource(function) - except IOError: + except OSError: raise Exception( "Interface Function does not accept " "function objects defined interactively " @@ -96,15 +95,13 @@ def __init__( self.inputs.on_trait_change(self._set_function_string, "function_str") self._input_names = ensure_list(input_names) self._output_names = ensure_list(output_names) - add_traits(self.inputs, [name for name in self._input_names]) + add_traits(self.inputs, self._input_names) self.imports = imports - self._out = {} - for name in self._output_names: - self._out[name] = None + self._out = {name: None for name in self._output_names} def _set_function_string(self, obj, name, old, new): if name == "function_str": - if hasattr(new, "__call__"): + if callable(new): function_source = getsource(new) fninfo = new.__code__ elif isinstance(new, (str, bytes)): diff --git a/nipype/interfaces/vista/__init__.py b/nipype/interfaces/vista/__init__.py index 928ff19fc2..414a002527 100644 --- a/nipype/interfaces/vista/__init__.py +++ b/nipype/interfaces/vista/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """VistaSoft contains Matlab code to perform a variety of analysis on MRI data.""" diff --git a/nipype/interfaces/vista/tests/__init__.py b/nipype/interfaces/vista/tests/__init__.py index 40a96afc6f..e69de29bb2 100644 --- a/nipype/interfaces/vista/tests/__init__.py +++ b/nipype/interfaces/vista/tests/__init__.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- diff --git a/nipype/interfaces/vista/tests/test_auto_Vnifti2Image.py b/nipype/interfaces/vista/tests/test_auto_Vnifti2Image.py index 56bf94b7cc..f06a118fc2 100644 --- a/nipype/interfaces/vista/tests/test_auto_Vnifti2Image.py +++ b/nipype/interfaces/vista/tests/test_auto_Vnifti2Image.py @@ -4,10 +4,24 @@ def test_Vnifti2Image_inputs(): input_map = dict( - args=dict(argstr="%s",), - attributes=dict(argstr="-attr %s", extensions=None, position=2,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True, position=1,), + args=dict( + argstr="%s", + ), + attributes=dict( + argstr="-attr %s", + extensions=None, + position=2, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + position=1, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -26,7 +40,11 @@ def test_Vnifti2Image_inputs(): def test_Vnifti2Image_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = Vnifti2Image.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/vista/tests/test_auto_VtoMat.py b/nipype/interfaces/vista/tests/test_auto_VtoMat.py index 46cac1b5b6..8d2b53ab0c 100644 --- a/nipype/interfaces/vista/tests/test_auto_VtoMat.py +++ b/nipype/interfaces/vista/tests/test_auto_VtoMat.py @@ -4,9 +4,19 @@ def test_VtoMat_inputs(): input_map = dict( - args=dict(argstr="%s",), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="-in %s", extensions=None, mandatory=True, position=1,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="-in %s", + extensions=None, + mandatory=True, + position=1, + ), out_file=dict( argstr="-out %s", extensions=None, @@ -25,7 +35,11 @@ def test_VtoMat_inputs(): def test_VtoMat_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = VtoMat.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/vista/vista.py b/nipype/interfaces/vista/vista.py index 12823b10cc..5e6571639a 100644 --- a/nipype/interfaces/vista/vista.py +++ b/nipype/interfaces/vista/vista.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/interfaces/vtkbase.py b/nipype/interfaces/vtkbase.py index 875ccb61d5..4b49d56815 100644 --- a/nipype/interfaces/vtkbase.py +++ b/nipype/interfaces/vtkbase.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -43,28 +42,28 @@ def vtk_version(): - """ Get VTK version """ + """Get VTK version""" global _vtk_version return _vtk_version def no_vtk(): - """ Checks if VTK is installed and the python wrapper is functional """ + """Checks if VTK is installed and the python wrapper is functional""" global _vtk_version return _vtk_version is None def no_tvtk(): - """ Checks if tvtk was found """ + """Checks if tvtk was found""" global _have_tvtk return not _have_tvtk def vtk_old(): - """ Checks if VTK uses the old-style pipeline (VTK<6.0) """ + """Checks if VTK uses the old-style pipeline (VTK<6.0)""" global _vtk_version if _vtk_version is None: - raise RuntimeException("VTK is not correctly installed.") + raise RuntimeError("VTK is not correctly installed.") return _vtk_version[0] < 6 @@ -80,7 +79,7 @@ def configure_input_data(obj, data): def vtk_output(obj): - """ Configure the input data for vtk pipeline object obj.""" + """Configure the input data for vtk pipeline object obj.""" if vtk_old(): return obj.output return obj.get_output() diff --git a/nipype/interfaces/workbench/__init__.py b/nipype/interfaces/workbench/__init__.py index fb68624c88..693ee395a8 100644 --- a/nipype/interfaces/workbench/__init__.py +++ b/nipype/interfaces/workbench/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Connectome Workbench is a visualization for neuroimaging data, esp. derived from HCP data.""" diff --git a/nipype/interfaces/workbench/base.py b/nipype/interfaces/workbench/base.py index d91c85d9f6..0cfb8624d7 100644 --- a/nipype/interfaces/workbench/base.py +++ b/nipype/interfaces/workbench/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/interfaces/workbench/cifti.py b/nipype/interfaces/workbench/cifti.py index 272aec1a3e..d8b0c1a721 100644 --- a/nipype/interfaces/workbench/cifti.py +++ b/nipype/interfaces/workbench/cifti.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """This module provides interfaces for workbench CIFTI commands""" diff --git a/nipype/interfaces/workbench/metric.py b/nipype/interfaces/workbench/metric.py index 6bbe7f98cf..9183488f93 100644 --- a/nipype/interfaces/workbench/metric.py +++ b/nipype/interfaces/workbench/metric.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """This module provides interfaces for workbench surface commands""" @@ -160,17 +159,17 @@ def _format_arg(self, opt, spec, val): and not self.inputs.area_metrics ): raise ValueError( - "Exactly one of area_surfs or area_metrics" " must be specified" + "Exactly one of area_surfs or area_metrics must be specified" ) if opt == "valid_roi_out" and val: # generate a filename and add it to argstr roi_out = self._gen_filename(self.inputs.in_file, suffix="_roi") iflogger.info("Setting roi output file as", roi_out) spec.argstr += " " + roi_out - return super(MetricResample, self)._format_arg(opt, spec, val) + return super()._format_arg(opt, spec, val) def _list_outputs(self): - outputs = super(MetricResample, self)._list_outputs() + outputs = super()._list_outputs() if self.inputs.valid_roi_out: roi_file = self._gen_filename(self.inputs.in_file, suffix="_roi") outputs["roi_file"] = os.path.abspath(roi_file) diff --git a/nipype/interfaces/workbench/tests/test_auto_CiftiSmooth.py b/nipype/interfaces/workbench/tests/test_auto_CiftiSmooth.py index 4be8b4aba7..03beac887a 100644 --- a/nipype/interfaces/workbench/tests/test_auto_CiftiSmooth.py +++ b/nipype/interfaces/workbench/tests/test_auto_CiftiSmooth.py @@ -4,7 +4,9 @@ def test_CiftiSmooth_inputs(): input_map = dict( - args=dict(argstr="%s",), + args=dict( + argstr="%s", + ), cerebellum_corrected_areas=dict( argstr="cerebellum-corrected-areas %s", extensions=None, @@ -12,21 +14,53 @@ def test_CiftiSmooth_inputs(): requires=["cerebellum_surf"], ), cerebellum_surf=dict( - argstr="-cerebellum-surface %s", extensions=None, position=9, - ), - cifti_roi=dict(argstr="-cifti-roi %s", extensions=None, position=11,), - direction=dict(argstr="%s", mandatory=True, position=3,), - environ=dict(nohash=True, usedefault=True,), - fix_zeros_surf=dict(argstr="-fix-zeros-surface", position=13,), - fix_zeros_vol=dict(argstr="-fix-zeros-volume", position=12,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), + argstr="-cerebellum-surface %s", + extensions=None, + position=9, + ), + cifti_roi=dict( + argstr="-cifti-roi %s", + extensions=None, + position=11, + ), + direction=dict( + argstr="%s", + mandatory=True, + position=3, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + fix_zeros_surf=dict( + argstr="-fix-zeros-surface", + position=13, + ), + fix_zeros_vol=dict( + argstr="-fix-zeros-volume", + position=12, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), left_corrected_areas=dict( - argstr="-left-corrected-areas %s", extensions=None, position=6, + argstr="-left-corrected-areas %s", + extensions=None, + position=6, ), left_surf=dict( - argstr="-left-surface %s", extensions=None, mandatory=True, position=5, + argstr="-left-surface %s", + extensions=None, + mandatory=True, + position=5, + ), + merged_volume=dict( + argstr="-merged-volume", + position=14, ), - merged_volume=dict(argstr="-merged-volume", position=14,), out_file=dict( argstr="%s", extensions=None, @@ -36,13 +70,26 @@ def test_CiftiSmooth_inputs(): position=4, ), right_corrected_areas=dict( - argstr="-right-corrected-areas %s", extensions=None, position=8, + argstr="-right-corrected-areas %s", + extensions=None, + position=8, ), right_surf=dict( - argstr="-right-surface %s", extensions=None, mandatory=True, position=7, + argstr="-right-surface %s", + extensions=None, + mandatory=True, + position=7, + ), + sigma_surf=dict( + argstr="%s", + mandatory=True, + position=1, + ), + sigma_vol=dict( + argstr="%s", + mandatory=True, + position=2, ), - sigma_surf=dict(argstr="%s", mandatory=True, position=1,), - sigma_vol=dict(argstr="%s", mandatory=True, position=2,), ) inputs = CiftiSmooth.input_spec() @@ -52,7 +99,11 @@ def test_CiftiSmooth_inputs(): def test_CiftiSmooth_outputs(): - output_map = dict(out_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + ) outputs = CiftiSmooth.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/workbench/tests/test_auto_MetricResample.py b/nipype/interfaces/workbench/tests/test_auto_MetricResample.py index eb9201b7f1..e7a861963b 100644 --- a/nipype/interfaces/workbench/tests/test_auto_MetricResample.py +++ b/nipype/interfaces/workbench/tests/test_auto_MetricResample.py @@ -4,17 +4,60 @@ def test_MetricResample_inputs(): input_map = dict( - area_metrics=dict(argstr="-area-metrics", position=5, xor=["area_surfs"],), - area_surfs=dict(argstr="-area-surfs", position=5, xor=["area_metrics"],), - args=dict(argstr="%s",), - current_area=dict(argstr="%s", extensions=None, position=6,), - current_sphere=dict(argstr="%s", extensions=None, mandatory=True, position=1,), - environ=dict(nohash=True, usedefault=True,), - in_file=dict(argstr="%s", extensions=None, mandatory=True, position=0,), - largest=dict(argstr="-largest", position=10,), - method=dict(argstr="%s", mandatory=True, position=3,), - new_area=dict(argstr="%s", extensions=None, position=7,), - new_sphere=dict(argstr="%s", extensions=None, mandatory=True, position=2,), + area_metrics=dict( + argstr="-area-metrics", + position=5, + xor=["area_surfs"], + ), + area_surfs=dict( + argstr="-area-surfs", + position=5, + xor=["area_metrics"], + ), + args=dict( + argstr="%s", + ), + current_area=dict( + argstr="%s", + extensions=None, + position=6, + ), + current_sphere=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=1, + ), + environ=dict( + nohash=True, + usedefault=True, + ), + in_file=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=0, + ), + largest=dict( + argstr="-largest", + position=10, + ), + method=dict( + argstr="%s", + mandatory=True, + position=3, + ), + new_area=dict( + argstr="%s", + extensions=None, + position=7, + ), + new_sphere=dict( + argstr="%s", + extensions=None, + mandatory=True, + position=2, + ), out_file=dict( argstr="%s", extensions=None, @@ -23,8 +66,15 @@ def test_MetricResample_inputs(): name_template="%s.out", position=4, ), - roi_metric=dict(argstr="-current-roi %s", extensions=None, position=8,), - valid_roi_out=dict(argstr="-valid-roi-out", position=9,), + roi_metric=dict( + argstr="-current-roi %s", + extensions=None, + position=8, + ), + valid_roi_out=dict( + argstr="-valid-roi-out", + position=9, + ), ) inputs = MetricResample.input_spec() @@ -34,7 +84,14 @@ def test_MetricResample_inputs(): def test_MetricResample_outputs(): - output_map = dict(out_file=dict(extensions=None,), roi_file=dict(extensions=None,),) + output_map = dict( + out_file=dict( + extensions=None, + ), + roi_file=dict( + extensions=None, + ), + ) outputs = MetricResample.output_spec() for key, metadata in list(output_map.items()): diff --git a/nipype/interfaces/workbench/tests/test_auto_WBCommand.py b/nipype/interfaces/workbench/tests/test_auto_WBCommand.py index 0a32276e5f..d2cc9a6b96 100644 --- a/nipype/interfaces/workbench/tests/test_auto_WBCommand.py +++ b/nipype/interfaces/workbench/tests/test_auto_WBCommand.py @@ -4,7 +4,13 @@ def test_WBCommand_inputs(): input_map = dict( - args=dict(argstr="%s",), environ=dict(nohash=True, usedefault=True,), + args=dict( + argstr="%s", + ), + environ=dict( + nohash=True, + usedefault=True, + ), ) inputs = WBCommand.input_spec() diff --git a/nipype/pipeline/__init__.py b/nipype/pipeline/__init__.py index 75b3b17c3a..63c5557f56 100644 --- a/nipype/pipeline/__init__.py +++ b/nipype/pipeline/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/pipeline/engine/__init__.py b/nipype/pipeline/engine/__init__.py index b13ba968ac..20829e63a7 100644 --- a/nipype/pipeline/engine/__init__.py +++ b/nipype/pipeline/engine/__init__.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/pipeline/engine/base.py b/nipype/pipeline/engine/base.py index a041fd12e0..27d3426863 100644 --- a/nipype/pipeline/engine/base.py +++ b/nipype/pipeline/engine/base.py @@ -1,17 +1,15 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Defines functionality for pipelined execution of interfaces.""" from copy import deepcopy import re -import numpy as np from ... import config from ...interfaces.base import DynamicTraitedSpec from ...utils.filemanip import loadpkl, savepkl -class EngineBase(object): +class EngineBase: """ Defines common attributes and functions for workflows and nodes. @@ -57,7 +55,7 @@ def name(self, name): def fullname(self): """Build the full name down the hierarchy.""" if self._hierarchy: - return "%s.%s" % (self._hierarchy, self.name) + return f"{self._hierarchy}.{self.name}" return self.name @property @@ -73,7 +71,7 @@ def itername(self): """Get the name of the expanded iterable.""" itername = self._id if self._hierarchy: - itername = "%s.%s" % (self._hierarchy, self._id) + itername = f"{self._hierarchy}.{self._id}" return itername def clone(self, name): @@ -88,7 +86,7 @@ def clone(self, name): """ if name == self.name: - raise ValueError('Cloning requires a new name, "%s" is ' "in use." % name) + raise ValueError('Cloning requires a new name, "%s" is in use.' % name) clone = deepcopy(self) clone.name = name if hasattr(clone, "_id"): diff --git a/nipype/pipeline/engine/nodes.py b/nipype/pipeline/engine/nodes.py index aeff5f12da..e29b56718b 100644 --- a/nipype/pipeline/engine/nodes.py +++ b/nipype/pipeline/engine/nodes.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Defines functionality for pipelined execution of interfaces @@ -9,6 +8,7 @@ import os import os.path as op +from pathlib import Path import shutil import socket from copy import deepcopy @@ -30,14 +30,12 @@ load_json, emptydirs, savepkl, - indirectory, silentrm, ) from ...interfaces.base import ( traits, InputMultiPath, - CommandLine, Undefined, DynamicTraitedSpec, Bunch, @@ -64,6 +62,10 @@ logger = logging.getLogger("nipype.workflow") +class NodeExecutionError(RuntimeError): + """A nipype-specific name for exceptions when executing a Node.""" + + class Node(EngineBase): """ Wraps interface objects for use in pipeline @@ -98,7 +100,7 @@ def __init__( run_without_submitting=False, n_procs=None, mem_gb=0.20, - **kwargs + **kwargs, ): """ Parameters @@ -170,11 +172,11 @@ def __init__( """ # Make sure an interface is set, and that it is an Interface if interface is None: - raise IOError("Interface must be provided") + raise OSError("Interface must be provided") if not isinstance(interface, Interface): - raise IOError("interface must be an instance of an Interface") + raise OSError("interface must be an instance of an Interface") - super(Node, self).__init__(name, kwargs.get("base_dir")) + super().__init__(name, kwargs.get("base_dir")) self._interface = interface self._hierarchy = None @@ -205,6 +207,9 @@ def __init__( self.needed_outputs = needed_outputs self.config = None + if hasattr(self._interface, "write_cmdline"): + self._interface.write_cmdline = True + @property def interface(self): """Return the underlying interface object""" @@ -234,7 +239,7 @@ def needed_outputs(self): @needed_outputs.setter def needed_outputs(self, new_outputs): """Needed outputs changes the hash, refresh if changed""" - new_outputs = sorted(list(set(new_outputs or []))) + new_outputs = sorted(set(new_outputs or [])) if new_outputs != self._needed_outputs: # Reset hash self._hashvalue = None @@ -286,9 +291,12 @@ def output_dir(self): if self._hierarchy: outputdir = op.join(outputdir, *self._hierarchy.split(".")) if self.parameterization: - params_str = ["{}".format(p) for p in self.parameterization] - if not str2bool(self.config["execution"]["parameterize_dirs"]): - params_str = [_parameterization_dir(p) for p in params_str] + maxlen = ( + 252 if str2bool(self.config["execution"]["parameterize_dirs"]) else 32 + ) + params_str = [ + _parameterization_dir(str(p), maxlen) for p in self.parameterization + ] outputdir = op.join(outputdir, *params_str) self._output_dir = op.realpath(op.join(outputdir, self.name)) @@ -439,11 +447,12 @@ def run(self, updatehash=False): ) # Check hash, check whether run should be enforced - logger.info('[Node] Setting-up "%s" in "%s".', self.fullname, outdir) + if not isinstance(self, MapNode): + logger.info(f'[Node] Setting-up "{self.fullname}" in "{outdir}".') cached, updated = self.is_cached() # If the node is cached, check on pklz files and finish - if not force_run and (updated or (not updated and updatehash)): + if cached and not force_run and (updated or updatehash): logger.debug("Only updating node hashes or skipping execution") inputs_file = op.join(outdir, "_inputs.pklz") if not op.exists(inputs_file): @@ -530,7 +539,6 @@ def run(self, updatehash=False): # Tear-up after success shutil.move(hashfile_unfinished, hashfile_unfinished.replace("_unfinished", "")) write_node_report(self, result=result, is_mapnode=isinstance(self, MapNode)) - logger.info('[Node] Finished "%s".', self.fullname) return result def _get_hashval(self): @@ -582,7 +590,7 @@ def _get_inputs(self): logger.critical("%s", e) if outputs is None: - raise RuntimeError( + raise NodeExecutionError( """\ Error populating the inputs of node "%s": the results file of the source node \ (%s) does not contain any outputs.""" @@ -643,7 +651,7 @@ def _load_results(self): logger.debug("Error populating inputs/outputs, (re)aggregating results...") except (AttributeError, ImportError) as err: logger.debug( - "attribute error: %s probably using " "different trait pickled file", + "attribute error: %s probably using different trait pickled file", str(err), ) old_inputs = loadpkl(op.join(cwd, "_inputs.pklz")) @@ -687,7 +695,7 @@ def _run_command(self, execute, copyfiles=True): except (FileNotFoundError, AttributeError): # if aggregation does not work, rerun the node logger.info( - "[Node] Some of the outputs were not found: " "rerunning node." + "[Node] Some of the outputs were not found: rerunning node." ) copyfiles = False # OE: this was like this before, execute = True # I'll keep them for safety @@ -697,72 +705,41 @@ def _run_command(self, execute, copyfiles=True): ) return result - outdir = self.output_dir() - # Run command: either execute is true or load_results failed. - result = InterfaceResult( - interface=self._interface.__class__, - runtime=Bunch( - cwd=outdir, - returncode=1, - environ=dict(os.environ), - hostname=socket.gethostname(), - ), - inputs=self._interface.inputs.get_traitsfree(), - ) - + outdir = Path(self.output_dir()) if copyfiles: self._originputs = deepcopy(self._interface.inputs) self._copyfiles_to_wd(execute=execute) - message = '[Node] Running "{}" ("{}.{}")'.format( - self.name, self._interface.__module__, self._interface.__class__.__name__ + # Run command: either execute is true or load_results failed. + logger.info( + f'[Node] Executing "{self.name}" <{self._interface.__module__}' + f".{self._interface.__class__.__name__}>" ) - if issubclass(self._interface.__class__, CommandLine): - try: - with indirectory(outdir): - cmd = self._interface.cmdline - except Exception as msg: - result.runtime.stderr = "{}\n\n{}".format( - getattr(result.runtime, "stderr", ""), msg - ) - _save_resultfile( - result, - outdir, - self.name, - rebase=str2bool(self.config["execution"]["use_relative_paths"]), - ) - raise - cmdfile = op.join(outdir, "command.txt") - with open(cmdfile, "wt") as fd: - print(cmd + "\n", file=fd) - message += ", a CommandLine Interface with command:\n{}".format(cmd) - logger.info(message) - try: - result = self._interface.run(cwd=outdir) - except Exception as msg: - result.runtime.stderr = "%s\n\n%s".format( - getattr(result.runtime, "stderr", ""), msg - ) - _save_resultfile( - result, + + # Invoke core run method of the interface ignoring exceptions + result = self._interface.run(cwd=outdir, ignore_exception=True) + logger.info( + f'[Node] Finished "{self.name}", elapsed time {result.runtime.duration}s.' + ) + + exc_tb = getattr(result.runtime, "traceback", None) + + if not exc_tb: + # Clean working directory if no errors + dirs2keep = None + if isinstance(self, MapNode): + dirs2keep = [op.join(outdir, "mapflow")] + + result.outputs = clean_working_directory( + result.outputs, outdir, - self.name, - rebase=str2bool(self.config["execution"]["use_relative_paths"]), + self._interface.inputs, + self.needed_outputs, + self.config, + dirs2keep=dirs2keep, ) - raise - - dirs2keep = None - if isinstance(self, MapNode): - dirs2keep = [op.join(outdir, "mapflow")] - result.outputs = clean_working_directory( - result.outputs, - outdir, - self._interface.inputs, - self.needed_outputs, - self.config, - dirs2keep=dirs2keep, - ) + # Store results file under all circumstances _save_resultfile( result, outdir, @@ -770,6 +747,27 @@ def _run_command(self, execute, copyfiles=True): rebase=str2bool(self.config["execution"]["use_relative_paths"]), ) + if exc_tb: + runtime = result.runtime + + def _tab(text): + from textwrap import indent + + if not text: + return "" + return indent(text, '\t') + + msg = f"Exception raised while executing Node {self.name}.\n\n" + if hasattr(runtime, 'cmdline'): + msg += ( + f"Cmdline:\n{_tab(runtime.cmdline)}\n" + f"Stdout:\n{_tab(runtime.stdout)}\n" + f"Stderr:\n{_tab(runtime.stderr)}\n" + ) + # Always pass along the traceback + msg += f"Traceback:\n{_tab(runtime.traceback)}" + raise NodeExecutionError(msg) + return result def _copyfiles_to_wd(self, execute=True, linksonly=False): @@ -822,6 +820,11 @@ def update(self, **opts): """Update inputs""" self.inputs.update(**opts) + def is_gpu_node(self): + return bool(getattr(self.inputs, 'use_cuda', False)) or bool( + getattr(self.inputs, 'use_gpu', False) + ) + class JoinNode(Node): """Wraps interface objects that join inputs into a list. @@ -872,7 +875,7 @@ def __init__( See Node docstring for additional keyword arguments. """ - super(JoinNode, self).__init__(interface, name, **kwargs) + super().__init__(interface, name, **kwargs) self._joinsource = None # The member should be defined self.joinsource = joinsource # Let the setter do the job @@ -938,9 +941,9 @@ def _add_join_item_fields(self): """ # create the new join item fields idx = self._next_slot_index - newfields = dict( - [(field, self._add_join_item_field(field, idx)) for field in self.joinfield] - ) + newfields = { + field: self._add_join_item_field(field, idx) for field in self.joinfield + } # increment the join slot index logger.debug("Added the %s join item fields %s.", self, newfields) self._next_slot_index += 1 @@ -1001,7 +1004,7 @@ def _override_join_traits(self, basetraits, fields): def _run_command(self, execute, copyfiles=True): """Collates the join inputs prior to delegating to the superclass.""" self._collate_join_field_inputs() - return super(JoinNode, self)._run_command(execute, copyfiles) + return super()._run_command(execute, copyfiles) def _collate_join_field_inputs(self): """ @@ -1113,7 +1116,7 @@ def __init__( See Node docstring for additional keyword arguments. """ - super(MapNode, self).__init__(interface, name, **kwargs) + super().__init__(interface, name, **kwargs) if isinstance(iterfield, (str, bytes)): iterfield = [iterfield] self.iterfield = iterfield @@ -1126,8 +1129,7 @@ def __init__( self._serial = serial def _create_dynamic_traits(self, basetraits, fields=None, nitems=None): - """Convert specific fields of a trait to accept multiple inputs - """ + """Convert specific fields of a trait to accept multiple inputs""" output = DynamicTraitedSpec() if fields is None: fields = basetraits.copyable_trait_names() @@ -1285,14 +1287,14 @@ def _collate_results(self, nodes): ) setattr(finalresult.outputs, key, values) - if returncode and any([code is not None for code in returncode]): + if returncode and any(code is not None for code in returncode): msg = [] for i, code in enumerate(returncode): if code is not None: msg += ["Subnode %d failed" % i] msg += ["Error: %s" % str(code)] - raise Exception( - "Subnodes of node: %s failed:\n%s" % (self.name, "\n".join(msg)) + raise NodeExecutionError( + "Subnodes of node: {} failed:\n{}".format(self.name, "\n".join(msg)) ) return finalresult @@ -1320,7 +1322,7 @@ def _get_inputs(self): self._interface.inputs, fields=self.iterfield ) self._inputs.trait_set(**old_inputs) - super(MapNode, self)._get_inputs() + super()._get_inputs() def _check_iterfield(self): """Checks iterfield @@ -1331,18 +1333,14 @@ def _check_iterfield(self): for iterfield in self.iterfield: if not isdefined(getattr(self.inputs, iterfield)): raise ValueError( - ("Input %s was not set but it is listed " "in iterfields.") - % iterfield + "Input %s was not set but it is listed in iterfields." % iterfield ) if len(self.iterfield) > 1: first_len = len(ensure_list(getattr(self.inputs, self.iterfield[0]))) for iterfield in self.iterfield[1:]: if first_len != len(ensure_list(getattr(self.inputs, iterfield))): raise ValueError( - ( - "All iterfields of a MapNode have to " - "have the same length. %s" - ) + "All iterfields of a MapNode have to have the same length. %s" % str(self.inputs) ) @@ -1388,7 +1386,7 @@ def _run_interface(self, execute=True, updatehash=False): ) ) except Exception as msg: - result.runtime.stderr = "%s\n\n%s".format( + result.runtime.stderr = "{}\n\n{}".format( getattr(result.runtime, "stderr", ""), msg ) _save_resultfile( diff --git a/nipype/pipeline/engine/report_template.html b/nipype/pipeline/engine/report_template.html index 3fb66b4a02..86b2745122 100644 --- a/nipype/pipeline/engine/report_template.html +++ b/nipype/pipeline/engine/report_template.html @@ -261,4 +261,3 @@

- diff --git a/nipype/pipeline/engine/tests/__init__.py b/nipype/pipeline/engine/tests/__init__.py index 99fb243f19..349937997e 100644 --- a/nipype/pipeline/engine/tests/__init__.py +++ b/nipype/pipeline/engine/tests/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/pipeline/engine/tests/test_base.py b/nipype/pipeline/engine/tests/test_base.py index ab80c2f158..5562a3338c 100644 --- a/nipype/pipeline/engine/tests/test_base.py +++ b/nipype/pipeline/engine/tests/test_base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/pipeline/engine/tests/test_engine.py b/nipype/pipeline/engine/tests/test_engine.py index f28b0f3bf3..7650be1cd3 100644 --- a/nipype/pipeline/engine/tests/test_engine.py +++ b/nipype/pipeline/engine/tests/test_engine.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Tests for the engine module -""" +"""Tests for the engine module""" from copy import deepcopy from glob import glob import os @@ -26,7 +24,7 @@ def test_1mod(iterables, expected): pipe = pe.Workflow(name="pipe") mod1 = pe.Node(interface=EngineTestInterface(), name="mod1") - setattr(mod1, "iterables", iterables["1"]) + mod1.iterables = iterables["1"] pipe.add_nodes([mod1]) pipe._flatgraph = pipe._create_flat_graph() pipe._execgraph = pe.generate_expanded_graph(deepcopy(pipe._flatgraph)) @@ -50,7 +48,7 @@ def test_2mods(iterables, expected): mod1 = pe.Node(interface=EngineTestInterface(), name="mod1") mod2 = pe.Node(interface=EngineTestInterface(), name="mod2") for nr in ["1", "2"]: - setattr(eval("mod" + nr), "iterables", iterables[nr]) + eval("mod" + nr).iterables = iterables[nr] pipe.connect([(mod1, mod2, [("output1", "input2")])]) pipe._flatgraph = pipe._create_flat_graph() pipe._execgraph = pe.generate_expanded_graph(deepcopy(pipe._flatgraph)) @@ -88,7 +86,7 @@ def test_3mods(iterables, expected, connect): mod2 = pe.Node(interface=EngineTestInterface(), name="mod2") mod3 = pe.Node(interface=EngineTestInterface(), name="mod3") for nr in ["1", "2", "3"]: - setattr(eval("mod" + nr), "iterables", iterables[nr]) + eval("mod" + nr).iterables = iterables[nr] if connect == ("1-2", "2-3"): pipe.connect( [ @@ -196,7 +194,6 @@ def test_synchronize_tuples_expansion(): def test_itersource_expansion(): - wf1 = pe.Workflow(name="test") node1 = pe.Node(EngineTestInterface(), name="node1") node1.iterables = ("input1", [1, 2]) @@ -326,8 +323,7 @@ def func2(a): def test_mapnode_json(tmpdir): - """Tests that mapnodes don't generate excess jsons - """ + """Tests that mapnodes don't generate excess jsons""" tmpdir.chdir() wd = os.getcwd() from nipype import MapNode, Function, Workflow @@ -357,9 +353,9 @@ def func1(in1): assert len(outjson) == 1 # check that multiple json's don't trigger rerun - with open(os.path.join(node.output_dir(), "test.json"), "wt") as fp: + with open(os.path.join(node.output_dir(), "test.json"), "w") as fp: fp.write("dummy file") - w1.config["execution"].update(**{"stop_on_first_rerun": True}) + w1.config["execution"].update(stop_on_first_rerun=True) w1.run() @@ -460,7 +456,7 @@ def test_deep_nested_write_graph_runs(tmpdir): pipe = pe.Workflow(name="pipe") parent = pipe for depth in range(10): - sub = pe.Workflow(name="pipe_nest_{}".format(depth)) + sub = pe.Workflow(name=f"pipe_nest_{depth}") parent.add_nodes([sub]) parent = sub mod1 = pe.Node(interface=EngineTestInterface(), name="mod1") @@ -483,14 +479,9 @@ def test_deep_nested_write_graph_runs(tmpdir): pass -import networkx - -# Format of the graph has slightly changed -graph_str = '""' if int(networkx.__version__.split(".")[0]) == 1 else "" - # examples of dot files used in the following test dotfile_orig = [ - "strict digraph " + graph_str + " {\n", + "strict digraph {\n", '"mod1 (engine)";\n', '"mod2 (engine)";\n', '"mod1 (engine)" -> "mod2 (engine)";\n', @@ -539,7 +530,7 @@ def test_deep_nested_write_graph_runs(tmpdir): "graph_type", ["orig", "flat", "exec", "hierarchical", "colored"] ) def test_write_graph_dotfile(tmpdir, graph_type, simple): - """ checking dot files for a workflow without iterables""" + """checking dot files for a workflow without iterables""" tmpdir.chdir() pipe = pe.Workflow(name="pipe") @@ -549,7 +540,9 @@ def test_write_graph_dotfile(tmpdir, graph_type, simple): pipe.write_graph(graph2use=graph_type, simple_form=simple, format="dot") with open("graph.dot") as f: - graph_str = f.read() + # Replace handles change in networkx behavior when graph is missing a name + # Probably around 3, but I haven't tracked it down. + graph_str = f.read().replace(' {', ' {') if simple: for line in dotfiles[graph_type]: @@ -573,7 +566,7 @@ def test_write_graph_dotfile(tmpdir, graph_type, simple): ) # graph_detailed is the same for orig, flat, exec (if no iterables) - # graph_detailed is not created for hierachical or colored + # graph_detailed is not created for hierarchical or colored if graph_type not in ["hierarchical", "colored"]: with open("graph_detailed.dot") as f: graph_str = f.read() @@ -632,7 +625,7 @@ def test_write_graph_dotfile(tmpdir, graph_type, simple): "graph_type", ["orig", "flat", "exec", "hierarchical", "colored"] ) def test_write_graph_dotfile_iterables(tmpdir, graph_type, simple): - """ checking dot files for a workflow with iterables""" + """checking dot files for a workflow with iterables""" tmpdir.chdir() pipe = pe.Workflow(name="pipe") @@ -643,7 +636,9 @@ def test_write_graph_dotfile_iterables(tmpdir, graph_type, simple): pipe.write_graph(graph2use=graph_type, simple_form=simple, format="dot") with open("graph.dot") as f: - graph_str = f.read() + # Replace handles change in networkx behavior when graph is missing a name + # Probably around 3, but I haven't tracked it down. + graph_str = f.read().replace(' {', ' {') if simple: for line in dotfiles_iter[graph_type]: @@ -666,7 +661,7 @@ def test_write_graph_dotfile_iterables(tmpdir, graph_type, simple): in graph_str ) - # graph_detailed is not created for hierachical or colored + # graph_detailed is not created for hierarchical or colored if graph_type not in ["hierarchical", "colored"]: with open("graph_detailed.dot") as f: graph_str = f.read() diff --git a/nipype/pipeline/engine/tests/test_join.py b/nipype/pipeline/engine/tests/test_join.py index b14d79a366..c177ad24d3 100644 --- a/nipype/pipeline/engine/tests/test_join.py +++ b/nipype/pipeline/engine/tests/test_join.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Tests for join expansion -""" +"""Tests for join expansion""" import pytest from .... import config @@ -40,7 +38,7 @@ class IncrementInputSpec(nib.TraitedSpec): class IncrementOutputSpec(nib.TraitedSpec): - output1 = nib.traits.Int(desc="ouput") + output1 = nib.traits.Int(desc="output") class IncrementInterface(nib.SimpleInterface): @@ -63,7 +61,7 @@ class SumInputSpec(nib.TraitedSpec): class SumOutputSpec(nib.TraitedSpec): - output1 = nib.traits.Int(desc="ouput") + output1 = nib.traits.Int(desc="output") operands = nib.traits.List(nib.traits.Int, desc="operands") @@ -91,7 +89,7 @@ class SetInputSpec(nib.TraitedSpec): class SetOutputSpec(nib.TraitedSpec): - output1 = nib.traits.Int(desc="ouput") + output1 = nib.traits.Int(desc="output") class SetInterface(nib.BaseInterface): @@ -406,7 +404,7 @@ def test_multifield_join_node(tmpdir): # node and 1 post-join node. assert len(result.nodes()) == 10, "The number of expanded nodes is incorrect." # the product inputs are [2, 4], [2, 5], [3, 4], [3, 5] - assert set(_products) == set([8, 10, 12, 15]), ( + assert set(_products) == {8, 10, 12, 15}, ( "The post-join products is incorrect: %s." % _products ) @@ -623,7 +621,7 @@ def test_name_prefix_join(tmpdir): tmpdir.chdir() def sq(x): - return x ** 2 + return x**2 wf = pe.Workflow("wf", base_dir=tmpdir.strpath) square = pe.Node(Function(function=sq), name="square") @@ -642,7 +640,7 @@ def test_join_nestediters(tmpdir): tmpdir.chdir() def exponent(x, p): - return x ** p + return x**p wf = pe.Workflow("wf", base_dir=tmpdir.strpath) diff --git a/nipype/pipeline/engine/tests/test_nodes.py b/nipype/pipeline/engine/tests/test_nodes.py index f5e2d5016c..19ffd714c6 100644 --- a/nipype/pipeline/engine/tests/test_nodes.py +++ b/nipype/pipeline/engine/tests/test_nodes.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -7,6 +6,7 @@ from .... import config from ....interfaces import utility as niu +from ....interfaces import base as nib from ... import engine as pe from ..utils import merge_dict from .test_base import EngineTestInterface @@ -258,9 +258,9 @@ def test_function(arg1): file1 = os.path.join(os.getcwd(), "file1.txt") file2 = os.path.join(os.getcwd(), "file2.txt") - with open(file1, "wt") as fp: + with open(file1, "w") as fp: fp.write("%d" % arg1) - with open(file2, "wt") as fp: + with open(file2, "w") as fp: fp.write("%d" % arg1) return file1, file2 @@ -334,3 +334,48 @@ def _producer(num=1, deadly_num=7): wf.base_dir = os.path.abspath("./test_output") with pytest.raises(RuntimeError): wf.run(plugin="MultiProc") + + +class FailCommandLine(nib.CommandLine): + input_spec = nib.CommandLineInputSpec + output_spec = nib.TraitedSpec + _cmd = 'nipype-node-execution-fail' + + +def test_NodeExecutionError(tmp_path, monkeypatch): + import stat + + monkeypatch.chdir(tmp_path) + + # create basic executable and add to PATH + exebin = tmp_path / 'bin' + exebin.mkdir() + exe = exebin / 'nipype-node-execution-fail' + exe.write_text( + '#!/bin/bash\necho "Running"\necho "This should fail" >&2\nexit 1', + encoding='utf-8', + ) + exe.chmod(exe.stat().st_mode | stat.S_IEXEC) + monkeypatch.setenv("PATH", str(exe.parent.absolute()), prepend=os.pathsep) + + # Test with cmdline interface + cmd = pe.Node(FailCommandLine(), name="cmd-fail", base_dir='cmd') + with pytest.raises(pe.nodes.NodeExecutionError) as exc: + cmd.run() + error_msg = str(exc.value) + + for attr in ("Cmdline:", "Stdout:", "Stderr:", "Traceback:"): + assert attr in error_msg + assert "This should fail" in error_msg + + # Test with function interface + def fail(): + raise Exception("Functions can fail too") + + func = pe.Node(niu.Function(function=fail), name='func-fail', base_dir='func') + with pytest.raises(pe.nodes.NodeExecutionError) as exc: + func.run() + error_msg = str(exc.value) + assert "Traceback:" in error_msg + assert "Cmdline:" not in error_msg + assert "Functions can fail too" in error_msg diff --git a/nipype/pipeline/engine/tests/test_utils.py b/nipype/pipeline/engine/tests/test_utils.py index 1e86e5a071..7ae8ce5b33 100644 --- a/nipype/pipeline/engine/tests/test_utils.py +++ b/nipype/pipeline/engine/tests/test_utils.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Tests for the engine utils module -""" +"""Tests for the engine utils module""" import os from copy import deepcopy import pytest @@ -11,7 +9,12 @@ from ....interfaces import base as nib from ....interfaces import utility as niu from .... import config -from ..utils import clean_working_directory, write_workflow_prov, load_resultfile +from ..utils import ( + clean_working_directory, + write_workflow_prov, + load_resultfile, + format_node, +) class InputSpec(nib.TraitedSpec): @@ -174,11 +177,11 @@ def test_mapnode_crash(tmpdir): iterfield=["WRONG"], name="myfunc", ) - node.inputs.WRONG = ["string{}".format(i) for i in range(3)] + node.inputs.WRONG = [f"string{i}" for i in range(3)] node.config = deepcopy(config._sections) node.config["execution"]["stop_on_first_crash"] = True node.base_dir = tmpdir.strpath - with pytest.raises(TypeError): + with pytest.raises(pe.nodes.NodeExecutionError): node.run() os.chdir(cwd) @@ -193,7 +196,7 @@ def test_mapnode_crash2(tmpdir): iterfield=["WRONG"], name="myfunc", ) - node.inputs.WRONG = ["string{}".format(i) for i in range(3)] + node.inputs.WRONG = [f"string{i}" for i in range(3)] node.base_dir = tmpdir.strpath with pytest.raises(Exception): @@ -211,7 +214,7 @@ def test_mapnode_crash3(tmpdir): iterfield=["WRONG"], name="myfunc", ) - node.inputs.WRONG = ["string{}".format(i) for i in range(3)] + node.inputs.WRONG = [f"string{i}" for i in range(3)] wf = pe.Workflow("testmapnodecrash") wf.add_nodes([node]) wf.base_dir = tmpdir.strpath @@ -226,7 +229,7 @@ class StrPathConfuserInputSpec(nib.TraitedSpec): class StrPathConfuserOutputSpec(nib.TraitedSpec): - out_tuple = nib.traits.Tuple(nib.File, nib.traits.String) + out_tuple = nib.Tuple(nib.File, nib.traits.String) out_dict_path = nib.traits.Dict(nib.traits.String, nib.File(exists=True)) out_dict_str = nib.traits.DictStrStr() out_list = nib.traits.List(nib.traits.String) @@ -327,3 +330,11 @@ def test_save_load_resultfile(tmpdir, use_relative): ) config.set("execution", "use_relative_paths", old_use_relative) + + +def test_format_node(): + node = pe.Node(niu.IdentityInterface(fields=["a", "b"]), name="node") + serialized = format_node(node) + workspace = {"Node": pe.Node} + exec("\n".join(serialized), workspace) + assert workspace["node"].interface._fields == node.interface._fields diff --git a/nipype/pipeline/engine/tests/test_workflows.py b/nipype/pipeline/engine/tests/test_workflows.py index 75f77525f8..980b54fa28 100644 --- a/nipype/pipeline/engine/tests/test_workflows.py +++ b/nipype/pipeline/engine/tests/test_workflows.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Tests for the engine workflows module -""" +"""Tests for the engine workflows module""" from glob import glob import os from shutil import rmtree @@ -21,7 +19,7 @@ def test_init(): with pytest.raises(TypeError): pe.Workflow() pipe = pe.Workflow(name="pipe") - assert type(pipe._graph) == nx.DiGraph + assert type(pipe._graph) is nx.DiGraph def test_connect(): @@ -83,8 +81,23 @@ def test_doubleconnect(): assert "Trying to connect" in str(excinfo.value) -def test_duplicate_node_check(): +def test_nested_workflow_doubleconnect(): + # double input with nested workflows + a = pe.Node(niu.IdentityInterface(fields=["a", "b"]), name="a") + b = pe.Node(niu.IdentityInterface(fields=["a", "b"]), name="b") + c = pe.Node(niu.IdentityInterface(fields=["a", "b"]), name="c") + flow1 = pe.Workflow(name="test1") + flow2 = pe.Workflow(name="test2") + flow3 = pe.Workflow(name="test3") + flow1.add_nodes([b]) + flow2.connect(a, "a", flow1, "b.a") + with pytest.raises(Exception) as excinfo: + flow3.connect(c, "a", flow2, "test1.b.a") + assert "Some connections were not found" in str(excinfo.value) + flow3.connect(c, "b", flow2, "test1.b.b") + +def test_duplicate_node_check(): wf = pe.Workflow(name="testidentity") original_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] @@ -119,7 +132,7 @@ def _test_function(arg1): file4 = os.path.join(os.getcwd(), "subdir", "file4.txt") os.mkdir("subdir") for filename in [file1, file2, file3, file4]: - with open(filename, "wt") as fp: + with open(filename, "w") as fp: fp.write("%d" % arg1) return file1, file2, os.path.join(os.getcwd(), "subdir") @@ -127,7 +140,7 @@ def _test_function(arg1): def _test_function2(in_file, arg): import os - with open(in_file, "rt") as fp: + with open(in_file) as fp: in_arg = fp.read() file1 = os.path.join(os.getcwd(), "file1.txt") @@ -135,7 +148,7 @@ def _test_function2(in_file, arg): file3 = os.path.join(os.getcwd(), "file3.txt") files = [file1, file2, file3] for filename in files: - with open(filename, "wt") as fp: + with open(filename, "w") as fp: fp.write("%d" % arg + in_arg) return file1, file2, 1 diff --git a/nipype/pipeline/engine/utils.py b/nipype/pipeline/engine/utils.py index 78d9417f9f..0f800aa02a 100644 --- a/nipype/pipeline/engine/utils.py +++ b/nipype/pipeline/engine/utils.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Utility routines for workflow graphs""" @@ -18,7 +17,7 @@ import numpy as np -from ... import logging, config, LooseVersion +from ... import logging, config from ...utils.filemanip import ( indirectory, relpath, @@ -51,14 +50,14 @@ logger = logging.getLogger("nipype.workflow") -def _parameterization_dir(param): +def _parameterization_dir(param, maxlen): """ Returns the directory name for the given parameterization string as follows: - - If the parameterization is longer than 32 characters, then + - If the parameterization is longer than maxlen characters, then return the SHA-1 hex digest. - Otherwise, return the parameterization unchanged. """ - if len(param) > 32: + if len(param) > maxlen: return sha1(param.encode()).hexdigest() return param @@ -67,13 +66,13 @@ def save_hashfile(hashfile, hashed_inputs): """Store a hashfile""" try: save_json(hashfile, hashed_inputs) - except (IOError, TypeError): + except (OSError, TypeError): err_type = sys.exc_info()[0] if err_type is TypeError: # XXX - SG current workaround is to just # create the hashed file and not put anything # in it - with open(hashfile, "wt") as fd: + with open(hashfile, "w") as fd: fd.writelines(str(hashed_inputs)) logger.debug("Unable to write a particular type to the json file") @@ -125,7 +124,7 @@ def write_node_report(node, result=None, is_mapnode=False): if result is None: logger.debug('[Node] Writing pre-exec report to "%s"', report_file) - report_file.write_text("\n".join(lines)) + report_file.write_text("\n".join(lines), encoding='utf-8') return logger.debug('[Node] Writing post-exec report to "%s"', report_file) @@ -138,7 +137,7 @@ def write_node_report(node, result=None, is_mapnode=False): outputs = result.outputs if outputs is None: lines += ["None"] - report_file.write_text("\n".join(lines)) + report_file.write_text("\n".join(lines), encoding='utf-8') return if isinstance(outputs, Bunch): @@ -163,7 +162,7 @@ def write_node_report(node, result=None, is_mapnode=False): subnode_report_files.append("subnode %d : %s" % (i, subnode_file)) lines.append(write_rst_list(subnode_report_files)) - report_file.write_text("\n".join(lines)) + report_file.write_text("\n".join(lines), encoding='utf-8') return lines.append(write_rst_header("Runtime info", level=1)) @@ -205,7 +204,7 @@ def write_node_report(node, result=None, is_mapnode=False): write_rst_dict(result.runtime.environ), ] - report_file.write_text("\n".join(lines)) + report_file.write_text("\n".join(lines), encoding='utf-8') def write_report(node, report_type=None, is_mapnode=False): @@ -291,7 +290,7 @@ def load_resultfile(results_file, resolve=True): raise FileNotFoundError(results_file) result = loadpkl(results_file) - if resolve and result.outputs: + if resolve and getattr(result, "outputs", None): try: outputs = result.outputs.get() except TypeError: # This is a Bunch @@ -333,7 +332,7 @@ def _write_inputs(node): try: func = create_function_from_source(val) except RuntimeError: - lines.append("%s.inputs.%s = '%s'" % (nodename, key, val)) + lines.append(f"{nodename}.inputs.{key} = '{val}'") else: funcname = [ name for name in func.__globals__ if name != "__builtins__" @@ -345,11 +344,9 @@ def _write_inputs(node): ) funcname = "%s_1" % funcname lines.append("from nipype.utils.functions import getsource") - lines.append( - "%s.inputs.%s = getsource(%s)" % (nodename, key, funcname) - ) + lines.append(f"{nodename}.inputs.{key} = getsource({funcname})") else: - lines.append("%s.inputs.%s = %s" % (nodename, key, val)) + lines.append(f"{nodename}.inputs.{key} = {val}") return lines @@ -361,24 +358,18 @@ def format_node(node, format="python", include_config=False): name = node.fullname.replace(".", "_") if format == "python": klass = node.interface - importline = "from %s import %s" % (klass.__module__, klass.__class__.__name__) + importline = f"from {klass.__module__} import {klass.__class__.__name__}" comment = "# Node: %s" % node.fullname spec = signature(node.interface.__init__) - args = [p.name for p in list(spec.parameters.values())] - args = args[1:] - if args: - filled_args = [] - for arg in args: - if hasattr(node.interface, "_%s" % arg): - filled_args.append( - "%s=%s" % (arg, getattr(node.interface, "_%s" % arg)) - ) - args = ", ".join(filled_args) - else: - args = "" + filled_args = [] + for param in spec.parameters.values(): + val = getattr(node.interface, f"_{param.name}", None) + if val is not None: + filled_args.append(f"{param.name}={val!r}") + args = ", ".join(filled_args) klass_name = klass.__class__.__name__ if isinstance(node, MapNode): - nodedef = '%s = MapNode(%s(%s), iterfield=%s, name="%s")' % ( + nodedef = '{} = MapNode({}({}), iterfield={}, name="{}")'.format( name, klass_name, args, @@ -386,7 +377,7 @@ def format_node(node, format="python", include_config=False): name, ) else: - nodedef = '%s = Node(%s(%s), name="%s")' % (name, klass_name, args, name) + nodedef = f'{name} = Node({klass_name}({args}), name="{name}")' lines = [importline, comment, nodedef] if include_config: @@ -396,10 +387,10 @@ def format_node(node, format="python", include_config=False): comment, nodedef, ] - lines.append("%s.config = %s" % (name, node.config)) + lines.append(f"{name}.config = {node.config}") if node.iterables is not None: - lines.append("%s.iterables = %s" % (name, node.iterables)) + lines.append(f"{name}.iterables = {node.iterables}") lines.extend(_write_inputs(node)) return lines @@ -443,11 +434,11 @@ def modify_paths(object, relative=True, basedir=None): else: out = os.path.abspath(os.path.join(basedir, object)) if not os.path.exists(out): - raise IOError("File %s not found" % out) + raise OSError("File %s not found" % out) else: out = object else: - raise TypeError("Object {} is undefined".format(object)) + raise TypeError(f"Object {object} is undefined") return out @@ -466,9 +457,9 @@ def get_print_name(node, simple_form=True): if len(pkglist) > 2: destclass = ".%s" % pkglist[2] if simple_form: - name = node.fullname + destclass + name = f"{node.fullname}{destclass}" else: - name = ".".join([node.fullname, interface]) + destclass + name = f"{node.fullname}.{interface}{destclass}" if simple_form: parts = name.split(".") if len(parts) > 2: @@ -492,9 +483,9 @@ def _create_dot_graph(graph, show_connectinfo=False, simple_form=True): srcname = get_print_name(edge[0], simple_form=simple_form) destname = get_print_name(edge[1], simple_form=simple_form) if show_connectinfo: - pklgraph.add_edge(srcname, destname, l=str(data["connect"])) + pklgraph.add_edge(f'"{srcname}"', f'"{destname}"', l=str(data["connect"])) else: - pklgraph.add_edge(srcname, destname) + pklgraph.add_edge(f'"{srcname}"', f'"{destname}"') return pklgraph @@ -519,15 +510,15 @@ def _write_detailed_dot(graph, dotfilename): edges = [] for n in nx.topological_sort(graph): nodename = n.itername - inports = [] + in_ports = [] for u, v, d in graph.in_edges(nbunch=n, data=True): for cd in d["connect"]: if isinstance(cd[0], (str, bytes)): outport = cd[0] else: outport = cd[0][0] - inport = cd[1] - ipstrip = "in%s" % _replacefunk(inport) + in_port = cd[1] + ipstrip = "in%s" % _replacefunk(in_port) opstrip = "out%s" % _replacefunk(outport) edges.append( "%s:%s:e -> %s:%s:w;" @@ -538,11 +529,11 @@ def _write_detailed_dot(graph, dotfilename): ipstrip, ) ) - if inport not in inports: - inports.append(inport) + if in_port not in in_ports: + in_ports.append(in_port) inputstr = ( ["{IN"] - + ["| %s" % (_replacefunk(ip), ip) for ip in sorted(inports)] + + [f"| {ip}" for ip in sorted(in_ports)] + ["}"] ) outports = [] @@ -556,10 +547,7 @@ def _write_detailed_dot(graph, dotfilename): outports.append(outport) outputstr = ( ["{OUT"] - + [ - "| %s" % (_replacefunk(oport), oport) - for oport in sorted(outports) - ] + + [f"| {oport}" for oport in sorted(outports)] + ["}"] ) srcpackage = "" @@ -568,7 +556,7 @@ def _write_detailed_dot(graph, dotfilename): if len(pkglist) > 2: srcpackage = pkglist[2] srchierarchy = ".".join(nodename.split(".")[1:-1]) - nodenamestr = "{ %s | %s | %s }" % ( + nodenamestr = "{{ {} | {} | {} }}".format( nodename.split(".")[-1], srcpackage, srchierarchy, @@ -586,7 +574,7 @@ def _write_detailed_dot(graph, dotfilename): for edge in sorted(edges): text.append(edge) text.append("}") - with open(dotfilename, "wt") as filep: + with open(dotfilename, "w") as filep: filep.write("\n".join(text)) return text @@ -657,8 +645,7 @@ def walk(children, level=0, path=None, usename=True): else: path[level] = child # Recurse into the next level - for child_paths in walk(tail, level + 1, path, usename): - yield child_paths + yield from walk(tail, level + 1, path, usename) def synchronize_iterables(iterables): @@ -702,15 +689,10 @@ def evaluate_connect_function(function_source, args, first_arg): try: output_value = func(first_arg, *list(args)) except NameError as e: - if e.args[0].startswith("global name") and e.args[0].endswith("is not defined"): - e.args = ( - e.args[0], - ( - "Due to engine constraints all imports have to be done " - "inside each function definition" - ), - ) - raise e + raise NameError( + f"{e}: Due to engine constraints all imports have to be done inside each " + " function definition." + ) return output_value @@ -759,15 +741,13 @@ def _merge_graphs( # nodes of the supergraph. supernodes = supergraph.nodes() ids = [n._hierarchy + n._id for n in supernodes] - if len(np.unique(ids)) != len(ids): + if len(set(ids)) != len(ids): # This should trap the problem of miswiring when multiple iterables are # used at the same level. The use of the template below for naming # updates to nodes is the general solution. raise Exception( - ( - "Execution graph does not have a unique set of node " - "names. Please rerun the workflow" - ) + "Execution graph does not have a unique set of node " + "names. Please rerun the workflow" ) edgeinfo = {} for n in list(subgraph.nodes()): @@ -831,8 +811,7 @@ def _merge_graphs( def _connect_nodes(graph, srcnode, destnode, connection_info): - """Add a connection between two nodes - """ + """Add a connection between two nodes""" data = graph.get_edge_data(srcnode, destnode, default=None) if not data: data = {"connect": connection_info} @@ -868,13 +847,12 @@ def _identity_nodes(graph, include_iterables): node for node in nx.topological_sort(graph) if isinstance(node.interface, IdentityInterface) - and (include_iterables or getattr(node, "iterables") is None) + and (include_iterables or node.iterables is None) ] def _remove_identity_node(graph, node): - """Remove identity nodes from an execution graph - """ + """Remove identity nodes from an execution graph""" portinputs, portoutputs = _node_ports(graph, node) for field, connections in list(portoutputs.items()): if portinputs: @@ -903,34 +881,34 @@ def _node_ports(graph, node): for _, v, d in graph.out_edges(node, data=True): for src, dest in d["connect"]: if isinstance(src, tuple): - srcport = src[0] + src_port = src[0] else: - srcport = src - if srcport not in portoutputs: - portoutputs[srcport] = [] - portoutputs[srcport].append((v, dest, src)) + src_port = src + if src_port not in portoutputs: + portoutputs[src_port] = [] + portoutputs[src_port].append((v, dest, src)) return (portinputs, portoutputs) def _propagate_root_output(graph, node, field, connections): """Propagates the given graph root node output port field connections to the out-edge destination nodes.""" - for destnode, inport, src in connections: + for destnode, in_port, src in connections: value = getattr(node.inputs, field) if isinstance(src, tuple): value = evaluate_connect_function(src[1], src[2], value) - destnode.set_input(inport, value) + destnode.set_input(in_port, value) def _propagate_internal_output(graph, node, field, connections, portinputs): """Propagates the given graph internal node output port field connections to the out-edge source node and in-edge destination nodes.""" - for destnode, inport, src in connections: + for destnode, in_port, src in connections: if field in portinputs: - srcnode, srcport = portinputs[field] - if isinstance(srcport, tuple) and isinstance(src, tuple): - src_func = srcport[1].split("\\n")[0] + srcnode, src_port = portinputs[field] + if isinstance(src_port, tuple) and isinstance(src, tuple): + src_func = src_port[1].split("\\n")[0] dst_func = src[1].split("\\n")[0] raise ValueError( "Does not support two inline functions " @@ -941,9 +919,9 @@ def _propagate_internal_output(graph, node, field, connections, portinputs): connect = graph.get_edge_data(srcnode, destnode, default={"connect": []}) if isinstance(src, tuple): - connect["connect"].append(((srcport, src[1], src[2]), inport)) + connect["connect"].append(((src_port, src[1], src[2]), in_port)) else: - connect = {"connect": [(srcport, inport)]} + connect = {"connect": [(src_port, in_port)]} old_connect = graph.get_edge_data( srcnode, destnode, default={"connect": []} ) @@ -953,7 +931,7 @@ def _propagate_internal_output(graph, node, field, connections, portinputs): value = getattr(node.inputs, field) if isinstance(src, tuple): value = evaluate_connect_function(src[1], src[2], value) - destnode.set_input(inport, value) + destnode.set_input(in_port, value) def generate_expanded_graph(graph_in): @@ -1021,11 +999,9 @@ def generate_expanded_graph(graph_in): # find the unique iterable source node in the graph try: iter_src = next( - ( - node - for node in graph_in.nodes() - if node.name == src_name and nx.has_path(graph_in, node, inode) - ) + node + for node in graph_in.nodes() + if node.name == src_name and nx.has_path(graph_in, node, inode) ) except StopIteration: raise ValueError( @@ -1038,7 +1014,7 @@ def generate_expanded_graph(graph_in): iterables = {} # the source node iterables values src_values = [getattr(iter_src.inputs, field) for field in src_fields] - # if there is one source field, then the key is the the source value, + # if there is one source field, then the key is the source value, # otherwise the key is the tuple of source values if len(src_values) == 1: key = src_values[0] @@ -1047,13 +1023,9 @@ def generate_expanded_graph(graph_in): # The itersource iterables is a {field: lookup} dictionary, where the # lookup is a {source key: iteration list} dictionary. Look up the # current iterable value using the predecessor itersource input values. - iter_dict = dict( - [ - (field, lookup[key]) - for field, lookup in inode.iterables - if key in lookup - ] - ) + iter_dict = { + field: lookup[key] for field, lookup in inode.iterables if key in lookup + } # convert the iterables to the standard {field: function} format @@ -1069,7 +1041,7 @@ def make_field_func(*pair): logger.debug("node: %s iterables: %s", inode, iterables) # collect the subnodes to expand - subnodes = [s for s in dfs_preorder(graph_in, inode)] + subnodes = list(dfs_preorder(graph_in, inode)) prior_prefix = [re.findall(r"\.(.)I", s._id) for s in subnodes if s._id] prior_prefix = sorted([l for item in prior_prefix for l in item]) if not prior_prefix: @@ -1084,11 +1056,7 @@ def make_field_func(*pair): inode._id += ".%sI" % iterable_prefix # merge the iterated subgraphs - # dj: the behaviour of .copy changes in version 2 - if LooseVersion(nx.__version__) < LooseVersion("2"): - subgraph = graph_in.subgraph(subnodes) - else: - subgraph = graph_in.subgraph(subnodes).copy() + subgraph = graph_in.subgraph(subnodes).copy() graph_in = _merge_graphs( graph_in, subnodes, @@ -1106,11 +1074,12 @@ def make_field_func(*pair): old_edge_dict = jedge_dict[jnode] # the edge source node replicates expansions = defaultdict(list) - for node in graph_in.nodes(): + for node in graph_in: for src_id in list(old_edge_dict.keys()): # Drop the original JoinNodes; only concerned with # generated Nodes - if hasattr(node, "joinfield") and node.itername == src_id: + itername = node.itername + if hasattr(node, "joinfield") and itername == src_id: continue # Patterns: # - src_id : Non-iterable node @@ -1119,13 +1088,13 @@ def make_field_func(*pair): # - src_id.[a-z]I.[a-z]\d+ : # Non-IdentityInterface w/ iterables # - src_idJ\d+ : JoinNode(IdentityInterface) - if re.match( - src_id + r"((\.[a-z](I\.[a-z])?|J)\d+)?$", node.itername - ): - expansions[src_id].append(node) + if itername.startswith(src_id): + suffix = itername[len(src_id) :] + if re.fullmatch(r"((\.[a-z](I\.[a-z])?|J)\d+)?", suffix): + expansions[src_id].append(node) for in_id, in_nodes in list(expansions.items()): logger.debug( - "The join node %s input %s was expanded" " to %d nodes.", + "The join node %s input %s was expanded to %d nodes.", jnode, in_id, len(in_nodes), @@ -1246,9 +1215,7 @@ def _standardize_iterables(node): if node.synchronize: if len(iterables) == 2: first, last = iterables - if all( - (isinstance(item, (str, bytes)) and item in fields for item in first) - ): + if all(isinstance(item, (str, bytes)) and item in fields for item in first): iterables = _transpose_iterables(first, last) # Convert a tuple to a list @@ -1290,16 +1257,14 @@ def _validate_iterables(node, iterables, fields): try: if len(item) != 2: raise ValueError( - "The %s iterables is not a [(field, values)]" " list" % node.name + "The %s iterables is not a [(field, values)] list" % node.name ) except TypeError as e: - raise TypeError( - "A %s iterables member is not iterable: %s" % (node.name, e) - ) + raise TypeError(f"A {node.name} iterables member is not iterable: {e}") field, _ = item if field not in fields: raise ValueError( - "The %s iterables field is unrecognized: %s" % (node.name, field) + f"The {node.name} iterables field is unrecognized: {field}" ) @@ -1314,7 +1279,7 @@ def _transpose_iterables(fields, values): Otherwise, the result is a list of (field: value list) pairs. """ if isinstance(values, dict): - transposed = dict([(field, defaultdict(list)) for field in fields]) + transposed = {field: defaultdict(list) for field in fields} for key, tuples in list(values.items()): for kvals in tuples: for idx, val in enumerate(kvals): @@ -1343,7 +1308,7 @@ def export_graph( format="png", simple_form=True, ): - """ Displays the graph layout of the pipeline + """Displays the graph layout of the pipeline This function requires that pygraphviz and matplotlib are available on the system. @@ -1409,9 +1374,9 @@ def format_dot(dotfilename, format="png"): """Dump a directed graph (Linux only; install via `brew` on OSX)""" try: formatted_dot, _ = _run_dot(dotfilename, format_ext=format) - except IOError as ioe: + except OSError as ioe: if "could not be found" in str(ioe): - raise IOError("Cannot draw directed graph; executable 'dot' is unavailable") + raise OSError("Cannot draw directed graph; executable 'dot' is unavailable") else: raise ioe return formatted_dot @@ -1422,8 +1387,8 @@ def _run_dot(dotfilename, format_ext): return dotfilename, None dot_base = os.path.splitext(dotfilename)[0] - formatted_dot = "{}.{}".format(dot_base, format_ext) - cmd = 'dot -T{} -o"{}" "{}"'.format(format_ext, formatted_dot, dotfilename) + formatted_dot = f"{dot_base}.{format_ext}" + cmd = f'dot -T{format_ext} -o"{formatted_dot}" "{dotfilename}"' res = CommandLine(cmd, terminal_output="allatonce", resource_monitor=False).run() return formatted_dot, res @@ -1439,8 +1404,7 @@ def get_all_files(infile): def walk_outputs(object): - """Extract every file and directory from a python structure - """ + """Extract every file and directory from a python structure""" out = [] if isinstance(object, dict): for _, val in sorted(object.items()): @@ -1468,8 +1432,7 @@ def walk_files(cwd): def clean_working_directory( outputs, cwd, inputs, needed_outputs, config, files2keep=None, dirs2keep=None ): - """Removes all files not needed for further analysis from the directory - """ + """Removes all files not needed for further analysis from the directory""" if not outputs: return outputs_to_keep = list(outputs.trait_get().keys()) @@ -1511,23 +1474,21 @@ def clean_working_directory( needed_files = temp logger.debug("Needed files: %s", ";".join(needed_files)) logger.debug("Needed dirs: %s", ";".join(needed_dirs)) - files2remove = [] if str2bool(config["execution"]["remove_unnecessary_outputs"]): - for f in walk_files(cwd): - if f not in needed_files: - if not needed_dirs: - files2remove.append(f) - elif not any([f.startswith(dname) for dname in needed_dirs]): - files2remove.append(f) + files2remove = [ + f + for f in walk_files(cwd) + if f not in needed_files and not f.startswith(tuple(needed_dirs)) + ] + elif not str2bool(config["execution"]["keep_inputs"]): + input_files = { + path for path, type in walk_outputs(inputs.trait_get()) if type == "f" + } + files2remove = [ + f for f in walk_files(cwd) if f in input_files and f not in needed_files + ] else: - if not str2bool(config["execution"]["keep_inputs"]): - input_files = [] - inputdict = inputs.trait_get() - input_files.extend(walk_outputs(inputdict)) - input_files = [path for path, type in input_files if type == "f"] - for f in walk_files(cwd): - if f in input_files and f not in needed_files: - files2remove.append(f) + files2remove = [] logger.debug("Removing files: %s", ";".join(files2remove)) for f in files2remove: os.remove(f) @@ -1583,8 +1544,7 @@ def merge_bundles(g1, g2): def write_workflow_prov(graph, filename=None, format="all"): - """Write W3C PROV Model JSON file - """ + """Write W3C PROV Model JSON file""" if not filename: filename = os.path.join(os.getcwd(), "workflow_provenance") @@ -1598,7 +1558,7 @@ def write_workflow_prov(graph, filename=None, format="all"): _, hashval, _, _ = node.hash_exists() attrs = { pm.PROV["type"]: nipype_ns[classname], - pm.PROV["label"]: "_".join((classname, node.name)), + pm.PROV["label"]: f"{classname}_{node.name}", nipype_ns["hashval"]: hashval, } process = ps.g.activity(get_id(), None, None, attrs) @@ -1682,7 +1642,7 @@ def write_workflow_resources(graph, filename=None, append=None): # If we append different runs, then we will see different # "bursts" of timestamps corresponding to those executions. if append and os.path.isfile(filename): - with open(filename, "r") as rsf: + with open(filename) as rsf: big_dict = json.load(rsf) for _, node in enumerate(graph.nodes()): @@ -1691,13 +1651,13 @@ def write_workflow_resources(graph, filename=None, append=None): params = "" if node.parameterization: - params = "_".join(["{}".format(p) for p in node.parameterization]) + params = "_".join([f"{p}" for p in node.parameterization]) try: rt_list = node.result.runtime except Exception: logger.warning( - "Could not access runtime info for node %s" " (%s interface)", + "Could not access runtime info for node %s (%s interface)", nodename, classname, ) @@ -1734,8 +1694,7 @@ def write_workflow_resources(graph, filename=None, append=None): def topological_sort(graph, depth_first=False): - """Returns a depth first sorted order if depth_first is True - """ + """Returns a depth first sorted order if depth_first is True""" import networkx as nx nodesort = list(nx.topological_sort(graph)) @@ -1744,16 +1703,12 @@ def topological_sort(graph, depth_first=False): logger.debug("Performing depth first search") nodes = [] groups = [] - group = 0 G = nx.Graph() G.add_nodes_from(graph.nodes()) G.add_edges_from(graph.edges()) components = nx.connected_components(G) - for desc in components: - group += 1 - indices = [] - for node in desc: - indices.append(nodesort.index(node)) + for group, desc in enumerate(components, start=1): + indices = [nodesort.index(node) for node in desc] nodes.extend( np.array(nodesort)[np.array(indices)[np.argsort(indices)]].tolist() ) diff --git a/nipype/pipeline/engine/workflows.py b/nipype/pipeline/engine/workflows.py index d1fde0ba32..54577f21b8 100644 --- a/nipype/pipeline/engine/workflows.py +++ b/nipype/pipeline/engine/workflows.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Defines functionality for pipelined execution of interfaces @@ -9,7 +8,6 @@ import os import os.path as op import sys -from datetime import datetime from copy import deepcopy import pickle import shutil @@ -17,6 +15,7 @@ import numpy as np from ... import config, logging +from ...utils.datetime import utcnow from ...utils.misc import str2bool from ...utils.functions import getsource, create_function_from_source @@ -56,9 +55,12 @@ def __init__(self, name, base_dir=None): """ import networkx as nx - super(Workflow, self).__init__(name, base_dir) + super().__init__(name, base_dir) self._graph = nx.DiGraph() + self._nodes_cache = set() + self._nested_workflows_cache = set() + # PUBLIC API def clone(self, name): """Clone a workflow @@ -75,7 +77,7 @@ def clone(self, name): unique name for the workflow """ - clone = super(Workflow, self).clone(name) + clone = super().clone(name) clone._reset_hierarchy() return clone @@ -117,7 +119,7 @@ def connect(self, *args, **kwargs): 'targetinput'), ...]), ...] sourceoutput1 will always be the first argument to func - and func will be evaluated and the results sent ot targetinput + and func will be evaluated and the results sent to targetinput currently func needs to define all its needed imports within the function as we use the inspect module to get at the source code @@ -141,7 +143,7 @@ def connect(self, *args, **kwargs): self.disconnect(connection_list) return - newnodes = [] + newnodes = set() for srcnode, destnode, _ in connection_list: if self in [srcnode, destnode]: msg = ( @@ -149,11 +151,11 @@ def connect(self, *args, **kwargs): " src[%s] dest[%s] workflow[%s]" ) % (srcnode, destnode, self.name) - raise IOError(msg) + raise OSError(msg) if (srcnode not in newnodes) and not self._has_node(srcnode): - newnodes.append(srcnode) + newnodes.add(srcnode) if (destnode not in newnodes) and not self._has_node(destnode): - newnodes.append(destnode) + newnodes.add(destnode) if newnodes: self._check_nodes(newnodes) for node in newnodes: @@ -163,15 +165,15 @@ def connect(self, *args, **kwargs): connected_ports = {} for srcnode, destnode, connects in connection_list: if destnode not in connected_ports: - connected_ports[destnode] = [] + connected_ports[destnode] = set() # check to see which ports of destnode are already # connected. if not disconnect and (destnode in self._graph.nodes()): for edge in self._graph.in_edges(destnode): data = self._graph.get_edge_data(*edge) - for sourceinfo, destname in data["connect"]: - if destname not in connected_ports[destnode]: - connected_ports[destnode] += [destname] + connected_ports[destnode].update( + destname for _, destname in data["connect"] + ) for source, dest in connects: # Currently datasource/sink/grabber.io modules # determine their inputs/outputs depending on @@ -189,10 +191,8 @@ def connect(self, *args, **kwargs): and ( ".io" in str(destnode._interface.__class__) or any( - [ - ".io" in str(val) - for val in destnode._interface.__class__.__bases__ - ] + ".io" in str(val) + for val in destnode._interface.__class__.__bases__ ) ) ): @@ -203,10 +203,8 @@ def connect(self, *args, **kwargs): and ( ".io" in str(srcnode._interface.__class__) or any( - [ - ".io" in str(val) - for val in srcnode._interface.__class__.__bases__ - ] + ".io" in str(val) + for val in srcnode._interface.__class__.__bases__ ) ) ): @@ -226,12 +224,10 @@ def connect(self, *args, **kwargs): ) if sourcename and not srcnode._check_outputs(sourcename): not_found.append(["out", srcnode.name, sourcename]) - connected_ports[destnode] += [dest] + connected_ports[destnode].add(dest) infostr = [] for info in not_found: - infostr += [ - "Module %s has no %sput called %s\n" % (info[1], info[0], info[2]) - ] + infostr += [f"Module {info[1]} has no {info[0]}put called {info[2]}\n"] if not_found: raise Exception("\n".join(["Some connections were not found"] + infostr)) @@ -269,6 +265,9 @@ def connect(self, *args, **kwargs): "(%s, %s): new edge data: %s", srcnode, destnode, str(edge_data) ) + if newnodes: + self._update_node_cache() + def disconnect(self, *args): """Disconnect nodes See the docstring for connect for format. @@ -286,7 +285,7 @@ def disconnect(self, *args): for srcnode, dstnode, conn in connection_list: logger.debug("disconnect(): %s->%s %s", srcnode, dstnode, str(conn)) if self in [srcnode, dstnode]: - raise IOError( + raise OSError( "Workflow connect cannot contain itself as node: src[%s] " "dest[%s] workflow[%s]" ) % (srcnode, dstnode, self.name) @@ -298,11 +297,12 @@ def disconnect(self, *args): edge_data = self._graph.get_edge_data(srcnode, dstnode, {"connect": []}) ed_conns = [(c[0], c[1]) for c in edge_data["connect"]] - remove = [] - for edge in conn: - if edge in ed_conns: - # idx = ed_conns.index(edge) - remove.append((edge[0], edge[1])) + remove = [ + # idx = ed_conns.index(edge) + (edge[0], edge[1]) + for edge in conn + if edge in ed_conns + ] logger.debug("disconnect(): remove list %s", str(remove)) for el in remove: @@ -315,7 +315,7 @@ def disconnect(self, *args): self._graph.add_edges_from([(srcnode, dstnode, edge_data)]) def add_nodes(self, nodes): - """ Add nodes to a workflow + """Add nodes to a workflow Parameters ---------- @@ -325,13 +325,13 @@ def add_nodes(self, nodes): newnodes = [] all_nodes = self._get_all_nodes() for node in nodes: - if self._has_node(node): - raise IOError("Node %s already exists in the workflow" % node) + if node in all_nodes: + raise OSError("Node %s already exists in the workflow" % node) if isinstance(node, Workflow): for subnode in node._get_all_nodes(): if subnode in all_nodes: - raise IOError( - ("Subnode %s of node %s already exists " "in the workflow") + raise OSError( + "Subnode %s of node %s already exists in the workflow" % (subnode, node) ) newnodes.append(node) @@ -346,9 +346,10 @@ def add_nodes(self, nodes): if node._hierarchy is None: node._hierarchy = self.name self._graph.add_nodes_from(newnodes) + self._update_node_cache() def remove_nodes(self, nodes): - """ Remove nodes from a workflow + """Remove nodes from a workflow Parameters ---------- @@ -356,6 +357,7 @@ def remove_nodes(self, nodes): A list of EngineBase-based objects """ self._graph.remove_nodes_from(nodes) + self._update_node_cache() # Input-Output access @property @@ -367,8 +369,7 @@ def outputs(self): return self._get_outputs() def get_node(self, name): - """Return an internal node by name - """ + """Return an internal node by name""" nodenames = name.split(".") nodename = nodenames[0] outnode = [ @@ -383,18 +384,14 @@ def get_node(self, name): return outnode def list_node_names(self): - """List names of all nodes in a workflow - """ + """List names of all nodes in a workflow""" import networkx as nx outlist = [] for node in nx.topological_sort(self._graph): if isinstance(node, Workflow): outlist.extend( - [ - ".".join((node.name, nodename)) - for nodename in node.list_node_names() - ] + f"{node.name}.{nodename}" for nodename in node.list_node_names() ) else: outlist.append(node.name) @@ -480,16 +477,11 @@ def write_graph( def write_hierarchical_dotfile( self, dotfilename=None, colored=False, simple_form=True ): - dotlist = ["digraph %s{" % self.name] - dotlist.append( - self._get_dot(prefix=" ", colored=colored, simple_form=simple_form) - ) - dotlist.append("}") - dotstr = "\n".join(dotlist) + dotlist = self._get_dot(prefix=" ", colored=colored, simple_form=simple_form) + dotstr = f"digraph {self.name}{{\n{dotlist}\n}}" if dotfilename: - fp = open(dotfilename, "wt") - fp.writelines(dotstr) - fp.close() + with open(dotfilename, "w") as fp: + fp.writelines(dotstr) else: logger.info(dotstr) @@ -520,16 +512,16 @@ def export( all_lines = None lines = ["# Workflow"] - importlines = ["from nipype.pipeline.engine import Workflow, " "Node, MapNode"] + importlines = ["from nipype.pipeline.engine import Workflow, Node, MapNode"] functions = {} if format == "python": connect_template = '%s.connect(%%s, %%s, %%s, "%%s")' % self.name connect_template2 = '%s.connect(%%s, "%%s", %%s, "%%s")' % self.name - wfdef = '%s = Workflow("%s")' % (self.name, self.name) + wfdef = f'{self.name} = Workflow("{self.name}")' lines.append(wfdef) if include_config: - lines.append("%s.config = %s" % (self.name, self.config)) - for idx, node in enumerate(nodes): + lines.append(f"{self.name}.config = {self.config}") + for node in nodes: nodename = node.fullname.replace(".", "_") # write nodes nodelines = format_node( @@ -557,7 +549,7 @@ def export( ][0] functions[args[1]] = funcname args[1] = funcname - args = tuple([arg for arg in args if arg]) + args = tuple(arg for arg in args if arg) line_args = ( u.fullname.replace(".", "_"), args, @@ -576,18 +568,19 @@ def export( ) lines.append(connect_template2 % line_args) functionlines = ["# Functions"] - for function in functions: - functionlines.append(pickle.loads(function).rstrip()) + functionlines.extend( + pickle.loads(function).rstrip() for function in functions + ) all_lines = importlines + functionlines + lines if not filename: - filename = "%s%s.py" % (prefix, self.name) - with open(filename, "wt") as fp: + filename = f"{prefix}{self.name}.py" + with open(filename, "w") as fp: fp.writelines("\n".join(all_lines)) return all_lines def run(self, plugin=None, plugin_args=None, updatehash=False): - """ Execute the workflow + """Execute the workflow Parameters ---------- @@ -630,7 +623,7 @@ def run(self, plugin=None, plugin_args=None, updatehash=False): if str2bool(self.config["execution"]["create_report"]): self._write_report_info(self.base_dir, self.name, execgraph) runner.run(execgraph, updatehash=updatehash, config=self.config) - datestr = datetime.utcnow().strftime("%Y%m%dT%H%M%S") + datestr = utcnow().strftime("%Y%m%dT%H%M%S") if str2bool(self.config["execution"]["write_provenance"]): prov_base = op.join(self.base_dir, "workflow_provenance_%s" % datestr) logger.info("Provenance file prefix: %s" % prov_base) @@ -666,7 +659,7 @@ def _write_report_info(self, workingdir, name, graph): report_file = "%s/_report/report.rst" % node.output_dir().replace( report_dir, "" ) - result_file = "%s/result_%s.pklz" % ( + result_file = "{}/result_{}.pklz".format( node.output_dir().replace(report_dir, ""), node.name, ) @@ -736,8 +729,7 @@ def _set_needed_outputs(self, graph): node.needed_outputs = sorted(node.needed_outputs) def _configure_exec_nodes(self, graph): - """Ensure that each node knows where to get inputs from - """ + """Ensure that each node knows where to get inputs from""" for node in graph.nodes(): node.input_source = {} for edge in graph.in_edges(node): @@ -749,9 +741,7 @@ def _configure_exec_nodes(self, graph): ) def _check_nodes(self, nodes): - """Checks if any of the nodes are already in the graph - - """ + """Checks if any of the nodes are already in the graph""" node_names = [node.name for node in self._graph.nodes()] node_lineage = [node._hierarchy for node in self._graph.nodes()] for node in nodes: @@ -760,41 +750,78 @@ def _check_nodes(self, nodes): try: this_node_lineage = node_lineage[idx] except IndexError: - raise IOError('Duplicate node name "%s" found.' % node.name) + raise OSError('Duplicate node name "%s" found.' % node.name) else: if this_node_lineage in [node._hierarchy, self.name]: - raise IOError('Duplicate node name "%s" found.' % node.name) + raise OSError('Duplicate node name "%s" found.' % node.name) else: node_names.append(node.name) def _has_attr(self, parameter, subtype="in"): - """Checks if a parameter is available as an input or output - """ + """Checks if a parameter is available as an input or output""" + hierarchy = parameter.split(".") + + # Connecting to a workflow needs at least two values, + # the name of the child node and the name of the input/output + if len(hierarchy) < 2: + return False + + attrname = hierarchy.pop() + nodename = hierarchy.pop() + + def _check_is_already_connected(workflow, node, attrname): + for _, _, d in workflow._graph.in_edges(nbunch=node, data=True): + for cd in d["connect"]: + if attrname == cd[1]: + return False + return True + + targetworkflow = self + while hierarchy: + workflowname = hierarchy.pop(0) + workflow = None + for node in targetworkflow._graph.nodes(): + if node.name == workflowname: + if isinstance(node, Workflow): + workflow = node + break + if workflow is None: + return False + # Verify input does not already have an incoming connection + # in the hierarchy of workflows + if subtype == "in": + hierattrname = ".".join(hierarchy + [nodename, attrname]) + if not _check_is_already_connected( + targetworkflow, workflow, hierattrname + ): + return False + targetworkflow = workflow + + targetnode = None + for node in targetworkflow._graph.nodes(): + if node.name == nodename: + if isinstance(node, Workflow): + return False + else: + targetnode = node + break + if targetnode is None: + return False + if subtype == "in": - subobject = self.inputs + if not hasattr(targetnode.inputs, attrname): + return False else: - subobject = self.outputs - attrlist = parameter.split(".") - cur_out = subobject - for attr in attrlist: - if not hasattr(cur_out, attr): + if not hasattr(targetnode.outputs, attrname): return False - cur_out = getattr(cur_out, attr) - return True - def _get_parameter_node(self, parameter, subtype="in"): - """Returns the underlying node corresponding to an input or - output parameter - """ + # Verify input does not already have an incoming connection + # in the target workflow if subtype == "in": - subobject = self.inputs - else: - subobject = self.outputs - attrlist = parameter.split(".") - cur_out = subobject - for attr in attrlist[:-1]: - cur_out = getattr(cur_out, attr) - return cur_out.traits()[attrlist[-1]].node + if not _check_is_already_connected(targetworkflow, targetnode, attrname): + return False + + return True def _check_outputs(self, parameter): return self._has_attr(parameter, subtype="out") @@ -814,10 +841,11 @@ def _get_inputs(self): if isinstance(node, Workflow): setattr(inputdict, node.name, node.inputs) else: - taken_inputs = [] - for _, _, d in self._graph.in_edges(nbunch=node, data=True): - for cd in d["connect"]: - taken_inputs.append(cd[1]) + taken_inputs = [ + cd[1] + for _, _, d in self._graph.in_edges(nbunch=node, data=True) + for cd in d["connect"] + ] unconnectedinputs = TraitedSpec() for key, trait in list(node.inputs.items()): if key not in taken_inputs: @@ -829,8 +857,7 @@ def _get_inputs(self): return inputdict def _get_outputs(self): - """Returns all possible output ports that are not already connected - """ + """Returns all possible output ports that are not already connected""" outputdict = TraitedSpec() for node in self._graph.nodes(): outputdict.add_trait(node.name, traits.Instance(TraitedSpec)) @@ -845,8 +872,7 @@ def _get_outputs(self): return outputdict def _set_input(self, objekt, name, newvalue): - """Trait callback function to update a node input - """ + """Trait callback function to update a node input""" objekt.traits()[name].node.set_input(name, newvalue) def _set_node_input(self, node, param, source, sourceinfo): @@ -865,22 +891,28 @@ def _set_node_input(self, node, param, source, sourceinfo): node.set_input(param, deepcopy(newval)) def _get_all_nodes(self): - allnodes = [] - for node in self._graph.nodes(): - if isinstance(node, Workflow): - allnodes.extend(node._get_all_nodes()) - else: - allnodes.append(node) + allnodes = self._nodes_cache - self._nested_workflows_cache + for node in self._nested_workflows_cache: + allnodes |= node._get_all_nodes() return allnodes - def _has_node(self, wanted_node): - for node in self._graph.nodes(): - if wanted_node == node: - return True + def _update_node_cache(self): + nodes = set(self._graph) + + added_nodes = nodes.difference(self._nodes_cache) + removed_nodes = self._nodes_cache.difference(nodes) + + self._nodes_cache = nodes + self._nested_workflows_cache.difference_update(removed_nodes) + + for node in added_nodes: if isinstance(node, Workflow): - if node._has_node(wanted_node): - return True - return False + self._nested_workflows_cache.add(node) + + def _has_node(self, wanted_node): + return wanted_node in self._nodes_cache or any( + wf._has_node(wanted_node) for wf in self._nested_workflows_cache + ) def _create_flat_graph(self): """Make a simple DAG where no node is a workflow.""" @@ -890,28 +922,26 @@ def _create_flat_graph(self): return workflowcopy._graph def _reset_hierarchy(self): - """Reset the hierarchy on a graph - """ + """Reset the hierarchy on a graph""" for node in self._graph.nodes(): if isinstance(node, Workflow): node._reset_hierarchy() for innernode in node._graph.nodes(): - innernode._hierarchy = ".".join((self.name, innernode._hierarchy)) + innernode._hierarchy = f"{self.name}.{innernode._hierarchy}" else: node._hierarchy = self.name def _generate_flatgraph(self): - """Generate a graph containing only Nodes or MapNodes - """ + """Generate a graph containing only Nodes or MapNodes""" import networkx as nx logger.debug("expanding workflow: %s", self) nodes2remove = [] if not nx.is_directed_acyclic_graph(self._graph): raise Exception( - ("Workflow: %s is not a directed acyclic graph " "(DAG)") % self.name + ("Workflow: %s is not a directed acyclic graph (DAG)") % self.name ) - nodes = list(nx.topological_sort(self._graph)) + nodes = list(self._graph.nodes) for node in nodes: logger.debug("processing node: %s", node) if isinstance(node, Workflow): @@ -924,7 +954,7 @@ def _generate_flatgraph(self): logger.debug("in: connections-> %s", str(d["connect"])) for cd in deepcopy(d["connect"]): logger.debug("in: %s", str(cd)) - dstnode = node._get_parameter_node(cd[1], subtype="in") + dstnode = node.get_node(cd[1].rsplit(".", 1)[0]) srcnode = u srcout = cd[0] dstin = cd[1].split(".")[-1] @@ -944,7 +974,7 @@ def _generate_flatgraph(self): parameter = cd[0][0] else: parameter = cd[0] - srcnode = node._get_parameter_node(parameter, subtype="out") + srcnode = node.get_node(parameter.rsplit(".", 1)[0]) if isinstance(cd[0], tuple): srcout = list(cd[0]) srcout[0] = parameter.split(".")[-1] @@ -961,7 +991,7 @@ def _generate_flatgraph(self): # logger.debug('expanding workflow: %s', node) node._generate_flatgraph() for innernode in node._graph.nodes(): - innernode._hierarchy = ".".join((self.name, innernode._hierarchy)) + innernode._hierarchy = f"{self.name}.{innernode._hierarchy}" self._graph.add_nodes_from(node._graph.nodes()) self._graph.add_edges_from(node._graph.edges(data=True)) if nodes2remove: @@ -971,8 +1001,7 @@ def _generate_flatgraph(self): def _get_dot( self, prefix=None, hierarchy=None, colored=False, simple_form=True, level=0 ): - """Create a dot file with connection info - """ + """Create a dot file with connection info""" import networkx as nx if prefix is None: @@ -996,7 +1025,7 @@ def _get_dot( if level > len(colorset) - 2: level = 3 # Loop back to blue - dotlist = ['%slabel="%s";' % (prefix, self.name)] + dotlist = [f'{prefix}label="{self.name}";'] for node in nx.topological_sort(self._graph): fullname = ".".join(hierarchy + [node.fullname]) nodename = fullname.replace(".", "_") @@ -1016,7 +1045,7 @@ def _get_dot( else: if colored: dotlist.append( - ('%s[label="%s", style=filled,' ' fillcolor="%s"];') + ('%s[label="%s", style=filled, fillcolor="%s"];') % (nodename, node_class_name, colorset[level]) ) else: @@ -1030,23 +1059,25 @@ def _get_dot( nodename = fullname.replace(".", "_") dotlist.append("subgraph cluster_%s {" % nodename) if colored: - dotlist.append( - prefix + prefix + 'edge [color="%s"];' % (colorset[level + 1]) - ) - dotlist.append(prefix + prefix + "style=filled;") - dotlist.append( - prefix + prefix + 'fillcolor="%s";' % (colorset[level + 2]) + dotlist.extend( + ( + f'{prefix * 2}edge [color="{colorset[level + 1]}"];', + f"{prefix * 2}style=filled;", + f'{prefix * 2}fillcolor="{colorset[level + 2]}";', + ) ) - dotlist.append( - node._get_dot( - prefix=prefix + prefix, - hierarchy=hierarchy + [self.name], - colored=colored, - simple_form=simple_form, - level=level + 3, + dotlist.extend( + ( + node._get_dot( + prefix=prefix + prefix, + hierarchy=hierarchy + [self.name], + colored=colored, + simple_form=simple_form, + level=level + 3, + ), + "}", ) ) - dotlist.append("}") else: for subnode in self._graph.successors(node): if node._hierarchy != subnode._hierarchy: @@ -1056,8 +1087,10 @@ def _get_dot( subnodefullname = ".".join(hierarchy + [subnode.fullname]) nodename = nodefullname.replace(".", "_") subnodename = subnodefullname.replace(".", "_") - for _ in self._graph.get_edge_data(node, subnode)["connect"]: - dotlist.append("%s -> %s;" % (nodename, subnodename)) + dotlist.extend( + f"{nodename} -> {subnodename};" + for _ in self._graph.get_edge_data(node, subnode)["connect"] + ) logger.debug("connection: %s", dotlist[-1]) # add between workflow connections for u, v, d in self._graph.edges(data=True): diff --git a/nipype/pipeline/plugins/__init__.py b/nipype/pipeline/plugins/__init__.py index 83f4869a41..0b1ba01637 100644 --- a/nipype/pipeline/plugins/__init__.py +++ b/nipype/pipeline/plugins/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/pipeline/plugins/base.py b/nipype/pipeline/plugins/base.py index 4be8eb232b..1571ab71a9 100644 --- a/nipype/pipeline/plugins/base.py +++ b/nipype/pipeline/plugins/base.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Common graph operations for execution.""" @@ -21,7 +20,19 @@ logger = logging.getLogger("nipype.workflow") -class PluginBase(object): +def _graph_to_lil_matrix(graph, nodelist): + """Provide a sparse linked list matrix across various NetworkX versions""" + import scipy.sparse as ssp + + try: + from networkx import to_scipy_sparse_array + except ImportError: # NetworkX < 2.7 + from networkx import to_scipy_sparse_matrix as to_scipy_sparse_array + + return ssp.lil_matrix(to_scipy_sparse_array(graph, nodelist=nodelist, format="lil")) + + +class PluginBase: """Base class for plugins.""" def __init__(self, plugin_args=None): @@ -81,7 +92,7 @@ class DistributedPluginBase(PluginBase): a boolean numpy array (N,) signifying whether a process is currently running. depidx : :obj:`numpy.matrix` - a boolean matrix (NxN) storing the dependency structure accross + a boolean matrix (NxN) storing the dependency structure across processes. Process dependencies are derived from each column. """ @@ -91,7 +102,7 @@ def __init__(self, plugin_args=None): Initialize runtime attributes to none """ - super(DistributedPluginBase, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) self.procs = None self.depidx = None self.refidx = None @@ -123,6 +134,7 @@ def run(self, graph, config, updatehash=False): self.mapnodesubids = {} # setup polling - TODO: change to threaded model notrun = [] + errors = [] old_progress_stats = None old_presub_stats = None @@ -146,7 +158,7 @@ def run(self, graph, config, updatehash=False): "Progress: %d jobs, %d/%d/%d " "(done/running/ready), %d/%d " "(pending_tasks/waiting).", - *progress_stats + *progress_stats, ) old_progress_stats = progress_stats toappend = [] @@ -155,14 +167,16 @@ def run(self, graph, config, updatehash=False): taskid, jobid = self.pending_tasks.pop() try: result = self._get_result(taskid) - except Exception: + except Exception as exc: notrun.append(self._clean_queue(jobid, graph)) + errors.append(exc) else: if result: if result["traceback"]: notrun.append( self._clean_queue(jobid, graph, result=result) ) + errors.append("".join(result["traceback"])) else: self._task_finished_cb(jobid) self._remove_node_dirs() @@ -194,6 +208,20 @@ def run(self, graph, config, updatehash=False): # close any open resources self._postrun_check() + if errors: + # If one or more nodes failed, re-rise first of them + error, cause = errors[0], None + if isinstance(error, str): + error = RuntimeError(error) + + if len(errors) > 1: + error, cause = ( + RuntimeError(f"{len(errors)} raised. Re-raising first."), + error, + ) + + raise error from cause + def _get_result(self, taskid): raise NotImplementedError @@ -371,7 +399,7 @@ def _local_hash_check(self, jobid, graph): if ( cached and updated - and (overwrite is False or overwrite is None and not always_run) + and (overwrite is False or (overwrite is None and not always_run)) ): logger.debug( "Skipping cached node %s with ID %s.", self.procs[jobid], jobid @@ -392,7 +420,7 @@ def _local_hash_check(self, jobid, graph): return False def _task_finished_cb(self, jobid, cached=False): - """ Extract outputs and assign to inputs of dependent tasks + """Extract outputs and assign to inputs of dependent tasks This is called when a job is completed. """ @@ -413,19 +441,10 @@ def _task_finished_cb(self, jobid, cached=False): self.refidx[self.refidx[:, jobid].nonzero()[0], jobid] = 0 def _generate_dependency_list(self, graph): - """ Generates a dependency list for a list of graphs. - """ - import networkx as nx - + """Generates a dependency list for a list of graphs.""" self.procs, _ = topological_sort(graph) - try: - self.depidx = nx.to_scipy_sparse_matrix( - graph, nodelist=self.procs, format="lil" - ) - except: - self.depidx = nx.to_scipy_sparse_matrix(graph, nodelist=self.procs) - self.refidx = deepcopy(self.depidx) - self.refidx.astype = np.int + self.depidx = _graph_to_lil_matrix(graph, nodelist=self.procs) + self.refidx = self.depidx.astype(int) self.proc_done = np.zeros(len(self.procs), dtype=bool) self.proc_pending = np.zeros(len(self.procs), dtype=bool) @@ -436,7 +455,7 @@ def _remove_node_deps(self, jobid, crashfile, graph): dfs_preorder = nx.dfs_preorder except AttributeError: dfs_preorder = nx.dfs_preorder_nodes - subnodes = [s for s in dfs_preorder(graph, self.procs[jobid])] + subnodes = list(dfs_preorder(graph, self.procs[jobid])) for node in subnodes: idx = self.procs.index(node) self.proc_done[idx] = True @@ -444,8 +463,7 @@ def _remove_node_deps(self, jobid, crashfile, graph): return dict(node=self.procs[jobid], dependents=subnodes, crashfile=crashfile) def _remove_node_dirs(self): - """Removes directories whose outputs have already been used up - """ + """Removes directories whose outputs have already been used up""" if str2bool(self._config["execution"]["remove_node_directories"]): indices = np.nonzero((self.refidx.sum(axis=1) == 0).__array__())[0] for idx in indices: @@ -465,11 +483,10 @@ def _remove_node_dirs(self): class SGELikeBatchManagerBase(DistributedPluginBase): - """Execute workflow with SGE/OGE/PBS like batch system - """ + """Execute workflow with SGE/OGE/PBS like batch system""" def __init__(self, template, plugin_args=None): - super(SGELikeBatchManagerBase, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) self._template = template self._qsub_args = None if plugin_args: @@ -483,13 +500,11 @@ def __init__(self, template, plugin_args=None): self._pending = {} def _is_pending(self, taskid): - """Check if a task is pending in the batch system - """ + """Check if a task is pending in the batch system""" raise NotImplementedError def _submit_batchtask(self, scriptfile, node): - """Submit a task to the batch system - """ + """Submit a task to the batch system""" raise NotImplementedError def _get_result(self, taskid): @@ -519,14 +534,14 @@ def _get_result(self, taskid): results_file = None try: error_message = ( - "Job id ({0}) finished or terminated, but " - "results file does not exist after ({1}) " + "Job id ({}) finished or terminated, but " + "results file does not exist after ({}) " "seconds. Batch dir contains crashdump file " "if node raised an exception.\n" - "Node working directory: ({2}) ".format(taskid, timeout, node_dir) + "Node working directory: ({}) ".format(taskid, timeout, node_dir) ) - raise IOError(error_message) - except IOError as e: + raise OSError(error_message) + except OSError: result_data["traceback"] = "\n".join(format_exception(*sys.exc_info())) else: results_file = glob(os.path.join(node_dir, "result_*.pklz"))[0] @@ -544,14 +559,15 @@ def _get_result(self, taskid): return result_out def _submit_job(self, node, updatehash=False): - """submit job and return taskid - """ + """submit job and return taskid""" pyscript = create_pyscript(node, updatehash=updatehash) batch_dir, name = os.path.split(pyscript) name = ".".join(name.split(".")[:-1]) - batchscript = "\n".join((self._template, "%s %s" % (sys.executable, pyscript))) + batchscript = "\n".join( + (self._template.rstrip("\n"), f"{sys.executable} {pyscript}") + ) batchscriptfile = os.path.join(batch_dir, "batchscript_%s.sh" % name) - with open(batchscriptfile, "wt") as fp: + with open(batchscriptfile, "w") as fp: fp.writelines(batchscript) return self._submit_batchtask(batchscriptfile, node) @@ -560,15 +576,12 @@ def _clear_task(self, taskid): class GraphPluginBase(PluginBase): - """Base class for plugins that distribute graphs to workflows - """ + """Base class for plugins that distribute graphs to workflows""" def __init__(self, plugin_args=None): if plugin_args and plugin_args.get("status_callback"): - logger.warning( - "status_callback not supported for Graph submission" " plugins" - ) - super(GraphPluginBase, self).__init__(plugin_args=plugin_args) + logger.warning("status_callback not supported for Graph submission plugins") + super().__init__(plugin_args=plugin_args) def run(self, graph, config, updatehash=False): import networkx as nx @@ -605,7 +618,7 @@ def _get_args(self, node, keywords): else: tmp_value = node.plugin_args[keyword] - if "overwrite" in node.plugin_args and node.plugin_args["overwrite"]: + if node.plugin_args.get("overwrite"): value = tmp_value else: value += tmp_value @@ -615,7 +628,7 @@ def _get_args(self, node, keywords): def _submit_graph(self, pyfiles, dependencies, nodes): """ pyfiles: list of files corresponding to a topological sort - dependencies: dictionary of dependencies based on the toplogical sort + dependencies: dictionary of dependencies based on the topological sort """ raise NotImplementedError diff --git a/nipype/pipeline/plugins/condor.py b/nipype/pipeline/plugins/condor.py index cd0ad985e2..789eaecfab 100644 --- a/nipype/pipeline/plugins/condor.py +++ b/nipype/pipeline/plugins/condor.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via Condor -""" +"""Parallel workflow execution via Condor""" import os from time import sleep @@ -39,12 +37,12 @@ def __init__(self, **kwargs): """ self._retry_timeout = 2 self._max_tries = 2 - if "plugin_args" in kwargs and kwargs["plugin_args"]: + if kwargs.get("plugin_args"): if "retry_timeout" in kwargs["plugin_args"]: self._retry_timeout = kwargs["plugin_args"]["retry_timeout"] if "max_tries" in kwargs["plugin_args"]: self._max_tries = kwargs["plugin_args"]["max_tries"] - super(CondorPlugin, self).__init__(template, **kwargs) + super().__init__(template, **kwargs) def _is_pending(self, taskid): cmd = CommandLine( @@ -56,9 +54,7 @@ def _is_pending(self, taskid): iflogger.setLevel(logging.getLevelName("CRITICAL")) result = cmd.run(ignore_exception=True) iflogger.setLevel(oldlevel) - if result.runtime.stdout.count("\n%d" % taskid): - return True - return False + return bool(result.runtime.stdout.count("\n%d" % taskid)) def _submit_batchtask(self, scriptfile, node): cmd = CommandLine( @@ -72,16 +68,16 @@ def _submit_batchtask(self, scriptfile, node): if self._qsub_args: qsubargs = self._qsub_args if "qsub_args" in node.plugin_args: - if "overwrite" in node.plugin_args and node.plugin_args["overwrite"]: + if node.plugin_args.get("overwrite"): qsubargs = node.plugin_args["qsub_args"] else: qsubargs += " " + node.plugin_args["qsub_args"] if self._qsub_args: qsubargs = self._qsub_args if "-o" not in qsubargs: - qsubargs = "%s -o %s" % (qsubargs, path) + qsubargs = f"{qsubargs} -o {path}" if "-e" not in qsubargs: - qsubargs = "%s -e %s" % (qsubargs, path) + qsubargs = f"{qsubargs} -e {path}" if node._hierarchy: jobname = ".".join((dict(os.environ)["LOGNAME"], node._hierarchy, node._id)) else: @@ -89,7 +85,7 @@ def _submit_batchtask(self, scriptfile, node): jobnameitems = jobname.split(".") jobnameitems.reverse() jobname = ".".join(jobnameitems) - cmd.inputs.args = "%s -N %s %s" % (qsubargs, jobname, scriptfile) + cmd.inputs.args = f"{qsubargs} -N {jobname} {scriptfile}" oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName("CRITICAL")) tries = 0 @@ -105,7 +101,7 @@ def _submit_batchtask(self, scriptfile, node): raise RuntimeError( "\n".join( ( - ("Could not submit condor " "cluster" " for node %s") + "Could not submit condor cluster for node %s" % node._id, str(e), ) diff --git a/nipype/pipeline/plugins/dagman.py b/nipype/pipeline/plugins/dagman.py index 98b07eeb10..1c424c24ef 100644 --- a/nipype/pipeline/plugins/dagman.py +++ b/nipype/pipeline/plugins/dagman.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via Condor DAGMan -""" +"""Parallel workflow execution via Condor DAGMan""" + import os import sys import uuid @@ -78,7 +77,7 @@ def __init__(self, **kwargs): ): if ( "plugin_args" in kwargs - and not kwargs["plugin_args"] is None + and kwargs["plugin_args"] is not None and id_ in kwargs["plugin_args"] ): if id_ == "wrapper_cmd": @@ -89,7 +88,7 @@ def __init__(self, **kwargs): val = self._get_str_or_file(kwargs["plugin_args"][id_]) setattr(self, var, val) # TODO remove after some time - if "plugin_args" in kwargs and not kwargs["plugin_args"] is None: + if "plugin_args" in kwargs and kwargs["plugin_args"] is not None: plugin_args = kwargs["plugin_args"] if "template" in plugin_args: warn( @@ -99,14 +98,14 @@ def __init__(self, **kwargs): warn( "the 'submit_specs' argument is deprecated, use 'override_specs' instead" ) - super(CondorDAGManPlugin, self).__init__(**kwargs) + super().__init__(**kwargs) def _submit_graph(self, pyfiles, dependencies, nodes): # location of all scripts, place dagman output in here too batch_dir, _ = os.path.split(pyfiles[0]) # DAG description filename dagfilename = os.path.join(batch_dir, "workflow-%s.dag" % uuid.uuid4()) - with open(dagfilename, "wt") as dagfileptr: + with open(dagfilename, "w") as dagfileptr: # loop over all scripts, create submit files, and define them # as jobs in the DAG for idx, pyscript in enumerate(pyfiles): @@ -130,7 +129,7 @@ def _submit_graph(self, pyfiles, dependencies, nodes): ], ) # add required slots to the template - template = "%s\n%s\n%s\nqueue\n" % ( + template = "{}\n{}\n{}\nqueue\n".format( "%(initial_specs)s", template, "%(override_specs)s", @@ -147,7 +146,7 @@ def _submit_graph(self, pyfiles, dependencies, nodes): ) if wrapper_cmd is not None: specs["executable"] = wrapper_cmd - specs["nodescript"] = "%s %s %s" % ( + specs["nodescript"] = "{} {} {}".format( wrapper_args % specs, # give access to variables sys.executable, pyscript, @@ -155,7 +154,7 @@ def _submit_graph(self, pyfiles, dependencies, nodes): submitspec = template % specs # write submit spec for this job submitfile = os.path.join(batch_dir, "%s.submit" % name) - with open(submitfile, "wt") as submitfileprt: + with open(submitfile, "w") as submitfileprt: submitfileprt.writelines(submitspec) submitfileprt.close() # define job in DAG @@ -176,14 +175,14 @@ def _submit_graph(self, pyfiles, dependencies, nodes): terminal_output="allatonce", ) # needs -update_submit or re-running a workflow will fail - cmd.inputs.args = "%s -update_submit %s" % (self._dagman_args, dagfilename) + cmd.inputs.args = f"{self._dagman_args} -update_submit {dagfilename}" cmd.run() logger.info("submitted all jobs to Condor DAGMan") if self._block: # wait for DAGMan to settle down, no time wasted it is already running time.sleep(10) if not os.path.exists("%s.condor.sub" % dagfilename): - raise EnvironmentError( + raise OSError( "DAGMan did not create its submit file, please check the logs" ) # wait for completion diff --git a/nipype/pipeline/plugins/debug.py b/nipype/pipeline/plugins/debug.py index 16ea8f44ee..4798e083bd 100644 --- a/nipype/pipeline/plugins/debug.py +++ b/nipype/pipeline/plugins/debug.py @@ -1,23 +1,20 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Debug plugin -""" +"""Debug plugin""" import networkx as nx from .base import PluginBase, logger class DebugPlugin(PluginBase): - """Execute workflow in series - """ + """Execute workflow in series""" def __init__(self, plugin_args=None): - super(DebugPlugin, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) if ( plugin_args and "callable" in plugin_args - and hasattr(plugin_args["callable"], "__call__") + and callable(plugin_args["callable"]) ): self._callable = plugin_args["callable"] else: diff --git a/nipype/pipeline/plugins/ipython.py b/nipype/pipeline/plugins/ipython.py index 8a786a16f1..2c80eb4655 100644 --- a/nipype/pipeline/plugins/ipython.py +++ b/nipype/pipeline/plugins/ipython.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Parallel workflow execution via IPython controller -""" +"""Parallel workflow execution via IPython controller""" from pickle import dumps import sys @@ -44,13 +42,12 @@ def execute_task(pckld_task, node_config, updatehash): class IPythonPlugin(DistributedPluginBase): - """Execute workflow with ipython - """ + """Execute workflow with ipython""" def __init__(self, plugin_args=None): if IPython_not_loaded: raise ImportError("Please install ipyparallel to use this plugin.") - super(IPythonPlugin, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) valid_args = ( "url_file", "profile", @@ -84,7 +81,7 @@ def run(self, graph, config, updatehash=False): self.iparallel = sys.modules[name] except ImportError as e: raise ImportError( - "ipyparallel not found. Parallel execution " "will be unavailable" + "ipyparallel not found. Parallel execution will be unavailable" ) from e try: self.taskclient = self.iparallel.Client(**self.client_args) @@ -97,7 +94,7 @@ def run(self, graph, config, updatehash=False): raise Exception("Ipython kernel not installed") from e else: raise e - return super(IPythonPlugin, self).run(graph, config, updatehash=updatehash) + return super().run(graph, config, updatehash=updatehash) def _get_result(self, taskid): if taskid not in self.taskmap: diff --git a/nipype/pipeline/plugins/legacymultiproc.py b/nipype/pipeline/plugins/legacymultiproc.py index 528184472d..4c39be1ab2 100644 --- a/nipype/pipeline/plugins/legacymultiproc.py +++ b/nipype/pipeline/plugins/legacymultiproc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Parallel workflow execution via multiprocessing @@ -28,7 +27,7 @@ except ImportError: def indent(text, prefix): - """ A textwrap.indent replacement for Python < 3.3 """ + """A textwrap.indent replacement for Python < 3.3""" if not prefix: return text splittext = text.splitlines(True) @@ -76,7 +75,7 @@ def run_node(node, updatehash, taskid): # Pythons 2.7, 3.4-3.7.0, and 3.7.1 have three different implementations of # pool.Pool().Process(), and the type of the result varies based on the default # multiprocessing context, so we need to dynamically patch the daemon property -class NonDaemonMixin(object): +class NonDaemonMixin: @property def daemon(self): return False @@ -135,7 +134,7 @@ def __init__( if context is None: context = mp.get_context() context = _nondaemon_context_mapper[context._name] - super(NonDaemonPool, self).__init__( + super().__init__( processes=processes, initializer=initializer, initargs=initargs, @@ -143,7 +142,6 @@ def __init__( context=context, ) - except ImportError: class NonDaemonProcess(NonDaemonMixin, mp.Process): @@ -195,7 +193,7 @@ class LegacyMultiProcPlugin(DistributedPluginBase): def __init__(self, plugin_args=None): # Init variables and instance attributes - super(LegacyMultiProcPlugin, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) self._taskresult = {} self._task_obj = {} self._taskid = 0 @@ -270,7 +268,7 @@ def _submit_job(self, node, updatehash=False): return self._taskid def _prerun_check(self, graph): - """Check if any node exeeds the available resources""" + """Check if any node exceeds the available resources""" tasks_mem_gb = [] tasks_num_th = [] for node in graph.nodes(): @@ -279,7 +277,7 @@ def _prerun_check(self, graph): if np.any(np.array(tasks_mem_gb) > self.memory_gb): logger.warning( - "Some nodes exceed the total amount of memory available " "(%0.2fGB).", + "Some nodes exceed the total amount of memory available (%0.2fGB).", self.memory_gb, ) if self.raise_insufficient: diff --git a/nipype/pipeline/plugins/linear.py b/nipype/pipeline/plugins/linear.py index 650bff280f..aa29a5951b 100644 --- a/nipype/pipeline/plugins/linear.py +++ b/nipype/pipeline/plugins/linear.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Local serial workflow execution -""" +"""Local serial workflow execution""" import os from .base import PluginBase, logger, report_crash, report_nodes_not_run, str2bool @@ -10,8 +8,7 @@ class LinearPlugin(PluginBase): - """Execute workflow in series - """ + """Execute workflow in series""" def run(self, graph, config, updatehash=False): """Executes a pre-defined pipeline in a serial order. @@ -35,6 +32,8 @@ def run(self, graph, config, updatehash=False): old_wd = os.getcwd() notrun = [] donotrun = [] + stop_on_first_crash = str2bool(config["execution"]["stop_on_first_crash"]) + errors = [] nodes, _ = topological_sort(graph) for node in nodes: endstatus = "end" @@ -44,27 +43,38 @@ def run(self, graph, config, updatehash=False): if self._status_callback: self._status_callback(node, "start") node.run(updatehash=updatehash) - except: + except Exception as exc: endstatus = "exception" # bare except, but i really don't know where a # node might fail crashfile = report_crash(node) - if str2bool(config["execution"]["stop_on_first_crash"]): - raise # remove dependencies from queue - subnodes = [s for s in dfs_preorder(graph, node)] + subnodes = list(dfs_preorder(graph, node)) notrun.append( {"node": node, "dependents": subnodes, "crashfile": crashfile} ) donotrun.extend(subnodes) # Delay raising the crash until we cleaned the house - if str2bool(config["execution"]["stop_on_first_crash"]): - os.chdir(old_wd) # Return wherever we were before - report_nodes_not_run(notrun) # report before raising - raise + errors.append(exc) + + if stop_on_first_crash: + break finally: if self._status_callback: self._status_callback(node, endstatus) os.chdir(old_wd) # Return wherever we were before report_nodes_not_run(notrun) + if errors: + # If one or more nodes failed, re-rise first of them + error, cause = errors[0], None + if isinstance(error, str): + error = RuntimeError(error) + + if len(errors) > 1: + error, cause = ( + RuntimeError(f"{len(errors)} raised. Re-raising first."), + error, + ) + + raise error from cause diff --git a/nipype/pipeline/plugins/lsf.py b/nipype/pipeline/plugins/lsf.py index a88fbb6675..4ca380dfaa 100644 --- a/nipype/pipeline/plugins/lsf.py +++ b/nipype/pipeline/plugins/lsf.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via LSF -""" +"""Parallel workflow execution via LSF""" import os import re @@ -32,14 +30,14 @@ def __init__(self, **kwargs): self._retry_timeout = 2 self._max_tries = 2 self._bsub_args = "" - if "plugin_args" in kwargs and kwargs["plugin_args"]: + if kwargs.get("plugin_args"): if "retry_timeout" in kwargs["plugin_args"]: self._retry_timeout = kwargs["plugin_args"]["retry_timeout"] if "max_tries" in kwargs["plugin_args"]: self._max_tries = kwargs["plugin_args"]["max_tries"] if "bsub_args" in kwargs["plugin_args"]: self._bsub_args = kwargs["plugin_args"]["bsub_args"] - super(LSFPlugin, self).__init__(template, **kwargs) + super().__init__(template, **kwargs) def _is_pending(self, taskid): """LSF lists a status of 'PEND' when a job has been submitted but is @@ -55,10 +53,9 @@ def _is_pending(self, taskid): result = cmd.run(ignore_exception=True) iflogger.setLevel(oldlevel) # logger.debug(result.runtime.stdout) - if "DONE" in result.runtime.stdout or "EXIT" in result.runtime.stdout: - return False - else: - return True + return ( + "DONE" not in result.runtime.stdout and "EXIT" not in result.runtime.stdout + ) def _submit_batchtask(self, scriptfile, node): cmd = CommandLine( @@ -71,15 +68,15 @@ def _submit_batchtask(self, scriptfile, node): if self._bsub_args: bsubargs = self._bsub_args if "bsub_args" in node.plugin_args: - if "overwrite" in node.plugin_args and node.plugin_args["overwrite"]: + if node.plugin_args.get("overwrite"): bsubargs = node.plugin_args["bsub_args"] else: bsubargs += " " + node.plugin_args["bsub_args"] if "-o" not in bsubargs: # -o outfile - bsubargs = "%s -o %s" % (bsubargs, scriptfile + ".log") + bsubargs = "{} -o {}".format(bsubargs, scriptfile + ".log") if "-e" not in bsubargs: # -e error file - bsubargs = "%s -e %s" % (bsubargs, scriptfile + ".log") + bsubargs = "{} -e {}".format(bsubargs, scriptfile + ".log") if node._hierarchy: jobname = ".".join((dict(os.environ)["LOGNAME"], node._hierarchy, node._id)) else: @@ -87,7 +84,7 @@ def _submit_batchtask(self, scriptfile, node): jobnameitems = jobname.split(".") jobnameitems.reverse() jobname = ".".join(jobnameitems) - cmd.inputs.args = "%s -J %s sh %s" % ( + cmd.inputs.args = "{} -J {} sh {}".format( bsubargs, jobname, scriptfile, @@ -108,7 +105,7 @@ def _submit_batchtask(self, scriptfile, node): raise RuntimeError( "\n".join( ( - ("Could not submit lsf task" " for node %s") % node._id, + "Could not submit lsf task for node %s" % node._id, str(e), ) ) @@ -121,7 +118,7 @@ def _submit_batchtask(self, scriptfile, node): if match: taskid = int(match.groups()[0]) else: - raise IOError( + raise OSError( "Can't parse submission job output id: %s" % result.runtime.stdout ) self._pending[taskid] = node.output_dir() diff --git a/nipype/pipeline/plugins/multiproc.py b/nipype/pipeline/plugins/multiproc.py index eac662533c..be0e006229 100644 --- a/nipype/pipeline/plugins/multiproc.py +++ b/nipype/pipeline/plugins/multiproc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Parallel workflow execution via multiprocessing @@ -22,13 +21,14 @@ from ...utils.profiler import get_system_total_memory_gb from ..engine import MapNode from .base import DistributedPluginBase +from ...utils.gpu_count import gpu_count try: from textwrap import indent except ImportError: def indent(text, prefix): - """ A textwrap.indent replacement for Python < 3.3 """ + """A textwrap.indent replacement for Python < 3.3""" if not prefix: return text splittext = text.splitlines(True) @@ -101,6 +101,7 @@ class MultiProcPlugin(DistributedPluginBase): - non_daemon: boolean flag to execute as non-daemon processes - n_procs: maximum number of threads to be executed in parallel + - n_gpu_procs: maximum number of GPU threads to be executed in parallel - memory_gb: maximum memory (in GB) that can be used at once. - raise_insufficient: raise error if the requested resources for a node over the maximum `n_procs` and/or `memory_gb` @@ -114,7 +115,7 @@ class MultiProcPlugin(DistributedPluginBase): def __init__(self, plugin_args=None): # Init variables and instance attributes - super(MultiProcPlugin, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) self._taskresult = {} self._task_obj = {} self._taskid = 0 @@ -131,10 +132,24 @@ def __init__(self, plugin_args=None): ) self.raise_insufficient = self.plugin_args.get("raise_insufficient", True) + # GPU found on system + self.n_gpus_visible = gpu_count() + # proc per GPU set by user + self.n_gpu_procs = self.plugin_args.get('n_gpu_procs', self.n_gpus_visible) + + # total no. of processes allowed on all gpus + if self.n_gpu_procs > self.n_gpus_visible: + logger.info( + 'Total number of GPUs proc requested (%d) exceeds the available number of GPUs (%d) on the system. Using requested GPU slots at your own risk!', + self.n_gpu_procs, + self.n_gpus_visible, + ) + # Instantiate different thread pools for non-daemon processes logger.debug( - "[MultiProc] Starting (n_procs=%d, " "mem_gb=%0.2f, cwd=%s)", + "[MultiProc] Starting (n_procs=%d, n_gpu_procs=%d, mem_gb=%0.2f, cwd=%s)", self.processors, + self.n_gpu_procs, self.memory_gb, self._cwd, ) @@ -182,16 +197,19 @@ def _submit_job(self, node, updatehash=False): return self._taskid def _prerun_check(self, graph): - """Check if any node exeeds the available resources""" + """Check if any node exceeds the available resources""" tasks_mem_gb = [] tasks_num_th = [] + tasks_gpu_th = [] for node in graph.nodes(): tasks_mem_gb.append(node.mem_gb) tasks_num_th.append(node.n_procs) + if node.is_gpu_node(): + tasks_gpu_th.append(node.n_procs) if np.any(np.array(tasks_mem_gb) > self.memory_gb): logger.warning( - "Some nodes exceed the total amount of memory available " "(%0.2fGB).", + "Some nodes exceed the total amount of memory available (%0.2fGB).", self.memory_gb, ) if self.raise_insufficient: @@ -204,6 +222,10 @@ def _prerun_check(self, graph): ) if self.raise_insufficient: raise RuntimeError("Insufficient resources available for job") + if np.any(np.array(tasks_gpu_th) > self.n_gpu_procs): + logger.warning('Nodes demand more GPU than allowed (%d).', self.n_gpu_procs) + if self.raise_insufficient: + raise RuntimeError('Insufficient GPU resources available for job') def _postrun_check(self): self.pool.shutdown() @@ -214,11 +236,14 @@ def _check_resources(self, running_tasks): """ free_memory_gb = self.memory_gb free_processors = self.processors + free_gpu_slots = self.n_gpu_procs for _, jobid in running_tasks: free_memory_gb -= min(self.procs[jobid].mem_gb, free_memory_gb) free_processors -= min(self.procs[jobid].n_procs, free_processors) + if self.procs[jobid].is_gpu_node(): + free_gpu_slots -= min(self.procs[jobid].n_procs, free_gpu_slots) - return free_memory_gb, free_processors + return free_memory_gb, free_processors, free_gpu_slots def _send_procs_to_workers(self, updatehash=False, graph=None): """ @@ -233,7 +258,9 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): ) # Check available resources by summing all threads and memory used - free_memory_gb, free_processors = self._check_resources(self.pending_tasks) + free_memory_gb, free_processors, free_gpu_slots = self._check_resources( + self.pending_tasks + ) stats = ( len(self.pending_tasks), @@ -242,6 +269,8 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): self.memory_gb, free_processors, self.processors, + free_gpu_slots, + self.n_gpu_procs, ) if self._stats != stats: tasks_list_msg = "" @@ -257,13 +286,15 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): tasks_list_msg = indent(tasks_list_msg, " " * 21) logger.info( "[MultiProc] Running %d tasks, and %d jobs ready. Free " - "memory (GB): %0.2f/%0.2f, Free processors: %d/%d.%s", + "memory (GB): %0.2f/%0.2f, Free processors: %d/%d, Free GPU slot:%d/%d.%s", len(self.pending_tasks), len(jobids), free_memory_gb, self.memory_gb, free_processors, self.processors, + free_gpu_slots, + self.n_gpu_procs, tasks_list_msg, ) self._stats = stats @@ -305,28 +336,39 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): # Check requirements of this job next_job_gb = min(self.procs[jobid].mem_gb, self.memory_gb) next_job_th = min(self.procs[jobid].n_procs, self.processors) + next_job_gpu_th = min(self.procs[jobid].n_procs, self.n_gpu_procs) + + is_gpu_node = self.procs[jobid].is_gpu_node() # If node does not fit, skip at this moment - if next_job_th > free_processors or next_job_gb > free_memory_gb: + if ( + next_job_th > free_processors + or next_job_gb > free_memory_gb + or (is_gpu_node and next_job_gpu_th > free_gpu_slots) + ): logger.debug( - "Cannot allocate job %d (%0.2fGB, %d threads).", + "Cannot allocate job %d (%0.2fGB, %d threads, %d GPU slots).", jobid, next_job_gb, next_job_th, + next_job_gpu_th, ) continue free_memory_gb -= next_job_gb free_processors -= next_job_th + if is_gpu_node: + free_gpu_slots -= next_job_gpu_th logger.debug( "Allocating %s ID=%d (%0.2fGB, %d threads). Free: " - "%0.2fGB, %d threads.", + "%0.2fGB, %d threads, %d GPU slots.", self.procs[jobid].fullname, jobid, next_job_gb, next_job_th, free_memory_gb, free_processors, + free_gpu_slots, ) # change job status in appropriate queues @@ -337,8 +379,11 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): if self._local_hash_check(jobid, graph): continue + cached, updated = self.procs[jobid].is_cached() # updatehash and run_without_submitting are also run locally - if updatehash or self.procs[jobid].run_without_submitting: + if (cached and updatehash and not updated) or self.procs[ + jobid + ].run_without_submitting: logger.debug("Running node %s on master thread", self.procs[jobid]) try: self.procs[jobid].run(updatehash=updatehash) @@ -353,6 +398,8 @@ def _send_procs_to_workers(self, updatehash=False, graph=None): self._remove_node_dirs() free_memory_gb += next_job_gb free_processors += next_job_th + if is_gpu_node: + free_gpu_slots += next_job_gpu_th # Display stats next loop self._stats = None diff --git a/nipype/pipeline/plugins/oar.py b/nipype/pipeline/plugins/oar.py index 4ce64305eb..b9c4a050ab 100644 --- a/nipype/pipeline/plugins/oar.py +++ b/nipype/pipeline/plugins/oar.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via OAR http://oar.imag.fr -""" +"""Parallel workflow execution via OAR http://oar.imag.fr""" + import os import stat from time import sleep @@ -27,7 +26,7 @@ class OARPlugin(SGELikeBatchManagerBase): """ - # Addtional class variables + # Additional class variables _max_jobname_len = 15 _oarsub_args = "" @@ -38,7 +37,7 @@ def __init__(self, **kwargs): self._retry_timeout = 2 self._max_tries = 2 self._max_jobname_length = 15 - if "plugin_args" in kwargs and kwargs["plugin_args"]: + if kwargs.get("plugin_args"): if "oarsub_args" in kwargs["plugin_args"]: self._oarsub_args = kwargs["plugin_args"]["oarsub_args"] if "retry_timeout" in kwargs["plugin_args"]: @@ -47,7 +46,7 @@ def __init__(self, **kwargs): self._max_tries = kwargs["plugin_args"]["max_tries"] if "max_jobname_len" in kwargs["plugin_args"]: self._max_jobname_len = kwargs["plugin_args"]["max_jobname_len"] - super(OARPlugin, self).__init__(template, **kwargs) + super().__init__(template, **kwargs) def _is_pending(self, taskid): # subprocess.Popen requires taskid to be a string @@ -75,7 +74,7 @@ def _submit_batchtask(self, scriptfile, node): if self._oarsub_args: oarsubargs = self._oarsub_args if "oarsub_args" in node.plugin_args: - if "overwrite" in node.plugin_args and node.plugin_args["overwrite"]: + if node.plugin_args.get("overwrite"): oarsubargs = node.plugin_args["oarsub_args"] else: oarsubargs += " " + node.plugin_args["oarsub_args"] @@ -90,12 +89,12 @@ def _submit_batchtask(self, scriptfile, node): jobname = jobname[0 : self._max_jobname_len] if "-O" not in oarsubargs: - oarsubargs = "%s -O %s" % ( + oarsubargs = "{} -O {}".format( oarsubargs, os.path.join(path, jobname + ".stdout"), ) if "-E" not in oarsubargs: - oarsubargs = "%s -E %s" % ( + oarsubargs = "{} -E {}".format( oarsubargs, os.path.join(path, jobname + ".stderr"), ) @@ -103,7 +102,7 @@ def _submit_batchtask(self, scriptfile, node): oarsubargs = "%s -J" % (oarsubargs) os.chmod(scriptfile, stat.S_IEXEC | stat.S_IREAD | stat.S_IWRITE) - cmd.inputs.args = "%s -n %s -S %s" % (oarsubargs, jobname, scriptfile) + cmd.inputs.args = f"{oarsubargs} -n {jobname} -S {scriptfile}" oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName("CRITICAL")) @@ -121,7 +120,7 @@ def _submit_batchtask(self, scriptfile, node): raise RuntimeError( "\n".join( ( - ("Could not submit OAR task" " for node %s") % node._id, + "Could not submit OAR task for node %s" % node._id, str(e), ) ) @@ -142,5 +141,5 @@ def _submit_batchtask(self, scriptfile, node): break taskid = json.loads(o)["job_id"] self._pending[taskid] = node.output_dir() - logger.debug("submitted OAR task: %s for node %s" % (taskid, node._id)) + logger.debug(f"submitted OAR task: {taskid} for node {node._id}") return taskid diff --git a/nipype/pipeline/plugins/pbs.py b/nipype/pipeline/plugins/pbs.py index b322d88743..01c80efc5a 100644 --- a/nipype/pipeline/plugins/pbs.py +++ b/nipype/pipeline/plugins/pbs.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via PBS/Torque -""" +"""Parallel workflow execution via PBS/Torque""" + import os from time import sleep @@ -24,7 +23,7 @@ class PBSPlugin(SGELikeBatchManagerBase): """ - # Addtional class variables + # Additional class variables _max_jobname_len = 15 def __init__(self, **kwargs): @@ -34,18 +33,18 @@ def __init__(self, **kwargs): self._retry_timeout = 2 self._max_tries = 2 self._max_jobname_length = 15 - if "plugin_args" in kwargs and kwargs["plugin_args"]: + if kwargs.get("plugin_args"): if "retry_timeout" in kwargs["plugin_args"]: self._retry_timeout = kwargs["plugin_args"]["retry_timeout"] if "max_tries" in kwargs["plugin_args"]: self._max_tries = kwargs["plugin_args"]["max_tries"] if "max_jobname_len" in kwargs["plugin_args"]: self._max_jobname_len = kwargs["plugin_args"]["max_jobname_len"] - super(PBSPlugin, self).__init__(template, **kwargs) + super().__init__(template, **kwargs) def _is_pending(self, taskid): result = CommandLine( - "qstat -f {}".format(taskid), + f"qstat -f {taskid}", environ=dict(os.environ), terminal_output="file_split", resource_monitor=False, @@ -73,14 +72,14 @@ def _submit_batchtask(self, scriptfile, node): if self._qsub_args: qsubargs = self._qsub_args if "qsub_args" in node.plugin_args: - if "overwrite" in node.plugin_args and node.plugin_args["overwrite"]: + if node.plugin_args.get("overwrite"): qsubargs = node.plugin_args["qsub_args"] else: qsubargs += " " + node.plugin_args["qsub_args"] if "-o" not in qsubargs: - qsubargs = "%s -o %s" % (qsubargs, path) + qsubargs = f"{qsubargs} -o {path}" if "-e" not in qsubargs: - qsubargs = "%s -e %s" % (qsubargs, path) + qsubargs = f"{qsubargs} -e {path}" if node._hierarchy: jobname = ".".join((dict(os.environ)["LOGNAME"], node._hierarchy, node._id)) else: @@ -89,7 +88,7 @@ def _submit_batchtask(self, scriptfile, node): jobnameitems.reverse() jobname = ".".join(jobnameitems) jobname = jobname[0 : self._max_jobname_len] - cmd.inputs.args = "%s -N %s %s" % (qsubargs, jobname, scriptfile) + cmd.inputs.args = f"{qsubargs} -N {jobname} {scriptfile}" oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName("CRITICAL")) @@ -105,7 +104,7 @@ def _submit_batchtask(self, scriptfile, node): else: iflogger.setLevel(oldlevel) raise RuntimeError( - "Could not submit pbs task for node {}\n{}".format(node._id, e) + f"Could not submit pbs task for node {node._id}\n{e}" ) else: break @@ -113,6 +112,6 @@ def _submit_batchtask(self, scriptfile, node): # retrieve pbs taskid taskid = result.runtime.stdout.split(".")[0] self._pending[taskid] = node.output_dir() - logger.debug("submitted pbs task: {} for node {}".format(taskid, node._id)) + logger.debug(f"submitted pbs task: {taskid} for node {node._id}") return taskid diff --git a/nipype/pipeline/plugins/pbsgraph.py b/nipype/pipeline/plugins/pbsgraph.py index 6304e715b7..0cb925af38 100644 --- a/nipype/pipeline/plugins/pbsgraph.py +++ b/nipype/pipeline/plugins/pbsgraph.py @@ -1,5 +1,5 @@ -"""Parallel workflow execution via PBS/Torque -""" +"""Parallel workflow execution via PBS/Torque""" + import os import sys @@ -27,7 +27,7 @@ class PBSGraphPlugin(SGEGraphPlugin): def _submit_graph(self, pyfiles, dependencies, nodes): batch_dir, _ = os.path.split(pyfiles[0]) submitjobsfile = os.path.join(batch_dir, "submit_jobs.sh") - with open(submitjobsfile, "wt") as fp: + with open(submitjobsfile, "w") as fp: fp.writelines("#!/usr/bin/env sh\n") for idx, pyscript in enumerate(pyfiles): node = nodes[idx] @@ -35,11 +35,9 @@ def _submit_graph(self, pyfiles, dependencies, nodes): batch_dir, name = os.path.split(pyscript) name = ".".join(name.split(".")[:-1]) - batchscript = "\n".join( - (template, "%s %s" % (sys.executable, pyscript)) - ) + batchscript = "\n".join((template, f"{sys.executable} {pyscript}")) batchscriptfile = os.path.join(batch_dir, "batchscript_%s.sh" % name) - with open(batchscriptfile, "wt") as batchfp: + with open(batchscriptfile, "w") as batchfp: batchfp.writelines(batchscript) batchfp.close() deps = "" diff --git a/nipype/pipeline/plugins/semaphore_singleton.py b/nipype/pipeline/plugins/semaphore_singleton.py index 12fa7c7777..1ab42de2fc 100644 --- a/nipype/pipeline/plugins/semaphore_singleton.py +++ b/nipype/pipeline/plugins/semaphore_singleton.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import threading semaphore = threading.Semaphore(0) diff --git a/nipype/pipeline/plugins/sge.py b/nipype/pipeline/plugins/sge.py index 17a5093ae2..ce8e046f01 100644 --- a/nipype/pipeline/plugins/sge.py +++ b/nipype/pipeline/plugins/sge.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via SGE -""" +"""Parallel workflow execution via SGE""" + import os import pwd import re @@ -20,13 +19,12 @@ def sge_debug_print(message): - """ Needed for debugging on big jobs. Once this is fully vetted, it can be removed. - """ + """Needed for debugging on big jobs. Once this is fully vetted, it can be removed.""" logger.debug(DEBUGGING_PREFIX + " " + "=!" * 3 + " " + message) # print DEBUGGING_PREFIX + " " + "=!" * 3 + " " + message -class QJobInfo(object): +class QJobInfo: """Information about a single job created by OGE/SGE or similar Each job is responsible for knowing it's own refresh state :author Hans J. Johnson @@ -51,7 +49,7 @@ def __init__( self._job_time = job_time # The job start time self._job_info_creation_time = ( time.time() - ) # When this job was created (for comparing against initalization) + ) # When this job was created (for comparing against initialization) self._job_queue_name = job_queue_name # Where the job is running self._job_slots = int(job_slots) # How many slots are being used self._qsub_command_line = qsub_command_line @@ -79,12 +77,11 @@ def is_pending(self): return self._job_queue_state == "pending" def is_job_state_pending(self): - """ Return True, unless job is in the "zombie" status - """ + """Return True, unless job is in the "zombie" status""" time_diff = time.time() - self._job_info_creation_time if self.is_zombie(): sge_debug_print( - "DONE! QJobInfo.IsPending found in 'zombie' list, returning False so claiming done!\n{0}".format( + "DONE! QJobInfo.IsPending found in 'zombie' list, returning False so claiming done!\n{}".format( self ) ) @@ -93,10 +90,8 @@ def is_job_state_pending(self): # if initializing for more than 5 minute, failure due to # initialization and completion before registration sge_debug_print( - "FAILURE! QJobInfo.IsPending found long running at {1} seconds" - "'initializing' returning False for to break loop!\n{0}".format( - self, time_diff - ) + f"FAILURE! QJobInfo.IsPending found long running at {time_diff} seconds " + f"'initializing' returning False for to break loop!\n{self}" ) is_pending_status = True # Job initialization took too long, so report! else: # self.is_running() || self.is_pending(): @@ -113,7 +108,7 @@ def set_state(self, new_state): self._job_queue_state = new_state -class QstatSubstitute(object): +class QstatSubstitute: """A wrapper for Qstat to avoid overloading the SGE/OGS server with rapid continuous qstat requests""" @@ -133,7 +128,7 @@ def __init__( self._remove_old_jobs() def _remove_old_jobs(self): - """ This is only called during initialization of the function for the purpose + """This is only called during initialization of the function for the purpose of identifying jobs that are not part of this run of nipype. They are jobs that existed prior to starting a new jobs, so they are irrelevant. """ @@ -144,7 +139,7 @@ def _remove_old_jobs(self): def add_startup_job(self, taskid, qsub_command_line): """ :param taskid: The job id - :param qsub_command_line: When initializing, re-use the job_queue_name + :param qsub_command_line: When initializing, reuse the job_queue_name :return: NONE """ taskid = int(taskid) # Ensure that it is an integer @@ -154,13 +149,13 @@ def add_startup_job(self, taskid, qsub_command_line): @staticmethod def _qacct_verified_complete(taskid): - """ request definitive job completion information for the current job - from the qacct report + """request definitive job completion information for the current job + from the qacct report """ sge_debug_print( "WARNING: " "CONTACTING qacct for finished jobs, " - "{0}: {1}".format(time.time(), "Verifying Completion") + "{}: {}".format(time.time(), "Verifying Completion") ) this_command = "qacct" @@ -183,12 +178,11 @@ def _qacct_verified_complete(taskid): qacct_result, _ = proc.communicate() if qacct_result.find(str(taskid)): is_complete = True - sge_debug_print("NOTE: qacct for jobs\n{0}".format(qacct_result)) + sge_debug_print(f"NOTE: qacct for jobs\n{qacct_result}") break except: sge_debug_print("NOTE: qacct call failed") time.sleep(5) - pass return is_complete def _parse_qstat_job_list(self, xml_job_list): @@ -229,7 +223,7 @@ def _parse_qstat_job_list(self, xml_job_list): time.mktime(time.strptime(job_time_text, "%Y-%m-%dT%H:%M:%S")) ) except: - job_time = float(0.0) + job_time = 0.0 # Make job entry task_id = int(job_num) @@ -237,9 +231,7 @@ def _parse_qstat_job_list(self, xml_job_list): self._task_dictionary[task_id].update_info( job_queue_state, job_time, job_queue_name, job_slots ) - sge_debug_print( - "Updating job: {0}".format(self._task_dictionary[task_id]) - ) + sge_debug_print(f"Updating job: {self._task_dictionary[task_id]}") current_jobs_parsed.append(task_id) # Changed from job_num as "in" is used to check which does not cast else: @@ -261,35 +253,33 @@ def _parse_qstat_job_list(self, xml_job_list): else: sge_debug_print( "ERROR: Job not in current parselist, " - "and not in done list {0}: {1}".format( + "and not in done list {}: {}".format( dictionary_job, self._task_dictionary[dictionary_job] ) ) - pass if self._task_dictionary[dictionary_job].is_initializing(): is_completed = self._qacct_verified_complete(dictionary_job) if is_completed: self._task_dictionary[dictionary_job].set_state("zombie") else: sge_debug_print( - "ERROR: Job not in still in intializing mode, " - "and not in done list {0}: {1}".format( + "ERROR: Job not in still in initialization mode, " + "and not in done list {}: {}".format( dictionary_job, self._task_dictionary[dictionary_job] ) ) - pass def _run_qstat(self, reason_for_qstat, force_instant=True): - """ request all job information for the current user in xmlformat. - See documentation from java documentation: - http://arc.liv.ac.uk/SGE/javadocs/jgdi/com/sun/grid/jgdi/monitoring/filter/JobStateFilter.html - -s r gives running jobs - -s z gives recently completed jobs (**recently** is very ambiguous) - -s s suspended jobs + """request all job information for the current user in xmlformat. + See documentation from java documentation: + http://arc.liv.ac.uk/SGE/javadocs/jgdi/com/sun/grid/jgdi/monitoring/filter/JobStateFilter.html + -s r gives running jobs + -s z gives recently completed jobs (**recently** is very ambiguous) + -s s suspended jobs """ sge_debug_print( "WARNING: CONTACTING qmaster for jobs, " - "{0}: {1}".format(time.time(), reason_for_qstat) + "{}: {}".format(time.time(), reason_for_qstat) ) if force_instant: this_command = self._qstat_instant_executable @@ -320,13 +310,12 @@ def _run_qstat(self, reason_for_qstat, force_instant=True): self._parse_qstat_job_list(runjobs) break except Exception as inst: - exception_message = "QstatParsingError:\n\t{0}\n\t{1}\n".format( + exception_message = "QstatParsingError:\n\t{}\n\t{}\n".format( type(inst), # the exception instance inst, # __str__ allows args to printed directly ) sge_debug_print(exception_message) time.sleep(5) - pass def print_dictionary(self): """For debugging""" @@ -341,39 +330,35 @@ def is_job_pending(self, task_id): job_is_pending = self._task_dictionary[task_id].is_job_state_pending() # Double check pending jobs in case of change (since we don't check at the beginning) if job_is_pending: - self._run_qstat( - "checking job pending status {0}".format(task_id), False - ) + self._run_qstat(f"checking job pending status {task_id}", False) job_is_pending = self._task_dictionary[task_id].is_job_state_pending() else: - self._run_qstat("checking job pending status {0}".format(task_id), True) + self._run_qstat(f"checking job pending status {task_id}", True) if task_id in self._task_dictionary: # Trust the cache, only False if state='zombie' job_is_pending = self._task_dictionary[task_id].is_job_state_pending() else: sge_debug_print( - "ERROR: Job {0} not in task list, " + "ERROR: Job {} not in task list, " "even after forced qstat!".format(task_id) ) job_is_pending = False if not job_is_pending: - sge_debug_print("DONE! Returning for {0} claiming done!".format(task_id)) + sge_debug_print(f"DONE! Returning for {task_id} claiming done!") if task_id in self._task_dictionary: - sge_debug_print( - "NOTE: Adding {0} to OutOfScopeJobs list!".format(task_id) - ) + sge_debug_print(f"NOTE: Adding {task_id} to OutOfScopeJobs list!") self._out_of_scope_jobs.append(int(task_id)) self._task_dictionary.pop(task_id) else: sge_debug_print( - "ERROR: Job {0} not in task list, " + "ERROR: Job {} not in task list, " "but attempted to be removed!".format(task_id) ) return job_is_pending def qsub_sanitize_job_name(testjobname): - """ Ensure that qsub job names must begin with a letter. + """Ensure that qsub job names must begin with a letter. Numbers and punctuation are not allowed. @@ -410,7 +395,7 @@ def __init__(self, **kwargs): instant_qstat = "qstat" cached_qstat = "qstat" - if "plugin_args" in kwargs and kwargs["plugin_args"]: + if kwargs.get("plugin_args"): if "retry_timeout" in kwargs["plugin_args"]: self._retry_timeout = kwargs["plugin_args"]["retry_timeout"] if "max_tries" in kwargs["plugin_args"]: @@ -421,7 +406,7 @@ def __init__(self, **kwargs): cached_qstat = kwargs["plugin_args"]["qstatCachedProgramPath"] self._refQstatSubstitute = QstatSubstitute(instant_qstat, cached_qstat) - super(SGEPlugin, self).__init__(template, **kwargs) + super().__init__(template, **kwargs) def _is_pending(self, taskid): return self._refQstatSubstitute.is_job_pending(int(taskid)) @@ -438,14 +423,14 @@ def _submit_batchtask(self, scriptfile, node): if self._qsub_args: qsubargs = self._qsub_args if "qsub_args" in node.plugin_args: - if "overwrite" in node.plugin_args and node.plugin_args["overwrite"]: + if node.plugin_args.get("overwrite"): qsubargs = node.plugin_args["qsub_args"] else: qsubargs += " " + node.plugin_args["qsub_args"] if "-o" not in qsubargs: - qsubargs = "%s -o %s" % (qsubargs, path) + qsubargs = f"{qsubargs} -o {path}" if "-e" not in qsubargs: - qsubargs = "%s -e %s" % (qsubargs, path) + qsubargs = f"{qsubargs} -e {path}" if node._hierarchy: jobname = ".".join((dict(os.environ)["LOGNAME"], node._hierarchy, node._id)) else: @@ -454,7 +439,7 @@ def _submit_batchtask(self, scriptfile, node): jobnameitems.reverse() jobname = ".".join(jobnameitems) jobname = qsub_sanitize_job_name(jobname) - cmd.inputs.args = "%s -N %s %s" % (qsubargs, jobname, scriptfile) + cmd.inputs.args = f"{qsubargs} -N {jobname} {scriptfile}" oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName("CRITICAL")) tries = 0 @@ -471,7 +456,7 @@ def _submit_batchtask(self, scriptfile, node): raise RuntimeError( "\n".join( ( - ("Could not submit sge task" " for node %s") % node._id, + "Could not submit sge task for node %s" % node._id, str(e), ) ) diff --git a/nipype/pipeline/plugins/sgegraph.py b/nipype/pipeline/plugins/sgegraph.py index 489e48186c..3b33b73dee 100644 --- a/nipype/pipeline/plugins/sgegraph.py +++ b/nipype/pipeline/plugins/sgegraph.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via SGE -""" +"""Parallel workflow execution via SGE""" + import os import sys @@ -47,7 +46,7 @@ class SGEGraphPlugin(GraphPluginBase): def __init__(self, **kwargs): self._qsub_args = "" self._dont_resubmit_completed_jobs = False - if "plugin_args" in kwargs and kwargs["plugin_args"]: + if kwargs.get("plugin_args"): plugin_args = kwargs["plugin_args"] if "template" in plugin_args: self._template = plugin_args["template"] @@ -59,7 +58,7 @@ def __init__(self, **kwargs): self._dont_resubmit_completed_jobs = plugin_args[ "dont_resubmit_completed_jobs" ] - super(SGEGraphPlugin, self).__init__(**kwargs) + super().__init__(**kwargs) def _submit_graph(self, pyfiles, dependencies, nodes): def make_job_name(jobnumber, nodeslist): @@ -68,7 +67,7 @@ def make_job_name(jobnumber, nodeslist): - nodeslist: The name of the node being processed - return: A string representing this job to be displayed by SGE """ - job_name = "j{0}_{1}".format(jobnumber, nodeslist[jobnumber]._id) + job_name = f"j{jobnumber}_{nodeslist[jobnumber]._id}" # Condition job_name to be a valid bash identifier (i.e. - is invalid) job_name = job_name.replace("-", "_").replace(".", "_").replace(":", "_") return job_name @@ -85,7 +84,7 @@ def make_job_name(jobnumber, nodeslist): node_status_done = node_completed_status(node) # if the node itself claims done, then check to ensure all - # dependancies are also done + # dependencies are also done if node_status_done and idx in dependencies: for child_idx in dependencies[idx]: if child_idx in cache_doneness_per_node: @@ -96,7 +95,7 @@ def make_job_name(jobnumber, nodeslist): cache_doneness_per_node[idx] = node_status_done - with open(submitjobsfile, "wt") as fp: + with open(submitjobsfile, "w") as fp: fp.writelines("#!/usr/bin/env bash\n") fp.writelines("# Condense format attempted\n") for idx, pyscript in enumerate(pyfiles): @@ -110,9 +109,7 @@ def make_job_name(jobnumber, nodeslist): batch_dir, name = os.path.split(pyscript) name = ".".join(name.split(".")[:-1]) - batchscript = "\n".join( - (template, "%s %s" % (sys.executable, pyscript)) - ) + batchscript = "\n".join((template, f"{sys.executable} {pyscript}")) batchscriptfile = os.path.join( batch_dir, "batchscript_%s.sh" % name ) @@ -120,21 +117,19 @@ def make_job_name(jobnumber, nodeslist): batchscriptoutfile = batchscriptfile + ".o" batchscripterrfile = batchscriptfile + ".e" - with open(batchscriptfile, "wt") as batchfp: + with open(batchscriptfile, "w") as batchfp: batchfp.writelines(batchscript) batchfp.close() deps = "" if idx in dependencies: values = " " for jobid in dependencies[idx]: - # Avoid dependancies of done jobs + # Avoid dependencies of done jobs if ( not self._dont_resubmit_completed_jobs or not cache_doneness_per_node[jobid] ): - values += "${{{0}}},".format( - make_job_name(jobid, nodes) - ) + values += f"${{{make_job_name(jobid, nodes)}}}," if ( values != " " ): # i.e. if some jobs were added to dependency list @@ -144,10 +139,10 @@ def make_job_name(jobnumber, nodeslist): # Do not use default output locations if they are set in self._qsub_args stderrFile = "" if self._qsub_args.count("-e ") == 0: - stderrFile = "-e {errFile}".format(errFile=batchscripterrfile) + stderrFile = f"-e {batchscripterrfile}" stdoutFile = "" if self._qsub_args.count("-o ") == 0: - stdoutFile = "-o {outFile}".format(outFile=batchscriptoutfile) + stdoutFile = f"-o {batchscriptoutfile}" full_line = "{jobNm}=$(qsub {outFileOption} {errFileOption} {extraQSubArgs} {dependantIndex} -N {jobNm} {batchscript} | awk '/^Your job/{{print $3}}')\n".format( jobNm=jobname, outFileOption=stdoutFile, diff --git a/nipype/pipeline/plugins/slurm.py b/nipype/pipeline/plugins/slurm.py index 44cdac70d5..bdc142059f 100644 --- a/nipype/pipeline/plugins/slurm.py +++ b/nipype/pipeline/plugins/slurm.py @@ -5,6 +5,7 @@ Parallel workflow execution with SLURM """ + import os import re from time import sleep @@ -31,7 +32,6 @@ class SLURMPlugin(SGELikeBatchManagerBase): """ def __init__(self, **kwargs): - template = "#!/bin/bash" self._retry_timeout = 2 @@ -40,7 +40,7 @@ def __init__(self, **kwargs): self._sbatch_args = None self._jobid_re = "Submitted batch job ([0-9]*)" - if "plugin_args" in kwargs and kwargs["plugin_args"]: + if kwargs.get("plugin_args"): if "retry_timeout" in kwargs["plugin_args"]: self._retry_timeout = kwargs["plugin_args"]["retry_timeout"] if "max_tries" in kwargs["plugin_args"]: @@ -55,7 +55,7 @@ def __init__(self, **kwargs): if "sbatch_args" in kwargs["plugin_args"]: self._sbatch_args = kwargs["plugin_args"]["sbatch_args"] self._pending = {} - super(SLURMPlugin, self).__init__(self._template, **kwargs) + super().__init__(self._template, **kwargs) def _is_pending(self, taskid): try: @@ -100,14 +100,18 @@ def _submit_batchtask(self, scriptfile, node): if self._sbatch_args: sbatch_args = self._sbatch_args if "sbatch_args" in node.plugin_args: - if "overwrite" in node.plugin_args and node.plugin_args["overwrite"]: + if node.plugin_args.get("overwrite"): sbatch_args = node.plugin_args["sbatch_args"] else: sbatch_args += " " + node.plugin_args["sbatch_args"] if "-o" not in sbatch_args: - sbatch_args = "%s -o %s" % (sbatch_args, os.path.join(path, "slurm-%j.out")) + sbatch_args = "{} -o {}".format( + sbatch_args, os.path.join(path, "slurm-%j.out") + ) if "-e" not in sbatch_args: - sbatch_args = "%s -e %s" % (sbatch_args, os.path.join(path, "slurm-%j.out")) + sbatch_args = "{} -e {}".format( + sbatch_args, os.path.join(path, "slurm-%j.out") + ) if node._hierarchy: jobname = ".".join((dict(os.environ)["LOGNAME"], node._hierarchy, node._id)) else: @@ -115,7 +119,7 @@ def _submit_batchtask(self, scriptfile, node): jobnameitems = jobname.split(".") jobnameitems.reverse() jobname = ".".join(jobnameitems) - cmd.inputs.args = "%s -J %s %s" % (sbatch_args, jobname, scriptfile) + cmd.inputs.args = f"{sbatch_args} -J {jobname} {scriptfile}" oldlevel = iflogger.level iflogger.setLevel(logging.getLevelName("CRITICAL")) tries = 0 @@ -132,15 +136,14 @@ def _submit_batchtask(self, scriptfile, node): raise RuntimeError( "\n".join( ( - ("Could not submit sbatch task" " for node %s") - % node._id, + "Could not submit sbatch task for node %s" % node._id, str(e), ) ) ) else: break - logger.debug("Ran command ({0})".format(cmd.cmdline)) + logger.debug(f"Ran command ({cmd.cmdline})") iflogger.setLevel(oldlevel) # retrieve taskid lines = [line for line in result.runtime.stdout.split("\n") if line] diff --git a/nipype/pipeline/plugins/slurmgraph.py b/nipype/pipeline/plugins/slurmgraph.py index 9468c76ba1..05824b016b 100644 --- a/nipype/pipeline/plugins/slurmgraph.py +++ b/nipype/pipeline/plugins/slurmgraph.py @@ -1,6 +1,5 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via SLURM -""" +"""Parallel workflow execution via SLURM""" + import os import sys @@ -42,7 +41,7 @@ class SLURMGraphPlugin(GraphPluginBase): def __init__(self, **kwargs): self._sbatch_args = "" - if "plugin_args" in kwargs and kwargs["plugin_args"]: + if kwargs.get("plugin_args"): if "retry_timeout" in kwargs["plugin_args"]: self._retry_timeout = kwargs["plugin_args"]["retry_timeout"] if "max_tries" in kwargs["plugin_args"]: @@ -59,7 +58,7 @@ def __init__(self, **kwargs): ] else: self._dont_resubmit_completed_jobs = False - super(SLURMGraphPlugin, self).__init__(**kwargs) + super().__init__(**kwargs) def _submit_graph(self, pyfiles, dependencies, nodes): def make_job_name(jobnumber, nodeslist): @@ -68,7 +67,7 @@ def make_job_name(jobnumber, nodeslist): - nodeslist: The name of the node being processed - return: A string representing this job to be displayed by SLURM """ - job_name = "j{0}_{1}".format(jobnumber, nodeslist[jobnumber]._id) + job_name = f"j{jobnumber}_{nodeslist[jobnumber]._id}" # Condition job_name to be a valid bash identifier (i.e. - is invalid) job_name = job_name.replace("-", "_").replace(".", "_").replace(":", "_") return job_name @@ -85,7 +84,7 @@ def make_job_name(jobnumber, nodeslist): node_status_done = node_completed_status(node) # if the node itself claims done, then check to ensure all - # dependancies are also done + # dependencies are also done if node_status_done and idx in dependencies: for child_idx in dependencies[idx]: if child_idx in cache_doneness_per_node: @@ -96,7 +95,7 @@ def make_job_name(jobnumber, nodeslist): cache_doneness_per_node[idx] = node_status_done - with open(submitjobsfile, "wt") as fp: + with open(submitjobsfile, "w") as fp: fp.writelines("#!/usr/bin/env bash\n") fp.writelines("# Condense format attempted\n") for idx, pyscript in enumerate(pyfiles): @@ -110,9 +109,7 @@ def make_job_name(jobnumber, nodeslist): batch_dir, name = os.path.split(pyscript) name = ".".join(name.split(".")[:-1]) - batchscript = "\n".join( - (template, "%s %s" % (sys.executable, pyscript)) - ) + batchscript = "\n".join((template, f"{sys.executable} {pyscript}")) batchscriptfile = os.path.join( batch_dir, "batchscript_%s.sh" % name ) @@ -120,21 +117,19 @@ def make_job_name(jobnumber, nodeslist): batchscriptoutfile = batchscriptfile + ".o" batchscripterrfile = batchscriptfile + ".e" - with open(batchscriptfile, "wt") as batchfp: + with open(batchscriptfile, "w") as batchfp: batchfp.writelines(batchscript) batchfp.close() deps = "" if idx in dependencies: values = "" for jobid in dependencies[idx]: - # Avoid dependancies of done jobs + # Avoid dependencies of done jobs if ( not self._dont_resubmit_completed_jobs or not cache_doneness_per_node[jobid] ): - values += "${{{0}}}:".format( - make_job_name(jobid, nodes) - ) + values += f"${{{make_job_name(jobid, nodes)}}}:" if ( values != "" ): # i.e. if some jobs were added to dependency list @@ -144,10 +139,10 @@ def make_job_name(jobnumber, nodeslist): # Do not use default output locations if they are set in self._sbatch_args stderrFile = "" if self._sbatch_args.count("-e ") == 0: - stderrFile = "-e {errFile}".format(errFile=batchscripterrfile) + stderrFile = f"-e {batchscripterrfile}" stdoutFile = "" if self._sbatch_args.count("-o ") == 0: - stdoutFile = "-o {outFile}".format(outFile=batchscriptoutfile) + stdoutFile = f"-o {batchscriptoutfile}" full_line = "{jobNm}=$(sbatch {outFileOption} {errFileOption} {extraSBatchArgs} {dependantIndex} -J {jobNm} {batchscript} | awk '/^Submitted/ {{print $4}}')\n".format( jobNm=jobname, outFileOption=stdoutFile, diff --git a/nipype/pipeline/plugins/somaflow.py b/nipype/pipeline/plugins/somaflow.py index d621c7967a..16bedaab23 100644 --- a/nipype/pipeline/plugins/somaflow.py +++ b/nipype/pipeline/plugins/somaflow.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- -"""Parallel workflow execution via PBS/Torque -""" +"""Parallel workflow execution via PBS/Torque""" import os import sys @@ -15,23 +13,26 @@ class SomaFlowPlugin(GraphPluginBase): - """Execute using Soma workflow - """ + """Execute using Soma workflow""" def __init__(self, plugin_args=None): if soma_not_loaded: raise ImportError("SomaFlow could not be imported") - super(SomaFlowPlugin, self).__init__(plugin_args=plugin_args) + super().__init__(plugin_args=plugin_args) def _submit_graph(self, pyfiles, dependencies, nodes): - jobs = [] - soma_deps = [] - for idx, fname in enumerate(pyfiles): - name = os.path.splitext(os.path.split(fname)[1])[0] - jobs.append(Job(command=[sys.executable, fname], name=name)) - for key, values in list(dependencies.items()): - for val in values: - soma_deps.append((jobs[val], jobs[key])) + jobs = [ + Job( + command=[sys.executable, fname], + name=os.path.splitext(os.path.split(fname)[1])[0], + ) + for fname in pyfiles + ] + soma_deps = [ + (jobs[val], jobs[key]) + for key, values in dependencies.items() + for val in values + ] wf = Workflow(jobs, soma_deps) logger.info("serializing workflow") diff --git a/nipype/pipeline/plugins/tests/__init__.py b/nipype/pipeline/plugins/tests/__init__.py index 99fb243f19..349937997e 100644 --- a/nipype/pipeline/plugins/tests/__init__.py +++ b/nipype/pipeline/plugins/tests/__init__.py @@ -1,3 +1,2 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/pipeline/plugins/tests/test_base.py b/nipype/pipeline/plugins/tests/test_base.py index fddcfa2368..11acb369e9 100644 --- a/nipype/pipeline/plugins/tests/test_base.py +++ b/nipype/pipeline/plugins/tests/test_base.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Tests for the engine module -""" +"""Tests for the engine module""" import numpy as np import scipy.sparse as ssp diff --git a/nipype/pipeline/plugins/tests/test_callback.py b/nipype/pipeline/plugins/tests/test_callback.py index 8baa356fdd..b10238ec4a 100644 --- a/nipype/pipeline/plugins/tests/test_callback.py +++ b/nipype/pipeline/plugins/tests/test_callback.py @@ -1,9 +1,9 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Tests for workflow callbacks -""" +"""Tests for workflow callbacks.""" +from pathlib import Path from time import sleep +import json import pytest import nipype.interfaces.utility as niu import nipype.pipeline.engine as pe @@ -17,7 +17,7 @@ def bad_func(): raise Exception -class Status(object): +class Status: def __init__(self): self.statuses = [] @@ -61,3 +61,51 @@ def test_callback_exception(tmpdir, plugin, stop_on_first_crash): sleep(0.5) # Wait for callback to be called (python 2.7) assert so.statuses == [("f_node", "start"), ("f_node", "exception")] + + +@pytest.mark.parametrize("plugin", ["Linear", "MultiProc", "LegacyMultiProc"]) +def test_callback_gantt(tmp_path: Path, plugin: str) -> None: + import logging + + from os import path + + from nipype.utils.profiler import log_nodes_cb + from nipype.utils.draw_gantt_chart import generate_gantt_chart + + log_filename = tmp_path / "callback.log" + logger = logging.getLogger("callback") + logger.setLevel(logging.DEBUG) + handler = logging.FileHandler(log_filename) + logger.addHandler(handler) + + # create workflow + wf = pe.Workflow(name="test", base_dir=str(tmp_path)) + f_node = pe.Node( + niu.Function(function=func, input_names=[], output_names=[]), name="f_node" + ) + wf.add_nodes([f_node]) + wf.config["execution"] = {"crashdump_dir": wf.base_dir, "poll_sleep_duration": 2} + + plugin_args = {"status_callback": log_nodes_cb} + if plugin != "Linear": + plugin_args["n_procs"] = 8 + wf.run(plugin=plugin, plugin_args=plugin_args) + + with open(log_filename, "r") as _f: + loglines = _f.readlines() + + # test missing duration + first_line = json.loads(loglines[0]) + if "duration" in first_line: + del first_line["duration"] + loglines[0] = f"{json.dumps(first_line)}\n" + + # test duplicate timestamp warning + loglines.append(loglines[-1]) + + with open(log_filename, "w") as _f: + _f.write("".join(loglines)) + + with pytest.warns(Warning): + generate_gantt_chart(str(log_filename), 1 if plugin == "Linear" else 8) + assert (tmp_path / "callback.log.html").exists() diff --git a/nipype/pipeline/plugins/tests/test_debug.py b/nipype/pipeline/plugins/tests/test_debug.py index 82361a0228..fafb6a276d 100644 --- a/nipype/pipeline/plugins/tests/test_debug.py +++ b/nipype/pipeline/plugins/tests/test_debug.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os import nipype.interfaces.base as nib diff --git a/nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py b/nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py index f490729485..cd79fbe31c 100644 --- a/nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py +++ b/nipype/pipeline/plugins/tests/test_legacymultiproc_nondaemon.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Testing module for functions and classes from multiproc.py -""" +"""Testing module for functions and classes from multiproc.py""" # Import packages import os import sys @@ -41,7 +39,7 @@ def dummyFunction(filename): This function writes the value 45 to the given filename. """ j = 0 - for i in range(0, 10): + for i in range(10): j += i # j is now 45 (0+1+2+3+4+5+6+7+8+9) @@ -50,7 +48,6 @@ def dummyFunction(filename): f.write(str(j)) for n in range(numberOfThreads): - # mark thread as alive a[n] = True @@ -64,11 +61,9 @@ def dummyFunction(filename): # block until all processes are done allDone = False while not allDone: - time.sleep(1) for n in range(numberOfThreads): - a[n] = t[n].is_alive() if not any(a): @@ -126,7 +121,7 @@ def run_multiproc_nondaemon_with_flag(nondaemon_flag): plugin_args={"n_procs": 2, "non_daemon": nondaemon_flag}, ) - names = [".".join((node._hierarchy, node.name)) for node in execgraph.nodes()] + names = [f"{node._hierarchy}.{node.name}" for node in execgraph.nodes()] node = list(execgraph.nodes())[names.index("pipe.f2")] result = node.get_output("sum_out") os.chdir(cur_dir) @@ -134,6 +129,9 @@ def run_multiproc_nondaemon_with_flag(nondaemon_flag): return result +@pytest.mark.skipif( + sys.version_info >= (3, 8), reason="multiprocessing issues in Python 3.8" +) def test_run_multiproc_nondaemon_false(): """ This is the entry point for the test. Two times a pipe of several @@ -152,6 +150,9 @@ def test_run_multiproc_nondaemon_false(): assert shouldHaveFailed +@pytest.mark.skipif( + sys.version_info >= (3, 8), reason="multiprocessing issues in Python 3.8" +) def test_run_multiproc_nondaemon_true(): # with nondaemon_flag = True, the execution should succeed result = run_multiproc_nondaemon_with_flag(True) diff --git a/nipype/pipeline/plugins/tests/test_linear.py b/nipype/pipeline/plugins/tests/test_linear.py index 9ccb5157fc..519d978de6 100644 --- a/nipype/pipeline/plugins/tests/test_linear.py +++ b/nipype/pipeline/plugins/tests/test_linear.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os import nipype.interfaces.base as nib @@ -40,7 +39,7 @@ def test_run_in_series(tmpdir): pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 execgraph = pipe.run(plugin="Linear") - names = [".".join((node._hierarchy, node.name)) for node in execgraph.nodes()] + names = [f"{node._hierarchy}.{node.name}" for node in execgraph.nodes()] node = list(execgraph.nodes())[names.index("pipe.mod1")] result = node.get_output("output1") assert result == [1, 1] diff --git a/nipype/pipeline/plugins/tests/test_multiproc.py b/nipype/pipeline/plugins/tests/test_multiproc.py index 2e8967cfbe..484c0d07bc 100644 --- a/nipype/pipeline/plugins/tests/test_multiproc.py +++ b/nipype/pipeline/plugins/tests/test_multiproc.py @@ -1,9 +1,9 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Test the resource management of MultiProc """ +import sys import os import pytest from nipype.pipeline import engine as pe @@ -33,6 +33,9 @@ def _list_outputs(self): return outputs +@pytest.mark.skipif( + sys.version_info >= (3, 8), reason="multiprocessing issues in Python 3.8" +) def test_run_multiproc(tmpdir): tmpdir.chdir() @@ -53,6 +56,7 @@ def test_run_multiproc(tmpdir): class InputSpecSingleNode(nib.TraitedSpec): input1 = nib.traits.Int(desc="a random int") input2 = nib.traits.Int(desc="a random int") + use_gpu = nib.traits.Bool(False, mandatory=False, desc="boolean for GPU nodes") class OutputSpecSingleNode(nib.TraitedSpec): @@ -114,6 +118,27 @@ def test_no_more_threads_than_specified(tmpdir): pipe.run(plugin="MultiProc", plugin_args={"n_procs": max_threads}) +def test_no_more_gpu_threads_than_specified(tmpdir): + tmpdir.chdir() + + pipe = pe.Workflow(name="pipe") + n1 = pe.Node(SingleNodeTestInterface(), name="n1", n_procs=2) + n1.inputs.use_gpu = True + n1.inputs.input1 = 4 + pipe.add_nodes([n1]) + + max_threads = 2 + max_gpu = 1 + with pytest.raises(RuntimeError): + pipe.run( + plugin="MultiProc", + plugin_args={"n_procs": max_threads, 'n_gpu_procs': max_gpu}, + ) + + +@pytest.mark.skipif( + sys.version_info >= (3, 8), reason="multiprocessing issues in Python 3.8" +) def test_hold_job_until_procs_available(tmpdir): tmpdir.chdir() diff --git a/nipype/pipeline/plugins/tests/test_oar.py b/nipype/pipeline/plugins/tests/test_oar.py index 1024daaef9..fcb1efac6e 100644 --- a/nipype/pipeline/plugins/tests/test_oar.py +++ b/nipype/pipeline/plugins/tests/test_oar.py @@ -1,7 +1,5 @@ -# -*- coding: utf-8 -*- import os -from shutil import rmtree -from tempfile import mkdtemp +from shutil import which import nipype.interfaces.base as nib import pytest @@ -31,22 +29,17 @@ def _list_outputs(self): return outputs -@pytest.mark.xfail(reason="not known") -def test_run_oar(): - cur_dir = os.getcwd() - temp_dir = mkdtemp(prefix="test_engine_", dir=os.getcwd()) - os.chdir(temp_dir) - - pipe = pe.Workflow(name="pipe") +@pytest.mark.skipif(which("oarsub") is None, reason="OAR not installed") +@pytest.mark.timeout(60) +def test_run_oargraph(tmp_path): + pipe = pe.Workflow(name="pipe", base_dir=str(tmp_path)) mod1 = pe.Node(interface=OarTestInterface(), name="mod1") mod2 = pe.MapNode(interface=OarTestInterface(), iterfield=["input1"], name="mod2") pipe.connect([(mod1, mod2, [("output1", "input1")])]) pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 execgraph = pipe.run(plugin="OAR") - names = [".".join((node._hierarchy, node.name)) for node in execgraph.nodes()] + names = [f"{node._hierarchy}.{node.name}" for node in execgraph.nodes()] node = list(execgraph.nodes())[names.index("pipe.mod1")] result = node.get_output("output1") assert result == [1, 1] - os.chdir(cur_dir) - rmtree(temp_dir) diff --git a/nipype/pipeline/plugins/tests/test_pbs.py b/nipype/pipeline/plugins/tests/test_pbs.py index bb85443940..7a44ba3dc7 100644 --- a/nipype/pipeline/plugins/tests/test_pbs.py +++ b/nipype/pipeline/plugins/tests/test_pbs.py @@ -1,8 +1,4 @@ -# -*- coding: utf-8 -*- -import os -from shutil import rmtree -from tempfile import mkdtemp -from time import sleep +from shutil import which import nipype.interfaces.base as nib import pytest @@ -32,22 +28,16 @@ def _list_outputs(self): return outputs -@pytest.mark.xfail(reason="not known") -def test_run_pbsgraph(): - cur_dir = os.getcwd() - temp_dir = mkdtemp(prefix="test_engine_") - os.chdir(temp_dir) - - pipe = pe.Workflow(name="pipe") +@pytest.mark.skipif(which("qsub") is None, reason="PBS not installed") +@pytest.mark.timeout(60) +def test_run_pbsgraph(tmp_path): + pipe = pe.Workflow(name="pipe", base_dir=str(tmp_path)) mod1 = pe.Node(interface=PbsTestInterface(), name="mod1") mod2 = pe.MapNode(interface=PbsTestInterface(), iterfield=["input1"], name="mod2") pipe.connect([(mod1, mod2, [("output1", "input1")])]) - pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 execgraph = pipe.run(plugin="PBSGraph") - names = [".".join((node._hierarchy, node.name)) for node in execgraph.nodes()] + names = [f"{node._hierarchy}.{node.name}" for node in execgraph.nodes()] node = list(execgraph.nodes())[names.index("pipe.mod1")] result = node.get_output("output1") assert result == [1, 1] - os.chdir(cur_dir) - rmtree(temp_dir) diff --git a/nipype/pipeline/plugins/tests/test_sgelike.py b/nipype/pipeline/plugins/tests/test_sgelike.py new file mode 100644 index 0000000000..26c3d70a06 --- /dev/null +++ b/nipype/pipeline/plugins/tests/test_sgelike.py @@ -0,0 +1,36 @@ +from nipype.pipeline.plugins.base import SGELikeBatchManagerBase +from nipype.interfaces.utility import Function +import nipype.pipeline.engine as pe +import pytest +from unittest.mock import patch +import subprocess + + +def crasher(): + raise ValueError + + +def submit_batchtask(self, scriptfile, node): + self._pending[1] = node.output_dir() + subprocess.call(["bash", scriptfile]) + return 1 + + +def is_pending(self, taskid): + return False + + +@patch.object(SGELikeBatchManagerBase, "_submit_batchtask", new=submit_batchtask) +@patch.object(SGELikeBatchManagerBase, "_is_pending", new=is_pending) +def test_crashfile_creation(tmp_path): + pipe = pe.Workflow(name="pipe", base_dir=str(tmp_path)) + pipe.config["execution"]["crashdump_dir"] = str(tmp_path) + pipe.add_nodes([pe.Node(interface=Function(function=crasher), name="crasher")]) + sgelike_plugin = SGELikeBatchManagerBase("") + with pytest.raises(RuntimeError): + assert pipe.run(plugin=sgelike_plugin) + + crashfiles = list(tmp_path.glob("crash*crasher*.pklz")) + list( + tmp_path.glob("crash*crasher*.txt") + ) + assert len(crashfiles) == 1 diff --git a/nipype/pipeline/plugins/tests/test_somaflow.py b/nipype/pipeline/plugins/tests/test_somaflow.py index 5fe5935e1d..4c074522d8 100644 --- a/nipype/pipeline/plugins/tests/test_somaflow.py +++ b/nipype/pipeline/plugins/tests/test_somaflow.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- import os -from time import sleep import nipype.interfaces.base as nib import pytest @@ -43,7 +41,7 @@ def test_run_somaflow(tmpdir): pipe.base_dir = os.getcwd() mod1.inputs.input1 = 1 execgraph = pipe.run(plugin="SomaFlow") - names = [".".join((node._hierarchy, node.name)) for node in execgraph.nodes()] + names = [f"{node._hierarchy}.{node.name}" for node in execgraph.nodes()] node = list(execgraph.nodes())[names.index("pipe.mod1")] result = node.get_output("output1") assert result == [1, 1] diff --git a/nipype/pipeline/plugins/tests/test_tools.py b/nipype/pipeline/plugins/tests/test_tools.py index 17b435bbb6..e352253dbe 100644 --- a/nipype/pipeline/plugins/tests/test_tools.py +++ b/nipype/pipeline/plugins/tests/test_tools.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Tests for the engine module -""" -import numpy as np -import scipy.sparse as ssp +"""Tests for the engine module""" import re -import mock +from unittest import mock from nipype.pipeline.plugins.tools import report_crash diff --git a/nipype/pipeline/plugins/tools.py b/nipype/pipeline/plugins/tools.py index ef213be36d..7e066b0ea3 100644 --- a/nipype/pipeline/plugins/tools.py +++ b/nipype/pipeline/plugins/tools.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Common graph operations for execution -""" +"""Common graph operations for execution""" import os import getpass from socket import gethostname @@ -18,8 +16,7 @@ def report_crash(node, traceback=None, hostname=None): - """Writes crash related information to a file - """ + """Writes crash related information to a file""" name = node._id host = None traceback = traceback or format_exception(*sys.exc_info()) @@ -56,8 +53,8 @@ def report_crash(node, traceback=None, hostname=None): try: login_name = getpass.getuser() except KeyError: - login_name = "UID{:d}".format(os.getuid()) - crashfile = "crash-%s-%s-%s-%s" % (timeofcrash, login_name, name, str(uuid.uuid4())) + login_name = f"UID{os.getuid():d}" + crashfile = f"crash-{timeofcrash}-{login_name}-{name}-{uuid.uuid4()}" crashdir = node.config["execution"].get("crashdump_dir", os.getcwd()) os.makedirs(crashdir, exist_ok=True) @@ -85,28 +82,23 @@ def report_nodes_not_run(notrun): if notrun: logger.info("***********************************") for info in notrun: - logger.error( - "could not run node: %s" - % ".".join((info["node"]._hierarchy, info["node"]._id)) - ) + node = info["node"] + logger.error(f"could not run node: {node._hierarchy}.{node._id}") logger.info("crashfile: %s" % info["crashfile"]) logger.debug("The following dependent nodes were not run") for subnode in info["dependents"]: logger.debug(subnode._id) logger.info("***********************************") - raise RuntimeError( - ("Workflow did not execute cleanly. " "Check log for details") - ) def create_pyscript(node, updatehash=False, store_exception=True): # pickle node timestamp = strftime("%Y%m%d_%H%M%S") if node._hierarchy: - suffix = "%s_%s_%s" % (timestamp, node._hierarchy, node._id) + suffix = f"{timestamp}_{node._hierarchy}_{node._id}" batch_dir = os.path.join(node.base_dir, node._hierarchy.split(".")[0], "batch") else: - suffix = "%s_%s" % (timestamp, node._id) + suffix = f"{timestamp}_{node._id}" batch_dir = os.path.join(node.base_dir, "batch") if not os.path.exists(batch_dir): os.makedirs(batch_dir) @@ -180,6 +172,6 @@ def create_pyscript(node, updatehash=False, store_exception=True): """ cmdstr = cmdstr % (mpl_backend, pkl_file, batch_dir, node.config, suffix) pyscript = os.path.join(batch_dir, "pyscript_%s.py" % suffix) - with open(pyscript, "wt") as fp: + with open(pyscript, "w") as fp: fp.writelines(cmdstr) return pyscript diff --git a/nipype/pkg_info.py b/nipype/pkg_info.py index fbba2f138c..4370f495f8 100644 --- a/nipype/pkg_info.py +++ b/nipype/pkg_info.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import configparser import os @@ -9,7 +8,7 @@ def pkg_commit_hash(pkg_path): - """ Get short form of commit hash given directory `pkg_path` + """Get short form of commit hash given directory `pkg_path` There should be a file called 'COMMIT_INFO.txt' in `pkg_path`. This is a file in INI file format, with at least one section: ``commit hash`` and two @@ -41,7 +40,7 @@ def pkg_commit_hash(pkg_path): # Try and get commit from written commit text file pth = os.path.join(pkg_path, COMMIT_INFO_FNAME) if not os.path.isfile(pth): - raise IOError("Missing commit info file %s" % pth) + raise OSError("Missing commit info file %s" % pth) cfg_parser = configparser.RawConfigParser() with open(pth, encoding="utf-8") as fp: cfg_parser.read_file(fp) @@ -66,7 +65,7 @@ def pkg_commit_hash(pkg_path): def get_pkg_info(pkg_path): - """ Return dict describing the context of this package + """Return dict describing the context of this package Parameters ---------- diff --git a/nipype/refs.py b/nipype/refs.py index 0478d7ceed..9d81b314eb 100644 --- a/nipype/refs.py +++ b/nipype/refs.py @@ -1,7 +1,7 @@ # Use duecredit (duecredit.org) to provide a citation to relevant work to # be cited. This does nothing, unless the user has duecredit installed, # And calls this with duecredit (as in `python -m duecredit script.py`): -from .external.due import due, Doi, BibTeX +from .external.due import due, Doi due.cite( Doi("10.3389/fninf.2011.00013"), diff --git a/nipype/scripts/cli.py b/nipype/scripts/cli.py index 73b599a978..8c544b8967 100644 --- a/nipype/scripts/cli.py +++ b/nipype/scripts/cli.py @@ -145,12 +145,12 @@ def run(ctx, module, interface, list, help): iface_names = list_interfaces(module) click.echo("Available Interfaces:") for if_name in iface_names: - click.echo(" {}".format(if_name)) + click.echo(f" {if_name}") # check the interface elif module_given and interface: # create the argument parser - description = "Run {}".format(interface) + description = f"Run {interface}" prog = " ".join([ctx.command_path, module.__name__, interface] + ctx.args) iface_parser = argparse.ArgumentParser(description=description, prog=prog) @@ -164,7 +164,7 @@ def run(ctx, module, interface, list, help): iface_parser.print_help() except: print( - "An error ocurred when trying to print the full" + "An error occurred when trying to print the full" "command help, printing usage." ) finally: @@ -209,7 +209,7 @@ def convert(): type=UnexistingFilePath, required=True, callback=check_not_none, - help="JSON file name where the Boutiques descriptor will be " "written.", + help="JSON file name where the Boutiques descriptor will be written.", ) @click.option( "-c", diff --git a/nipype/scripts/crash_files.py b/nipype/scripts/crash_files.py index 84464ccddb..1caa0c430b 100644 --- a/nipype/scripts/crash_files.py +++ b/nipype/scripts/crash_files.py @@ -1,7 +1,5 @@ """Utilities to manipulate and search through .pklz crash files.""" -import re -import sys import os.path as op from glob import glob diff --git a/nipype/scripts/instance.py b/nipype/scripts/instance.py index 0d736de796..d9cc425e9a 100644 --- a/nipype/scripts/instance.py +++ b/nipype/scripts/instance.py @@ -1,7 +1,7 @@ -# -*- coding: utf-8 -*- """ Import lib and class meta programming utilities. """ + import inspect import importlib @@ -29,7 +29,7 @@ def import_module(module_path): try: mod = importlib.import_module(module_path) except: - raise ImportError("Error when importing object {}.".format(module_path)) + raise ImportError(f"Error when importing object {module_path}.") else: return mod @@ -39,7 +39,7 @@ def list_interfaces(module): the given module. """ iface_names = [] - for k, v in sorted(list(module.__dict__.items())): + for k, v in sorted(module.__dict__.items()): if inspect.isclass(v) and issubclass(v, Interface): iface_names.append(k) return iface_names diff --git a/nipype/scripts/utils.py b/nipype/scripts/utils.py index 28e11cd8f6..8d8dc52627 100644 --- a/nipype/scripts/utils.py +++ b/nipype/scripts/utils.py @@ -1,9 +1,7 @@ -# -*- coding: utf-8 -*- """ Utilities for the CLI functions. """ - import re import click import json @@ -25,7 +23,7 @@ # validators def check_not_none(ctx, param, value): if value is None: - raise click.BadParameter("got {}.".format(value)) + raise click.BadParameter(f"got {value}.") return value @@ -73,12 +71,12 @@ def add_args_options(arg_parser, interface): if not spec.is_trait_type(traits.TraitCompound): trait_type = type(spec.trait_type.default_value) if trait_type in (bytes, str, int, float): - if trait_type == bytes: + if trait_type is bytes: trait_type = str args["type"] = trait_type elif len(spec.inner_traits) == 1: trait_type = type(spec.inner_traits[0].trait_type.default_value) - if trait_type == bytes: + if trait_type is bytes: trait_type = str if trait_type in (bytes, bool, str, int, float): args["type"] = trait_type @@ -102,12 +100,10 @@ def add_args_options(arg_parser, interface): if has_multiple_inner_traits: raise NotImplementedError( - ( - "This interface cannot be used. via the" - " command line as multiple inner traits" - " are currently not supported for mandatory" - " argument: {}.".format(name) - ) + "This interface cannot be used. via the" + " command line as multiple inner traits" + " are currently not supported for mandatory" + " argument: {}.".format(name) ) arg_parser.add_argument(name, help=desc, **args) else: diff --git a/nipype/sphinxext/__init__.py b/nipype/sphinxext/__init__.py index 7f877fb023..c30bc66036 100644 --- a/nipype/sphinxext/__init__.py +++ b/nipype/sphinxext/__init__.py @@ -1,4 +1,3 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/sphinxext/apidoc/__init__.py b/nipype/sphinxext/apidoc/__init__.py index 9c64cb4fb9..429848d2f5 100644 --- a/nipype/sphinxext/apidoc/__init__.py +++ b/nipype/sphinxext/apidoc/__init__.py @@ -2,7 +2,10 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Settings for sphinxext.interfaces and connection to sphinx-apidoc.""" import re -from sphinxcontrib.napoleon import ( +from packaging.version import Version + +import sphinx +from sphinx.ext.napoleon import ( Config as NapoleonConfig, _patch_python_domain, _skip_member as _napoleon_skip_member, @@ -38,13 +41,25 @@ class Config(NapoleonConfig): (requires duecredit to be installed). """ - _config_values = { - "nipype_skip_classes": ( - ["Tester", "InputSpec", "OutputSpec", "Numpy", "NipypeTester",], - "env", - ), - **NapoleonConfig._config_values, - } + + if Version(sphinx.__version__) >= Version("8.2.1"): + _config_values = ( + ( + "nipype_skip_classes", + ["Tester", "InputSpec", "OutputSpec", "Numpy", "NipypeTester"], + "env", + frozenset({list[str]}), + ), + *NapoleonConfig._config_values, + ) + else: + _config_values = { + "nipype_skip_classes": ( + ["Tester", "InputSpec", "OutputSpec", "Numpy", "NipypeTester"], + "env", + ), + **NapoleonConfig._config_values, + } def setup(app): @@ -81,8 +96,12 @@ def setup(app): app.connect("autodoc-process-docstring", _process_docstring) app.connect("autodoc-skip-member", _skip_member) - for name, (default, rebuild) in Config._config_values.items(): - app.add_config_value(name, default, rebuild) + if Version(sphinx.__version__) >= Version("8.2.1"): + for name, default, rebuild, types in Config._config_values: + app.add_config_value(name, default, rebuild, types=types) + else: + for name, (default, rebuild) in Config._config_values.items(): + app.add_config_value(name, default, rebuild) return {"version": __version__, "parallel_read_safe": True} diff --git a/nipype/sphinxext/apidoc/docstring.py b/nipype/sphinxext/apidoc/docstring.py index 445a95bfa2..cbecc0a5de 100644 --- a/nipype/sphinxext/apidoc/docstring.py +++ b/nipype/sphinxext/apidoc/docstring.py @@ -2,8 +2,8 @@ # vi: set ft=python sts=4 ts=4 sw=4 et: """Reformat interface docstrings.""" import re -from sphinxcontrib.napoleon._upstream import _ -from sphinxcontrib.napoleon.docstring import NumpyDocstring +from sphinx.locale import _ +from sphinx.ext.napoleon.docstring import NumpyDocstring class NipypeDocstring(NumpyDocstring): @@ -34,7 +34,7 @@ class InterfaceDocstring(NipypeDocstring): docstring : :obj:`str` or :obj:`list` of :obj:`str` The docstring to parse, given either as a string or split into individual lines. - config: :obj:`sphinxcontrib.napoleon.Config` or :obj:`sphinx.config.Config` + config: :obj:`sphinx.ext.napoleon.Config` or :obj:`sphinx.config.Config` The configuration settings to use. If not given, defaults to the config object on `app`; or if `app` is not given defaults to the a new :class:`nipype.sphinxext.apidoc.Config` object. @@ -62,7 +62,7 @@ class InterfaceDocstring(NipypeDocstring): _name_rgx = re.compile( r"^\s*(:(?P\w+):`(?P[a-zA-Z0-9_.-]+)`|" r" (?P[a-zA-Z0-9_.-]+))\s*", - re.X, + re.VERBOSE, ) def __init__( @@ -169,9 +169,7 @@ def _parse_spec(inputs, name, spec): desc_lines += ["(Nipype **default** value: ``%s``)" % str(default)] - out_rst = [ - "{name} : {type}".format(name=name, type=spec.full_info(inputs, name, None)) - ] + out_rst = [f"{name} : {spec.full_info(inputs, name, None)}"] out_rst += _indent(desc_lines, 4) return out_rst diff --git a/nipype/sphinxext/documenter.py b/nipype/sphinxext/documenter.py index 5300d81165..eee0f626b9 100644 --- a/nipype/sphinxext/documenter.py +++ b/nipype/sphinxext/documenter.py @@ -1,4 +1,5 @@ """sphinx autodoc ext.""" + from sphinx.locale import _ from sphinx.ext import autodoc from nipype.interfaces.base import BaseInterface @@ -46,9 +47,7 @@ def add_directive_header(self, sig: str) -> None: for line in lines.splitlines(): self.add_line(line, sourcename) else: - self.add_line( - ".. %s:%s:: %s%s" % (domain, directive, name, sig), sourcename - ) + self.add_line(f".. {domain}:{directive}:: {name}{sig}", sourcename) if self.options.noindex: self.add_line(" :noindex:", sourcename) if self.objpath: @@ -73,9 +72,9 @@ def add_directive_header(self, sig: str) -> None: if b.__module__ in ("__builtin__", "builtins"): bases_links.append(":class:`%s`" % b.__name__) elif based_interface: - bases_links.append(":ref:`%s.%s`" % (b.__module__, b.__name__)) + bases_links.append(f":ref:`{b.__module__}.{b.__name__}`") else: - bases_links.append(":class:`%s.%s`" % (b.__module__, b.__name__)) + bases_links.append(f":class:`{b.__module__}.{b.__name__}`") self.add_line(" " + _("Bases: %s") % ", ".join(bases_links), sourcename) diff --git a/nipype/sphinxext/gh.py b/nipype/sphinxext/gh.py index c373f84c1a..07a6513fb4 100644 --- a/nipype/sphinxext/gh.py +++ b/nipype/sphinxext/gh.py @@ -1,4 +1,5 @@ """Build a file URL.""" + import os import inspect import subprocess @@ -23,7 +24,7 @@ def get_url(https://github.com/obj): revision = _get_git_revision() if revision is not None: shortfile = os.path.join("nipype", filename.split("nipype/")[-1]) - uri = "http://github.com/nipy/nipype/blob/%s/%s" % (revision, shortfile,) + uri = f"http://github.com/nipy/nipype/blob/%7Brevision%7D/%7Bshortfile%7D" lines, lstart = inspect.getsourcelines(obj) lend = len(lines) + lstart return "%s#L%d-L%d" % (uri, lstart, lend) diff --git a/nipype/sphinxext/plot_workflow.py b/nipype/sphinxext/plot_workflow.py index 78b5f71384..74745f99cb 100644 --- a/nipype/sphinxext/plot_workflow.py +++ b/nipype/sphinxext/plot_workflow.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -106,6 +105,7 @@ Provide a customized template for preparing restructured text. """ + import sys import os import shutil @@ -113,12 +113,11 @@ import re import textwrap from os.path import relpath -from errno import EEXIST import traceback missing_imports = [] try: - from docutils.parsers.rst import directives + from docutils.parsers.rst import directives, Directive from docutils.parsers.rst.directives.images import Image align = Image.align @@ -132,7 +131,6 @@ def format_template(template, **kw): return jinja2.Template(template).render(**kw) - except ImportError as e: missing_imports.append(str(e)) try: @@ -146,26 +144,6 @@ def format_template(template, **kw): missing_imports.append(str(e)) -def wf_directive( - name, - arguments, - options, - content, - lineno, - content_offset, - block_text, - state, - state_machine, -): - if len(missing_imports) == 0: - return run(arguments, content, options, state_machine, state, lineno) - else: - raise ImportError("\n".join(missing_imports)) - - -wf_directive.__doc__ = __doc__ - - def _option_boolean(arg): if not arg or not arg.strip(): # no argument given, assume used as a flag @@ -232,12 +210,12 @@ def mark_wf_labels(app, document): break -def setup(app): - setup.app = app - setup.config = app.config - setup.confdir = app.confdir - - options = { +class WorkflowDirective(Directive): + has_content = True + required_arguments = 0 + optional_arguments = 2 + final_argument_whitespace = False + option_spec = { "alt": directives.unchanged, "height": directives.length_or_unitless, "width": directives.length_or_percentage_or_unitless, @@ -253,7 +231,227 @@ def setup(app): "simple_form": _option_boolean, } - app.add_directive("workflow", wf_directive, True, (0, 2, False), **options) + def run(self): + if missing_imports: + raise ImportError("\n".join(missing_imports)) + + document = self.state_machine.document + config = document.settings.env.config + nofigs = "nofigs" in self.options + + formats = get_wf_formats(config) + default_fmt = formats[0][0] + + graph2use = self.options.get("graph2use", "hierarchical") + simple_form = self.options.get("simple_form", True) + + self.options.setdefault("include-source", config.wf_include_source) + keep_context = "context" in self.options + context_opt = None if not keep_context else self.options["context"] + + rst_file = document.attributes["source"] + rst_dir = os.path.dirname(rst_file) + + if len(self.arguments): + if not config.wf_basedir: + source_file_name = os.path.join( + setup.app.builder.srcdir, directives.uri(self.arguments[0]) + ) + else: + source_file_name = os.path.join( + setup.confdir, config.wf_basedir, directives.uri(self.arguments[0]) + ) + + # If there is content, it will be passed as a caption. + caption = "\n".join(self.content) + + # If the optional function name is provided, use it + if len(self.arguments) == 2: + function_name = self.arguments[1] + else: + function_name = None + + with open(source_file_name, encoding="utf-8") as fd: + code = fd.read() + output_base = os.path.basename(source_file_name) + else: + source_file_name = rst_file + code = textwrap.dedent("\n".join([str(c) for c in self.content])) + counter = document.attributes.get("_wf_counter", 0) + 1 + document.attributes["_wf_counter"] = counter + base, _ = os.path.splitext(os.path.basename(source_file_name)) + output_base = "%s-%d.py" % (base, counter) + function_name = None + caption = "" + + base, source_ext = os.path.splitext(output_base) + if source_ext in (".py", ".rst", ".txt"): + output_base = base + else: + source_ext = "" + + # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames + output_base = output_base.replace(".", "-") + + # is it in doctest format? + is_doctest = contains_doctest(code) + if "format" in self.options: + if self.options["format"] == "python": + is_doctest = False + else: + is_doctest = True + + # determine output directory name fragment + source_rel_name = relpath(source_file_name, setup.confdir) + source_rel_dir = os.path.dirname(source_rel_name) + while source_rel_dir.startswith(os.path.sep): + source_rel_dir = source_rel_dir[1:] + + # build_dir: where to place output files (temporarily) + build_dir = os.path.join( + os.path.dirname(setup.app.doctreedir), "wf_directive", source_rel_dir + ) + # get rid of .. in paths, also changes pathsep + # see note in Python docs for warning about symbolic links on Windows. + # need to compare source and dest paths at end + build_dir = os.path.normpath(build_dir) + + if not os.path.exists(build_dir): + os.makedirs(build_dir) + + # output_dir: final location in the builder's directory + dest_dir = os.path.abspath( + os.path.join(setup.app.builder.outdir, source_rel_dir) + ) + if not os.path.exists(dest_dir): + os.makedirs(dest_dir) # no problem here for me, but just use built-ins + + # how to link to files from the RST file + dest_dir_link = os.path.join( + relpath(setup.confdir, rst_dir), source_rel_dir + ).replace(os.path.sep, "/") + try: + build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, "/") + except ValueError: + # on Windows, relpath raises ValueError when path and start are on + # different mounts/drives + build_dir_link = build_dir + source_link = dest_dir_link + "/" + output_base + source_ext + + # make figures + try: + results = render_figures( + code, + source_file_name, + build_dir, + output_base, + keep_context, + function_name, + config, + graph2use, + simple_form, + context_reset=context_opt == "reset", + close_figs=context_opt == "close-figs", + ) + errors = [] + except GraphError as err: + reporter = self.state.memo.reporter + sm = reporter.system_message( + 2, + "Exception occurred in plotting %s\n from %s:\n%s" + % (output_base, source_file_name, err), + line=self.lineno, + ) + results = [(code, [])] + errors = [sm] + + # Properly indent the caption + caption = "\n".join(" " + line.strip() for line in caption.split("\n")) + + # generate output restructuredtext + total_lines = [] + for j, (code_piece, images) in enumerate(results): + if self.options["include-source"]: + if is_doctest: + lines = [""] + lines += [row.rstrip() for row in code_piece.split("\n")] + else: + lines = [".. code-block:: python", ""] + lines += [" %s" % row.rstrip() for row in code_piece.split("\n")] + source_code = "\n".join(lines) + else: + source_code = "" + + if nofigs: + images = [] + + opts = [ + f":{key}: {val}" + for key, val in list(self.options.items()) + if key in ("alt", "height", "width", "scale", "align", "class") + ] + + only_html = ".. only:: html" + only_latex = ".. only:: latex" + only_texinfo = ".. only:: texinfo" + + # Not-None src_link signals the need for a source link in the generated + # html + if j == 0 and config.wf_html_show_source_link: + src_link = source_link + else: + src_link = None + + result = format_template( + config.wf_template or TEMPLATE, + default_fmt=default_fmt, + dest_dir=dest_dir_link, + build_dir=build_dir_link, + source_link=src_link, + multi_image=len(images) > 1, + only_html=only_html, + only_latex=only_latex, + only_texinfo=only_texinfo, + options=opts, + images=images, + source_code=source_code, + html_show_formats=config.wf_html_show_formats and len(images), + caption=caption, + ) + + total_lines.extend(result.split("\n")) + total_lines.extend("\n") + + if total_lines: + self.state_machine.insert_input(total_lines, source=source_file_name) + + # copy image files to builder's output directory, if necessary + os.makedirs(dest_dir, exist_ok=True) + for code_piece, images in results: + for img in images: + for fn in img.filenames(): + destimg = os.path.join(dest_dir, os.path.basename(fn)) + if fn != destimg: + shutil.copyfile(fn, destimg) + + # copy script (if necessary) + target_name = os.path.join(dest_dir, output_base + source_ext) + with open(target_name, "w", encoding="utf-8") as f: + if source_file_name == rst_file: + code_escaped = unescape_doctest(code) + else: + code_escaped = code + f.write(code_escaped) + + return errors + + +def setup(app): + setup.app = app + setup.config = app.config + setup.confdir = app.confdir + + app.add_directive("workflow", WorkflowDirective) app.add_config_value("graph2use", "hierarchical", "html") app.add_config_value("simple_form", True, "html") app.add_config_value("wf_pre_code", None, True) @@ -285,7 +483,7 @@ def contains_doctest(text): return False except SyntaxError: pass - r = re.compile(r"^\s*>>>", re.M) + r = re.compile(r"^\s*>>>", re.MULTILINE) m = r.search(text) return bool(m) @@ -385,14 +583,14 @@ def remove_coding(text): wf_context = dict() -class ImageFile(object): +class ImageFile: def __init__(self, basename, dirname): self.basename = basename self.dirname = dirname self.formats = [] def filename(self, fmt): - return os.path.join(self.dirname, "%s.%s" % (self.basename, fmt)) + return os.path.join(self.dirname, f"{self.basename}.{fmt}") def filenames(self): return [self.filename(fmt) for fmt in self.formats] @@ -474,7 +672,7 @@ def _dummy_print(*arg, **kwarg): exec(code, ns) if function_name is not None: exec(function_name + "()", ns) - except (Exception, SystemExit) as err: + except (Exception, SystemExit): raise GraphError(traceback.format_exc()) finally: os.chdir(pwd) @@ -548,213 +746,3 @@ def render_figures( img.formats.append(fmt) return [(code, [img])] - - -def run(arguments, content, options, state_machine, state, lineno): - document = state_machine.document - config = document.settings.env.config - nofigs = "nofigs" in options - - formats = get_wf_formats(config) - default_fmt = formats[0][0] - - graph2use = options.get("graph2use", "hierarchical") - simple_form = options.get("simple_form", True) - - options.setdefault("include-source", config.wf_include_source) - keep_context = "context" in options - context_opt = None if not keep_context else options["context"] - - rst_file = document.attributes["source"] - rst_dir = os.path.dirname(rst_file) - - if len(arguments): - if not config.wf_basedir: - source_file_name = os.path.join( - setup.app.builder.srcdir, directives.uri(arguments[0]) - ) - else: - source_file_name = os.path.join( - setup.confdir, config.wf_basedir, directives.uri(arguments[0]) - ) - - # If there is content, it will be passed as a caption. - caption = "\n".join(content) - - # If the optional function name is provided, use it - if len(arguments) == 2: - function_name = arguments[1] - else: - function_name = None - - with io.open(source_file_name, "r", encoding="utf-8") as fd: - code = fd.read() - output_base = os.path.basename(source_file_name) - else: - source_file_name = rst_file - code = textwrap.dedent("\n".join([str(c) for c in content])) - counter = document.attributes.get("_wf_counter", 0) + 1 - document.attributes["_wf_counter"] = counter - base, _ = os.path.splitext(os.path.basename(source_file_name)) - output_base = "%s-%d.py" % (base, counter) - function_name = None - caption = "" - - base, source_ext = os.path.splitext(output_base) - if source_ext in (".py", ".rst", ".txt"): - output_base = base - else: - source_ext = "" - - # ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames - output_base = output_base.replace(".", "-") - - # is it in doctest format? - is_doctest = contains_doctest(code) - if "format" in options: - if options["format"] == "python": - is_doctest = False - else: - is_doctest = True - - # determine output directory name fragment - source_rel_name = relpath(source_file_name, setup.confdir) - source_rel_dir = os.path.dirname(source_rel_name) - while source_rel_dir.startswith(os.path.sep): - source_rel_dir = source_rel_dir[1:] - - # build_dir: where to place output files (temporarily) - build_dir = os.path.join( - os.path.dirname(setup.app.doctreedir), "wf_directive", source_rel_dir - ) - # get rid of .. in paths, also changes pathsep - # see note in Python docs for warning about symbolic links on Windows. - # need to compare source and dest paths at end - build_dir = os.path.normpath(build_dir) - - if not os.path.exists(build_dir): - os.makedirs(build_dir) - - # output_dir: final location in the builder's directory - dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir, source_rel_dir)) - if not os.path.exists(dest_dir): - os.makedirs(dest_dir) # no problem here for me, but just use built-ins - - # how to link to files from the RST file - dest_dir_link = os.path.join( - relpath(setup.confdir, rst_dir), source_rel_dir - ).replace(os.path.sep, "/") - try: - build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, "/") - except ValueError: - # on Windows, relpath raises ValueError when path and start are on - # different mounts/drives - build_dir_link = build_dir - source_link = dest_dir_link + "/" + output_base + source_ext - - # make figures - try: - results = render_figures( - code, - source_file_name, - build_dir, - output_base, - keep_context, - function_name, - config, - graph2use, - simple_form, - context_reset=context_opt == "reset", - close_figs=context_opt == "close-figs", - ) - errors = [] - except GraphError as err: - reporter = state.memo.reporter - sm = reporter.system_message( - 2, - "Exception occurred in plotting %s\n from %s:\n%s" - % (output_base, source_file_name, err), - line=lineno, - ) - results = [(code, [])] - errors = [sm] - - # Properly indent the caption - caption = "\n".join(" " + line.strip() for line in caption.split("\n")) - - # generate output restructuredtext - total_lines = [] - for j, (code_piece, images) in enumerate(results): - if options["include-source"]: - if is_doctest: - lines = [""] - lines += [row.rstrip() for row in code_piece.split("\n")] - else: - lines = [".. code-block:: python", ""] - lines += [" %s" % row.rstrip() for row in code_piece.split("\n")] - source_code = "\n".join(lines) - else: - source_code = "" - - if nofigs: - images = [] - - opts = [ - ":%s: %s" % (key, val) - for key, val in list(options.items()) - if key in ("alt", "height", "width", "scale", "align", "class") - ] - - only_html = ".. only:: html" - only_latex = ".. only:: latex" - only_texinfo = ".. only:: texinfo" - - # Not-None src_link signals the need for a source link in the generated - # html - if j == 0 and config.wf_html_show_source_link: - src_link = source_link - else: - src_link = None - - result = format_template( - config.wf_template or TEMPLATE, - default_fmt=default_fmt, - dest_dir=dest_dir_link, - build_dir=build_dir_link, - source_link=src_link, - multi_image=len(images) > 1, - only_html=only_html, - only_latex=only_latex, - only_texinfo=only_texinfo, - options=opts, - images=images, - source_code=source_code, - html_show_formats=config.wf_html_show_formats and len(images), - caption=caption, - ) - - total_lines.extend(result.split("\n")) - total_lines.extend("\n") - - if total_lines: - state_machine.insert_input(total_lines, source=source_file_name) - - # copy image files to builder's output directory, if necessary - os.makedirs(dest_dir, exist_ok=True) - for code_piece, images in results: - for img in images: - for fn in img.filenames(): - destimg = os.path.join(dest_dir, os.path.basename(fn)) - if fn != destimg: - shutil.copyfile(fn, destimg) - - # copy script (if necessary) - target_name = os.path.join(dest_dir, output_base + source_ext) - with io.open(target_name, "w", encoding="utf-8") as f: - if source_file_name == rst_file: - code_escaped = unescape_doctest(code) - else: - code_escaped = code - f.write(code_escaped) - - return errors diff --git a/nipype/testing/__init__.py b/nipype/testing/__init__.py index c22de2cc7a..e3fbd80e6a 100644 --- a/nipype/testing/__init__.py +++ b/nipype/testing/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """The testing directory contains a small set of imaging files to be @@ -16,11 +15,8 @@ template = funcfile transfm = funcfile -from . import decorators from .utils import package_check, TempFATFS -skipif = decorators.dec.skipif - def example_data(infile="functional.nii"): """returns path to empty example data files for doc tests @@ -30,6 +26,6 @@ def example_data(infile="functional.nii"): basedir = os.path.dirname(filepath) outfile = os.path.join(basedir, "data", infile) if not os.path.exists(outfile): - raise IOError("%s empty data file does NOT exist" % outfile) + raise OSError("%s empty data file does NOT exist" % outfile) return outfile diff --git a/nipype/testing/data/5tt_in.mif b/nipype/testing/data/5tt_in.mif new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/README b/nipype/testing/data/README index 550854c57e..ed70b57e43 100644 --- a/nipype/testing/data/README +++ b/nipype/testing/data/README @@ -1,5 +1,5 @@ This directory contains empty, dummy files which are meant to be used -in the doctests of nipype. For verion 0.3 of nipype, we're using +in the doctests of nipype. For version 0.3 of nipype, we're using Traits and for input files, the code checks to confirm the assigned files actually exist. It doesn't matter what the files are, or even if they contain "real data", only that they exist. Again, these files diff --git a/nipype/testing/data/T2.nii b/nipype/testing/data/T2.nii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/csffod.mif b/nipype/testing/data/csffod.mif new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/design.mat b/nipype/testing/data/design.mat index e69de29bb2..5f27af3198 100644 --- a/nipype/testing/data/design.mat +++ b/nipype/testing/data/design.mat @@ -0,0 +1,6 @@ +/NumWaves 3 +/NumPoints 3 +/Matrix +0 0 0 +0 0 0 +0 0 0 diff --git a/nipype/testing/data/design.txt b/nipype/testing/data/design.txt new file mode 100644 index 0000000000..d5de7d6a40 --- /dev/null +++ b/nipype/testing/data/design.txt @@ -0,0 +1,3 @@ +0 0 0 +0 0 0 +0 0 0 diff --git a/nipype/testing/data/gmfod.mif b/nipype/testing/data/gmfod.mif new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/grad.b b/nipype/testing/data/grad.b new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/grads.txt b/nipype/testing/data/grads.txt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/gtmseg.mgz b/nipype/testing/data/gtmseg.mgz new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/gtmseg.nii b/nipype/testing/data/gtmseg.nii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/lh.aparc_a2009s.freesurfer.annot b/nipype/testing/data/lh.aparc_a2009s.freesurfer.annot new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/lh.area.structural b/nipype/testing/data/lh.area.structural new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/lh.central.structural.gii b/nipype/testing/data/lh.central.structural.gii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/lh.pbt.structural b/nipype/testing/data/lh.pbt.structural new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/lh.sphere.reg.structural.gii b/nipype/testing/data/lh.sphere.reg.structural.gii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/lh.sphere.structural.gii b/nipype/testing/data/lh.sphere.structural.gii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/ref_tac.dat b/nipype/testing/data/ref_tac.dat new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/rh.aparc_a2009s.freesurfer.annot b/nipype/testing/data/rh.aparc_a2009s.freesurfer.annot new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/rh.central.structural.gii b/nipype/testing/data/rh.central.structural.gii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/rh.pbt.structural b/nipype/testing/data/rh.pbt.structural new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/rh.sphere.reg.structural.gii b/nipype/testing/data/rh.sphere.reg.structural.gii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/rh.sphere.structural.gii b/nipype/testing/data/rh.sphere.structural.gii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/sh.mif b/nipype/testing/data/sh.mif new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/sub-01_ses-baseline_pet.nii.gz b/nipype/testing/data/sub-01_ses-baseline_pet.nii.gz new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/sub-01_ses-baseline_pet_mean_reg.lta b/nipype/testing/data/sub-01_ses-baseline_pet_mean_reg.lta new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/tac.nii b/nipype/testing/data/tac.nii new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/timing.dat b/nipype/testing/data/timing.dat new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/data/wmfod.mif b/nipype/testing/data/wmfod.mif new file mode 100644 index 0000000000..e69de29bb2 diff --git a/nipype/testing/decorators.py b/nipype/testing/decorators.py deleted file mode 100644 index 36c647634c..0000000000 --- a/nipype/testing/decorators.py +++ /dev/null @@ -1,98 +0,0 @@ -# -*- coding: utf-8 -*- -# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- -# vi: set ft=python sts=4 ts=4 sw=4 et: -""" -Extend numpy's decorators to use nipype's gui and data labels. -""" -from numpy.testing import dec - -from nibabel.data import DataError - - -def make_label_dec(label, ds=None): - """Factory function to create a decorator that applies one or more labels. - - Parameters - ---------- - label : str or sequence - One or more labels that will be applied by the decorator to the - functions it decorates. Labels are attributes of the decorated function - with their value set to True. - ds : str - An optional docstring for the resulting decorator. If not given, a - default docstring is auto-generated. - - Returns - ------- - ldec : function - A decorator. - - Examples - -------- - >>> slow = make_label_dec('slow') - >>> slow.__doc__ - "Labels a test as 'slow'" - - >>> rare = make_label_dec(['slow','hard'], - ... "Mix labels 'slow' and 'hard' for rare tests") - >>> @rare - ... def f(): pass - ... - >>> - >>> f.slow - True - >>> f.hard - True - """ - if isinstance(label, str): - labels = [label] - else: - labels = label - # Validate that the given label(s) are OK for use in setattr() by doing a - # dry run on a dummy function. - tmp = lambda: None - for label in labels: - setattr(tmp, label, True) - # This is the actual decorator we'll return - - def decor(f): - for label in labels: - setattr(f, label, True) - return f - - # Apply the user's docstring - if ds is None: - ds = "Labels a test as %r" % label - decor.__doc__ = ds - return decor - - -# For tests that need further review - - -def needs_review(msg): - """ Skip a test that needs further review. - - Parameters - ---------- - msg : string - msg regarding the review that needs to be done - """ - - def skip_func(func): - return dec.skipif(True, msg)(func) - - return skip_func - - -# Easier version of the numpy knownfailure -def knownfailure(f): - return dec.knownfailureif(True)(f) - - -def if_datasource(ds, msg): - try: - ds.get_filename() - except DataError: - return dec.skipif(True, msg) - return lambda f: f diff --git a/nipype/testing/fixtures.py b/nipype/testing/fixtures.py index 6f5b12495c..b28741b9d8 100644 --- a/nipype/testing/fixtures.py +++ b/nipype/testing/fixtures.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/testing/tests/test_utils.py b/nipype/testing/tests/test_utils.py index fb2992b7e6..c3b1cae638 100644 --- a/nipype/testing/tests/test_utils.py +++ b/nipype/testing/tests/test_utils.py @@ -1,24 +1,21 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Test testing utilities -""" +"""Test testing utilities""" import os -import warnings import subprocess -from mock import patch, MagicMock +from unittest.mock import patch, MagicMock +from unittest import SkipTest from nipype.testing.utils import TempFATFS def test_tempfatfs(): try: fatfs = TempFATFS() - except (IOError, OSError): - warnings.warn("Cannot mount FAT filesystems with FUSE") - else: - with fatfs as tmp_dir: - assert os.path.exists(tmp_dir) + except OSError: + raise SkipTest("Cannot mount FAT filesystems with FUSE") + with fatfs as tmp_dir: + assert os.path.exists(tmp_dir) @patch( @@ -28,7 +25,7 @@ def test_tempfatfs(): def test_tempfatfs_calledprocesserror(): try: TempFATFS() - except IOError as e: + except OSError as e: assert isinstance(e, IOError) assert isinstance(e.__cause__, subprocess.CalledProcessError) else: @@ -40,7 +37,7 @@ def test_tempfatfs_calledprocesserror(): def test_tempfatfs_oserror(): try: TempFATFS() - except IOError as e: + except OSError as e: assert isinstance(e, IOError) assert isinstance(e.__cause__, OSError) else: diff --git a/nipype/testing/utils.py b/nipype/testing/utils.py index e666a7586f..96a94d6564 100644 --- a/nipype/testing/utils.py +++ b/nipype/testing/utils.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Additional handy utilities for testing -""" +"""Additional handy utilities for testing""" import os import time import shutil @@ -18,7 +16,7 @@ import nibabel as nb -class TempFATFS(object): +class TempFATFS: def __init__(self, size_in_mbytes=8, delay=0.5): """Temporary filesystem for testing non-POSIX filesystems on a POSIX system. @@ -55,19 +53,19 @@ def __init__(self, size_in_mbytes=8, delay=0.5): args=mkfs_args, stdout=self.dev_null, stderr=self.dev_null ) except CalledProcessError as e: - raise IOError("mkfs.vfat failed") from e + raise OSError("mkfs.vfat failed") from e try: self.fusefat = subprocess.Popen( args=mount_args, stdout=self.dev_null, stderr=self.dev_null ) except OSError as e: - raise IOError("fusefat is not installed") from e + raise OSError("fusefat is not installed") from e time.sleep(self.delay) if self.fusefat.poll() is not None: - raise IOError("fusefat terminated too soon") + raise OSError("fusefat terminated too soon") open(self.canary, "wb").close() diff --git a/nipype/tests/test_nipype.py b/nipype/tests/test_nipype.py index 60fa92d141..3f103b5529 100644 --- a/nipype/tests/test_nipype.py +++ b/nipype/tests/test_nipype.py @@ -1,3 +1,4 @@ +import os from .. import get_info from ..info import get_nipype_gitversion import pytest @@ -40,69 +41,57 @@ def _check_no_et(): return et -def test_no_et(tmp_path): +def test_no_et_bare(tmp_path): from unittest.mock import patch from nipype.pipeline import engine as pe from nipype.interfaces import utility as niu from nipype.interfaces.base import BaseInterface + et = os.getenv("NIPYPE_NO_ET") is None + # Pytest doesn't trigger this, so let's pretend it's there with patch.object(BaseInterface, "_etelemetry_version_data", {}): - # Direct function call - environment not set f = niu.Function(function=_check_no_et) res = f.run() - assert res.outputs.out is True + assert res.outputs.out == et # Basic node - environment not set n = pe.Node( niu.Function(function=_check_no_et), name="n", base_dir=str(tmp_path) ) res = n.run() - assert res.outputs.out is True + assert res.outputs.out == et # Linear run - environment not set wf1 = pe.Workflow(name="wf1", base_dir=str(tmp_path)) wf1.add_nodes([pe.Node(niu.Function(function=_check_no_et), name="n")]) res = wf1.run() - assert next(iter(res.nodes)).result.outputs.out is True - - # MultiProc run - environment initialized with NIPYPE_NO_ET - wf2 = pe.Workflow(name="wf2", base_dir=str(tmp_path)) - wf2.add_nodes([pe.Node(niu.Function(function=_check_no_et), name="n")]) - res = wf2.run(plugin="MultiProc", plugin_args={"n_procs": 1}) - assert next(iter(res.nodes)).result.outputs.out is False - - # LegacyMultiProc run - environment initialized with NIPYPE_NO_ET - wf3 = pe.Workflow(name="wf3", base_dir=str(tmp_path)) - wf3.add_nodes([pe.Node(niu.Function(function=_check_no_et), name="n")]) - res = wf3.run(plugin="LegacyMultiProc", plugin_args={"n_procs": 1}) - assert next(iter(res.nodes)).result.outputs.out is False - - # run_without_submitting - environment not set - wf4 = pe.Workflow(name="wf4", base_dir=str(tmp_path)) - wf4.add_nodes( - [ - pe.Node( - niu.Function(function=_check_no_et), - run_without_submitting=True, - name="n", - ) - ] - ) - res = wf4.run(plugin="MultiProc", plugin_args={"n_procs": 1}) - assert next(iter(res.nodes)).result.outputs.out is True - - # LegacyMultiProc run - environment initialized with NIPYPE_NO_ET - wf5 = pe.Workflow(name="wf5", base_dir=str(tmp_path)) - wf5.add_nodes( - [ - pe.Node( - niu.Function(function=_check_no_et), - run_without_submitting=True, - name="n", - ) - ] + assert next(iter(res.nodes)).result.outputs.out == et + + +@pytest.mark.parametrize("plugin", ("MultiProc", "LegacyMultiProc")) +@pytest.mark.parametrize("run_without_submitting", (True, False)) +def test_no_et_multiproc(tmp_path, plugin, run_without_submitting): + from unittest.mock import patch + from nipype.pipeline import engine as pe + from nipype.interfaces import utility as niu + from nipype.interfaces.base import BaseInterface + + et = os.getenv("NIPYPE_NO_ET") is None + + # Multiprocessing runs initialize new processes with NIPYPE_NO_ET + # This does not apply to unsubmitted jobs, run by the main thread + expectation = et if run_without_submitting else False + + # Pytest doesn't trigger this, so let's pretend it's there + with patch.object(BaseInterface, "_etelemetry_version_data", {}): + wf = pe.Workflow(name="wf2", base_dir=str(tmp_path)) + n = pe.Node( + niu.Function(function=_check_no_et), + run_without_submitting=run_without_submitting, + name="n", ) - res = wf5.run(plugin="LegacyMultiProc", plugin_args={"n_procs": 1}) - assert next(iter(res.nodes)).result.outputs.out is True + wf.add_nodes([n]) + res = wf.run(plugin=plugin, plugin_args={"n_procs": 1}) + assert next(iter(res.nodes)).result.outputs.out is expectation diff --git a/nipype/utils/__init__.py b/nipype/utils/__init__.py index 6508602eb8..56d7dfb2c7 100644 --- a/nipype/utils/__init__.py +++ b/nipype/utils/__init__.py @@ -1,5 +1,2 @@ -# -*- coding: utf-8 -*- - -from .config import NUMPY_MMAP from .onetime import OneTimeProperty, setattr_on_read from .tmpdirs import TemporaryDirectory, InTemporaryDirectory diff --git a/nipype/utils/config.py b/nipype/utils/config.py index 6f1b385672..8317270d83 100644 --- a/nipype/utils/config.py +++ b/nipype/utils/config.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -14,9 +13,8 @@ import errno import atexit from warnings import warn -from distutils.version import LooseVersion +from looseversion import LooseVersion import configparser -import numpy as np from simplejson import load, dump @@ -28,7 +26,6 @@ "filemanip_level": ("logging.utils_level", "1.0"), } -NUMPY_MMAP = LooseVersion(np.__version__) >= LooseVersion("1.12.0") DEFAULT_CONFIG_TPL = """\ [logging] @@ -84,7 +81,7 @@ def mkdir_p(path): raise -class NipypeConfig(object): +class NipypeConfig: """Base nipype config class""" def __init__(self, *args, **kwargs): @@ -208,25 +205,25 @@ def get_data(self, key): if not os.path.exists(self.data_file): return None with SoftFileLock("%s.lock" % self.data_file): - with open(self.data_file, "rt") as file: + with open(self.data_file) as file: datadict = load(file) if key in datadict: return datadict[key] return None def save_data(self, key, value): - """Store config flie""" + """Store config file""" datadict = {} if os.path.exists(self.data_file): with SoftFileLock("%s.lock" % self.data_file): - with open(self.data_file, "rt") as file: + with open(self.data_file) as file: datadict = load(file) else: dirname = os.path.dirname(self.data_file) if not os.path.exists(dirname): mkdir_p(dirname) with SoftFileLock("%s.lock" % self.data_file): - with open(self.data_file, "wt") as file: + with open(self.data_file, "w") as file: datadict[key] = value dump(datadict, file) @@ -355,7 +352,7 @@ def _mock(): # Older versions of xvfbwrapper used vdisplay_num if not hasattr(self._display, "new_display"): - setattr(self._display, "new_display", self._display.vdisplay_num) + self._display.new_display = self._display.vdisplay_num return self.get_display() def stop_display(self): diff --git a/nipype/utils/datetime.py b/nipype/utils/datetime.py new file mode 100644 index 0000000000..4a9779f20f --- /dev/null +++ b/nipype/utils/datetime.py @@ -0,0 +1,19 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +""" +Utilities for dates and time +""" + +from datetime import datetime as dt +import sys + +if sys.version_info >= (3, 11): + from datetime import UTC + + def utcnow(): + """Adapter since 3.12 prior utcnow is deprecated, + but not EOLed 3.8 does not have datetime.UTC""" + return dt.now(UTC) + +else: + utcnow = dt.utcnow diff --git a/nipype/utils/docparse.py b/nipype/utils/docparse.py index 576a235892..7731329265 100644 --- a/nipype/utils/docparse.py +++ b/nipype/utils/docparse.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Utilities to pull in documentation from command-line tools. @@ -40,8 +39,8 @@ def grab_doc(cmd, trap_error=True): stdout, stderr = proc.communicate() if trap_error and proc.returncode: - msg = "Attempting to run %s. Returned Error: %s" % (cmd, stderr) - raise IOError(msg) + msg = f"Attempting to run {cmd}. Returned Error: {stderr}" + raise OSError(msg) if stderr: # A few programs, like fast and fnirt, send their help to @@ -119,7 +118,7 @@ def format_params(paramlist, otherlist=None): otherlist.insert(0, hdr) otherlist.insert(0, "\n") otherparams = "\n".join(otherlist) - doc = "".join([doc, otherparams]) + doc = f"{doc}{otherparams}" return doc @@ -132,7 +131,7 @@ def insert_doc(doc, new_items): Parameters ---------- doc : str - The existing docstring we're inserting docmentation into. + The existing docstring we're inserting documentation into. new_items : list List of strings to be inserted in the ``doc``. @@ -167,13 +166,7 @@ def insert_doc(doc, new_items): # Add rest of documents tmpdoc.extend(doclist[2:]) # Insert newlines - newdoc = [] - for line in tmpdoc: - newdoc.append(line) - newdoc.append("\n") - # We add one too many newlines, remove it. - newdoc.pop(-1) - return "".join(newdoc) + return "\n".join(tmpdoc) def build_doc(doc, opts): @@ -191,7 +184,7 @@ def build_doc(doc, opts): ------- newdoc : string The docstring with flags replaced with attribute names and - formated to match nipy standards (as best we can). + formatted to match nipy standards (as best we can). """ @@ -206,7 +199,7 @@ def build_doc(doc, opts): # Probably an empty line continue # For lines we care about, the first item is the flag - if "," in linelist[0]: # sometimes flags are only seperated by comma + if "," in linelist[0]: # sometimes flags are only separated by comma flag = linelist[0].split(",")[0] else: flag = linelist[0] @@ -223,7 +216,7 @@ def build_doc(doc, opts): # For all the docs I've looked at, the flags all have # indentation (spaces) at the start of the line. # Other parts of the docs, like 'usage' statements - # start with alpha-numeric characters. We only care + # start with alphanumeric characters. We only care # about the flags. flags_doc.append(line) return format_params(newdoc, flags_doc) @@ -246,7 +239,7 @@ def get_doc(cmd, opt_map, help_flag=None, trap_error=True): Returns ------- doc : string - The formated docstring + The formatted docstring """ res = CommandLine( @@ -258,7 +251,7 @@ def get_doc(cmd, opt_map, help_flag=None, trap_error=True): if cmd_path == "": raise Exception("Command %s not found" % cmd.split(" ")[0]) if help_flag: - cmd = " ".join((cmd, help_flag)) + cmd = f"{cmd} {help_flag}" doc = grab_doc(cmd, trap_error) opts = reverse_opt_map(opt_map) return build_doc(doc, opts) @@ -290,7 +283,7 @@ def _parse_doc(doc, style=["--"]): flag = [ item for i, item in enumerate(linelist) - if i < 2 and any([item.startswith(s) for s in style]) and len(item) > 1 + if i < 2 and item.startswith(tuple(style)) and len(item) > 1 ] if flag: if len(flag) == 1: @@ -339,7 +332,7 @@ def get_params_from_doc(cmd, style="--", help_flag=None, trap_error=True): if cmd_path == "": raise Exception("Command %s not found" % cmd.split(" ")[0]) if help_flag: - cmd = " ".join((cmd, help_flag)) + cmd = f"{cmd} {help_flag}" doc = grab_doc(cmd, trap_error) return _parse_doc(doc, style) diff --git a/nipype/utils/draw_gantt_chart.py b/nipype/utils/draw_gantt_chart.py index 0da078af84..64a0d793db 100644 --- a/nipype/utils/draw_gantt_chart.py +++ b/nipype/utils/draw_gantt_chart.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ @@ -6,12 +5,13 @@ ``nipype.utils.profiler.log_nodes_cb()`` """ # Import packages -import sys import random import datetime import simplejson as json +from typing import Union from collections import OrderedDict +from warnings import warn # Pandas try: @@ -21,7 +21,6 @@ "Pandas not found; in order for full functionality of this module " "install the pandas package" ) - pass def create_event_dict(start_time, nodes_list): @@ -69,9 +68,9 @@ def create_event_dict(start_time, nodes_list): finish_delta = (node["finish"] - start_time).total_seconds() # Populate dictionary - if events.get(start_delta) or events.get(finish_delta): + if events.get(start_delta): err_msg = "Event logged twice or events started at exact same time!" - raise KeyError(err_msg) + warn(err_msg, category=Warning) events[start_delta] = start_node events[finish_delta] = finish_node @@ -98,14 +97,42 @@ def log_to_dict(logfile): """ # Init variables - with open(logfile, "r") as content: + with open(logfile) as content: # read file separating each line lines = content.readlines() nodes_list = [json.loads(l) for l in lines] + def _convert_string_to_datetime( + datestring: Union[str, datetime.datetime], + ) -> datetime.datetime: + """Convert a date string to a datetime object.""" + if isinstance(datestring, datetime.datetime): + datetime_object = datestring + elif isinstance(datestring, str): + date_format = ( + "%Y-%m-%dT%H:%M:%S.%f%z" + if "+" in datestring + else "%Y-%m-%dT%H:%M:%S.%f" + ) + datetime_object: datetime.datetime = datetime.datetime.strptime( + datestring, date_format + ) + else: + msg = f"{datestring} is not a string or datetime object." + raise TypeError(msg) + return datetime_object + + date_object_node_list: list = list() + for n in nodes_list: + if "start" in n: + n["start"] = _convert_string_to_datetime(n["start"]) + if "finish" in n: + n["finish"] = _convert_string_to_datetime(n["finish"]) + date_object_node_list.append(n) + # Return list of nodes - return nodes_list + return date_object_node_list def calculate_resource_timeseries(events, resource): @@ -139,12 +166,18 @@ def calculate_resource_timeseries(events, resource): # Iterate through the events for _, event in sorted(events.items()): if event["event"] == "start": - if resource in event and event[resource] != "Unknown": - all_res += float(event[resource]) + if resource in event: + try: + all_res += float(event[resource]) + except ValueError: + continue current_time = event["start"] elif event["event"] == "finish": - if resource in event and event[resource] != "Unknown": - all_res -= float(event[resource]) + if resource in event: + try: + all_res -= float(event[resource]) + except ValueError: + continue current_time = event["finish"] res[current_time] = all_res @@ -269,7 +302,14 @@ def draw_nodes(start, nodes_list, cores, minute_scale, space_between_minutes, co # Left left = 60 for core in range(len(end_times)): - if end_times[core] < node_start: + try: + end_time_condition = end_times[core] < node_start + except TypeError: + # if one has a timezone and one does not + end_time_condition = end_times[core].replace( + tzinfo=None + ) < node_start.replace(tzinfo=None) + if end_time_condition: left += core * 30 end_times[core] = datetime.datetime( node_finish.year, @@ -292,7 +332,7 @@ def draw_nodes(start, nodes_list, cores, minute_scale, space_between_minutes, co "offset": offset, "scale_duration": scale_duration, "color": color, - "node_name": node["name"], + "node_name": node.get("name", node.get("id", "")), "node_dur": node["duration"] / 60.0, "node_start": node_start.strftime("%Y-%m-%d %H:%M:%S"), "node_finish": node_finish.strftime("%Y-%m-%d %H:%M:%S"), @@ -322,8 +362,7 @@ def draw_resource_bar( left, resource, ): - """ - """ + """ """ # Memory header result = "

%s

" % (left, resource) @@ -513,10 +552,33 @@ def generate_gantt_chart( # Read in json-log to get list of node dicts nodes_list = log_to_dict(logfile) + # Only include nodes with timing information, and convert timestamps + # from strings to datetimes + nodes_list = [ + { + k: ( + datetime.datetime.strptime(i[k], "%Y-%m-%dT%H:%M:%S.%f") + if k in {"start", "finish"} and isinstance(i[k], str) + else i[k] + ) + for k in i + } + for i in nodes_list + if "start" in i and "finish" in i + ] + + for node in nodes_list: + if "duration" not in node: + node["duration"] = (node["finish"] - node["start"]).total_seconds() + # Create the header of the report with useful information start_node = nodes_list[0] last_node = nodes_list[-1] - duration = (last_node["finish"] - start_node["start"]).total_seconds() + duration: float = 0.0 + if isinstance(start_node["start"], datetime.date) and isinstance( + last_node["finish"], datetime.date + ): + duration = (last_node["finish"] - start_node["start"]).total_seconds() # Get events based dictionary of node run stats events = create_event_dict(start_node["start"], nodes_list) @@ -528,7 +590,7 @@ def generate_gantt_chart( html_string += ( "

Finish: " + last_node["finish"].strftime("%Y-%m-%d %H:%M:%S") + "

" ) - html_string += "

Duration: " + "{0:.2f}".format(duration / 60) + " minutes

" + html_string += "

Duration: " + f"{duration / 60:.2f}" + " minutes

" html_string += "

Nodes: " + str(len(nodes_list)) + "

" html_string += "

Cores: " + str(cores) + "

" html_string += close_header diff --git a/nipype/utils/filemanip.py b/nipype/utils/filemanip.py index 735cc610b6..4916cbacef 100644 --- a/nipype/utils/filemanip.py +++ b/nipype/utils/filemanip.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Miscellaneous file manipulation functions -""" +"""Miscellaneous file manipulation functions""" import sys import pickle import errno @@ -20,43 +18,18 @@ from pathlib import Path import simplejson as json from time import sleep, time +import scipy.io as sio from .. import logging, config, __version__ as version from .misc import is_container fmlogger = logging.getLogger("nipype.utils") -related_filetype_sets = [ - (".hdr", ".img", ".mat"), - (".nii", ".mat"), - (".BRIK", ".HEAD"), -] +related_filetype_sets = [(".hdr", ".img", ".mat"), (".nii", ".mat"), (".BRIK", ".HEAD")] -def _resolve_with_filenotfound(path, **kwargs): - """ Raise FileNotFoundError instead of OSError """ - try: - return path.resolve(**kwargs) - except OSError as e: - if isinstance(e, FileNotFoundError): - raise - raise FileNotFoundError(str(path)) - - -def path_resolve(path, strict=False): - try: - return _resolve_with_filenotfound(path, strict=strict) - except TypeError: # PY35 - pass - - path = path.absolute() - if strict or path.exists(): - return _resolve_with_filenotfound(path) - - # This is a hacky shortcut, using path.absolute() unmodified - # In cases where the existing part of the path contains a - # symlink, different results will be produced - return path +# Previously a patch, not worth deprecating +path_resolve = Path.resolve def split_filename(fname): @@ -74,7 +47,7 @@ def split_filename(fname): fname : str filename from fname, without extension ext : str - file extension from fname + file extension from fname706 Examples -------- @@ -152,12 +125,10 @@ def fname_presuffix(fname, prefix="", suffix="", newpath=None, use_ext=True): def fnames_presuffix(fnames, prefix="", suffix="", newpath=None, use_ext=True): - """Calls fname_presuffix for a list of files. - """ - f2 = [] - for fname in fnames: - f2.append(fname_presuffix(fname, prefix, suffix, newpath, use_ext)) - return f2 + """Calls fname_presuffix for a list of files.""" + return [ + fname_presuffix(fname, prefix, suffix, newpath, use_ext) for fname in fnames + ] def hash_rename(filename, hashvalue): @@ -165,7 +136,7 @@ def hash_rename(filename, hashvalue): and sets path to output_directory """ path, name, ext = split_filename(filename) - newfilename = "".join((name, "_0x", hashvalue, ext)) + newfilename = f"{name}_0x{hashvalue}{ext}" return op.join(path, newfilename) @@ -215,7 +186,7 @@ def hash_infile(afile, chunk_len=8192, crypto=hashlib.md5, raise_notfound=False) def hash_timestamp(afile): - """ Computes md5 hash of the timestamp of a file """ + """Computes md5 hash of the timestamp of a file""" md5hex = None if op.isfile(afile): md5obj = md5() @@ -439,7 +410,7 @@ def copyfile( fmlogger.debug("Copying File: %s->%s", newfile, originalfile) shutil.copyfile(originalfile, newfile) except shutil.Error as e: - fmlogger.warning(e.message) + fmlogger.warning(str(e)) # Associated files if copy_related_files: @@ -473,14 +444,15 @@ def get_related_files(filename, include_this_file=True): include_this_file : bool If true, output includes the input filename. """ - related_files = [] path, name, this_type = split_filename(filename) - for type_set in related_filetype_sets: - if this_type in type_set: - for related_type in type_set: - if include_this_file or related_type != this_type: - related_files.append(op.join(path, name + related_type)) - if not len(related_files): + related_files = [ + op.join(path, f"{name}{related_type}") + for type_set in related_filetype_sets + if this_type in type_set + for related_type in type_set + if include_this_file or related_type != this_type + ] + if not related_files: related_files = [filename] return related_files @@ -521,21 +493,20 @@ def copyfiles(filelist, dest, copy=False, create_new=False): def ensure_list(filename): - """Returns a list given either a string or a list - """ + """Returns a list given either a string or a list""" if isinstance(filename, (str, bytes)): return [filename] elif isinstance(filename, list): return filename elif is_container(filename): - return [x for x in filename] + return list(filename) else: return None def simplify_list(filelist): """Returns a list if filelist is a list of length greater than 1, - otherwise returns the first element + otherwise returns the first element """ if len(filelist) > 1: return filelist @@ -589,13 +560,13 @@ def load_json(filename): """ - with open(filename, "r") as fp: + with open(filename) as fp: data = json.load(fp) return data def loadcrash(infile, *args): - if infile.endswith("pkl") or infile.endswith("pklz"): + if infile.endswith(("pkl", "pklz")): return loadpkl(infile) else: raise ValueError("Only pickled crashfiles are supported") @@ -614,15 +585,15 @@ def loadpkl(infile): if infile.exists(): timed_out = False break - fmlogger.debug("'{}' missing; waiting 2s".format(infile)) + fmlogger.debug(f"'{infile}' missing; waiting 2s") sleep(2) if timed_out: error_message = ( - "Result file {0} expected, but " - "does not exist after ({1}) " + "Result file {} expected, but " + "does not exist after ({}) " "seconds.".format(infile, timeout) ) - raise IOError(error_message) + raise OSError(error_message) with pklopen(str(infile), "rb") as pkl_file: pkl_contents = pkl_file.read() @@ -678,14 +649,14 @@ def loadpkl(infile): def crash2txt(filename, record): - """ Write out plain text crash file """ + """Write out plain text crash file""" with open(filename, "w") as fp: if "node" in record: node = record["node"] - fp.write("Node: {}\n".format(node.fullname)) - fp.write("Working directory: {}\n".format(node.output_dir())) + fp.write(f"Node: {node.fullname}\n") + fp.write(f"Working directory: {node.output_dir()}\n") fp.write("\n") - fp.write("Node inputs:\n{}\n".format(node.inputs)) + fp.write(f"Node inputs:\n{node.inputs}\n") fp.write("".join(record["traceback"])) @@ -699,7 +670,7 @@ def read_stream(stream, logger=None, encoding=None): """ - default_encoding = encoding or locale.getdefaultlocale()[1] or "UTF-8" + default_encoding = encoding or locale.getpreferredencoding(do_setlocale=False) logger = logger or fmlogger try: out = stream.decode(default_encoding) @@ -716,7 +687,7 @@ def savepkl(filename, record, versioning=False): if versioning: metadata = json.dumps({"version": version}) f.write(metadata.encode("utf-8")) - f.write("\n".encode("utf-8")) + f.write(b"\n") pickle.dump(record, f) content = f.getvalue() @@ -724,7 +695,16 @@ def savepkl(filename, record, versioning=False): tmpfile = filename + ".tmp" with pkl_open(tmpfile, "wb") as pkl_file: pkl_file.write(content) - os.rename(tmpfile, filename) + for _ in range(5): + try: + os.rename(tmpfile, filename) + break + except FileNotFoundError as e: + last_e = e + fmlogger.debug(str(e)) + sleep(2) + else: + raise last_e rst_levels = ["=", "-", "~", "+"] @@ -735,17 +715,11 @@ def write_rst_header(header, level=0): def write_rst_list(items, prefix=""): - out = [] - for item in items: - out.append("{} {}".format(prefix, str(item))) - return "\n".join(out) + "\n\n" + return "\n".join(f"{prefix} {item}" for item in ensure_list(items)) + "\n\n" def write_rst_dict(info, prefix=""): - out = [] - for key, value in sorted(info.items()): - out.append("{}* {} : {}".format(prefix, key, str(value))) - return "\n".join(out) + "\n\n" + return "\n".join(f"{prefix}* {k} : {v}" for k, v in sorted(info.items())) + "\n\n" def dist_is_editable(dist): @@ -786,8 +760,13 @@ def emptydirs(path, noexist_ok=False): try: shutil.rmtree(path) except OSError as ex: - elcont = os.listdir(path) - if ex.errno == errno.ENOTEMPTY and not elcont: + elcont = [ + Path(root) / file + for root, _, files in os.walk(path) + for file in files + if not file.startswith(".nfs") + ] + if ex.errno in [errno.ENOTEMPTY, errno.EBUSY] and not elcont: fmlogger.warning( "An exception was raised trying to remove old %s, but the path" " seems empty. Is it an NFS mount?. Passing the exception.", @@ -799,7 +778,7 @@ def emptydirs(path, noexist_ok=False): else: raise ex - os.makedirs(path) + os.makedirs(path, exist_ok=True) def silentrm(filename): @@ -870,15 +849,13 @@ def get_dependencies(name, environ): o, e = proc.communicate() deps = o.rstrip() except Exception as ex: - deps = '"%s" failed' % command - fmlogger.warning( - "Could not get dependencies of %s. Error:\n%s", name, ex.message - ) + deps = f"{command!r} failed" + fmlogger.warning(f"Could not get dependencies of {name}s. Error:\n{ex}") return deps def canonicalize_env(env): - """Windows requires that environment be dicts with bytes as keys and values + """Windows requires that environment be dicts with str as keys and values This function converts any unicode entries for Windows only, returning the dictionary untouched in other environments. @@ -890,7 +867,7 @@ def canonicalize_env(env): Returns ------- env : dict - Windows: environment dictionary with bytes keys and values + Windows: environment dictionary with str keys and values Other: untouched input ``env`` """ if os.name != "nt": @@ -898,10 +875,10 @@ def canonicalize_env(env): out_env = {} for key, val in env.items(): - if not isinstance(key, bytes): - key = key.encode("utf-8") - if not isinstance(val, bytes): - val = val.encode("utf-8") + if not isinstance(key, str): + key = key.decode("utf-8") + if not isinstance(val, str): + val = val.decode("utf-8") out_env[key] = val return out_env @@ -924,12 +901,10 @@ def relpath(path, start=None): unc_path, rest = op.splitunc(path) unc_start, rest = op.splitunc(start) if bool(unc_path) ^ bool(unc_start): - raise ValueError( - ("Cannot mix UNC and non-UNC paths " "(%s and %s)") % (path, start) - ) + raise ValueError(f"Cannot mix UNC and non-UNC paths ({path} and {start})") else: raise ValueError( - "path is on drive %s, start on drive %s" % (path_list[0], start_list[0]) + f"path is on drive {path_list[0]}, start on drive {start_list[0]}" ) # Work out how much of the filepath is shared by start and path. for i in range(min(len(start_list), len(path_list))): @@ -952,3 +927,59 @@ def indirectory(path): yield finally: os.chdir(cwd) + + +def load_spm_mat(spm_mat_file, **kwargs): + try: + mat = sio.loadmat(spm_mat_file, **kwargs) + except NotImplementedError: + import h5py + import numpy as np + + mat = dict(SPM=np.array([[sio.matlab.mat_struct()]])) + + # Get Vbeta, Vcon, and Vspm file names + with h5py.File(spm_mat_file, "r") as h5file: + fnames = dict() + try: + fnames["Vbeta"] = [ + u"".join(chr(c[0]) for c in h5file[obj_ref[0]]) + for obj_ref in h5file["SPM"]["Vbeta"]["fname"] + ] + except Exception: + fnames["Vbeta"] = [] + for contr_type in ["Vcon", "Vspm"]: + try: + fnames[contr_type] = [ + u"".join(chr(c[0]) for c in h5file[obj_ref[0]]["fname"]) + for obj_ref in h5file["SPM"]["xCon"][contr_type] + ] + except Exception: + fnames[contr_type] = [] + + # Structure Vbeta as returned by scipy.io.loadmat + obj_list = [] + for i in range(len(fnames["Vbeta"])): + obj = sio.matlab.mat_struct() + setattr(obj, "fname", np.array([fnames["Vbeta"][i]])) + obj_list.append(obj) + if len(obj_list) > 0: + setattr(mat["SPM"][0, 0], "Vbeta", np.array([obj_list])) + else: + setattr(mat["SPM"][0, 0], "Vbeta", np.empty((0, 0), dtype=object)) + + # Structure Vcon and Vspm as returned by scipy.io.loadmat + obj_list = [] + for i in range(len(fnames["Vcon"])): + obj = sio.matlab.mat_struct() + for contr_type in ["Vcon", "Vspm"]: + temp = sio.matlab.mat_struct() + setattr(temp, "fname", np.array([fnames[contr_type][i]])) + setattr(obj, contr_type, np.array([[temp]])) + obj_list.append(obj) + if len(obj_list) > 0: + setattr(mat["SPM"][0, 0], "xCon", np.array([obj_list])) + else: + setattr(mat["SPM"][0, 0], "xCon", np.empty((0, 0), dtype=object)) + + return mat diff --git a/nipype/utils/functions.py b/nipype/utils/functions.py index c53a221d48..262f48665e 100644 --- a/nipype/utils/functions.py +++ b/nipype/utils/functions.py @@ -1,8 +1,8 @@ -# -*- coding: utf-8 -*- """ Handles custom functions used in Function interface. Future imports are avoided to keep namespace as clear as possible. """ + import inspect from textwrap import dedent @@ -34,7 +34,7 @@ def create_function_from_source(function_source, imports=None): exec(function_source, ns) except Exception as e: - msg = "Error executing function\n{}\n".format(function_source) + msg = f"Error executing function\n{function_source}\n" msg += ( "Functions in connection strings have to be standalone. " "They cannot be declared either interactively or inside " diff --git a/nipype/utils/gpu_count.py b/nipype/utils/gpu_count.py new file mode 100644 index 0000000000..70eb6d724e --- /dev/null +++ b/nipype/utils/gpu_count.py @@ -0,0 +1,46 @@ +# -*- DISCLAIMER: this file contains code derived from gputil (https://github.com/anderskm/gputil) +# and therefore is distributed under to the following license: +# +# MIT License +# +# Copyright (c) 2017 anderskm +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +import platform +import shutil +import subprocess +import os + + +def gpu_count(): + nvidia_smi = shutil.which('nvidia-smi') + if nvidia_smi is None and platform.system() == "Windows": + nvidia_smi = f'{os.environ["systemdrive"]}\\Program Files\\NVIDIA Corporation\\NVSMI\\nvidia-smi.exe' + if nvidia_smi is None: + return 0 + try: + p = subprocess.run( + [nvidia_smi, "--query-gpu=name", "--format=csv,noheader,nounits"], + stdout=subprocess.PIPE, + text=True, + ) + except (OSError, UnicodeDecodeError): + return 0 + return len(p.stdout.splitlines()) diff --git a/nipype/utils/imagemanip.py b/nipype/utils/imagemanip.py new file mode 100644 index 0000000000..15680dc6e4 --- /dev/null +++ b/nipype/utils/imagemanip.py @@ -0,0 +1,19 @@ +"""Image manipulation utilities (mostly, NiBabel manipulations).""" + +import nibabel as nb + + +def copy_header(header_file, in_file, keep_dtype=True): + """Copy header from a reference image onto another image.""" + hdr_img = nb.load(header_file) + out_img = nb.load(in_file, mmap=False) + hdr = hdr_img.header.copy() + if keep_dtype: + hdr.set_data_dtype(out_img.get_data_dtype()) + + new_img = out_img.__class__(out_img.dataobj, None, hdr) + if not keep_dtype: + new_img.set_data_dtype(hdr_img.get_data_dtype()) + + new_img.to_filename(in_file) + return in_file diff --git a/nipype/utils/logger.py b/nipype/utils/logger.py index 3638843722..209da82d93 100644 --- a/nipype/utils/logger.py +++ b/nipype/utils/logger.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: @@ -16,11 +15,10 @@ from logging.handlers import RotatingFileHandler as RFHandler -class Logging(object): - """Nipype logging class - """ +class Logging: + """Nipype logging class""" - fmt = "%(asctime)s,%(msecs)d %(name)-2s " "%(levelname)-2s:\n\t %(message)s" + fmt = "%(asctime)s,%(msecs)d %(name)-2s %(levelname)-2s:\n\t %(message)s" datefmt = "%y%m%d-%H:%M:%S" def __init__(self, config): diff --git a/nipype/utils/matlabtools.py b/nipype/utils/matlabtools.py index 4a25b6f180..d871885c06 100644 --- a/nipype/utils/matlabtools.py +++ b/nipype/utils/matlabtools.py @@ -1,7 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -""" Useful Functions for working with matlab""" +"""Useful Functions for working with matlab""" # Stdlib imports import os @@ -13,7 +12,7 @@ def fltcols(vals): - """ Trivial little function to make 1xN float vector """ + """Trivial little function to make 1xN float vector""" return np.atleast_2d(np.array(vals, dtype=float)) @@ -57,7 +56,7 @@ def mlab_tempfile(dir=None): # infinite loop for some strange reason, we only try 100 times. for n in range(100): f = tempfile.NamedTemporaryFile(suffix=".m", prefix="tmp_matlab_", dir=dir) - # Check the file name for matlab compilance + # Check the file name for matlab compliance fname = os.path.splitext(os.path.basename(f.name))[0] if valid_name.match(fname): break diff --git a/nipype/utils/misc.py b/nipype/utils/misc.py index 85743ba01d..3f76fbab3c 100644 --- a/nipype/utils/misc.py +++ b/nipype/utils/misc.py @@ -1,28 +1,17 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Miscellaneous utility functions -""" +"""Miscellaneous utility functions""" import os import sys import re -from collections import Iterator +from collections.abc import Iterator from warnings import warn -from distutils.version import LooseVersion +from looseversion import LooseVersion import numpy as np -try: - from textwrap import indent as textwrap_indent -except ImportError: - - def textwrap_indent(text, prefix): - """ A textwrap.indent replacement for Python < 3.3 """ - if not prefix: - return text - splittext = text.splitlines(True) - return prefix + prefix.join(splittext) +import textwrap def human_order_sorted(l): @@ -34,7 +23,7 @@ def atoi(text): def natural_keys(text): if isinstance(text, tuple): text = text[0] - return [atoi(c) for c in re.split("(\d+)", text)] + return [atoi(c) for c in re.split(r"(\d+)", text)] return sorted(l, key=natural_keys) @@ -63,7 +52,7 @@ def trim(docstring, marker=None): if ( marker is not None and stripped - and all([s == stripped[0] for s in stripped]) + and all(s == stripped[0] for s in stripped) and stripped[0] not in [":"] ): line = line.replace(stripped[0], marker) @@ -97,12 +86,7 @@ def is_container(item): True if container False if not (eg string) """ - if isinstance(item, str): - return False - elif hasattr(item, "__iter__"): - return True - else: - return False + return not isinstance(item, str) and hasattr(item, "__iter__") def container_to_string(cont): @@ -154,7 +138,7 @@ def package_check( packages. Default is *Nipype*. checker : object, optional The class that will perform the version checking. Default is - distutils.version.LooseVersion. + nipype.external.version.LooseVersion. exc_failed_import : Exception, optional Class of the exception to be thrown if import failed. exc_failed_check : Exception, optional @@ -168,11 +152,11 @@ def package_check( """ if app: - msg = "%s requires %s" % (app, pkg_name) + msg = f"{app} requires {pkg_name}" else: msg = "Nipype requires %s" % pkg_name if version: - msg += " with version >= %s" % (version,) + msg += f" with version >= {version}" try: mod = __import__(pkg_name) except ImportError as e: @@ -256,10 +240,7 @@ def unflatten(in_list, prev_structure): if not isinstance(prev_structure, list): return next(in_list) - out = [] - for item in prev_structure: - out.append(unflatten(in_list, item)) - return out + return [unflatten(in_list, item) for item in prev_structure] def normalize_mc_params(params, source): @@ -296,12 +277,16 @@ def dict_diff(dold, dnew, indent=0): typical use -- log difference for hashed_inputs """ - # First check inputs, since they usually are lists of tuples - # and dicts are required. - if isinstance(dnew, list): - dnew = dict(dnew) - if isinstance(dold, list): - dold = dict(dold) + try: + dnew, dold = dict(dnew), dict(dold) + except Exception: + return textwrap.indent( + f"""\ +Diff between nipype inputs failed: +* Cached inputs: {dold} +* New inputs: {dnew}""", + " " * indent, + ) # Compare against hashed_inputs # Keys: should rarely differ @@ -321,26 +306,36 @@ def dict_diff(dold, dnew, indent=0): diffkeys = len(diff) + def _shorten(value): + if isinstance(value, str) and len(value) > 50: + return f"{value[:10]}...{value[-10:]}" + if isinstance(value, (tuple, list)) and len(value) > 10: + return tuple(list(value[:2]) + ["..."] + list(value[-2:])) + return value + + def _uniformize(val): + if isinstance(val, dict): + return {k: _uniformize(v) for k, v in val.items()} + if isinstance(val, (list, tuple)): + return tuple(_uniformize(el) for el in val) + return val + # Values in common keys would differ quite often, # so we need to join the messages together for k in new_keys.intersection(old_keys): - try: - new, old = dnew[k], dold[k] - same = new == old - if not same: - # Since JSON does not discriminate between lists and - # tuples, we might need to cast them into the same type - # as the last resort. And lets try to be more generic - same = old.__class__(new) == old - except Exception: - same = False - if not same: - diff += [" * %s: %r != %r" % (k, dnew[k], dold[k])] + # Reading from JSON produces lists, but internally we typically + # use tuples. At this point these dictionary values can be + # immutable (and therefore the preference for tuple). + new = _uniformize(dnew[k]) + old = _uniformize(dold[k]) + + if new != old: + diff += [f" * {k}: {_shorten(new)!r} != {_shorten(old)!r}"] if len(diff) > diffkeys: diff.insert(diffkeys, "Some dictionary entries had differing values:") - return textwrap_indent("\n".join(diff), " " * indent) + return textwrap.indent("\n".join(diff), " " * indent) def rgetcwd(error=True): diff --git a/nipype/utils/nipype2boutiques.py b/nipype/utils/nipype2boutiques.py index 0a12e59f28..90785f447e 100644 --- a/nipype/utils/nipype2boutiques.py +++ b/nipype/utils/nipype2boutiques.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # This tool exports a Nipype interface in the Boutiques # (https://github.com/boutiques) JSON format. Boutiques tools # can be imported in CBRAIN (https://github.com/aces/cbrain) @@ -290,7 +288,7 @@ def get_boutiques_input( if handler_type == "TraitCompound": input_list = [] # Recursively create an input for each trait - for i in range(0, len(trait_handler.handlers)): + for i in range(len(trait_handler.handlers)): inp = get_boutiques_input( inputs, interface, @@ -475,13 +473,11 @@ def get_boutiques_output(outputs, name, spec, interface, tool_inputs): output["list"] = True if output_value: # Check if all extensions are the same - extensions = [] - for val in output_value: - extensions.append(os.path.splitext(val)[1]) + extensions = {os.path.splitext(val)[1] for val in output_value} # If extensions all the same, set path template as # wildcard + extension. Otherwise just use a wildcard - if len(set(extensions)) == 1: - output["path-template"] = "*" + extensions[0] + if len(extensions) == 1: + output["path-template"] = "*" + extensions.pop() else: output["path-template"] = "*" return output @@ -574,8 +570,9 @@ def generate_custom_inputs(desc_inputs): if desc_input["type"] == "Flag": custom_input_dicts.append({desc_input["id"]: True}) elif desc_input.get("value-choices") and not desc_input.get("list"): - for value in desc_input["value-choices"]: - custom_input_dicts.append({desc_input["id"]: value}) + custom_input_dicts.extend( + {desc_input["id"]: value} for value in desc_input["value-choices"] + ) return custom_input_dicts diff --git a/nipype/utils/nipype_cmd.py b/nipype/utils/nipype_cmd.py index 7cfff832c1..ec0f603f3f 100644 --- a/nipype/utils/nipype_cmd.py +++ b/nipype/utils/nipype_cmd.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- import os import argparse import inspect @@ -6,7 +5,6 @@ from ..interfaces.base import Interface, InputMultiPath, traits from ..interfaces.base.support import get_trait_desc -from .misc import str2bool def listClasses(module=None): @@ -14,7 +12,7 @@ def listClasses(module=None): __import__(module) pkg = sys.modules[module] print("Available Interfaces:") - for k, v in sorted(list(pkg.__dict__.items())): + for k, v in sorted(pkg.__dict__.items()): if inspect.isclass(v) and issubclass(v, Interface): print("\t%s" % k) @@ -53,7 +51,7 @@ def run_instance(interface, options): try: setattr(interface.inputs, input_name, value) except ValueError as e: - print("Error when setting the value of %s: '%s'" % (input_name, str(e))) + print(f"Error when setting the value of {input_name}: '{e}'") print(interface.inputs) res = interface.run() @@ -61,7 +59,6 @@ def run_instance(interface, options): def main(argv): - if len(argv) == 2 and not argv[1].startswith("-"): listClasses(argv[1]) sys.exit(0) diff --git a/nipype/utils/onetime.py b/nipype/utils/onetime.py index e9a905254b..188c8f9147 100644 --- a/nipype/utils/onetime.py +++ b/nipype/utils/onetime.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Descriptor support for NIPY. @@ -19,26 +18,25 @@ """ -class OneTimeProperty(object): - """A descriptor to make special properties that become normal attributes. - """ +class OneTimeProperty: + """A descriptor to make special properties that become normal attributes.""" def __init__(self, func): """Create a OneTimeProperty instance. - Parameters - ---------- - func : method + Parameters + ---------- + func : method - The method that will be called the first time to compute a value. - Afterwards, the method's name will be a standard attribute holding - the value of this computation. + The method that will be called the first time to compute a value. + Afterwards, the method's name will be a standard attribute holding + the value of this computation. """ self.getter = func self.name = func.__name__ def __get__(self, obj, type=None): - """ Called on attribute access on the class or instance. """ + """Called on attribute access on the class or instance.""" if obj is None: # Being called on the class, return the original function. # This way, introspection works on the class. diff --git a/nipype/utils/profiler.py b/nipype/utils/profiler.py index 20e024693f..cc2b4f7905 100644 --- a/nipype/utils/profiler.py +++ b/nipype/utils/profiler.py @@ -1,16 +1,16 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Utilities to keep track of performance """ import os +import numpy as np import threading from time import time try: import psutil -except ImportError as exc: +except ImportError: psutil = None @@ -20,12 +20,30 @@ resource_monitor = config.resource_monitor # Init variables -_MB = 1024.0 ** 2 +_MB = 1024.0**2 + + +class ResourceMonitorMock: + """A mock class to use when the monitor is disabled.""" + + @property + def fname(self): + """Get/set the internal filename""" + return None + + def __init__(self, pid, freq=5, fname=None, python=True): + pass + + def start(self): + pass + + def stop(self): + return {} class ResourceMonitor(threading.Thread): """ - A ``Thread`` to monitor a specific PID with a certain frequence + A ``Thread`` to monitor a specific PID with a certain frequency to a file """ @@ -57,7 +75,7 @@ def fname(self): return self._fname def stop(self): - """Stop monitoring""" + """Stop monitoring.""" if not self._event.is_set(): self._event.set() self.join() @@ -65,6 +83,25 @@ def stop(self): self._logfile.flush() self._logfile.close() + retval = { + "mem_peak_gb": None, + "cpu_percent": None, + } + + # Read .prof file in and set runtime values + vals = np.loadtxt(self._fname, delimiter=",") + if vals.size: + vals = np.atleast_2d(vals) + retval["mem_peak_gb"] = vals[:, 2].max() / 1024 + retval["cpu_percent"] = vals[:, 1].max() + retval["prof_dict"] = { + "time": vals[:, 0].tolist(), + "cpus": vals[:, 1].tolist(), + "rss_GiB": (vals[:, 2] / 1024).tolist(), + "vms_GiB": (vals[:, 3] / 1024).tolist(), + } + return retval + def _sample(self, cpu_interval=None): cpu = 0.0 rss = 0.0 @@ -94,7 +131,7 @@ def _sample(self, cpu_interval=None): except psutil.NoSuchProcess: pass - print("%f,%f,%f,%f" % (time(), cpu, rss / _MB, vms / _MB), file=self._logfile) + print(f"{time():f},{cpu:f},{rss / _MB:f},{vms / _MB:f}", file=self._logfile) self._logfile.flush() def run(self): @@ -137,9 +174,9 @@ def log_nodes_cb(node, status): status_dict = { "name": node.name, "id": node._id, - "start": getattr(node.result.runtime, "startTime"), - "finish": getattr(node.result.runtime, "endTime"), - "duration": getattr(node.result.runtime, "duration"), + "start": node.result.runtime.startTime, + "finish": node.result.runtime.endTime, + "duration": node.result.runtime.duration, "runtime_threads": getattr(node.result.runtime, "cpu_percent", "N/A"), "runtime_memory_gb": getattr(node.result.runtime, "mem_peak_gb", "N/A"), "estimated_memory_gb": node.mem_gb, @@ -165,14 +202,14 @@ def get_system_total_memory_gb(): # Get memory if "linux" in sys.platform: - with open("/proc/meminfo", "r") as f_in: + with open("/proc/meminfo") as f_in: meminfo_lines = f_in.readlines() mem_total_line = [line for line in meminfo_lines if "MemTotal" in line][0] mem_total = float(mem_total_line.split()[1]) - memory_gb = mem_total / (1024.0 ** 2) + memory_gb = mem_total / (1024.0**2) elif "darwin" in sys.platform: mem_str = os.popen("sysctl hw.memsize").read().strip().split(" ")[-1] - memory_gb = float(mem_str) / (1024.0 ** 3) + memory_gb = float(mem_str) / (1024.0**3) else: err_msg = "System platform: %s is not supported" raise Exception(err_msg) @@ -349,7 +386,7 @@ def _use_resources(n_procs, mem_gb): # Getsize of one character string BSIZE = sys.getsizeof(" ") - sys.getsizeof(" ") BOFFSET = sys.getsizeof("") - _GB = 1024.0 ** 3 + _GB = 1024.0**3 def _use_gb_ram(mem_gb): """A test function to consume mem_gb GB of RAM""" diff --git a/nipype/utils/provenance.py b/nipype/utils/provenance.py index 5493f7c330..ba71ac6d6e 100644 --- a/nipype/utils/provenance.py +++ b/nipype/utils/provenance.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- from collections import OrderedDict from copy import deepcopy @@ -22,7 +21,7 @@ niiri = pm.Namespace("niiri", "http://iri.nidash.org/") crypto = pm.Namespace( "crypto", - ("http://id.loc.gov/vocabulary/preservation/" "cryptographicHashFunctions/"), + ("http://id.loc.gov/vocabulary/preservation/cryptographicHashFunctions/"), ) get_id = lambda: niiri[uuid1().hex] @@ -121,7 +120,7 @@ def _get_sorteddict(object, dictwithhash=False): else: out = hash elif isinstance(object, float): - out = "%.10f".format(object) + out = f"{object:.10f}" else: out = object return out @@ -144,7 +143,7 @@ def safe_encode(x, as_literal=True): if os.path.exists(x): if x[0] != os.pathsep: x = os.path.abspath(x) - value = "file://{}{}".format(platform.node().lower(), x) + value = f"file://{platform.node().lower()}{x}" if not as_literal: return value try: @@ -181,7 +180,7 @@ def safe_encode(x, as_literal=True): try: jsonstr = json.dumps(outdict) except UnicodeDecodeError as excp: - jsonstr = "Could not encode dictionary. {}".format(excp) + jsonstr = f"Could not encode dictionary. {excp}" logger.warning("Prov: %s", jsonstr) if not as_literal: @@ -211,7 +210,7 @@ def safe_encode(x, as_literal=True): try: jsonstr = json.dumps(x) except UnicodeDecodeError as excp: - jsonstr = "Could not encode list/tuple. {}".format(excp) + jsonstr = f"Could not encode list/tuple. {excp}" logger.warning("Prov: %s", jsonstr) if not as_literal: @@ -237,7 +236,7 @@ def safe_encode(x, as_literal=True): jsonstr = dumps(x) ltype = nipype_ns["pickle"] except TypeError as excp: - jsonstr = "Could not encode object. {}".format(excp) + jsonstr = f"Could not encode object. {excp}" if not as_literal: return jsonstr @@ -301,7 +300,7 @@ def write_provenance(results, filename="provenance", format="all"): import traceback err_msg = traceback.format_exc() - if getattr(e, "args"): + if e.args: err_msg += "\n\nException arguments:\n" + ", ".join( ['"%s"' % arg for arg in e.args] ) @@ -310,7 +309,7 @@ def write_provenance(results, filename="provenance", format="all"): return prov -class ProvStore(object): +class ProvStore: def __init__(self): self.g = pm.ProvDocument() self.g.add_namespace(foaf) @@ -327,7 +326,7 @@ def add_results(self, results, keep_provenance=False): inputs = results.inputs outputs = results.outputs classname = interface.__name__ - modulepath = "{0}.{1}".format(interface.__module__, interface.__name__) + modulepath = f"{interface.__module__}.{interface.__name__}" activitytype = "".join([i.capitalize() for i in modulepath.split(".")]) a0_attrs = { @@ -443,7 +442,7 @@ def add_results(self, results, keep_provenance=False): def write_provenance(self, filename="provenance", format="all"): if format in ["provn", "all"]: - with open(filename + ".provn", "wt") as fp: + with open(filename + ".provn", "w") as fp: fp.writelines(self.g.get_provn()) try: if format in ["rdf", "all"]: diff --git a/nipype/utils/spm_docs.py b/nipype/utils/spm_docs.py index 6864992e0e..3702378d1f 100644 --- a/nipype/utils/spm_docs.py +++ b/nipype/utils/spm_docs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Grab documentation from spm.""" @@ -28,7 +27,7 @@ def grab_doc(task_name): # We need to tell Matlab where to find our spm_get_doc.m file. cwd = os.path.dirname(__file__) # Build matlab command - mcmd = "addpath('%s');spm_get_doc('%s')" % (cwd, task_name) + mcmd = f"addpath('{cwd}');spm_get_doc('{task_name}')" cmd.inputs.script_lines = mcmd # Run the command and get the documentation out of the result. out = cmd.run() @@ -38,7 +37,7 @@ def grab_doc(task_name): def _strip_header(doc): """Strip Matlab header and splash info off doc. - Searches for the tag 'NIPYPE' in the doc and returns everyting after that. + Searches for the tag 'NIPYPE' in the doc and returns everything after that. """ hdr = "NIPYPE" @@ -48,7 +47,7 @@ def _strip_header(doc): try: index = doc.index(hdr) except ValueError as e: - raise IOError("This docstring was not generated by Nipype!\n") from e + raise OSError("This docstring was not generated by Nipype!\n") from e index += len(hdr) index += 1 diff --git a/nipype/utils/spm_flat_config.m b/nipype/utils/spm_flat_config.m index 6e489251b2..4f5f2929dd 100644 --- a/nipype/utils/spm_flat_config.m +++ b/nipype/utils/spm_flat_config.m @@ -1,7 +1,7 @@ function cfgstruct = spm_flat_config(print_names) % Get a flat spm_config structure, with option to print out names % -% This calls spm_config() to get the the nested configuration +% This calls spm_config() to get the nested configuration % structure from spm. We use this to fetch documentation, the % flattened structure is much easier to search through. If % print_names is true (value of 1) it will print out the configuration diff --git a/nipype/utils/subprocess.py b/nipype/utils/subprocess.py index 2c8c38a2f8..2fa9e52c3b 100644 --- a/nipype/utils/subprocess.py +++ b/nipype/utils/subprocess.py @@ -1,8 +1,6 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -"""Miscellaneous utility functions -""" +"""Miscellaneous utility functions""" import os import sys import gc @@ -10,6 +8,7 @@ import select import locale import datetime +from pathlib import Path from subprocess import Popen, STDOUT, PIPE from .filemanip import canonicalize_env, read_stream @@ -18,7 +17,7 @@ iflogger = logging.getLogger("nipype.interface") -class Stream(object): +class Stream: """Function to capture stdout and stderr streams with timestamps stackoverflow.com/questions/4984549/merge-and-sync-stdout-and-stderr/5188359 @@ -30,7 +29,7 @@ def __init__(self, name, impl): self._buf = "" self._rows = [] self._lastidx = 0 - self.default_encoding = locale.getdefaultlocale()[1] or "UTF-8" + self.default_encoding = locale.getpreferredencoding(do_setlocale=False) def fileno(self): "Pass-through for file descriptor." @@ -63,13 +62,13 @@ def _read(self, drain): self._buf = rest now = datetime.datetime.now().isoformat() rows = tmp.split("\n") - self._rows += [(now, "%s %s:%s" % (self._name, now, r), r) for r in rows] + self._rows += [(now, f"{self._name} {now}:{r}", r) for r in rows] for idx in range(self._lastidx, len(self._rows)): iflogger.info(self._rows[idx][1]) self._lastidx = len(self._rows) -def run_command(runtime, output=None, timeout=0.01): +def run_command(runtime, output=None, timeout=0.01, write_cmdline=False): """Run a command, read stdout and stderr, prefix with timestamp. The returned runtime contains a merged stdout+stderr log with timestamps @@ -100,6 +99,9 @@ def run_command(runtime, output=None, timeout=0.01): errfile = os.path.join(runtime.cwd, "stderr.nipype") stderr = open(errfile, "wb") + if write_cmdline: + (Path(runtime.cwd) / "command.txt").write_text(cmdline, encoding='utf-8') + proc = Popen( cmdline, stdout=stdout, @@ -122,9 +124,9 @@ def run_command(runtime, output=None, timeout=0.01): def _process(drain=0): try: res = select.select(streams, [], [], timeout) - except select.error as e: + except OSError as e: iflogger.info(e) - if e[0] == errno.EINTR: + if e.errno == errno.EINTR: return else: raise diff --git a/nipype/utils/tests/__init__.py b/nipype/utils/tests/__init__.py index 939910d6b6..00d7c65d5a 100644 --- a/nipype/utils/tests/__init__.py +++ b/nipype/utils/tests/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ diff --git a/nipype/utils/tests/test_cmd.py b/nipype/utils/tests/test_cmd.py index 211cc48a55..55b1a3e67c 100644 --- a/nipype/utils/tests/test_cmd.py +++ b/nipype/utils/tests/test_cmd.py @@ -45,9 +45,13 @@ def test_main_returns_0_on_help(self): assert exit_exception.code == 0 assert stderr.getvalue() == "" + if sys.version_info >= (3, 10): + options = "options" + else: + options = "optional arguments" assert ( stdout.getvalue() - == """usage: nipype_cmd [-h] module interface + == f"""usage: nipype_cmd [-h] module interface Nipype interface runner @@ -55,7 +59,7 @@ def test_main_returns_0_on_help(self): module Module name interface Interface name -optional arguments: +{options}: -h, --help show this help message and exit """ ) diff --git a/nipype/utils/tests/test_config.py b/nipype/utils/tests/test_config.py index 47dae20d88..f11908c3dd 100644 --- a/nipype/utils/tests/test_config.py +++ b/nipype/utils/tests/test_config.py @@ -1,11 +1,10 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os import sys import pytest from nipype import config -from mock import MagicMock +from unittest.mock import MagicMock try: import xvfbwrapper diff --git a/nipype/utils/tests/test_docparse.py b/nipype/utils/tests/test_docparse.py index 48812721b7..b6c8bbaaf3 100644 --- a/nipype/utils/tests/test_docparse.py +++ b/nipype/utils/tests/test_docparse.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/nipype/utils/tests/test_filemanip.py b/nipype/utils/tests/test_filemanip.py index e8e317935f..be16a9cea1 100644 --- a/nipype/utils/tests/test_filemanip.py +++ b/nipype/utils/tests/test_filemanip.py @@ -1,12 +1,10 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os import time -import warnings from pathlib import Path -import mock +from unittest import mock, SkipTest import pytest from ...testing import TempFATFS from ...utils.filemanip import ( @@ -28,9 +26,10 @@ get_related_files, indirectory, loadpkl, - loadcrash, savepkl, path_resolve, + write_rst_list, + emptydirs, ) @@ -87,7 +86,7 @@ def test_hash_rename(filename, newname): def test_check_forhash(): fname = "foobar" orig_hash = "_0x4323dbcefdc51906decd8edcb3327943" - hashed_name = "".join((fname, orig_hash, ".nii")) + hashed_name = f"{fname}{orig_hash}.nii" result, hash = check_forhash(hashed_name) assert result assert hash == [orig_hash] @@ -154,7 +153,7 @@ def test_copyfiles(_temp_analyze_files, _temp_analyze_files_prime): def test_linkchain(_temp_analyze_files): - if os.name is not "posix": + if os.name != "posix": return orig_img, orig_hdr = _temp_analyze_files pth, fname = os.path.split(orig_img) @@ -230,30 +229,30 @@ def test_recopy(_temp_analyze_files): def test_copyfallback(_temp_analyze_files): - if os.name is not "posix": + if os.name != "posix": return orig_img, orig_hdr = _temp_analyze_files pth, imgname = os.path.split(orig_img) pth, hdrname = os.path.split(orig_hdr) try: fatfs = TempFATFS() - except (IOError, OSError): - warnings.warn("Fuse mount failed. copyfile fallback tests skipped.") - else: - with fatfs as fatdir: - tgt_img = os.path.join(fatdir, imgname) - tgt_hdr = os.path.join(fatdir, hdrname) - for copy in (True, False): - for use_hardlink in (True, False): - copyfile(orig_img, tgt_img, copy=copy, use_hardlink=use_hardlink) - assert os.path.exists(tgt_img) - assert os.path.exists(tgt_hdr) - assert not os.path.islink(tgt_img) - assert not os.path.islink(tgt_hdr) - assert not os.path.samefile(orig_img, tgt_img) - assert not os.path.samefile(orig_hdr, tgt_hdr) - os.unlink(tgt_img) - os.unlink(tgt_hdr) + except OSError: + raise SkipTest("Fuse mount failed. copyfile fallback tests skipped.") + + with fatfs as fatdir: + tgt_img = os.path.join(fatdir, imgname) + tgt_hdr = os.path.join(fatdir, hdrname) + for copy in (True, False): + for use_hardlink in (True, False): + copyfile(orig_img, tgt_img, copy=copy, use_hardlink=use_hardlink) + assert os.path.exists(tgt_img) + assert os.path.exists(tgt_hdr) + assert not os.path.islink(tgt_img) + assert not os.path.islink(tgt_hdr) + assert not os.path.samefile(orig_img, tgt_img) + assert not os.path.samefile(orig_hdr, tgt_hdr) + os.unlink(tgt_img) + os.unlink(tgt_hdr) def test_get_related_files(_temp_analyze_files): @@ -295,7 +294,7 @@ def test_ensure_list(filename, expected): @pytest.mark.parametrize( - "list, expected", [(["foo.nii"], "foo.nii"), (["foo", "bar"], ["foo", "bar"]),] + "list, expected", [(["foo.nii"], "foo.nii"), (["foo", "bar"], ["foo", "bar"])] ) def test_simplify_list(list, expected): x = simplify_list(list) @@ -598,7 +597,7 @@ def __getstate__(self): class PickledBreaker: def __setstate__(self, d): - raise Exception() + raise Exception def test_versioned_pklization(tmpdir): @@ -611,7 +610,6 @@ def test_versioned_pklization(tmpdir): with mock.patch( "nipype.utils.tests.test_filemanip.Pickled", PickledBreaker ), mock.patch("nipype.__version__", "0.0.0"): - loadpkl("./pickled.pkz") @@ -630,7 +628,7 @@ def test_path_strict_resolve(tmpdir): """Check the monkeypatch to test strict resolution of Path.""" tmpdir.chdir() - # Default strict=False should work out out of the box + # Default strict=False should work out of the box testfile = Path("somefile.txt") resolved = "%s/somefile.txt" % tmpdir assert str(path_resolve(testfile)) == resolved @@ -653,3 +651,43 @@ def test_pickle(tmp_path, save_versioning): savepkl(pickle_fname, testobj, versioning=save_versioning) outobj = loadpkl(pickle_fname) assert outobj == testobj + + +@pytest.mark.parametrize( + "items,expected", + [ + ("", " \n\n"), + ("A string", " A string\n\n"), + (["A list", "Of strings"], " A list\n Of strings\n\n"), + (None, TypeError), + ], +) +def test_write_rst_list(tmp_path, items, expected): + if items is not None: + assert write_rst_list(items) == expected + else: + with pytest.raises(expected): + write_rst_list(items) + + +def nfs_unlink(pathlike, *, dir_fd=None): + if dir_fd is None: + path = Path(pathlike) + deleted = path.with_name(".nfs00000000") + path.rename(deleted) + else: + os.rename(pathlike, ".nfs1111111111", src_dir_fd=dir_fd, dst_dir_fd=dir_fd) + + +def test_emptydirs_dangling_nfs(tmp_path): + busyfile = tmp_path / "base" / "subdir" / "busyfile" + busyfile.parent.mkdir(parents=True) + busyfile.touch() + + with mock.patch("os.unlink") as mocked: + mocked.side_effect = nfs_unlink + emptydirs(tmp_path / "base") + + assert Path.exists(tmp_path / "base") + assert not busyfile.exists() + assert busyfile.parent.exists() # Couldn't remove diff --git a/nipype/utils/tests/test_functions.py b/nipype/utils/tests/test_functions.py index be73814cb8..a55f3f3416 100644 --- a/nipype/utils/tests/test_functions.py +++ b/nipype/utils/tests/test_functions.py @@ -1,15 +1,14 @@ -# -*- coding: utf-8 -*- import pytest from nipype.utils.functions import getsource, create_function_from_source def _func1(x): - return x ** 3 + return x**3 def test_func_to_str(): def func1(x): - return x ** 2 + return x**2 # Should be ok with both functions! for f in _func1, func1: diff --git a/nipype/utils/tests/test_imagemanip.py b/nipype/utils/tests/test_imagemanip.py new file mode 100644 index 0000000000..a488633cab --- /dev/null +++ b/nipype/utils/tests/test_imagemanip.py @@ -0,0 +1,30 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +import numpy as np +import nibabel as nb +import pytest +from ..imagemanip import copy_header + + +@pytest.mark.parametrize("keep_dtype", (True, False)) +def test_copy_header(tmp_path, keep_dtype): + """Cover copy_header.""" + fname1 = tmp_path / "reference.nii.gz" + fname2 = tmp_path / "target.nii.gz" + + nii = nb.Nifti1Image(np.zeros((10, 10, 10), dtype="uint8"), None, None) + nii.set_qform(np.diag((1.0, 2.0, 3.0, 1.0)), code=2) + nii.set_sform(np.diag((1.0, 2.0, 3.0, 1.0)), code=1) + nii.to_filename(str(fname1)) + + nii.set_data_dtype("float32") + nii.set_qform(np.eye(4), code=1) + nii.to_filename(str(fname2)) + + copied = nb.load(copy_header(fname1, fname2, keep_dtype=keep_dtype)) + ref = nb.load(str(fname1)) + assert np.all(copied.get_qform(coded=False) == ref.get_qform(coded=False)) + assert np.all(copied.get_sform(coded=False) == ref.get_sform(coded=False)) + assert copied.get_qform(coded=True)[1] == ref.get_qform(coded=True)[1] + assert copied.get_sform(coded=True)[1] == ref.get_sform(coded=True)[1] + assert (copied.header.get_data_dtype() == ref.header.get_data_dtype()) != keep_dtype diff --git a/nipype/utils/tests/test_misc.py b/nipype/utils/tests/test_misc.py index ad25c6ba14..6e71e7c0ca 100644 --- a/nipype/utils/tests/test_misc.py +++ b/nipype/utils/tests/test_misc.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -6,7 +5,13 @@ import pytest -from nipype.utils.misc import container_to_string, str2bool, flatten, unflatten +from nipype.utils.misc import ( + container_to_string, + str2bool, + flatten, + unflatten, + dict_diff, +) def test_cont_to_str(): @@ -95,3 +100,43 @@ def test_rgetcwd(monkeypatch, tmpdir): monkeypatch.delenv("PWD") with pytest.raises(OSError): rgetcwd(error=False) + + +def test_dict_diff(): + abtuple = [("a", "b")] + abdict = dict(abtuple) + + # Unchanged + assert dict_diff(abdict, abdict) == "" + assert dict_diff(abdict, abtuple) == "" + assert dict_diff(abtuple, abdict) == "" + assert dict_diff(abtuple, abtuple) == "" + + # Changed keys + diff = dict_diff({"a": "b"}, {"b": "a"}) + assert "Dictionaries had differing keys" in diff + assert "keys not previously seen: {'b'}" in diff + assert "keys not presently seen: {'a'}" in diff + + # Trigger recursive uniformization + complicated_val1 = [{"a": ["b"], "c": ("d", "e")}] + complicated_val2 = [{"a": ["x"], "c": ("d", "e")}] + uniformized_val1 = ({"a": ("b",), "c": ("d", "e")},) + uniformized_val2 = ({"a": ("x",), "c": ("d", "e")},) + + diff = dict_diff({"a": complicated_val1}, {"a": complicated_val2}) + assert "Some dictionary entries had differing values:" in diff + assert f"a: {uniformized_val2!r} != {uniformized_val1!r}" in diff + + # Trigger shortening + diff = dict_diff({"a": "b" * 60}, {"a": "c" * 70}) + assert "Some dictionary entries had differing values:" in diff + assert "a: 'cccccccccc...cccccccccc' != 'bbbbbbbbbb...bbbbbbbbbb'" in diff + + # Fail the dict conversion + diff = dict_diff({}, "not a dict") + assert diff == ( + "Diff between nipype inputs failed:\n" + "* Cached inputs: {}\n" + "* New inputs: not a dict" + ) diff --git a/nipype/utils/tests/test_nipype2boutiques.py b/nipype/utils/tests/test_nipype2boutiques.py index 758f621202..65e4a2e711 100644 --- a/nipype/utils/tests/test_nipype2boutiques.py +++ b/nipype/utils/tests/test_nipype2boutiques.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from ..nipype2boutiques import generate_boutiques_descriptor @@ -11,16 +10,16 @@ def test_generate(): desc = generate_boutiques_descriptor( module="nipype.interfaces.fsl", interface_name="FLIRT", - container_image=("mcin/" "docker-fsl:latest"), + container_image="mcin/docker-fsl:latest", container_index="index.docker.io", container_type="docker", verbose=False, save=False, ignore_inputs=ignored_inputs, - author=("Oxford Centre for Functional" " MRI of the Brain (FMRIB)"), + author="Oxford Centre for Functional MRI of the Brain (FMRIB)", ) - with open(example_data("nipype2boutiques_example.json"), "r") as desc_file: + with open(example_data("nipype2boutiques_example.json")) as desc_file: # Make sure that output descriptor matches the expected descriptor. output_desc = json.loads(desc) expected_desc = json.load(desc_file) diff --git a/nipype/utils/tests/test_provenance.py b/nipype/utils/tests/test_provenance.py index 393a66b6b2..f440acb2ed 100644 --- a/nipype/utils/tests/test_provenance.py +++ b/nipype/utils/tests/test_provenance.py @@ -1,11 +1,19 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: -import os +from nibabel.optpkg import optional_package +import pytest + +_, have_rdflib5, _ = optional_package("rdflib", min_version="5.0.0") from nipype.utils.provenance import ProvStore, safe_encode +needs_rdflib5 = pytest.mark.skipif( + not have_rdflib5, reason="Test requires rdflib 5.0.0 or higher" +) + +@needs_rdflib5 +@pytest.mark.timeout(60) def test_provenance(tmpdir): from nipype.interfaces.base import CommandLine @@ -17,6 +25,8 @@ def test_provenance(tmpdir): assert "echo hello" in provn +@needs_rdflib5 +@pytest.mark.timeout(60) def test_provenance_exists(tmpdir): tmpdir.chdir() from nipype import config diff --git a/nipype/utils/tmpdirs.py b/nipype/utils/tmpdirs.py index 4752514e8f..a399650c07 100644 --- a/nipype/utils/tmpdirs.py +++ b/nipype/utils/tmpdirs.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os @@ -8,7 +5,7 @@ from tempfile import template, mkdtemp -class TemporaryDirectory(object): +class TemporaryDirectory: """Create and return a temporary directory. This has the same behavior as mkdtemp but can be used as a context manager. For example: @@ -16,7 +13,7 @@ class TemporaryDirectory(object): with TemporaryDirectory() as tmpdir: ... - Upon exiting the context, the directory and everthing contained + Upon exiting the context, the directory and everything contained in it are removed. """ @@ -41,8 +38,8 @@ class InTemporaryDirectory(TemporaryDirectory): def __enter__(self): self._pwd = os.getcwd() os.chdir(self.name) - return super(InTemporaryDirectory, self).__enter__() + return super().__enter__() def __exit__(self, exc, value, tb): os.chdir(self._pwd) - return super(InTemporaryDirectory, self).__exit__(exc, value, tb) + return super().__exit__(exc, value, tb) diff --git a/nipype/workflows/__init__.py b/nipype/workflows/__init__.py index 760ee9229a..5a3f04b56e 100644 --- a/nipype/workflows/__init__.py +++ b/nipype/workflows/__init__.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000000..2b1282eb74 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,27 @@ +[build-system] +requires = ["setuptools >= 30.3.0"] +build-backend = "setuptools.build_meta" + +[tool.black] +skip-string-normalization = true + +[tool.pytest.ini_options] +minversion = "6" +testpaths = ["nipype"] +log_cli_level = "INFO" +xfail_strict = true +norecursedirs = [".git"] +addopts = [ + "-svx", + "-ra", + "--strict-config", + "--strict-markers", + "--doctest-modules", + "--cov=nipype", + "--cov-report=xml", + "--cov-config=pyproject.toml", +] +doctest_optionflags = "ALLOW_UNICODE NORMALIZE_WHITESPACE ELLIPSIS" +env = "PYTHONHASHSEED=0" +filterwarnings = ["ignore::DeprecationWarning"] +junit_family = "xunit2" diff --git a/requirements.txt b/requirements.txt index 8f16c7873c..331e2c5def 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,17 +1,16 @@ # Auto-generated by tools/update_requirements.py click>=6.6.0 -networkx>=1.9 +networkx>=2.0 nibabel>=2.1.0 -numpy>=1.12 ; python_version < "3.7" -numpy>=1.15.3 ; python_version >= "3.7" +numpy>=1.17 packaging prov>=1.5.2 pydot>=1.2.3 -pydotplus python-dateutil>=2.2 +rdflib>=5.0.0 scipy>=0.14 simplejson>=3.8.0 -traits>=4.6,!=5.0 +traits>=4.6,<6.4,!=5.0 filelock>=3.0.0 -etelemetry -neurdflib +etelemetry>=0.2.0 +looseversion diff --git a/setup.py b/setup.py index dc6ef0d973..f5d7787577 100755 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ class BuildWithCommitInfoCommand(build_py): - """ Return extended build command class for recording commit + """Return extended build command class for recording commit The extended command tries to run git to find the current commit, getting the empty string if it fails. It then writes the commit hash into a file @@ -74,7 +74,7 @@ def run(self): cfg_parser.read(pjoin("nipype", "COMMIT_INFO.txt")) cfg_parser.set("commit hash", "install_hash", repo_commit.strip()) out_pth = pjoin(self.build_lib, "nipype", "COMMIT_INFO.txt") - cfg_parser.write(open(out_pth, "wt")) + cfg_parser.write(open(out_pth, "w")) def main(): @@ -119,6 +119,7 @@ def main(): maintainer_email=ldict["MAINTAINER_EMAIL"], description=ldict["DESCRIPTION"], long_description=ldict["LONG_DESCRIPTION"], + long_description_content_type="text/x-rst", url=ldict["URL"], download_url=ldict["DOWNLOAD_URL"], license=ldict["LICENSE"], diff --git a/tools/checkspecs.py b/tools/checkspecs.py index a4707bd375..7c9ebf4157 100644 --- a/tools/checkspecs.py +++ b/tools/checkspecs.py @@ -8,15 +8,12 @@ import sys import warnings -from nipype.interfaces.base import BaseInterface - import black # Functions and classes -class InterfaceChecker(object): - """Class for checking all interface specifications - """ +class InterfaceChecker: + """Class for checking all interface specifications""" def __init__( self, @@ -25,7 +22,7 @@ def __init__( module_skip_patterns=None, class_skip_patterns=None, ): - r""" Initialize package for parsing + r"""Initialize package for parsing Parameters ---------- @@ -115,25 +112,23 @@ def _uri2path(self, uri): return path def _path2uri(self, dirpath): - """ Convert directory path to uri """ + """Convert directory path to uri""" relpath = dirpath.replace(self.root_path, self.package_name) if relpath.startswith(os.path.sep): relpath = relpath[1:] return relpath.replace(os.path.sep, ".") def _parse_module(self, uri): - """ Parse module defined in *uri* """ + """Parse module defined in *uri*""" filename = self._uri2path(uri) if filename is None: # nothing that we could handle here. return ([], []) - f = open(filename, "rt") - functions, classes = self._parse_lines(f, uri) - f.close() - return functions, classes + with open(filename) as f: + return self._parse_lines(f, uri) def _parse_lines(self, linesource, module): - """ Parse lines of text for functions and classes """ + """Parse lines of text for functions and classes""" functions = [] classes = [] for line in linesource: @@ -146,7 +141,7 @@ def _parse_lines(self, linesource, module): # exclude private stuff name = self._get_object_name(line) if not name.startswith("_") and self._survives_exclude( - ".".join((module, name)), "class" + f"{module}.{name}", "class" ): classes.append(name) else: @@ -161,7 +156,7 @@ def _normalize_repr(cls, value): return "[{}]".format(", ".join(map(cls._normalize_repr, value))) if isinstance(value, tuple): if len(value) == 1: - return "({},)".format(cls._normalize_repr(value[0])) + return f"({cls._normalize_repr(value[0])},)" return "({})".format(", ".join(map(cls._normalize_repr, value))) if isinstance(value, (str, bytes)): value = repr(value) @@ -182,6 +177,8 @@ def test_specs(self, uri): Returns ------- """ + from nipype.interfaces.base import BaseInterface + # get the names of all classes and functions _, classes = self._parse_module(uri) if not classes: @@ -248,7 +245,7 @@ def test_specs(self, uri): if not os.path.exists(nonautotest): cmd = [ "# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT", - "from ..%s import %s" % (uri.split(".")[-1], c), + "from ..{} import {}".format(uri.split(".")[-1], c), "", ] cmd.append("\ndef test_%s_inputs():" % c) @@ -260,7 +257,7 @@ def test_specs(self, uri): for key, value in sorted(trait.__dict__.items()): if key in in_built or key == "desc": continue - input_fields += "%s=%s,\n " % ( + input_fields += "{}={},\n ".format( key, self._normalize_repr(value), ) @@ -275,7 +272,7 @@ def test_specs(self, uri): ] fmt_cmd = black.format_str("\n".join(cmd), mode=black.FileMode()) - with open(testfile, "wt") as fp: + with open(testfile, "w") as fp: fp.writelines(fmt_cmd) else: print("%s has nonautotest" % c) @@ -288,7 +285,7 @@ def test_specs(self, uri): continue parent_metadata = [] if "parent" in trait.__dict__: - parent_metadata = list(getattr(trait, "parent").__dict__.keys()) + parent_metadata = list(trait.parent.__dict__) if ( key not in allowed_keys @@ -304,7 +301,7 @@ def test_specs(self, uri): bad_specs.append( [uri, c, "Inputs", traitname, "mandatory=False"] ) - if key == "usedefault" and trait.__dict__[key] == False: + if key == "usedefault" and trait.__dict__[key] is False: bad_specs.append( [uri, c, "Inputs", traitname, "usedefault=False"] ) @@ -324,7 +321,7 @@ def test_specs(self, uri): and "xor" not in trait.__dict__ ): if ( - trait.trait_type.__class__.__name__ is "Range" + trait.trait_type.__class__.__name__ == "Range" and trait.default == trait.trait_type._low ): continue @@ -351,7 +348,7 @@ def test_specs(self, uri): for key, value in sorted(trait.__dict__.items()): if key in in_built or key == "desc": continue - input_fields += "%s=%s,\n " % ( + input_fields += "{}={},\n ".format( key, self._normalize_repr(value), ) @@ -365,7 +362,7 @@ def test_specs(self, uri): assert getattr(outputs.traits()[key], metakey) == value""" ] fmt_cmd = black.format_str("\n".join(cmd), mode=black.FileMode()) - with open(testfile, "at") as fp: + with open(testfile, "a") as fp: fp.writelines("\n\n" + fmt_cmd) for traitname, trait in sorted( @@ -376,7 +373,7 @@ def test_specs(self, uri): continue parent_metadata = [] if "parent" in trait.__dict__: - parent_metadata = list(getattr(trait, "parent").__dict__.keys()) + parent_metadata = list(trait.parent.__dict__) if ( key not in allowed_keys @@ -387,7 +384,7 @@ def test_specs(self, uri): return bad_specs def _survives_exclude(self, matchstr, match_type): - """ Returns True if *matchstr* does not match patterns + """Returns True if *matchstr* does not match patterns ``self.package_name`` removed from front of string if present @@ -429,7 +426,7 @@ def _survives_exclude(self, matchstr, match_type): return True def discover_modules(self): - """ Return module sequence discovered from ``self.package_name`` + """Return module sequence discovered from ``self.package_name`` Parameters @@ -450,7 +447,7 @@ def discover_modules(self): # Check directory names for packages root_uri = self._path2uri(os.path.join(self.root_path, dirpath)) for dirname in dirnames[:]: # copy list - we modify inplace - package_uri = ".".join((root_uri, dirname)) + package_uri = f"{root_uri}.{dirname}" if self._uri2path(package_uri) and self._survives_exclude( package_uri, "package" ): @@ -460,7 +457,7 @@ def discover_modules(self): # Check filenames for modules for filename in filenames: module_name = filename[:-3] - module_uri = ".".join((root_uri, module_name)) + module_uri = f"{root_uri}.{module_name}" if self._uri2path(module_uri) and self._survives_exclude( module_uri, "module" ): @@ -480,31 +477,32 @@ def check_modules(self): if __name__ == "__main__": + os.environ["NIPYPE_NO_ET"] = "1" package = "nipype" ic = InterfaceChecker(package) # Packages that should not be included in generated API docs. ic.package_skip_patterns += [ - "\.external$", - "\.fixes$", - "\.utils$", - "\.pipeline", - "\.testing", - "\.caching", - "\.workflows", + r"\.external$", + r"\.fixes$", + r"\.utils$", + r"\.pipeline", + r"\.testing", + r"\.caching", + r"\.workflows", ] """ # Modules that should not be included in generated API docs. - ic.module_skip_patterns += ['\.version$', - '\.interfaces\.base$', - '\.interfaces\.matlab$', - '\.interfaces\.rest$', - '\.interfaces\.pymvpa$', - '\.interfaces\.slicer\.generate_classes$', - '\.interfaces\.spm\.base$', - '\.interfaces\.traits', - '\.pipeline\.alloy$', - '\.pipeline\.s3_node_wrapper$', - '.\testing', + ic.module_skip_patterns += ['\\.version$', + '\\.interfaces\\.base$', + '\\.interfaces\\.matlab$', + '\\.interfaces\\.rest$', + '\\.interfaces\\.pymvpa$', + '\\.interfaces\\.slicer\\.generate_classes$', + '\\.interfaces\\.spm\\.base$', + '\\.interfaces\\.traits', + '\\.pipeline\\.alloy$', + '\\.pipeline\\.s3_node_wrapper$', + '.\\testing', ] ic.class_skip_patterns += ['AFNI', 'ANTS', diff --git a/tools/ci/activate.sh b/tools/ci/activate.sh new file mode 100644 index 0000000000..567e13a67b --- /dev/null +++ b/tools/ci/activate.sh @@ -0,0 +1,9 @@ +if [ -e virtenv/bin/activate ]; then + source virtenv/bin/activate +elif [ -e virtenv/Scripts/activate ]; then + source virtenv/Scripts/activate +else + echo Cannot activate virtual environment + ls -R virtenv + false +fi diff --git a/tools/ci/build_archive.sh b/tools/ci/build_archive.sh new file mode 100755 index 0000000000..484ed19f6b --- /dev/null +++ b/tools/ci/build_archive.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +echo "Building archive" + +source tools/ci/activate.sh + +set -eu + +# Required dependencies +echo "INSTALL_TYPE = $INSTALL_TYPE" + +set -x + +if [ "$INSTALL_TYPE" == "sdist" ]; then + python setup.py egg_info # check egg_info while we're here + python setup.py sdist + export ARCHIVE=$( ls dist/*.tar.gz ) +elif [ "$INSTALL_TYPE" == "wheel" ]; then + python setup.py bdist_wheel + export ARCHIVE=$( ls dist/*.whl ) +elif [ "$INSTALL_TYPE" == "archive" ]; then + export ARCHIVE="package.tar.gz" + git archive -o $ARCHIVE HEAD +elif [ "$INSTALL_TYPE" == "pip" ]; then + export ARCHIVE="." +fi + +set +eux diff --git a/tools/ci/check.sh b/tools/ci/check.sh new file mode 100755 index 0000000000..5151854902 --- /dev/null +++ b/tools/ci/check.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +echo Running tests + +source tools/ci/activate.sh +source tools/ci/env.sh + +set -eu + +# Required variables +echo CHECK_TYPE = $CHECK_TYPE + +set -x + +if [ "${CHECK_TYPE}" == "test" ]; then + pytest --capture=no --verbose --doctest-modules -c nipype/pytest.ini \ + --cov-config .coveragerc --cov nipype --cov-report xml \ + --junitxml=test-results.xml nipype +elif [ "$CHECK_TYPE" = "specs" ]; then + make specs + git status -s + test -z "$(git status -s)" +elif [ "$CHECK_TYPE" = "style" ]; then + black --check nipype setup.py +else + false +fi + +set +eux + +echo Done running tests diff --git a/tools/ci/create_venv.sh b/tools/ci/create_venv.sh new file mode 100755 index 0000000000..7a28767396 --- /dev/null +++ b/tools/ci/create_venv.sh @@ -0,0 +1,24 @@ +#!/bin/bash + +echo Creating isolated virtual environment + +source tools/ci/env.sh + +set -eu + +# Required variables +echo SETUP_REQUIRES = $SETUP_REQUIRES + +set -x + +python -m pip install --upgrade pip virtualenv +virtualenv --python=python virtenv +source tools/ci/activate.sh +python --version +python -m pip install -U $SETUP_REQUIRES +which python +which pip + +set +eux + +echo Done creating isolated virtual environment diff --git a/tools/ci/env.sh b/tools/ci/env.sh new file mode 100644 index 0000000000..15e12275b6 --- /dev/null +++ b/tools/ci/env.sh @@ -0,0 +1,17 @@ +SETUP_REQUIRES="pip setuptools>=30.3.0 wheel" + +# Minimum requirements +REQUIREMENTS="-r requirements.txt" +# Minimum versions of minimum requirements +MIN_REQUIREMENTS="-r min-requirements.txt" + +# Numpy and scipy upload nightly/weekly/intermittent wheels +NIGHTLY_WHEELS="https://pypi.anaconda.org/scipy-wheels-nightly/simple" +STAGING_WHEELS="https://pypi.anaconda.org/multibuild-wheels-staging/simple" +PRE_PIP_FLAGS="--pre --extra-index-url $NIGHTLY_WHEELS --extra-index-url $STAGING_WHEELS" + +for CONF in /etc/fsl/fsl.sh /etc/afni/afni.sh; do + if [ -r $CONF ]; then source $CONF; fi +done + +FSLOUTPUTTYPE=NIFTI_GZ diff --git a/tools/ci/install.sh b/tools/ci/install.sh new file mode 100755 index 0000000000..428ffc8b8c --- /dev/null +++ b/tools/ci/install.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +echo Installing nipype + +source tools/ci/activate.sh +source tools/ci/env.sh + +set -eu + +# Required variables +echo INSTALL_TYPE = $INSTALL_TYPE +echo CHECK_TYPE = $CHECK_TYPE +echo NIPYPE_EXTRAS = $NIPYPE_EXTRAS +echo EXTRA_PIP_FLAGS = $EXTRA_PIP_FLAGS + +set -x + +if [ -n "$EXTRA_PIP_FLAGS" ]; then + EXTRA_PIP_FLAGS=${!EXTRA_PIP_FLAGS} +fi + +if [ "$INSTALL_TYPE" == "setup" ]; then + python setup.py install +else + pip install $EXTRA_PIP_FLAGS $ARCHIVE +fi + +# Basic import check +python -c 'import nipype; print(nipype.__version__)' + +if [ "$CHECK_TYPE" == "skiptests" ]; then + exit 0 +fi + +pip install $EXTRA_PIP_FLAGS "nipype[$NIPYPE_EXTRAS]" + +set +eux + +echo Done installing nipype diff --git a/tools/ci/install_deb_dependencies.sh b/tools/ci/install_deb_dependencies.sh new file mode 100755 index 0000000000..3dcf7ae9e4 --- /dev/null +++ b/tools/ci/install_deb_dependencies.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +echo "Installing NeuroDebian dependencies" + +set -eu + +echo "INSTALL_DEB_DEPENDENCIES = $INSTALL_DEB_DEPENDENCIES" + +DEPS=( + fsl + # afni + # elastix + fsl-atlases + xvfb + fusefat + graphviz +) + +if $INSTALL_DEB_DEPENDENCIES; then + bash <(wget -q -O- http://neuro.debian.net/_files/neurodebian-travis.sh) + sudo apt update + sudo apt install -y -qq ${DEPS[@]} +fi diff --git a/tools/ci/install_dependencies.sh b/tools/ci/install_dependencies.sh new file mode 100755 index 0000000000..617389cb5e --- /dev/null +++ b/tools/ci/install_dependencies.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +echo Installing dependencies + +source tools/ci/activate.sh +source tools/ci/env.sh + +set -eu + +# Required variables +echo EXTRA_PIP_FLAGS = $EXTRA_PIP_FLAGS +echo DEPENDS = $DEPENDS + +set -x + +if [ -n "$EXTRA_PIP_FLAGS" ]; then + EXTRA_PIP_FLAGS=${!EXTRA_PIP_FLAGS} +fi + +if [ -n "$DEPENDS" ]; then + pip install ${EXTRA_PIP_FLAGS} --prefer-binary ${!DEPENDS} +fi + +set +eux + +echo Done installing dependencies diff --git a/tools/ex2rst b/tools/ex2rst index dc3c6d5f37..1b19ce8726 100755 --- a/tools/ex2rst +++ b/tools/ex2rst @@ -98,7 +98,7 @@ def exfile2rst(filename): proc_line = None # handle doc start if not indocs: - # guarenteed to start with """ + # guaranteed to start with """ if len(cleanline) > 3 \ and (cleanline.endswith('"""') \ or cleanline.endswith("'''")): @@ -187,10 +187,13 @@ def exfile2rstfile(filename, opts): .. admonition:: Example source code You can download :download:`the full source code of this example <%s>`. - This same script is also included in the %s source distribution under the - :file:`examples` directory. + This same script is also included in `%s <%s>`__ under the :file:`%s` + directory. -""" % (filename, opts.project) +""" % (os.path.relpath(filename, opts.outdir), + "Nipype1 Examples Niflow", + "https://github.com/niflows/nipype1-examples", + "package/niflow/nipype1/examples") dfile.write(msg) diff --git a/tools/feedstock.sh b/tools/feedstock.sh index b37dba8671..831f04cf39 100755 --- a/tools/feedstock.sh +++ b/tools/feedstock.sh @@ -13,7 +13,7 @@ # GITHUB_TOKEN: Pre-established token for user or bot # # One of: -# CIRCLE_BRANCH: Name of release branch (rel/) +# CIRCLE_BRANCH: Name of release branch (rel/) # CIRCLE_TAG: Name of release tag () # # Depends: @@ -25,7 +25,7 @@ # # 2018 Chris Markiewicz -set -x +set -ex REPO=${1:-$CIRCLE_PROJECT_REPONAME} FEEDSTOCK=${2:-$REPO-feedstock} @@ -62,7 +62,7 @@ if git checkout -t $GITHUB_USER/$BRANCH; then NEW_PR=false else NEW_PR=true - git checkout -b $BRANCH origin/master + git checkout -b $BRANCH origin/main fi # Calculate hash @@ -77,7 +77,7 @@ fi # Set version, hash, and reset build number # Use ~ for separator in URL, to avoid slash issues -sed -i '' \ +sed -i \ -e 's/^\({% set version = "\).*\(" %}\)$/'"\1$VERSION\2/" \ -e 's/^\({% set sha256 = "\).*\(" %}\)$/'"\1$SHA256\2/" \ -e 's~^\( *url:\) .*$~\1 '"$URL_FMT~" \ @@ -90,7 +90,7 @@ git commit -m "$COMMIT_MSG" git push -u $GITHUB_USER $BRANCH if $NEW_PR; then - hub pull-request -b conda-forge:master -F - <> newchanges echo $( printf "%${#HEADER}s" | tr " " "=" ) >> newchanges +echo >> newchanges -if [[ "x$2" != "x" ]]; then - echo "(\`Full changelog \`__)" >> newchanges +MILESTONE=${2:-""} +if [[ "x$MILESTONE" != "x" ]]; then + echo "(\`Full changelog \`__)" >> newchanges + echo >> newchanges fi # Search for PRs since previous release -git log --grep="Merge pull request" `git describe --tags --abbrev=0`..HEAD --pretty='format: * %b %s' | sed 's+Merge pull request \#\([^\d]*\)\ from\ .*+(https://github.com/nipy/nipype/pull/\1)+' >> newchanges -echo "" >> newchanges -echo "" >> newchanges +MERGE_COMMITS=$( git log --grep="Merge pull request\|(#.*)$" `git describe --tags --abbrev=0`..HEAD --pretty='format:%h' ) +for COMMIT in ${MERGE_COMMITS//\n}; do + SUB=$( git log -n 1 --pretty="format:%s" $COMMIT ) + if ( echo $SUB | grep "^Merge pull request" ); then + # Merge commit + PR=$( echo $SUB | sed -e "s/Merge pull request \#\([0-9]*\).*/\1/" ) + TITLE=$( git log -n 1 --pretty="format:%b" $COMMIT ) + else + # Squashed merge + PR=$( echo $SUB | sed -e "s/.*(\#\([0-9]*\))$/\1/" ) + TITLE=$( echo $SUB | sed -e "s/\(.*\)(\#[0-9]*)$/\1/" ) + fi + echo " * $TITLE (https://github.com/nipy/nipype/pull/$PR)" >> newchanges +done +echo >> newchanges +echo >> newchanges # Append old CHANGES if [[ "$UPCOMING" == "0" ]]; then @@ -43,4 +59,3 @@ fi # Replace old CHANGES with new file mv newchanges $CHANGES - diff --git a/tools/update_mailmap.sh b/tools/update_mailmap.sh new file mode 100644 index 0000000000..4602e85e3a --- /dev/null +++ b/tools/update_mailmap.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +# usage -> bash update_mailmap.sh +# by default, will use the latest tag + +set -ux + +ROOT=$( git rev-parse --show-toplevel ) +MAILMAP=$ROOT/.mailmap + +LAST=$(git describe --tags `git rev-list --tags --max-count=1`) +RELEASE=${1:-$LAST} + +IFS=$'\n' +for NAME in $(git shortlog -nse $RELEASE.. | cut -f2-); do + echo $NAME +done + +# sort and write +sort $MAILMAP > .tmpmailmap +cp .tmpmailmap $MAILMAP +rm .tmpmailmap diff --git a/tools/update_requirements.py b/tools/update_requirements.py index 4dd14a37d7..b7a8a6cf8e 100755 --- a/tools/update_requirements.py +++ b/tools/update_requirements.py @@ -15,4 +15,4 @@ # Write requirements lines[1:-1] = requirements -reqs.write_text("\n".join(lines)) +reqs.write_text("\n".join(lines), encoding='utf-8') diff --git a/tools/update_zenodo.py b/tools/update_zenodo.py index 18cc588061..359740363b 100755 --- a/tools/update_zenodo.py +++ b/tools/update_zenodo.py @@ -1,77 +1,82 @@ #!/usr/bin/env python3 +# /// script +# requires-python = ">=3.11" +# dependencies = [ +# "fuzzywuzzy", +# "gitpython", +# "python-levenshtein", +# ] +# /// """Update and sort the creators list of the zenodo record.""" -import sys -import shutil -from pathlib import Path +import git import json +from subprocess import run, PIPE +from pathlib import Path from fuzzywuzzy import fuzz, process -import subprocess as sp + + +def decommify(name): + return " ".join(name.split(", ")[::-1]) + # These names should go last -CREATORS_LAST = ["Gorgolewski, Krzysztof J.", "Ghosh, Satrajit"] +CREATORS_LAST = ["Krzysztof J. Gorgolewski", "Satrajit Ghosh"] + +# Contributors that have requested not to be cited (or bothered) +BLACKLIST = {"Jonathan R. Williford"} if __name__ == "__main__": - contrib_file = Path("line-contributors.txt") - lines = [] - if contrib_file.exists(): - print("WARNING: Reusing existing line-contributors.txt file.", file=sys.stderr) - lines = contrib_file.read_text().splitlines() - - git_line_summary_path = shutil.which("git-line-summary") - if not lines and git_line_summary_path: - print("Running git-line-summary on nipype repo") - lines = sp.check_output([git_line_summary_path]).decode().splitlines() - contrib_file.write_text("\n".join(lines)) - - if not lines: - raise RuntimeError( - """\ -Could not find line-contributors from git repository.%s""" - % """ \ -git-line-summary not found, please install git-extras. """ - * (git_line_summary_path is None) + git_root = Path(git.Repo(".", search_parent_directories=True).working_dir) + zenodo_file = git_root / ".zenodo.json" + + zenodo = json.loads(zenodo_file.read_text()) if zenodo_file.exists() else {} + + creator_map = { + decommify(creator["name"]): creator for creator in zenodo.get("creators", []) + } + + shortlog = run(["git", "shortlog", "-ns"], stdout=PIPE) + commit_counts = dict( + line.split("\t", 1)[::-1] + for line in shortlog.stdout.decode().split("\n") + if line + ) + + existing_creators = set(creator_map.keys()) + + committers = [] + + # Stable sort: + # Number of commits in descending order + # Ties broken by alphabetical order of first name + for committer, _ in sorted(commit_counts.items(), key=lambda x: (-int(x[1]), x[0])): + matches = process.extract( + committer, creator_map.keys(), scorer=fuzz.token_sort_ratio, limit=2 ) + match, score = matches[0] + if score <= 80: + if committer not in BLACKLIST: + print("No entry to sort:", committer) + continue + existing_creators.discard(match) + committers.append(match) + + for unmatched in sorted(existing_creators): + print("No matching commits:", unmatched) + # Keep the entries to avoid removing people for bad matching + committers.append(unmatched) - data = [" ".join(line.strip().split()[1:-1]) for line in lines if "%" in line] + for last_author in CREATORS_LAST: + if committers[-1] != last_author: + committers.remove(last_author) + committers.append(last_author) - # load zenodo from master - zenodo_file = Path(".zenodo.json") - zenodo = json.loads(zenodo_file.read_text()) - zen_names = [ - " ".join(val["name"].split(",")[::-1]).strip() for val in zenodo["creators"] + creators = [ + creator_map.get(committer, {"name": committer}) for committer in committers ] - total_names = len(zen_names) - - name_matches = [] - position = 1 - for ele in data: - matches = process.extract(ele, zen_names, scorer=fuzz.token_sort_ratio, limit=2) - # matches is a list [('First match', % Match), ('Second match', % Match)] - if matches[0][1] <= 80: - # skip unmatched names - print("No entry to sort:", ele) - continue - idx = zen_names.index(matches[0][0]) - val = zenodo["creators"][idx] - - if val not in name_matches: - if val["name"] not in CREATORS_LAST: - val["position"] = position - position += 1 - else: - val["position"] = total_names + CREATORS_LAST.index(val["name"]) - name_matches.append(val) - - for missing in zenodo["creators"]: - if "position" not in missing: - missing["position"] = position - position += 1 - name_matches.append(missing) - - zenodo["creators"] = sorted(name_matches, key=lambda k: k["position"]) - # Remove position - for creator in zenodo["creators"]: - del creator["position"] - - zenodo_file.write_text("%s\n" % json.dumps(zenodo, indent=2, sort_keys=True)) + zenodo["creators"] = creators + + zenodo_file.write_text( + "%s\n" % json.dumps(zenodo, indent=2, ensure_ascii=False), encoding='utf-8' + ) diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000000..571b93628b --- /dev/null +++ b/tox.ini @@ -0,0 +1,108 @@ +[tox] +requires = + tox>=4 +envlist = + py3{9,10,11,12,13}-none # Test nipype functionality on all versions + py3{9,12,13}-full # Test with extra dependencies on oldest and two newest + py39-min # Test with minimal dependencies + py3{11,12,13}-pre # Test with pre-release on SPEC0-supported Python +skip_missing_interpreters = true + +# Configuration that allows us to split tests across GitHub runners effectively +[gh-actions] +python = + 3.9: py39 + 3.10: py310 + 3.11: py311 + 3.12: py312 + 3.13: py313 + +[gh-actions:env] +DEPENDS = + min: min + none: none + full: full + pre: pre + +[testenv] +description = Pytest with coverage +labels = test +pip_pre = + pre: true +pass_env = + # Parsed from `git grep getenv` and `git grep os.environ` + # May not all be needed + NIPYPE_NO_ET + NO_ET + ANTSPATH + CI_SKIP_TEST + FREESURFER_HOME + USER + FSLDIR + FSLOUTPUTTYPE + FSL_COURSE_DATA + NIPYPE_NO_MATLAB + OMP_NUM_THREADS + NIPYPE_NO_R + SPMMCRCMD + FORCE_SPMMCR + LOGNAME + AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY + MATLABCMD + MRTRIX3_HOME + RCMD + ETS_TOOLKIT + NIPYPE_CONFIG_DIR + DISPLAY + PATHEXT + # getpass.getuser() sources for Windows: + LOGNAME + USER + LNAME + USERNAME + # Pass user color preferences through + PY_COLORS + FORCE_COLOR + NO_COLOR + CLICOLOR + CLICOLOR_FORCE + PYTHON_GIL +extras = + tests + full: doc + full: profiler + full: duecredit + full: ssh + full: nipy +setenv = + FSLOUTPUTTYPE=NIFTI_GZ + pre: PIP_EXTRA_INDEX_URL=https://pypi.anaconda.org/scientific-python-nightly-wheels/simple + pre: UV_EXTRA_INDEX_URL=https://pypi.anaconda.org/scientific-python-nightly-wheels/simple +uv_resolution = + min: lowest-direct + +commands = + python -c "import nipype; print(nipype.__version__)" + pytest --durations=20 --durations-min=1.0 --cov-report term-missing {posargs:-n auto} + +[testenv:specs] +description = Rebuild spec tests +deps = + black + # Rebuild dipy specs + dipy + # Faster to install old numpy than unreleased Dipy + # This can be dropped once a Dipy release supports numpy 2 + numpy<2 +commands = + python tools/checkspecs.py + +[testenv:style] +description = Check our style guide +labels = check +deps = + black +skip_install = true +commands = + black --check --diff nipype setup.py