diff --git a/.github/workflows/ci-cd.yml b/.github/workflows/ci-cd.yml new file mode 100644 index 0000000..ecb6e9e --- /dev/null +++ b/.github/workflows/ci-cd.yml @@ -0,0 +1,146 @@ +name: CI/CD + +on: + push: + branches: [ main, develop ] + pull_request: + branches: [ main, develop ] + release: + types: [published] + +defaults: + run: + shell: bash + +jobs: + test: + strategy: + matrix: + os: [ubuntu-latest] + python-version: ["3.8", "3.12"] + fail-fast: false + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash -l {0} + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Unset header + # checkout@v2 adds a header that makes branch protection report errors + # because the Github action bot is not a collaborator on the repo + run: git config --local --unset http.https://github.com/.extraheader + - name: Fetch tags + run: git fetch --prune --unshallow + - name: Install Dcm2niix + run: | + curl -fLO https://github.com/rordenlab/dcm2niix/releases/latest/download/dcm2niix_lnx.zip + unzip dcm2niix_lnx.zip + mv dcm2niix /usr/local/bin + - name: Install Minconda + uses: conda-incubator/setup-miniconda@v2 + with: + auto-activate-base: true + activate-environment: "" + - name: Install MRtrix via Conda + run: | + conda install -c mrtrix3 mrtrix3 + mrconvert --version + - name: Disable etelemetry + run: echo "NO_ET=TRUE" >> $GITHUB_ENV + - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Update build tools + run: python3 -m pip install --upgrade pip + - name: Install Package + run: python3 -m pip install -e .[test] -e ./extras[test] + - name: Pytest + run: pytest -vvs --cov fileformats --cov-config .coveragerc --cov-report xml . + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v2 + with: + fail_ci_if_error: true + token: ${{ secrets.CODECOV_TOKEN }} + + build: + needs: [test] + runs-on: ubuntu-latest + strategy: + matrix: + pkg: + - ["main", "."] + - ["extras", "./extras"] + steps: + - uses: actions/checkout@v3 + with: + submodules: recursive + fetch-depth: 0 + - name: Unset header + # checkout@v2 adds a header that makes branch protection report errors + # because the Github action bot is not a collaborator on the repo + run: git config --local --unset http.https://github.com/.extraheader + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: '3.12' + - name: Install build tools + run: python3 -m pip install build twine + - name: Build source and wheel distributions + run: python3 -m build ${{ matrix.pkg[1] }} + - name: Check distributions + run: twine check ${{ matrix.pkg[1] }}/dist/* + - uses: actions/upload-artifact@v3 + with: + name: built-${{ matrix.pkg[0] }} + path: ${{ matrix.pkg[1] }}/dist + + deploy: + needs: [build] + runs-on: ubuntu-latest + steps: + - name: Download build + uses: actions/download-artifact@v3 + with: + name: built-main + path: dist + - name: Check for PyPI token on tag + id: deployable + if: github.event_name == 'release' + env: + PYPI_API_TOKEN: "${{ secrets.PYPI_API_TOKEN }}" + run: if [ -n "$PYPI_API_TOKEN" ]; then echo "DEPLOY=true" >> $GITHUB_OUTPUT; fi + - name: Upload to PyPI + if: steps.deployable.outputs.DEPLOY + uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.PYPI_API_TOKEN }} + + deploy-extras: + needs: [build, deploy] + runs-on: ubuntu-latest + steps: + - name: Download build + uses: actions/download-artifact@v3 + with: + name: built-extras + path: dist + - name: Check for PyPI token on tag + id: deployable + if: github.event_name == 'release' + env: + EXTRAS_PYPI_API_TOKEN: "${{ secrets.EXTRAS_PYPI_API_TOKEN }}" + run: if [ -n "$EXTRAS_PYPI_API_TOKEN" ]; then echo "DEPLOY=true" >> $GITHUB_OUTPUT; fi + - name: Upload to PyPI + if: steps.deployable.outputs.DEPLOY + uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.EXTRAS_PYPI_API_TOKEN }} + +# Deploy on tags if PYPI_API_TOKEN is defined in the repository secrets. +# Secrets are not accessible in the if: condition [0], so set an output variable [1] +# [0] https://github.community/t/16928 +# [1] https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-output-parameter diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml deleted file mode 100644 index 914b4f1..0000000 --- a/.github/workflows/publish.yml +++ /dev/null @@ -1,40 +0,0 @@ -# This workflows will upload a Python Package using Twine when a release is created -# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries - -name: Upload to PyPI - -on: - release: - types: [published] - -jobs: - deploy: - runs-on: ubuntu-latest - - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Get history and tags for SCM versioning to work - run: | - git fetch --prune --unshallow - git fetch --depth=1 origin +refs/tags/*:refs/tags/* - - name: Unset header - # checkout@v2 adds a header that makes branch protection report errors - # because the Github action bot is not a collaborator on the repo - run: git config --local --unset http.https://github.com/.extraheader - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Install dependencies - run: | - python -m pip install --upgrade pip - pip install twine build - - - name: Build and publish - env: - TWINE_USERNAME: __token__ - TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }} - run: | - python -m build - twine upload dist/* diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml deleted file mode 100644 index fc23b76..0000000 --- a/.github/workflows/tests.yml +++ /dev/null @@ -1,55 +0,0 @@ -name: Tests - -on: - push: - branches: - - main - - develop - pull_request: - -defaults: - run: - shell: bash - -jobs: - build: - strategy: - matrix: - os: [ubuntu-latest] - python-version: ["3.8", "3.11"] - fail-fast: false - runs-on: ${{ matrix.os }} - defaults: - run: - shell: bash -l {0} - steps: - - uses: actions/checkout@v2 - - name: Get history and tags for SCM versioning to work - run: | - git fetch --prune --unshallow - git fetch --depth=1 origin +refs/tags/*:refs/tags/* - - name: Disable etelemetry - run: echo "NO_ET=TRUE" >> $GITHUB_ENV - - - name: Install System Packages - run: sudo apt install libopenjp2-7 - - - name: Set up Python ${{ matrix.python-version }} on ${{ matrix.os }} - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.python-version }} - - - name: Update build tools - run: python -m pip install --upgrade pip flit_scm - - - name: Install Package - run: python -m pip install .[test,extended] - - - name: Pytest - run: pytest -vvs --cov fileformats.medimage --cov-config .coveragerc --cov-report xml - - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v2 - with: - fail_ci_if_error: true - token: ${{ secrets.CODECOV_TOKEN }} diff --git a/README.rst b/README.rst index e87688f..8b6faad 100644 --- a/README.rst +++ b/README.rst @@ -1,7 +1,7 @@ FileFormats - Medimage ====================== -.. image:: https://github.com/ArcanaFramework/fileformats-medimage/actions/workflows/tests.yml/badge.svg - :target: https://github.com/ArcanaFramework/fileformats-medimage/actions/workflows/tests.yml +.. image:: https://github.com/ArcanaFramework/fileformats-medimage/actions/workflows/ci-cd.yml/badge.svg + :target: https://github.com/ArcanaFramework/fileformats-medimage/actions/workflows/ci-cd.yml .. image:: https://codecov.io/gh/ArcanaFramework/fileformats-medimage/branch/main/graph/badge.svg?token=UIS0OGPST7 :target: https://codecov.io/gh/ArcanaFramework/fileformats-medimage .. image:: https://img.shields.io/pypi/pyversions/fileformats-medimage.svg diff --git a/extras/LICENSE b/extras/LICENSE new file mode 100644 index 0000000..7111479 --- /dev/null +++ b/extras/LICENSE @@ -0,0 +1,91 @@ +Creative Commons Attribution 4.0 International Public License +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + +Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. +Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. +Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. +Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. +Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. +Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. +Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. +Licensor means the individual(s) or entity(ies) granting rights under this Public License. +Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. +Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. +You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. +Section 2 – Scope. + +License grant. +Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: +reproduce and Share the Licensed Material, in whole or in part; and +produce, reproduce, and Share Adapted Material. +Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. +Term. The term of this Public License is specified in Section 6(a). +Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. +Downstream recipients. +Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. +No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. +No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). +Other rights. + +Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. +Patent and trademark rights are not licensed under this Public License. +To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + +Attribution. + +If You Share the Licensed Material (including in modified form), You must: + +retain the following if it is supplied by the Licensor with the Licensed Material: +identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); +a copyright notice; +a notice that refers to this Public License; +a notice that refers to the disclaimer of warranties; +a URI or hyperlink to the Licensed Material to the extent reasonably practicable; +indicate if You modified the Licensed Material and retain an indication of any previous modifications; and +indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. +You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. +If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. +If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + +for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; +if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and +You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. +Section 5 – Disclaimer of Warranties and Limitation of Liability. + +Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. +To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. +The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. +Section 6 – Term and Termination. + +This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. +Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + +automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or +upon express reinstatement by the Licensor. +For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. +For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. +Sections 1, 5, 6, 7, and 8 survive termination of this Public License. +Section 7 – Other Terms and Conditions. + +The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. +Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. +Section 8 – Interpretation. + +For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. +To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. +No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. +Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. + +Additional languages available: العربية, čeština, Deutsch, Ελληνικά, Español, euskara, suomeksi, français, hrvatski, Bahasa Indonesia, italiano, 日本語, 한국어, Lietuvių, latviski, te reo Māori, Nederlands, norsk, polski, português, română, русский, Slovenščina, svenska, Türkçe, українська, 中文, 華語. Please read the FAQ for more information about official translations. \ No newline at end of file diff --git a/extras/README.rst b/extras/README.rst new file mode 100644 index 0000000..b5cb5fb --- /dev/null +++ b/extras/README.rst @@ -0,0 +1,52 @@ +FileFormats Medimage Extras +=========================== +.. image:: https://github.com/ArcanaFramework/fileformats-medimage/actions/workflows/ci-cd.yml/badge.svg + :target: https://github.com/ArcanaFramework/fileformats-medimage/actions/workflows/ci-cd.yml +.. image:: https://codecov.io/gh/ArcanaFramework/fileformats-medimage/branch/main/graph/badge.svg?token=UIS0OGPST7 + :target: https://codecov.io/gh/ArcanaFramework/fileformats-medimage +.. image:: https://img.shields.io/pypi/pyversions/fileformats-medimage-extras.svg + :target: https://pypi.python.org/pypi/fileformats-medimage-extras/ + :alt: Supported Python versions +.. image:: https://img.shields.io/badge/docs-latest-brightgreen.svg?style=flat + :target: https://arcanaframework.github.io/fileformats/ + :alt: Documentation Status + + +This is a extras module for the +`fileformats-medimage `__ package, which provides +additional functionality to format classes (i.e. aside from basic identification and validation), such as +conversion tools, metadata parsers, test data generators, etc... + + +Prerequisites +------------- + +In order to perform conversions between DICOM and neuroimaging formats such as NIfTI you +will need to install the following packages + +* `Dcm2niix `__ +* `MRtrix3 `__ + +Please see their installation instructions for the best method for your system +(alternatively the +`Test GitHub action `__ +contains an example installation for Ubuntu) + + +Installation +------------ + +This extension can be installed for Python 3 using *pip*:: + + $ pip3 install fileformats-medimage-extras + + +License +------- + +This work is licensed under a +`Creative Commons Attribution 4.0 International License `_ + +.. image:: https://i.creativecommons.org/l/by/4.0/88x31.png + :target: http://creativecommons.org/licenses/by/4.0/ + :alt: Creative Commons Attribution 4.0 International License diff --git a/extras/fileformats/extras/medimage/__init__.py b/extras/fileformats/extras/medimage/__init__.py new file mode 100644 index 0000000..436dbbe --- /dev/null +++ b/extras/fileformats/extras/medimage/__init__.py @@ -0,0 +1,5 @@ +from ._version import __version__ +from . import converters +from . import dicom +from . import diffusion +from . import nifti diff --git a/extras/fileformats/extras/medimage/_version.py b/extras/fileformats/extras/medimage/_version.py new file mode 100644 index 0000000..7519301 --- /dev/null +++ b/extras/fileformats/extras/medimage/_version.py @@ -0,0 +1,4 @@ +# file generated by setuptools_scm +# don't change, don't track in version control +__version__ = version = '0.1.6.dev12+ga52eb33' +__version_tuple__ = version_tuple = (0, 1, 6, 'dev12', 'ga52eb33') diff --git a/extras/fileformats/extras/medimage/converters.py b/extras/fileformats/extras/medimage/converters.py new file mode 100644 index 0000000..5682a33 --- /dev/null +++ b/extras/fileformats/extras/medimage/converters.py @@ -0,0 +1,208 @@ +from pathlib import Path +import attrs +import json +import typing as ty +import tempfile +import jq +from fileformats.core import hook +import pydra +from fileformats.medimage.base import MedicalImage +from fileformats.medimage.dicom import DicomDir, DicomCollection, DicomSeries +from fileformats.medimage import ( + Analyze, + Nifti, + NiftiGz, + NiftiX, + NiftiGzX, + NiftiXBvec, + NiftiBvec, + NiftiGzBvec, + NiftiGzXBvec, +) + +try: + from pydra.tasks.mrtrix3.utils import MRConvert +except ImportError: + from pydra.tasks.mrtrix3.latest import mrconvert as MRConvert +from pydra.tasks.dcm2niix import Dcm2Niix + + +@hook.converter(source_format=MedicalImage, target_format=Analyze, out_ext=Analyze.ext) +def mrconvert(name, out_ext: str): + """Initiate an MRConvert task with the output file extension set + + Parameters + ---------- + name : str + name of the converter task + out_ext : str + extension of the output file, used by MRConvert to determine the desired format + + Returns + ------- + pydra.ShellCommandTask + the converter task + """ + return MRConvert(name=name, out_file="out" + out_ext) + + +@pydra.mark.task +def ensure_dicom_dir(dicom: DicomCollection) -> DicomDir: + if isinstance(dicom, DicomSeries): + dicom_dir_fspath = tempfile.mkdtemp() + dicom.copy(dicom_dir_fspath, mode=DicomDir.CopyMode.link) + dicom = DicomDir(dicom_dir_fspath) + elif not isinstance(dicom, DicomDir): + raise RuntimeError( + "Unrecognised input to ensure_dicom_dir, should be DicomSeries or DicomDir " + f"not {dicom}" + ) + return dicom + + +@hook.converter(source_format=DicomCollection, target_format=Nifti) +@hook.converter(source_format=DicomCollection, target_format=NiftiGz, compress="y") +@hook.converter(source_format=DicomCollection, target_format=NiftiX) +@hook.converter(source_format=DicomCollection, target_format=NiftiGzX, compress="y") +@hook.converter(source_format=DicomCollection, target_format=NiftiXBvec) +@hook.converter(source_format=DicomCollection, target_format=NiftiBvec) +@hook.converter(source_format=DicomCollection, target_format=NiftiGzBvec) +@hook.converter( + source_format=DicomCollection, target_format=NiftiGzXBvec, compress="y" +) +def extended_dcm2niix( + name, + compress: str = "n", + file_postfix: ty.Optional[str] = None, + side_car_jq: ty.Optional[str] = None, + extract_volume: ty.Optional[int] = None, + to_4d: bool = False, +): + """The Dcm2niix command wrapped in a workflow in order to map the inputs and outputs + onto "in_file" and "out_file", respectively, and implement optional post-conversion + manipulations to allow manual override of conversion issues. + + Parameters + ---------- + name : str + name of the workflow + compress : str, optional + whether to apply compression to the conversion, by default "n" + file_postfix : str, optional + select one of the multiple output files by its generated postfix. + See https://github.com/rordenlab/dcm2niix/blob/master/FILENAMING.md for + complete list of different postfixes that will be generated, by default None + side_car_jq : str, optional + JQ (https://stedolan.github.io/jq/) expression that can be provided to edit + the resulting JSON side-car. Can be used to fix any conversion issues or add + required fields manually, by default None + extract_volume : int, optional + extract a 3D volume from a 4D dataset by passing the index (0-based) of the + volume to extract, by default None + to_4d : bool, optional + whether to wrap resulting 3D NIfTI volume in a 4D dataset, by default False + + Returns + ------- + pydra.Workflow + the converter workflow + + Raises + ------ + ValueError + when mutually exclusive "extract_volume" and "to_4d" options are provided + """ + + if extract_volume is not None and to_4d: + raise ValueError( + f"'extract_volume' ({extract_volume}) and 'to_4d' are mutually exclusive" + ) + # Create workflow to map input field to "in_file" and optionally perform post-conversion + # steps to manipulate the converted NIfTI files + wf = pydra.Workflow( + name=name, + input_spec=["in_file"], + ) + wf.add( + ensure_dicom_dir( + dicom=wf.lzin.in_file, + name="ensure_dicom_dir", + ) + ) + + if file_postfix is None: + file_postfix = attrs.NOTHING # type: ignore + wf.add( + Dcm2Niix( + in_dir=wf.ensure_dicom_dir.lzout.out, + out_dir=Path("."), + name="dcm2niix", + compress=compress, + file_postfix=file_postfix, + ) + ) + out_file = wf.dcm2niix.lzout.out_file + out_json = wf.dcm2niix.lzout.out_json + # Add MRConvert step to either select a single volume of a 4D dataset or the inverse, + # wrap a single volume in a 4D dataset + if extract_volume is not None or to_4d: + if extract_volume: + coord = [3, extract_volume] + axes = [0, 1, 2] + else: # to_4d + coord = attrs.NOTHING # type: ignore + axes = [0, 1, 2, -1] + wf.add( + MRConvert( + in_file=out_file, + coord=coord, + axes=axes, + name="mrconvert", + ) + ) + out_file = wf.mrconvert.lzout.out_file + # Add JQ edit of side car to allow manual fixing of any conversion issues + if side_car_jq is not None: + wf.add( + edit_dcm2niix_side_car( + in_file=out_json, jq_expr=side_car_jq, name="json_edit" + ) + ) + out_json = wf.json_edit.lzout.out + + wf.add( + collect_dcm2niix_outputs( + name="collect_outputs", + out_file=out_file, + out_json=out_json, + out_bvec=wf.dcm2niix.lzout.out_bvec, + out_bval=wf.dcm2niix.lzout.out_bval, + ) + ) + # Set workflow outputs + wf.set_output(("out_file", wf.collect_outputs.lzout.out)) + return wf + + +@pydra.mark.task +def edit_dcm2niix_side_car(in_file: Path, jq_expr: str, out_file=None) -> Path: + """ "Applies ad-hoc edit of JSON side car with JQ query language""" + if out_file is None: + out_file = in_file + with open(in_file) as f: + dct = json.load(f) + dct = jq.compile(jq_expr).input(dct).first() + with open(out_file, "w") as f: + json.dump(dct, f) + return in_file + + +@pydra.mark.task +def collect_dcm2niix_outputs( + out_file: Path, out_json: Path, out_bvec: Path, out_bval: Path +) -> ty.List[Path]: + lst = [out_file] + for file in (out_json, out_bvec, out_bval): + if file is not attrs.NOTHING: + lst.append(file) + return lst diff --git a/extras/fileformats/extras/medimage/dicom.py b/extras/fileformats/extras/medimage/dicom.py new file mode 100644 index 0000000..98167d5 --- /dev/null +++ b/extras/fileformats/extras/medimage/dicom.py @@ -0,0 +1,74 @@ +from pathlib import Path +import typing as ty +from tempfile import mkdtemp +from random import Random +import pydicom +import numpy as np +from fileformats.core import FileSet +from fileformats.core.utils import gen_filename +from fileformats.medimage import MedicalImage, DicomCollection, DicomDir, DicomSeries +import medimages4tests.dummy.dicom.mri.t1w.siemens.skyra.syngo_d13c + + +@MedicalImage.read_array.register +def dicom_read_array(collection: DicomCollection): + image_stack = [] + for dcm_file in collection.contents: + image_stack.append(pydicom.dcmread(dcm_file).pixel_array) + return np.asarray(image_stack) + + +@MedicalImage.vox_sizes.register +def dicom_vox_sizes(collection: DicomCollection): + return tuple( + collection.metadata["PixelSpacing"] + [collection.metadata["SliceThickness"]] + ) + + +@MedicalImage.dims.register +def dicom_dims(collection: DicomCollection): + return tuple( + ( + collection.metadata["Rows"], + collection.metadata["DataColumns"], + len(list(collection.contents)), + ), + ) + + +@DicomCollection.series_number.register +def dicom_series_number(collection: DicomCollection): + return str(collection.metadata["SeriesNumber"]) + + +@FileSet.generate_sample_data.register +def dicom_dir_generate_sample_data(dcmdir: DicomDir, dest_dir: Path, seed: ty.Union[int, Random], stem: ty.Optional[str]): + dcm_dir = medimages4tests.dummy.dicom.mri.t1w.siemens.skyra.syngo_d13c.get_image() + # Set series number to random value to make it different + if isinstance(seed, Random): + rng = seed + else: + rng = Random(seed) + series_number = rng.randint(1, SERIES_NUMBER_RANGE) + dest = Path(dest_dir) / gen_filename(seed_or_rng=seed, stem=stem) + dest.mkdir() + for dcm_file in dcm_dir.iterdir(): + dcm = pydicom.dcmread(dcm_file) + dcm.SeriesNumber = series_number + pydicom.dcmwrite(dest / dcm_file.name, dcm) + return [dest] + + +@FileSet.generate_sample_data.register +def dicom_set_generate_sample_data(dcm_series: DicomSeries, dest_dir: Path, seed: int, stem: ty.Optional[str]): + rng = Random(seed) + dicom_dir = dicom_dir_generate_sample_data(dcm_series, dest_dir=mkdtemp(), seed=rng, stem=None)[0] + stem = gen_filename(rng, stem=stem) + fspaths = [] + for i, dicom_file in enumerate(dicom_dir.iterdir(), start=1): + fspaths.append(dicom_file.rename(dest_dir / f"{stem}-{i}.dcm")) + return fspaths + + +SERIES_NUMBER_TAG = ("0020", "0011") +SERIES_NUMBER_RANGE = int(1e8) diff --git a/extras/fileformats/extras/medimage/diffusion.py b/extras/fileformats/extras/medimage/diffusion.py new file mode 100644 index 0000000..0b8399f --- /dev/null +++ b/extras/fileformats/extras/medimage/diffusion.py @@ -0,0 +1,16 @@ +import numpy as np +from fileformats.medimage.diffusion import DwiEncoding, Bval, Bvec + + +@Bval.read_array.register +def bval_read_array(bval: Bval): + return np.asarray([float(ln) for ln in bval.read_contents().split()]) + + +@DwiEncoding.read_array.register +def bvec_read_array(bvec: Bvec): + bvals = bvec.b_values_file.read_array() + directions = np.asarray( + [[float(x) for x in ln.split()] for ln in bvec.read_contents().splitlines()] + ).T + return np.concatenate((directions, bvals.reshape((-1, 1))), axis=1) # type: ignore diff --git a/extras/fileformats/extras/medimage/nifti.py b/extras/fileformats/extras/medimage/nifti.py new file mode 100644 index 0000000..608871b --- /dev/null +++ b/extras/fileformats/extras/medimage/nifti.py @@ -0,0 +1,51 @@ +from pathlib import Path +import typing as ty +import nibabel +from fileformats.core import FileSet +from fileformats.medimage import MedicalImage, Nifti, NiftiGz, Nifti1, NiftiGzX, NiftiX +import medimages4tests.dummy.nifti + + +@FileSet.read_metadata.register +def nifti_read_metadata(nifti: Nifti): + return dict(nibabel.load(nifti.fspath).header) + + +@MedicalImage.read_array.register +def nifti_data_array(nifti: Nifti): + return nibabel.load(nifti.fspath).get_data() + + +@MedicalImage.vox_sizes.register +def nifti_vox_sizes(nifti: Nifti): + # FIXME: This won't work for 4-D files + return nifti.metadata["pixdim"][1:4] + + +@MedicalImage.dims.register +def nifti_dims(nifti: Nifti): + # FIXME: This won't work for 4-D files + return nifti.metadata["dim"][1:4] + + +@FileSet.generate_sample_data.register +def nifti_generate_sample_data(nifti: Nifti1, dest_dir: Path, seed: int, stem: ty.Optional[str]): + return medimages4tests.dummy.nifti.get_image(out_file=dest_dir / "nifti.nii") + + +@FileSet.generate_sample_data.register +def nifti_gz_generate_sample_data(nifti: NiftiGz, dest_dir: Path, seed: int, stem: ty.Optional[str]): + return medimages4tests.dummy.nifti.get_image( + out_file=dest_dir / "nifti.nii.gz", compressed=True + ) + + +@FileSet.generate_sample_data.register +def nifti_gz_x_generate_sample_data(nifti: NiftiGzX, dest_dir: Path, seed: int, stem: ty.Optional[str]): + return medimages4tests.mri.neuro.t1w.get_image() + + +@FileSet.generate_sample_data.register +def nifti_x_generate_sample_data(nifti: NiftiX, dest_dir: Path, seed: int, stem: ty.Optional[str]): + nifti_gz_x = NiftiGzX(medimages4tests.mri.neuro.t1w.get_image()) + return NiftiX.convert(nifti_gz_x) diff --git a/extras/fileformats/extras/medimage/tests/test_dicom_metadata.py b/extras/fileformats/extras/medimage/tests/test_dicom_metadata.py new file mode 100644 index 0000000..538f5d4 --- /dev/null +++ b/extras/fileformats/extras/medimage/tests/test_dicom_metadata.py @@ -0,0 +1,19 @@ +from fileformats.medimage import DicomSeries, DicomDir + + +def test_dicom_series_metadata(tmp_path): + series = DicomSeries.sample(tmp_path) + + # Check series number is not a list + assert not isinstance(series["SeriesNumber"], list) + # check the SOP Instance ID has been converted into a list + assert isinstance(series["SOPInstanceUID"], list) + + +def test_dicom_dir_metadata(tmp_path): + series = DicomDir.sample(tmp_path) + + # Check series number is not a list + assert not isinstance(series["SeriesNumber"], list) + # check the SOP Instance ID has been converted into a list + assert isinstance(series["SOPInstanceUID"], list) diff --git a/extras/fileformats/extras/medimage/tests/test_neuro_converters.py b/extras/fileformats/extras/medimage/tests/test_neuro_converters.py new file mode 100644 index 0000000..862f8f2 --- /dev/null +++ b/extras/fileformats/extras/medimage/tests/test_neuro_converters.py @@ -0,0 +1,85 @@ +import pytest +from fileformats.medimage import ( + NiftiGzX, + NiftiGzXBvec, + NiftiBvec, + Analyze, +) +from logging import getLogger + + +logger = getLogger("fileformats") + + +@pytest.mark.xfail(reason="refactoring of side car handling incomplete") +def test_dicom_to_nifti(dummy_t1w_dicom): + + nifti_gz_x = NiftiGzX.convert(dummy_t1w_dicom) + assert nifti_gz_x.metadata["EchoTime"] == 0.00207 + + +@pytest.mark.xfail(reason="refactoring of side car handling incomplete") +def test_dicom_to_nifti_select_echo(dummy_magfmap_dicom): + + nifti_gz_x_e1 = NiftiGzX.convert(dummy_magfmap_dicom, file_postfix="_e1") + nifti_gz_x_e2 = NiftiGzX.convert(dummy_magfmap_dicom, file_postfix="_e2") + assert nifti_gz_x_e1.metadata["EchoNumber"] == 1 + assert nifti_gz_x_e2.metadata["EchoNumber"] == 2 + + +def test_dicom_to_nifti_select_suffix(dummy_mixedfmap_dicom): + + nifti_gz_x_ph = NiftiGzX.convert(dummy_mixedfmap_dicom, file_postfix="_ph") + nifti_gz_x_imaginary = NiftiGzX.convert( + dummy_mixedfmap_dicom, file_postfix="_imaginary" + ) + nifti_gz_x_real = NiftiGzX.convert( + dummy_mixedfmap_dicom, file_postfix="_real" + ) + + assert list(nifti_gz_x_ph.dims()) == [256, 256, 60] + assert list(nifti_gz_x_imaginary.dims()) == [256, 256, 60] + assert list(nifti_gz_x_real.dims()) == [256, 256, 60] + + +def test_dicom_to_nifti_with_extract_volume(dummy_dwi_dicom): + + nifti_gz_x_e1 = NiftiGzX.convert(dummy_dwi_dicom, extract_volume=30) + assert nifti_gz_x_e1.metadata["dim"][0] == 3 + + +@pytest.mark.xfail(reason="refactoring of side car handling incomplete") +def test_dicom_to_nifti_with_jq_edit(dummy_t1w_dicom): + + nifti_gz_x = NiftiGzX.convert( + dummy_t1w_dicom, side_car_jq=".EchoTime *= 1000" + ) + assert nifti_gz_x.metadata["EchoTime"] == 2.07 + + +def test_dicom_to_niftix_with_fslgrad(dummy_dwi_dicom): + + logger.debug("Performing FSL grad conversion") + + nifti_gz_x_fsgrad = NiftiGzXBvec.convert(dummy_dwi_dicom) + + bvec_mags = [ + (v[0] ** 2 + v[1] ** 2 + v[2] ** 2) + for v in nifti_gz_x_fsgrad.encoding.directions + if any(v) + ] + + assert all(b in (0.0, 3000.0) for b in nifti_gz_x_fsgrad.encoding.b_values) + assert len(bvec_mags) == 60 + assert all(abs(1 - m) < 1e5 for m in bvec_mags) + + +# @pytest.mark.skip("Mrtrix isn't installed in test environment yet") +def test_dicom_to_nifti_as_4d(dummy_t1w_dicom): + + nifti_gz_x_e1 = NiftiGzX.convert(dummy_t1w_dicom, to_4d=True) + assert nifti_gz_x_e1.metadata["dim"][0] == 4 + + +def test_dicom_to_analyze(dummy_t1w_dicom): + Analyze.convert(dummy_t1w_dicom) diff --git a/extras/pyproject.toml b/extras/pyproject.toml new file mode 100644 index 0000000..dcdbe33 --- /dev/null +++ b/extras/pyproject.toml @@ -0,0 +1,92 @@ +[build-system] +requires = ["hatchling", "hatch-vcs"] +build-backend = "hatchling.build" + +[project] +name = "fileformats-medimage-extras" +description = "Classes for representing different file formats in Python classes for use in type hinting in data workflows" +readme = "README.rst" +requires-python = ">=3.8" +dependencies = [ + "fileformats >= 0.6", + "fileformats-extras >= 0.2.1", + "fileformats-medimage >= 0.3", + "jq >=1.4.0", + "nibabel >=5.0.0", + "numpy >=1.20", + "medimages4tests >=0.3.0", + "pydicom >=2.3.1", + "pydra >= 0.22.0", + "pydra-dcm2niix", + "pydra-mrtrix3", +] +license = {file = "LICENSE"} +authors = [ + {name = "Thomas G. Close", email = "tom.g.close@gmail.com"}, +] +maintainers = [ + {name = "Thomas G. Close", email = "tom.g.close@gmail.com"}, +] +keywords = [ + "file formats", + "data", +] +classifiers = [ + "Development Status :: 3 - Alpha", + "Environment :: Console", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Operating System :: MacOS :: MacOS X", + "Operating System :: Microsoft :: Windows", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Topic :: Scientific/Engineering", +] +dynamic = ["version"] + +[project.optional-dependencies] +dev = [ + "black", + "pre-commit", + "codespell", + "flake8", + "flake8-pyproject", +] +test = [ + "pytest >=6.2.5", + "pytest-env>=0.6.2", + "pytest-cov>=2.12.1", + "codecov", +] + +[project.urls] +repository = "https://github.com/ArcanaFramework/fileformats-medimage" + +[tool.hatch.version] +source = "vcs" +raw-options = {root = ".."} + +[tool.hatch.build.hooks.vcs] +version-file = "fileformats/extras/medimage/_version.py" + +[tool.hatch.build.targets.wheel] +packages = ["fileformats"] + +[tool.black] +target-version = ['py38'] +exclude = "fileformats/extras/medimage/_version.py" + +[tool.codespell] +ignore-words = ".codespell-ignorewords" + +[tool.flake8] +doctests = true +per-file-ignores = [ + "__init__.py:F401" +] +max-line-length = 88 +select = "C,E,F,W,B,B950" +extend-ignore = ['E203', 'E501', 'E129', 'F403'] diff --git a/fileformats/medimage/base.py b/fileformats/medimage/base.py index 482fd7d..b72869e 100644 --- a/fileformats/medimage/base.py +++ b/fileformats/medimage/base.py @@ -1,7 +1,7 @@ import typing as ty import logging from fileformats.generic import FileSet -from fileformats.core import mark +from fileformats.core import hook logger = logging.getLogger("fileformats") @@ -18,19 +18,19 @@ class MedicalImage(FileSet): IGNORE_HDR_KEYS = None binary = True - @mark.extra + @hook.extra def read_array(self): """ Returns the binary data of the image in a numpy array """ raise NotImplementedError - @mark.extra + @hook.extra def vox_sizes(self) -> ty.Tuple[float]: """The length of the voxels along each dimension""" raise NotImplementedError - @mark.extra + @hook.extra def dims(self) -> ty.Tuple[int]: """The dimensions of the image""" raise NotImplementedError diff --git a/fileformats/medimage/dicom.py b/fileformats/medimage/dicom.py index e57bd03..509b03e 100644 --- a/fileformats/medimage/dicom.py +++ b/fileformats/medimage/dicom.py @@ -4,7 +4,7 @@ from collections import defaultdict from pathlib import Path from functools import cached_property -from fileformats.core import mark, FileSet +from fileformats.core import hook, FileSet from fileformats.generic import DirectoryContaining, SetOf from fileformats.application import Dicom from .base import MedicalImage @@ -25,7 +25,7 @@ class DicomCollection(MedicalImage): def __len__(self): return len(self.contents) - @mark.extra + @hook.extra def series_number(self): raise NotImplementedError diff --git a/fileformats/medimage/diffusion.py b/fileformats/medimage/diffusion.py index cc06e62..849532f 100644 --- a/fileformats/medimage/diffusion.py +++ b/fileformats/medimage/diffusion.py @@ -1,5 +1,5 @@ import typing as ty -from fileformats.core import mark +from fileformats.core import hook from fileformats.core.mixin import WithAdjacentFiles from fileformats.generic import File from .nifti import NiftiGzX, NiftiGz, Nifti1, NiftiX @@ -9,7 +9,7 @@ class DwiEncoding(File): iana_mime: ty.Optional[str] = None - @mark.extra + @hook.extra def read_array(self): "Both the gradient direction and weighting combined into a single Nx4 array" raise NotImplementedError @@ -33,7 +33,7 @@ class Bval(File): ext = ".bval" - @mark.extra + @hook.extra def read_array(self): raise NotImplementedError @@ -43,7 +43,7 @@ class Bvec(WithAdjacentFiles, DwiEncoding): ext = ".bvec" - @mark.required + @hook.required @property def b_values_file(self) -> Bval: return Bval(self.select_by_ext(Bval)) @@ -51,7 +51,7 @@ def b_values_file(self) -> Bval: # NIfTI file format gzipped with BIDS side car class WithBvec(WithAdjacentFiles): - @mark.required + @hook.required @property def encoding(self) -> Bvec: return Bvec(self.select_by_ext(Bvec)) diff --git a/fileformats/medimage/misc.py b/fileformats/medimage/misc.py index 4b2d4ef..0289f0f 100644 --- a/fileformats/medimage/misc.py +++ b/fileformats/medimage/misc.py @@ -1,6 +1,6 @@ from fileformats.application import Gzip from fileformats.generic import File -from fileformats.core import mark +from fileformats.core import hook from fileformats.core.mixin import WithSeparateHeader, WithMagicVersion from .base import MedicalImage @@ -31,7 +31,7 @@ class Mgh(WithMagicVersion, File): ext = ".mgh" magic_pattern = rb"(....)" # First integer is the version string - @mark.check + @hook.check def is_supported_version(self): self.version == 1 diff --git a/fileformats/medimage/nifti.py b/fileformats/medimage/nifti.py index a0d60c3..015780b 100644 --- a/fileformats/medimage/nifti.py +++ b/fileformats/medimage/nifti.py @@ -1,6 +1,6 @@ import typing as ty from fileformats.generic import File -from fileformats.core import mark +from fileformats.core import hook from fileformats.core.mixin import ( WithSideCars, WithMagicNumber, WithAdjacentFiles) from fileformats.application import Json @@ -20,12 +20,12 @@ class WithBids(WithSideCars): primary_type = Nifti side_car_types = (Json,) - @mark.required + @hook.required @property def json_file(self): return Json(self.select_by_ext(Json)) - # @mark.required + # @hook.required # @property # def tsv_file(self): # return Tsv(self.select_by_ext(Tsv, allow_none=True)) @@ -70,7 +70,7 @@ class NiftiWithDataFile(WithAdjacentFiles, Nifti1): magic_number = "6E693100" alternate_exts = (".hdr",) - @mark.required + @hook.required @property def data_file(self): return self.select_by_ext(NiftiDataFile) diff --git a/pyproject.toml b/pyproject.toml index 7dbb5b8..db9ec00 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -66,6 +66,8 @@ version-file = "fileformats/medimage/_version.py" [tool.hatch.build.targets.wheel] packages = ["fileformats"] +exclude = ["tests"] +include = ["./fileformats"] [tool.black] target-version = ['py38']